hugot

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Apr 29, 2020 License: GPL-3.0 Imports: 13 Imported by: 9

README

Hugot GoDoc

WARNING: This code requires go1.7 context support in http.Request. NOTE: The API is in flux at present.

Hugot is a package for building chat bots. It is inspired by Go's http stdlib package.

Please see the GoDoc for examples and usage.

Documentation

Overview

Package hugot provides a simple interface for building extensible chat bots in an idiomatic go style. It is heavily influenced by net/http, and uses an internal message format that is compatible with Slack messages.

Note: This package requires go1.7

Adapters

Adapters are used to integrate with external chat systems. Currently the following adapters exist:

slack - github.com/tcolgate/hugot/adapters/slack - for https://slack.com/
mattermost - github.com/tcolgate/hugot/adapters/mattermost - for https://www.mattermost.org/
irc - github.com/tcolgate/hugot/adapters/irc - simple irc adapter
shell - github.com/tcolgate/hugot/adapters/shell - simple readline based adapter
ssh - github.com/tcolgate/hugot/adapters/ssh - Toy implementation of unauth'd ssh interface

Examples of using these adapters can be found in github.com/tcolgate/hugot/cmd

Handlers

Handlers process messages. There are a several built in handler types:

- Plain Handlers will execute for every message sent to them.

- Background handlers, are started when a bot is started. They do not receive messages but can send them. They are intended to implement long lived background tasks that react to external inputs.

- WebHook handlers can be used to implement web hooks by adding the bot to a http.ServeMux. A URL is built from the name of the handler.

In addition to these basic handlers some more complex handlers are supplied.

- Hears Handlers will execute for any message which matches a given regular expression.

- Command Handlers act as command line tools. Message are attempted to be processed as a command line. Quoted text is handle as a single argument. The passed message can be used as a flag.FlagSet.

- A Mux. The Mux will multiplex message across a set of handlers. In addition, a top level "help" Command handler is added to provide help on usage of the various handlers added to the Mux.

WARNING: The API is still subject to change.

Example
package main

import (
	"flag"
	"os"

	"context"

	"github.com/golang/glog"

	"github.com/tcolgate/hugot/adapters/slack"
	"github.com/tcolgate/hugot/bot"

	"github.com/tcolgate/hugot/handlers/command/ping"
	"github.com/tcolgate/hugot/handlers/hears/tableflip"
	"github.com/tcolgate/hugot/handlers/testweb"
)

func main() {
	slackToken := flag.String("token", os.Getenv("SLACK_TOKEN"), "Slack API Token")
	nick := flag.String("nick", "minion", "Bot nick")
	flag.Parse()

	// The context can be used to shutdown the bot and any
	// Background handlers gracefully.
	ctx := context.Background()
	a, err := slack.New(*slackToken, *nick)
	if err != nil {
		glog.Fatal(err)
	}

	testweb.Register()
	tableflip.Register()
	ping.Register()

	// This will start the default bot and process
	// all messages seen by the slack adapter
	bot.ListenAndServe(ctx, nil, a)
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AttachmentFieldFromTemplates added in v0.2.0

func AttachmentFieldFromTemplates(tmpls *template.Template, data interface{}) (slack.AttachmentField, error)

AttachmentFieldFromTemplates builds an attachment field from a set of templates templates can include "field_title","field_value", and "field_short". "field_short" should expand to "true" or "false".

func IsTextOnly

func IsTextOnly(s Sender) bool

IsTextOnly returns true if the sender only support text.

func NewAdapterContext

func NewAdapterContext(ctx context.Context, a Adapter) context.Context

NewAdapterContext creates a context for passing an adapter. This is mainly used by web handlers.

Types

type Adapter

type Adapter interface {
	Sender
	Receiver
}

Adapter can be used to communicate with an external chat system such as slack or IRC.

func AdapterFromContext

func AdapterFromContext(ctx context.Context) (Adapter, bool)

AdapterFromContext returns the Adapter stored in a context.

type Attachment

type Attachment slack.Attachment

Attachment represents a rich message attachment and is directly modeled on the Slack attachments API

func AttachmentFromTemplates added in v0.2.0

func AttachmentFromTemplates(tmpls *template.Template, data interface{}, fields ...slack.AttachmentField) (Attachment, error)

AttachmentFromTemplates builds an attachment from aset of templates. Template can include the following individual template items: title, title_link, color, author_name, author_link, author_icon, image_url, thumb_url, pretext, text, fallback, fields_json. fields_json will be parsed as json, and any fields found will be appended to those in the fields arguments

type BackgroundFunc

type BackgroundFunc func(ctx context.Context, w ResponseWriter)

BackgroundFunc describes the calling convention for Background handlers

type BackgroundHandler

type BackgroundHandler interface {
	Describer
	StartBackground(ctx context.Context, w ResponseWriter)
}

BackgroundHandler gets run when the bot starts listening. They are intended for publishing messages that are not in response to any specific incoming message.

func NewBackgroundHandler

func NewBackgroundHandler(name, desc string, f BackgroundFunc) BackgroundHandler

NewBackgroundHandler wraps f up as a BackgroundHandler with the name and description provided.

type ChannelManager added in v0.2.0

type ChannelManager interface {
	Adapter
	Join(channel string) error
	Invite(channel string, user string) error
	CreateChannel(channel string) error
	LeaveChannel(channel string) error
	SetChannelTopic(channel, topic string)
}

ChannelManager is implemented by adapters that allow us to manage channels

type Describer

type Describer interface {
	Describe() (string, string)
}

Describer returns the name and description of a handler. This is used to identify the handler within Command and HTTP Muxs, and to provide a descriptive name for the handler in help text.

type Handler

type Handler interface {
	Describer
	ProcessMessage(ctx context.Context, w ResponseWriter, m *Message) error
}

Handler is a handler with no actual functionality

type HandlerFunc added in v0.2.0

type HandlerFunc func(ctx context.Context, w ResponseWriter, m *Message) error

HandlerFunc describes a function that can be used as a hugot handler.

type Message

type Message struct {
	To      string
	From    string
	Channel string

	UserID string // Verified user identitify within the source adapter

	Text        string // A plain text message
	Attachments []Attachment

	Private bool
	ToBot   bool

	Store storage.Storer
}

Message describes a Message from or to a user. It is intended to provided a resonable lowest common denominator for modern chat systems. It takes the Slack message format to provide that minimum but makes no assumption about support for any markup. If used within a command handler, the message can also be used as a flag.FlagSet for adding and processing the message as a CLI command.

func (*Message) Copy added in v0.2.0

func (m *Message) Copy() *Message

Copy is used to provide a deep copy of a message

func (*Message) Reply

func (m *Message) Reply(txt string) *Message

Reply returns a messsage with Text tx and the From and To fields switched

func (*Message) Replyf

func (m *Message) Replyf(s string, is ...interface{}) *Message

Replyf returns message with txt set to the fmt.Printf style formatting, and the from/to fields switched.

type Receiver

type Receiver interface {
	Receive() <-chan *Message // Receive returns a channel that can be used to read one message, nil indicated there will be no more messages
}

Receiver cam ne used to receive messages

type ResponseWriter

type ResponseWriter interface {
	Sender
	io.Writer

	SetChannel(c string) // Forces messages to a certain channel
	SetTo(to string)     // Forces messages to a certain user
	SetSender(a Sender)  // Forces messages to a different sender or adapter

	Copy() ResponseWriter // Returns a copy of this response writer
}

ResponseWriter is used to Send messages back to a user.

func NewNullResponseWriter

func NewNullResponseWriter(m Message) ResponseWriter

NewNullResponseWriter creates a ResponseWriter that discards all message sent to it.

func NewResponseWriter added in v0.2.0

func NewResponseWriter(s Sender, m Message, adapterName string) ResponseWriter

NewResponseWriter creates a response writer that will send mesages via the provided sender.

func ResponseWriterFromContext

func ResponseWriterFromContext(ctx context.Context) (ResponseWriter, bool)

ResponseWriterFromContext constructs a ResponseWriter from the adapter stored in the context. A destination Channel/User must be set to send messages..

type Sender

type Sender interface {
	Send(ctx context.Context, m *Message)
}

Sender can be used to send messages

func SenderFromContext

func SenderFromContext(ctx context.Context) (Sender, bool)

SenderFromContext can be used to retrieve a valid sender from a context. This is mostly useful in WebHook handlers for sneding messages back to the inbound Adapter.

type TextOnly

type TextOnly interface {
	Sender
	IsTextOnly()
}

TextOnly is an interface to hint to handlers that the adapter they are talking to is a text only handler, to help adjust output.

type WebHookHandler

type WebHookHandler interface {
	Describer
	URL() *url.URL      // Is called to retrieve the location of the Handler
	SetURL(*url.URL)    // Is called after the WebHook is added, to inform it where it lives
	SetAdapter(Adapter) // Is called to set the default adapter for this handler to use
	http.Handler
}

WebHookHandler handlers are used to expose a registered handler via a web server. The SetURL method is called to inform the handler what it's external URL will be. This will normally be done by the Mux. Other handlers can use URL to generate links suitable for external use. You can use the http.Handler Request.Context() to get a ResponseWriter to write into the bots adapters. You need to SetChannel the resulting ResponseWriter to send messages.

func NewWebHookHandler

func NewWebHookHandler(name, desc string, hf http.HandlerFunc) WebHookHandler

NewWebHookHandler creates a new WebHookHandler provided name and description.

type WebHookHandlerFunc

type WebHookHandlerFunc func(ctx context.Context, hw ResponseWriter, w http.ResponseWriter, r *http.Request)

WebHookHandlerFunc describes the calling convention for a WebHook.

Directories

Path Synopsis
Package adapters contains a set of implementations of adapters that can be used to integrate hugot with existing chat networks.
Package adapters contains a set of implementations of adapters that can be used to integrate hugot with existing chat networks.
irc
Package irc implements a simple adapter for IRC using github.com/fluffle/goirc/client
Package irc implements a simple adapter for IRC using github.com/fluffle/goirc/client
mattermost
Package mattermost implements an adapter for http://mm.com
Package mattermost implements an adapter for http://mm.com
shell
Package shell implements a simple adapter that provides a readline style shell adapter for debugging purposes
Package shell implements a simple adapter that provides a readline style shell adapter for debugging purposes
slack
Package slack implements an adapter for http://slack.com using github.com/slack-go/slack
Package slack implements an adapter for http://slack.com using github.com/slack-go/slack
ssh
Package ssh implements an adapter that serves SSH connections.
Package ssh implements an adapter that serves SSH connections.
cmd
Package handlers provides a set of useful handlers for manipulating messages.
Package handlers provides a set of useful handlers for manipulating messages.
alias
Package alias imeplements user customizable aliases for commands.
Package alias imeplements user customizable aliases for commands.
command
Package command provides CLI style interactive commands.
Package command provides CLI style interactive commands.
command/ping
Package ping provides a handler that replies to any message sent
Package ping provides a handler that replies to any message sent
command/testcli
Package testcli provides an example Command handler with nested command handling.
Package testcli provides an example Command handler with nested command handling.
command/uptime
Package uptime provides a handler that replies to any message sent
Package uptime provides a handler that replies to any message sent
hears/tableflip
Package tableflip provides an exacmple Hears handler that will flip tables on behalf of embittered users.
Package tableflip provides an exacmple Hears handler that will flip tables on behalf of embittered users.
mux
roles
Package roles is intended to provide Roles Based access controls for users and channels.
Package roles is intended to provide Roles Based access controls for users and channels.
testweb
Package testweb provides an example webhook handler
Package testweb provides an example webhook handler
Package scope describes hugot's mesage scoping.
Package scope describes hugot's mesage scoping.
Package storage describes an interface for storing of hugot handler data in a Key/Value store.
Package storage describes an interface for storing of hugot handler data in a Key/Value store.
etcd
Package etcd implemets a hugot store over an etcd datastore
Package etcd implemets a hugot store over an etcd datastore
memory
Package memory implements a hugot store in memory.
Package memory implements a hugot store in memory.
prefix
Package prefix implements a hugot Storer that wraps another store and ddds an additional prefix to all keys.
Package prefix implements a hugot Storer that wraps another store and ddds an additional prefix to all keys.
properties
Package properties implements a layer on top of the scoped store.
Package properties implements a layer on top of the scoped store.
redis
Package redis implements a hugot Store that is backed by a redis database using gopkg.in/redis.v5
Package redis implements a hugot Store that is backed by a redis database using gopkg.in/redis.v5
scoped
Package scoped implements scoping for a hugot Store.
Package scoped implements scoping for a hugot Store.

Jump to

Keyboard shortcuts

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