slackbot

package module
v1.4.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 16, 2024 License: MIT Imports: 7 Imported by: 1

README

Go Reference

slackbot

Tiny Slack bot client using the web socket mode.

Prepare

see. https://api.slack.com/apis/connections/socket

The required tokens and permissions are:

  • app-level token (enable socket mode) *subscribe to bot events *message.channels *bot token
    • channels:history
    • channels:join
    • chat:write
    • files:write
    • users:read

Interface

Echo bot sample (see. sample/echo.go).

package main

import (
  "context"
  "fmt"
  "log"
  "os"
  "strings"

  "github.com/ikawaha/slackbot"
)

// Bot your bot
type Bot struct {
  *slackbot.Client
}

// NewBot creates a Slack bot.
func NewBot(appToken, botToken, botName string) (*Bot, error) {
  c, err := slackbot.New(appToken, botToken, slackbot.SetBotID(botName), slackbot.Debug())
  if err != nil {
    return nil, err
  }
  return &Bot{Client: c}, err
}

func main() {
  if len(os.Args) != 4 {
    fmt.Fprintf(os.Stderr, "usage: bot app-level-token slack-bot-token bot-name\n")
    os.Exit(1)
  }
  // set your app-level-token, bot token and bot name!
  bot, err := NewBot(os.Args[1], os.Args[2], os.Args[3])
  if err != nil {
    log.Fatal(err)
  }
  defer bot.Close()
  fmt.Println("^C exits")

  callPrefix := "<@" + bot.ID + ">"
  for {
    if err := bot.ReceiveMessage(context.TODO(), func(ctx context.Context, e *slackbot.Event) error {
      switch slackbot.EventType(e.Type) {
      case slackbot.Message:
        u, ok := bot.User(e.UserID)
        log.Printf("!!! user: %+v", u)
        if !ok || u.IsBot {
          return nil
        }
        if !strings.HasPrefix(e.Text, callPrefix) {
          return nil
        }
        msg := "Hi, " + u.Name + ": " + strings.TrimPrefix(e.Text, callPrefix)
        if err := bot.PostMessage(ctx, e.Channel, msg); err != nil {
          return err
        }
      case slackbot.SlashCommand:
        if err := bot.RespondToCommand(ctx, e.ResponseURL, e.Text, true); err != nil {
          return err
        }
      }
      return nil
    }); err != nil {
      log.Printf("%v", err)
    }
  }
}

Lisence

MIT

Documentation

Index

Constants

View Source
const (
	// AppMention is a Slack event type.
	// Subscribe to only the message events that mention your app or bot.
	AppMention = socketmode.AppMention

	// Message is a Slack event type.
	// A message was sent to a channel.
	Message = socketmode.Message

	// SlashCommand is a slash command.
	SlashCommand = socketmode.SlashCommand
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	Name string
	ID   string
	// contains filtered or unexported fields
}

Client represents a slack client.

func New

func New(appLevelToken, apiToken string, opts ...Option) (*Client, error)

New creates a slack bot from app-level token and API token.

func (*Client) Close

func (c *Client) Close() error

Close implements the io.Closer interface.

func (Client) PlainMessageText

func (c Client) PlainMessageText(msg string) string

PlainMessageText resolves meta tags of the message text and return it.

func (Client) PostMessage

func (c Client) PostMessage(ctx context.Context, channelID, msg string) error

PostMessage sends a message to the Slack channel.

func (Client) ReceiveMessage added in v1.2.0

func (c Client) ReceiveMessage(ctx context.Context, handler func(ctx context.Context, e *Event) error) error

ReceiveMessage receives a message and passes it to a handler for processing.

func (*Client) RefreshUsersCache added in v1.3.0

func (c *Client) RefreshUsersCache(ctx context.Context) error

RefreshUsersCache updates the client's cached user map.

func (Client) RespondToCommand added in v1.4.0

func (c Client) RespondToCommand(ctx context.Context, responseURL string, msg string, visible bool) error

RespondToCommand responds to the Slack command.

func (Client) UploadImage

func (c Client) UploadImage(ctx context.Context, channels []string, title, fileName, fileType, comment string, img io.Reader) error

UploadImage uploads an image by files.upload API. see. https://api.slack.com/methods/files.upload

func (*Client) User added in v1.3.0

func (c *Client) User(id string) (User, bool)

User returns the user corresponding to user ID from the client's user cache.

func (Client) Users

func (c Client) Users(ctx context.Context) (map[string]User, error)

Users lists all users in a Slack team and returns it's userID map.

func (Client) UsersList added in v1.3.0

func (c Client) UsersList(ctx context.Context) ([]User, error)

UsersList lists all users in a Slack team. see. https://api.slack.com/methods/users.list

type Event added in v1.3.0

type Event = socketmode.Event

Event is an alias type of the socket mode event.

type EventType added in v1.4.0

type EventType = socketmode.EventType

EventType is the Slack event type.

type Option added in v1.3.0

type Option func(*config) error

Option represents the client's option.

func CacheUsers added in v1.4.0

func CacheUsers() Option

CacheUsers lists all users in a Slack team and caches it. required scopes: `users:read`

func Debug added in v1.3.0

func Debug() Option

Debug is the debug option.

func SetBotID added in v1.4.0

func SetBotID(name string) Option

SetBotID sets bot ID and name to a client. When this option is specified, all user data in a Slack team will be cached even if the CacheUsers option is not set. required scopes: `users:read`

type User added in v1.3.0

type User = webapi.User

User is an alias type of the web api user.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL