slacker

package module
v0.0.0-...-4e99377 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2017 License: MIT Imports: 7 Imported by: 0

README

slacker Go Report Card GoDoc

Built on top of the Slack API github.com/nlopes/slack with the idea to simplify the Real-Time Messaging feature to easily create Slack Bots, assign commands to them and extract parameters.

Features

  • Easy definitions of commands and their input
  • Available bot initialization, errors and default handlers
  • Simple parsing of String, Integer, Float and Boolean parameters
  • Contains support for context.Context
  • Built-in help command
  • Bot responds to mentions and direct messages
  • Handlers run concurrently via goroutines
  • Full access to the Slack API github.com/nlopes/slack

Usage

Using govendor github.com/kardianos/govendor:

govendor fetch github.com/shomali11/slacker

Dependencies

Examples

Example 1

Defining a command using slacker

package main

import (
	"github.com/shomali11/slacker"
	"log"
)

func main() {
	bot := slacker.NewClient("<YOUR SLACK BOT TOKEN>")

	bot.Command("ping", "Ping!", func(request *slacker.Request, response slacker.ResponseWriter) {
		response.Reply("pong")
	})

	err := bot.Listen()
	if err != nil {
		log.Fatal(err)
	}
}

Example 2

Adding handlers to when the bot is connected, encounters an error and a default for when none of the commands match

package main

import (
	"github.com/shomali11/slacker"
	"log"
)

func main() {
	bot := slacker.NewClient("<YOUR SLACK BOT TOKEN>")

	bot.Init(func() {
		log.Println("Connected!")
	})

	bot.Err(func(err string) {
		log.Println(err)
	})

	bot.Default(func(request *slacker.Request, response slacker.ResponseWriter) {
		response.Reply("Say what?")
	})

	err := bot.Listen()
	if err != nil {
		log.Fatal(err)
	}
}

Example 3

Defining a command with a parameter

package main

import (
	"github.com/shomali11/slacker"
	"log"
)

func main() {
	bot := slacker.NewClient("<YOUR SLACK BOT TOKEN>")

	bot.Command("echo <word>", "Echo a word!", func(request *slacker.Request, response slacker.ResponseWriter) {
		word := request.Param("word")
		response.Reply(word)
	})

	err := bot.Listen()
	if err != nil {
		log.Fatal(err)
	}
}

Example 4

Defining a command with two parameters. Parsing one as a string and the other as an integer. (The second parameter is the default value in case no parameter was passed or could not parse the value)

package main

import (
	"github.com/shomali11/slacker"
	"log"
)

func main() {
	bot := slacker.NewClient("<YOUR SLACK BOT TOKEN>")

	bot.Command("repeat <word> <number>", "Repeat a word a number of times!", func(request *slacker.Request, response slacker.ResponseWriter) {
		word := request.StringParam("word", "Hello!")
		number := request.IntegerParam("number", 1)
		for i := 0; i < number; i++ {
			response.Reply(word)
		}
	})

	err := bot.Listen()
	if err != nil {
		log.Fatal(err)
	}
}

Example 5

Send an error message to the Slack channel

package main

import (
	"errors"
	"github.com/shomali11/slacker"
	"log"
)

func main() {
	bot := slacker.NewClient("<YOUR SLACK BOT TOKEN>")

	bot.Command("test", "Tests something", func(request *slacker.Request, response slacker.ResponseWriter) {
		response.ReportError(errors.New("Oops!"))
	})

	err := bot.Listen()
	if err != nil {
		log.Fatal(err)
	}
}

Example 6

Send a "Typing" indicator

package main

import (
	"github.com/shomali11/slacker"
	"log"
	"time"
)

func main() {
	bot := slacker.NewClient("<YOUR SLACK BOT TOKEN>")

	bot.Command("time", "Server time!", func(request *slacker.Request, response slacker.ResponseWriter) {
		response.Typing()

		time.Sleep(time.Second)
		
		response.Reply(time.Now().Format(time.RFC1123))
	})

	err := bot.Listen()
	if err != nil {
		log.Fatal(err)
	}
}

Example 7

Showcasing the ability to access the github.com/nlopes/slack API. In this example, we upload a file using the Slack API.

package main

import (
	"github.com/nlopes/slack"
	"github.com/shomali11/slacker"
	"log"
)

func main() {
	bot := slacker.NewClient("<YOUR SLACK BOT TOKEN>")

	bot.Command("upload <word>", "Upload a word!", func(request *slacker.Request, response slacker.ResponseWriter) {
		word := request.Param("word")
		channel := request.Event.Channel
		bot.Client.UploadFile(slack.FileUploadParameters{Content: word, Channels: []string{channel}})
	})

	err := bot.Listen()
	if err != nil {
		log.Fatal(err)
	}
}

Example 8

Showcasing the ability to leverage context.Context to add a timeout

package main

import (
	"context"
	"errors"
	"github.com/shomali11/slacker"
	"log"
	"time"
)

func main() {
	bot := slacker.NewClient("<YOUR SLACK BOT TOKEN>")

	bot.Command("process", "Process!", func(request *slacker.Request, response slacker.ResponseWriter) {
		timedContext, cancel := context.WithTimeout(request.Context, time.Second)
		defer cancel()

		select {
		case <-timedContext.Done():
			response.ReportError(errors.New("Timed out"))
		case <-time.After(time.Minute):
			response.Reply("Processing done!")
		}
	})

	err := bot.Listen()
	if err != nil {
		log.Fatal(err)
	}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BotCommand

type BotCommand struct {
	// contains filtered or unexported fields
}

BotCommand structure contains the bot's command, description and handler

func NewBotCommand

func NewBotCommand(usage string, description string, handler func(request *Request, response ResponseWriter)) *BotCommand

NewBotCommand creates a new bot command object

func (*BotCommand) Execute

func (c *BotCommand) Execute(request *Request, response ResponseWriter)

Execute executes the handler logic

func (*BotCommand) Match

func (c *BotCommand) Match(text string) (*proper.Properties, bool)

Match determines whether the bot should respond based on the text received

func (*BotCommand) Tokenize

func (c *BotCommand) Tokenize() []*commander.Token

Tokenize returns the command format's tokens

type Request

type Request struct {
	Context context.Context
	Event   *slack.MessageEvent
	// contains filtered or unexported fields
}

Request contains the Event received and parameters

func NewRequest

func NewRequest(ctx context.Context, event *slack.MessageEvent, properties *proper.Properties) *Request

NewRequest creates a new Request structure

func (*Request) BooleanParam

func (r *Request) BooleanParam(key string, defaultValue bool) bool

BooleanParam attempts to look up a boolean value by key. If not found, return the default boolean value

func (*Request) FloatParam

func (r *Request) FloatParam(key string, defaultValue float64) float64

FloatParam attempts to look up a float value by key. If not found, return the default float value

func (*Request) IntegerParam

func (r *Request) IntegerParam(key string, defaultValue int) int

IntegerParam attempts to look up a integer value by key. If not found, return the default integer value

func (*Request) Param

func (r *Request) Param(key string) string

Param attempts to look up a string value by key. If not found, return the an empty string

func (*Request) StringParam

func (r *Request) StringParam(key string, defaultValue string) string

StringParam attempts to look up a string value by key. If not found, return the default string value

type Response

type Response struct {
	// contains filtered or unexported fields
}

Response contains the channel and Real Time Messaging library

func NewResponse

func NewResponse(channel string, rtm *slack.RTM) *Response

NewResponse creates a new response structure

func (*Response) Reply

func (r *Response) Reply(text string)

Reply send a message back to the channel where we received the event from

func (*Response) ReportError

func (r *Response) ReportError(err error)

ReportError sends back a formatted error message to the channel where we received the event from

func (*Response) Typing

func (r *Response) Typing()

Typing send a typing indicator

type ResponseWriter

type ResponseWriter interface {
	Reply(text string)
	ReportError(err error)
	Typing()
}

A ResponseWriter interface is used to respond to an event

type Slacker

type Slacker struct {
	Client *slack.Client
	// contains filtered or unexported fields
}

Slacker contains the Slack API, botCommands, and handlers

func NewClient

func NewClient(token string) *Slacker

NewClient creates a new client using the Slack API

func (*Slacker) Command

func (s *Slacker) Command(usage string, description string, handler func(request *Request, response ResponseWriter))

Command define a new command and append it to the list of existing commands

func (*Slacker) Default

func (s *Slacker) Default(defaultHandler func(request *Request, response ResponseWriter))

Default handle when none of the commands are matched

func (*Slacker) Err

func (s *Slacker) Err(errorHandler func(err string))

Err handle when errors are encountered

func (*Slacker) Init

func (s *Slacker) Init(initHandler func())

Init handle the event when the bot is first connected

func (*Slacker) Listen

func (s *Slacker) Listen() error

Listen receives events from Slack and each is handled as needed

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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