hal

package
v0.0.0-...-2b3799d Latest Latest
Warning

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

Go to latest
Published: Jun 19, 2017 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const CounterTable = `` /* 191-byte string literal not displayed */
View Source
const DirEdgeTable = `` /* 490-byte string literal not displayed */
View Source
const DirNodeAttrTable = `` /* 374-byte string literal not displayed */
View Source
const DirNodeTable = `` /* 212-byte string literal not displayed */
View Source
const KEY_SIZE = 32

256-bit AES key and 96-bit nonce size in bytes

View Source
const KVTable = `` /* 267-byte string literal not displayed */
View Source
const NONCE_SIZE = 12
View Source
const PLUGIN_INST_TABLE = `` /* 243-byte string literal not displayed */
View Source
const PrefsTable = `` /* 607-byte string literal not displayed */

PrefsTable contains the SQL to create the prefs table key field is called pkey because key is a reserved word

View Source
const SECRETS_KEY_DSN = "hal.dsn"
View Source
const SECRETS_TABLE = `` /* 298-byte string literal not displayed */

SECRETS_TABLE holds encrypted key/value pairs along with their nonces. uses VARBINARY instead of BINARY to avoid null termination issues.

Variables

View Source
var TimeFormats = [...]string{
	"2006-01-02",
	"2006-01-02-07:00",
	"2006-01-02T15:04",
	"2006-01-02T15:04-07:00",
	"2006-01-02T15:04:05",
	"2006-01-02T15:04:05-07:00",
}

supported time formats for ParamInst.Time()

Functions

func AsciiTable

func AsciiTable(hdr []string, rows [][]string) string

Table takes a 2-dimensional array of strings and returns a single string formatted in a table appropriate for rendering in a fixed-width font. Should be suitable for Markdown table rendering. cheesy 2-pass technique, assuming straight fixed-width ASCII for now

func Cache

func Cache() *ttlCache

func DecrementCounter

func DecrementCounter(key string) error

func Directory

func Directory() *directory

func ExistsKV

func ExistsKV(key string) bool

ExistsKV checks to see if a key exists in the kv. False if any errors are encountered.

func ForceSqlDBHandle

func ForceSqlDBHandle(db *sql.DB)

ForceSqlDBHandle can be used to forcibly replace the DB handle with another one, e.g. go-sqlmock. This is mainly here for tests, but it's also useful for things like examples/repl to operate with no database.

func GetCounter

func GetCounter(key string) (value int, err error)

func GetKV

func GetKV(key string) (string, bool)

GetKV retreives a value from the database. Returns value,ok style. Returns "", false if the query fails and "", true if there was no value available.

func IncrementCounter

func IncrementCounter(key string) error

func IsDebug

func IsDebug() bool

IsDebug returns true of debug messages are enabled.

func PluginRegistry

func PluginRegistry() *pluginRegistry

func RmPrefId

func RmPrefId(id int) error

RmPrefId removes a preference from the database by its numeric id.

func SetCounter

func SetCounter(key string, value int) error

func SetKV

func SetKV(key, value string, ttl time.Duration) (err error)

SetKV inserts a new value in the database with the provided TTL. If the TTL is 0, it defaults to 10 years.

func SetPref

func SetPref(user, broker, room, plugin, key, value string) error

SetPref sets a preference and is shorthand for Pref{}.Set().

func SqlDB

func SqlDB() *sql.DB

DB returns the database singleton.

func SqlInit

func SqlInit(sqlTxt string) error

SqlInit executes the provided SQL once per runtime. Execution is not tracked across restarts so statements still need to use CREATE TABLE IF NOT EXISTS or other methods of achieving idempotent execution. Errors are returned unmodified, including primary key violations, so you may ignore them as needed.

func Utf8Table

func Utf8Table(hdr []string, rows [][]string) string

Utf8Table is like AsciiTable but it uses UTF8 characters for the table borders. It should look nice when rendered to an image by Hal's text->img.

Types

type BoolParam

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

keyed parameters that are boolean (flags), e.g. "--foo", "-f", "foo=true"

func (*BoolParam) Cmd

func (p *BoolParam) Cmd() *Cmd

Cmd returns the command the parameter belongs to. Panics if no command is attached.

func (*BoolParam) IsRequired

func (p *BoolParam) IsRequired() bool

func (*BoolParam) Key

func (p *BoolParam) Key() string

func (*BoolParam) Name

func (p *BoolParam) Name() string

Name returns the key string. Mostly for use in printing errors, etc. Implements NamedParam.

func (*BoolParam) SetDefault

func (p *BoolParam) SetDefault(def bool) *BoolParam

func (*BoolParam) SetUsage

func (p *BoolParam) SetUsage(usage string) *BoolParam

SetUsage sets the usage string for the paremeter. Returns the parameter.

func (*BoolParam) SubCmd

func (p *BoolParam) SubCmd() *SubCmd

func (*BoolParam) Usage

func (p *BoolParam) Usage() string

type BoolParamInst

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

BoolParamInst represents a flag/boolean parameter found in the command

func (*BoolParamInst) Cmd

func (p *BoolParamInst) Cmd() *Cmd

Cmd returns the command the parameter belongs to. Panics if no command is attached.

func (*BoolParamInst) Found

func (p *BoolParamInst) Found() bool

func (*BoolParamInst) Key

func (p *BoolParamInst) Key() string

func (*BoolParamInst) Name

func (p *BoolParamInst) Name() string

Name returns the key string. Mostly for use in printing errors, etc. Implements NamedParam.

func (*BoolParamInst) Param

func (p *BoolParamInst) Param() *BoolParam

func (*BoolParamInst) Required

func (p *BoolParamInst) Required() bool

func (*BoolParamInst) String

func (p *BoolParamInst) String() (string, error)

String returns the value as a string.

func (*BoolParamInst) SubCmdInst

func (p *BoolParamInst) SubCmdInst() *SubCmdInst

func (*BoolParamInst) Value

func (p *BoolParamInst) Value() bool

type Broker

type Broker interface {
	// the text name of the broker, arbitrary, but usually "slack" or "cli"
	Name() string
	Send(evt Evt)
	SendTable(evt Evt, header []string, rows [][]string)
	SendDM(evt Evt)
	SetTopic(roomId, topic string) error
	GetTopic(roomId string) (topic string, err error)
	Leave(roomId string) (err error)
	LooksLikeRoomId(room string) bool
	LooksLikeUserId(user string) bool
	RoomIdToName(id string) (name string)
	RoomNameToId(name string) (id string)
	UserIdToName(id string) (name string)
	UserNameToId(name string) (id string)
	Stream(out chan *Evt)
}

Broker is an instance of a broker that can send/receive events.

type Cmd

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

Cmd models a tree of commands and subcommands along with their parameters. The tree will almost always be 1 or 2 levels deep. Deeper is possible but unlikely to be much higher, KISS. TODO: switc to maps for (kv|bool|idx)params and maybe subCmds

func NewCmd

func NewCmd(token string, mustsubcmd bool) *Cmd

NewCmd returns an initialized Cmd.

func (*Cmd) AddAlias

func (c *Cmd) AddAlias(alias string) *Cmd

AddAlias adds an alias to the command and returns the paramter.

func (*Cmd) AddBoolParam

func (c *Cmd) AddBoolParam(key string, required bool) *BoolParam

AddBoolParam adds a boolean/flag parameter to the command and returns the new parameter.

func (*Cmd) AddIdxParam

func (c *Cmd) AddIdxParam(position int, name string, required bool) *IdxParam

AddIdxParam adds a positional parameter to the command and returns the new parameter.

func (*Cmd) AddKVParam

func (c *Cmd) AddKVParam(key string, required bool) *KVParam

AddKVParam creates and adds a key/value parameter to the command handle and returns the new parameter.

func (*Cmd) AddSubCmd

func (c *Cmd) AddSubCmd(token string) *SubCmd

AddCmd adds a subcommand to the handle and returns the new (sub-)command.

func (*Cmd) Aliases

func (c *Cmd) Aliases() []string

Aliases makes sure the Aliases list is initialized and returns the list.

func (*Cmd) Cmd

func (c *Cmd) Cmd() *Cmd

Cmd returns the command it was called on. It does nothing and exists to make it possible to format chained calls nicely.

func (*Cmd) GetBoolParam

func (c *Cmd) GetBoolParam(key string) *BoolParam

func (*Cmd) GetIdxParam

func (c *Cmd) GetIdxParam(idx int) *IdxParam

GetIdxParam gets a positional parameter by its index.

func (*Cmd) GetKVParam

func (c *Cmd) GetKVParam(key string) *KVParam

func (*Cmd) GetSubCmd

func (c *Cmd) GetSubCmd(token string) *SubCmd

GetSubCmd gets a subcommand by its token. Returns nil for no match.

func (*Cmd) HasBoolParam

func (c *Cmd) HasBoolParam(key string) bool

func (*Cmd) HasIdxParam

func (c *Cmd) HasIdxParam(idx int) bool

func (*Cmd) HasKVParam

func (c *Cmd) HasKVParam(key string) bool

func (*Cmd) HasKeyParam

func (c *Cmd) HasKeyParam(key string) bool

HasKeyParam returns true if there are any parameters defined with the provided key of either key type (bool or kv).

func (*Cmd) HasSubCmdToken

func (c *Cmd) HasSubCmdToken(token string) bool

HasSubCmdToken returns whether or not the proivded token is defined as a subcommand.

func (*Cmd) ListNamedParams

func (c *Cmd) ListNamedParams() []NamedParam

ListNamedParams returns a list of all parameters via the interface NamedParam. Mainly for use in printing options, etc..

func (*Cmd) ListSubCmds

func (c *Cmd) ListSubCmds() []*SubCmd

ListSubCmds makes sure the SubCmds list is initialized and returns the list.

func (*Cmd) MustSubCmd

func (c *Cmd) MustSubCmd() bool

MustSubCmd returns bool indicating if a subcommand is required.

func (*Cmd) Parent

func (c *Cmd) Parent() *Cmd

func (*Cmd) Process

func (c *Cmd) Process(argv []string) (*CmdInst, error)

parse a list of argv-style strings (0 is always the command name e.g. []string{"prefs"}) foo bar --baz foo --bar baz --version foo bar=baz foo x=y z=q init --foo baz TODO: automatic emdash cleanup TODO: enforce MustSubCmd TODO: return errors instead of nil/panic

func (*Cmd) SetUsage

func (c *Cmd) SetUsage(usage string) *Cmd

SetUsage sets the usage string for the command. Returns the command.

func (*Cmd) SubCmds

func (c *Cmd) SubCmds() []*SubCmd

TODO: remove this?

func (*Cmd) Token

func (c *Cmd) Token() string

func (*Cmd) Usage

func (c *Cmd) Usage() string

Usage returns the auto-generated usage string.

type CmdInst

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

func (*CmdInst) GetBoolParam

func (c *CmdInst) GetBoolParam(key string) *BoolParam

func (*CmdInst) GetBoolParamInst

func (c *CmdInst) GetBoolParamInst(key string) *BoolParamInst

GetBoolParamInst gets a key/value parameter instance by its key.

func (*CmdInst) GetIdxParam

func (c *CmdInst) GetIdxParam(idx int) *IdxParam

func (*CmdInst) GetIdxParamInst

func (c *CmdInst) GetIdxParamInst(idx int) *IdxParamInst

GetIdxParamInst gets a positional parameter instance by its index.

func (*CmdInst) GetIdxParamInstByName

func (c *CmdInst) GetIdxParamInstByName(name string) *IdxParamInst

GetIdxParamInsByNamet gets an indexed parameter instance by its name.

func (*CmdInst) GetKVParam

func (c *CmdInst) GetKVParam(key string) *KVParam

func (*CmdInst) GetKVParamInst

func (c *CmdInst) GetKVParamInst(key string) *KVParamInst

GetKVParamInst gets a key/value parameter instance by its key.

func (*CmdInst) HasBoolParam

func (c *CmdInst) HasBoolParam(key string) bool

func (*CmdInst) HasBoolParamInst

func (c *CmdInst) HasBoolParamInst(key string) bool

func (*CmdInst) HasIdxParam

func (c *CmdInst) HasIdxParam(idx int) bool

func (*CmdInst) HasIdxParamInst

func (c *CmdInst) HasIdxParamInst(idx int) bool

func (*CmdInst) HasKVParam

func (c *CmdInst) HasKVParam(key string) bool

func (*CmdInst) HasKVParamInst

func (c *CmdInst) HasKVParamInst(key string) bool

func (*CmdInst) ListBoolParamInsts

func (c *CmdInst) ListBoolParamInsts() []*BoolParamInst

ListBoolParamInsts initializes the boolparaminsts list on the fly and returns it.

func (*CmdInst) ListIdxParamInsts

func (c *CmdInst) ListIdxParamInsts() []*IdxParamInst

func (*CmdInst) ListKVParamInsts

func (c *CmdInst) ListKVParamInsts() []*KVParamInst

ListKVParamInsts initializes the kvparaminsts list on the fly and returns it.

func (*CmdInst) Remainder

func (c *CmdInst) Remainder() []string

Remainder initializes the remainder list on the fly and returns it.

func (*CmdInst) SubCmdInst

func (c *CmdInst) SubCmdInst() *SubCmdInst

func (*CmdInst) SubCmdToken

func (c *CmdInst) SubCmdToken() string

SubCmdToken returns the subcommand's token string. Returns empty string if there is no subcommand.

func (*CmdInst) Usage

func (c *CmdInst) Usage() string

Usage returns the auto-generated usage string for the Command Instance.

type DirEdge

type DirEdge struct {
	KeyA  string `json:"key_a"`
	KindA string `json:"kind_a"`
	KeyB  string `json:"key_b"`
	KindB string `json:"kind_b"`
	Ts    int    `json:"ts"`
}

type DirNode

type DirNode struct {
	Key  string `json:"key"`
	Kind string `json:"kind"`
	Ts   int    `json:"ts"`
}

type DirNodeAttr

type DirNodeAttr struct {
	Key   string `json:"key"`
	Kind  string `json:"kind"`
	Attr  string `json:"attr"`
	Value string `json:"value"`
	Ts    int    `json:"ts"`
}

type Evt

type Evt struct {
	ID        string       `json:"id"`      // ID for the event (assigned by upstream or broker)
	Body      string       `json:"body"`    // body of the event, regardless of source
	Command   string       `json:"command"` // optional command associated with the body, typically empty
	Subject   string       `json:"subject"` // the subject of the message, if available, typically empty
	Room      string       `json:"room"`    // the room where the event originated
	RoomId    string       `json:"room_id"` // the room id from the source broker
	User      string       `json:"user"`    // the username that created the event
	UserId    string       `json:"user_id"` // the user id from the source broker
	Time      time.Time    `json:"time"`    // timestamp of the event
	Broker    Broker       `json:"broker"`  // the broker the event came from
	IsChat    bool         `json:"is_chat"` // lets the broker differentiate chats and other events
	IsBot     bool         `json:"is_bot"`  // message was generated by the bot
	ToUser    bool         `json:"to_user"` // when true, always deliver outgoing event via DM
	ToRoom    bool         `json:"to_room"` // when true, always deliver outgoing event to the room
	ToFunc    bool         `json:"to_func"` // when true, call the ReplyFunc instead of the usual reply path
	ReplyFunc func(string) // a function to be called with a reply rather than the usual process
	Original  interface{}  // the original message container (e.g. slack.MessageEvent)
	// contains filtered or unexported fields
}

Evt is a generic container for events processed by the bot. Event sources are responsible for copying the appropriate data into the Evt fields. Routing and most plugins will not work if the body isn't copied, at a minimum. When ToUser and ToRoom are both true, the event will be delivered twice. The original event should usually be attached to the Original

func (*Evt) AsPref

func (e *Evt) AsPref() Pref

AsPref returns a a pref with user, room, broker, and plugin set using data from the event handle.

func (*Evt) BodyAsArgv

func (e *Evt) BodyAsArgv() []string

BodyAsArgv does minimal parsing of the event body, returning an argv-like array of strings with quoted strings intact (but with quotes removed). The goal is shell-like, and is not a full implementation. Leading/trailing whitespace is removed. Escaping quotes, etc. is not supported.

func (*Evt) BrokerName

func (e *Evt) BrokerName() string

BrokerName returns the text name of current broker.

func (*Evt) Clone

func (e *Evt) Clone() Evt

Clone() returns a copy of the event with the same broker/room/user and a current timestamp. Body, Command, and Subject will be empty. Time is updated to the current time. Original is carried through, so nil that if you don't want it preserved.

func (*Evt) Error

func (e *Evt) Error(err error)

Error replies to the event with the provided error. Future: need to figure out if there's going to be a kind of error handling module in Hal for making errors visible in a logging room, possibly on a different broker...

func (*Evt) FindPrefs

func (e *Evt) FindPrefs() Prefs

FindPrefs fetches the union of all matching settings from the database for user, broker, room, and plugin. Plugins can use the Prefs methods to filter from there.

func (*Evt) ForceToRoom

func (e *Evt) ForceToRoom() Evt

ForceToRoom clones the event and returns a copy with ToRoom set to true. Takes priority over reply-via-dm routing. Useful for chaining, e.g. evt.ToRoom().Replyf("go away!").

func (*Evt) ForceToUser

func (e *Evt) ForceToUser() Evt

ForceToUser clones the event and returns a copy with ToUser set to true. Takes priority over reply-via-dm routing. Useful for chaining.

func (*Evt) InstanceSettings

func (e *Evt) InstanceSettings() Prefs

InstanceSettings gets all the settings matching the settings defined by the plugin's Settings field.

func (*Evt) Reply

func (e *Evt) Reply(msg string)

Reply is a helper that crafts a new event from the provided string and initiates the reply on the broker attached to the event. The message is routed according to preferences and the ToUser/ToRoom fields on the event. If no preferences are set for the user/room/plugin the response will go to the room where the command originated. The "reply-via-dm" preference can be set to "true" to default to having replies to to DM instead of the room.

func (*Evt) ReplyDM

func (e *Evt) ReplyDM(msg string)

ReplyDM makes it convenient to reply to a user via DM. The user is drawn from the event's UserId field and passed to the broker's SendDM() method.

func (*Evt) ReplyTable

func (e *Evt) ReplyTable(hdr []string, rows [][]string)

ReplyTable sends a table of data back, formatting it according to preferences. TODO: move code from brokers/slack/broker.go/SendTable here TODO: document preferences here

func (*Evt) ReplyToRoom

func (e *Evt) ReplyToRoom(msg string)

ReplyToRoom crafts a new event from the provided string and sends it to the room the event originated from.

func (*Evt) Replyf

func (e *Evt) Replyf(msg string, a ...interface{})

Replyf is the same as Reply but allows for string formatting using fmt.Sprintf()

func (*Evt) String

func (e *Evt) String() string

type FontChar

type FontChar struct {
	String string // the UTF-8 single character
	Code   uint
	Width  uint
	Value  [16]uint8
}

FontChar is a single character of the font. The Code field might go away. It was extracted from the original font and was flaky so I switched to using the UTF8-string to index and locate glyphs.

type FontData

type FontData struct {
	Facename  string
	Height    int
	Width     int
	Ascent    int
	Pointsize int
	Weight    int
	Charset   int

	Chars [256]FontChar
	// contains filtered or unexported fields
}

FontData is a font and its metadata.

func FixedFont

func FixedFont() *FontData

FixedFont returns a handle for the embedded 8x16 VGA font.

func (*FontData) ParseColor

func (fd *FontData) ParseColor(in string, def color.Color) color.Color

ParseColor parses a 6-byte or 8-byte hex color string (HTML-style) and returns a color.RGBA. If anything goes wrong during parsing, it returns the default provided.

func (*FontData) StringToChars

func (fd *FontData) StringToChars(want string) []*FontChar

StringToChars takes a string and returns the FontChar

func (*FontData) StringToImage

func (fd *FontData) StringToImage(want string, clr color.Color) image.Image

StringToImage takes a string and renders it to an image.Image. Newlines are not respected. See: StringsToImage().

func (*FontData) StringToImages

func (fd *FontData) StringToImages(want string, clr color.Color) []image.Image

StringToImages takes a string and returns a list of images

func (*FontData) StringsToImage

func (fd *FontData) StringsToImage(want []string, clr color.Color) image.Image

StringsToImage renders an array of strings to an image, with each row in the provided list as a line. The image size is dependent on the text passed in.

type IdxParam

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

positional parameters (0 indexed)

func (*IdxParam) Cmd

func (p *IdxParam) Cmd() *Cmd

Cmd returns the command the parameter belongs to. Panics if no command is attached.

func (*IdxParam) Idx

func (p *IdxParam) Idx() int

func (*IdxParam) IsRequired

func (p *IdxParam) IsRequired() bool

func (*IdxParam) Name

func (p *IdxParam) Name() string

Name returns the name given to the indexed param. Implements NamedParam.

func (*IdxParam) SetDefault

func (p *IdxParam) SetDefault(def string) *IdxParam

func (*IdxParam) SetUsage

func (p *IdxParam) SetUsage(usage string) *IdxParam

SetUsage sets the usage string for the paremeter. Returns the parameter.

func (*IdxParam) SubCmd

func (p *IdxParam) SubCmd() *SubCmd

func (*IdxParam) Usage

func (p *IdxParam) Usage() string

type IdxParamInst

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

IdxParamInst represents a positional parameter found in the command

func (*IdxParamInst) Bool

func (p *IdxParamInst) Bool() (bool, error)

func (*IdxParamInst) Cmd

func (p *IdxParamInst) Cmd() *Cmd

Cmd returns the command the parameter belongs to. Panics if no command is attached.

func (*IdxParamInst) DefInt

func (p *IdxParamInst) DefInt(def int) int

func (*IdxParamInst) DefString

func (p *IdxParamInst) DefString(def string) string

func (*IdxParamInst) Duration

func (p *IdxParamInst) Duration() (time.Duration, error)

func (*IdxParamInst) Float

func (p *IdxParamInst) Float() (float64, error)

func (*IdxParamInst) Found

func (p *IdxParamInst) Found() bool

func (*IdxParamInst) Idx

func (p *IdxParamInst) Idx() int

func (*IdxParamInst) Int

func (p *IdxParamInst) Int() (int, error)

func (*IdxParamInst) MustString

func (p *IdxParamInst) MustString() string

func (*IdxParamInst) Name

func (p *IdxParamInst) Name() string

Name returns the name given to the indexed param. Implements NamedParam.

func (*IdxParamInst) Param

func (p *IdxParamInst) Param() *IdxParam

func (*IdxParamInst) Required

func (p *IdxParamInst) Required() bool

func (*IdxParamInst) String

func (p *IdxParamInst) String() (string, error)

String returns the value as a string.

func (*IdxParamInst) SubCmdInst

func (p *IdxParamInst) SubCmdInst() *SubCmdInst

func (*IdxParamInst) Time

func (p *IdxParamInst) Time() (time.Time, error)

func (*IdxParamInst) Value

func (p *IdxParamInst) Value() string

type Instance

type Instance struct {
	*Plugin
	RoomId   string // room id
	Broker   Broker // the broker that produces events
	Regex    string // a regex for filtering messages
	Settings Prefs  // runtime settings for the instance
	// contains filtered or unexported fields
}

Instance is an instance of a plugin tied to a room.

func (*Instance) LoadSettingsFromPrefs

func (inst *Instance) LoadSettingsFromPrefs()

LoadSettingsFromPrefs loads all of the settings specified in the plugin Settings list into the instance's Settings list. Any current settings are replaced. The search is run with room and plugin set to whatever values the instance has.

func (*Instance) Register

func (inst *Instance) Register() error

Register an instance with the bot so that it starts receiving messages.

func (*Instance) SaveSettingsToPrefs

func (inst *Instance) SaveSettingsToPrefs()

SaveSettingsToPrefs saves runtime instance preferences to the prefs table in the database.

func (*Instance) String

func (inst *Instance) String() string

func (*Instance) Unregister

func (inst *Instance) Unregister() error

Unregister removes an instance from the list of plugin instances.

type KVParam

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

key/value parameters, e.g. "--foo=bar", "foo=bar", "-f bar", "--foo bar"

func (*KVParam) AddAlias

func (p *KVParam) AddAlias(alias string) *KVParam

AddAlias adds an alias to the parameter and returns the paramter.

func (*KVParam) Aliases

func (p *KVParam) Aliases() []string

Aliases initializes the aliases list on the fly and returns it.

func (*KVParam) Cmd

func (p *KVParam) Cmd() *Cmd

Cmd returns the command the parameter belongs to. Panics if no command is attached.

func (*KVParam) IsRequired

func (p *KVParam) IsRequired() bool

func (*KVParam) Key

func (p *KVParam) Key() string

func (*KVParam) Name

func (p *KVParam) Name() string

Name returns the key string. Mostly for use in printing errors, etc. Implements NamedParam.

func (*KVParam) SetDefault

func (p *KVParam) SetDefault(def string) *KVParam

func (*KVParam) SetUsage

func (p *KVParam) SetUsage(usage string) *KVParam

SetUsage sets the usage string for the paremeter. Returns the parameter.

func (*KVParam) SubCmd

func (p *KVParam) SubCmd() *SubCmd

func (*KVParam) Usage

func (p *KVParam) Usage() string

type KVParamInst

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

KVParamInst represents a key/value parameter found in the command

func (*KVParamInst) Bool

func (p *KVParamInst) Bool() (bool, error)

func (*KVParamInst) Cmd

func (p *KVParamInst) Cmd() *Cmd

Cmd returns the command the parameter belongs to. Panics if no command is attached.

func (*KVParamInst) DefInt

func (p *KVParamInst) DefInt(def int) int

func (*KVParamInst) DefString

func (p *KVParamInst) DefString(def string) string

func (*KVParamInst) Duration

func (p *KVParamInst) Duration() (time.Duration, error)

func (*KVParamInst) Float

func (p *KVParamInst) Float() (float64, error)

func (*KVParamInst) Found

func (p *KVParamInst) Found() bool

func (*KVParamInst) Int

func (p *KVParamInst) Int() (int, error)

func (*KVParamInst) Key

func (p *KVParamInst) Key() string

func (*KVParamInst) MustString

func (p *KVParamInst) MustString() string

MustString returns the value as a string. If it was required/not-set, panic ensues. Empty string may be returned for not-required+not-set.

func (*KVParamInst) Name

func (p *KVParamInst) Name() string

Name returns the key string. Mostly for use in printing errors, etc. Implements NamedParam.

func (*KVParamInst) Param

func (p *KVParamInst) Param() *KVParam

func (*KVParamInst) Required

func (p *KVParamInst) Required() bool

func (*KVParamInst) String

func (p *KVParamInst) String() (string, error)

String returns the value as a string.

func (*KVParamInst) SubCmdInst

func (p *KVParamInst) SubCmdInst() *SubCmdInst

func (*KVParamInst) Time

func (p *KVParamInst) Time() (time.Time, error)

func (*KVParamInst) Value

func (p *KVParamInst) Value() string

type LogEntry

type LogEntry struct {
	Time    time.Time
	Prefix  string
	Body    string
	IsDebug bool
}

func (*LogEntry) String

func (l *LogEntry) String() string

String returns the LogEntry as a formatted log string.

type Logger

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

Logger provides a handle for using Hal's logging facility. Any Logger created ultimately uses the same singleton.

func (*Logger) Debugf

func (l *Logger) Debugf(msg string, a ...interface{})

Debugf formats the message and propagates it. No work is performed if debugging is disabled.

func (*Logger) DisableDbgStdout

func (l *Logger) DisableDbgStdout()

DisableDbgStdout disables the automatic forwarding of debug messages to stdout.

func (*Logger) DisableDebug

func (l *Logger) DisableDebug()

DisableDebug disables debug message propagation.

func (*Logger) DisableLogStdout

func (l *Logger) DisableLogStdout()

DisableLogStdout disables the automatic forwarding of log messages to stdout.

func (*Logger) EnableDebug

func (l *Logger) EnableDebug()

EnableDebug enables debug message propagation.

func (*Logger) Fatalf

func (l *Logger) Fatalf(msg string, a ...interface{})

Fatalf formats the message, propagates the log, then exits the program.

func (*Logger) IsDebug

func (l *Logger) IsDebug() bool

IsDebug returns true of debug messages are enabled.

func (*Logger) NewDebugSink

func (l *Logger) NewDebugSink() chan LogEntry

NewLogSink creates a new channel that will receive debug messages. It is allocated and ready to go on return. Do not close it.

func (*Logger) NewLogSink

func (l *Logger) NewLogSink() chan LogEntry

NewLogSink creates a new channel that will receive log messages. It is allocated and ready to go on return. Do not close it.

func (*Logger) Panic

func (l *Logger) Panic(msg string)

Panic panics immediately. No attempt is made to forward/propagate.

func (*Logger) Panicf

func (l *Logger) Panicf(msg string, a ...interface{})

Panicf formats a message and panics. Not propagated.

func (*Logger) Printf

func (l *Logger) Printf(msg string, a ...interface{})

Printf formats the message and propagates it as a log message.

func (*Logger) Println

func (l *Logger) Println(a ...interface{})

Println merges the arguments and propagates the result as a log message.

func (*Logger) SetPrefix

func (l *Logger) SetPrefix(prefix string)

SetPrefix sets a new prefix that will be prepended to every message from the logger handle.

type NamedParam

type NamedParam interface {
	Name() string
	Usage() string
	IsRequired() bool
}

type PeriodicFunc

type PeriodicFunc struct {
	Name     string
	Interval time.Duration
	Function func()
	NoRand   bool // set to true to disable randomizing the first execution
	// contains filtered or unexported fields
}

func GetPeriodicFunc

func GetPeriodicFunc(name string) *PeriodicFunc

GetPeriodicFunc finds a periodic function by name and returns a pointer to it. If the name is not found, nil is returned.

func (*PeriodicFunc) Bump

func (pf *PeriodicFunc) Bump()

Bump schedules a periodic function to update outside of the scheduled times. The value of pf.Last() is updated when this is used.

func (*PeriodicFunc) Last

func (pf *PeriodicFunc) Last() time.Time

Last returns the wallclock time of the last run of the function.

func (*PeriodicFunc) Register

func (pf *PeriodicFunc) Register()

Register puts a pf in the global list and makes it available to GetPeriodicFunc. Anonymous pf's work fine but are not retreivable.

func (*PeriodicFunc) Start

func (pf *PeriodicFunc) Start()

Start a periodic function.

func (*PeriodicFunc) Status

func (pf *PeriodicFunc) Status() string

Status returns initialized/running/stopped state as a string.

func (*PeriodicFunc) Stop

func (pf *PeriodicFunc) Stop()

Stop a periodic function.

type Plugin

type Plugin struct {
	Name      string          // a unique name (used to launch instances)
	Func      func(Evt)       // the code to execute for each matched event
	Init      func(*Instance) // plugin hook called at instance creation time
	Command   string          // the name of the command for invocation, e.g. "atlas", "uptime"
	Regex     string          // the default regex match, to be used when Command isn't sufficient
	BotEvents bool            // set to true to receive events generated by the bot user
	Settings  Prefs           // required+autoloaded preferences + defaults
	Secrets   []string        // required+autoloaded secret key names
}

Plugin is a function with metadata to assist with message routing. Plugins are registered at startup by the main program and wired up to receive events when an instance is created e.g. by the pluginmgr plugin. The Command and Regex can be set to pre-filter messages. Regex should only be used for custom REs. Most commands should use Command to set a static string and the RE will be generated automatically and consistently.

func (*Plugin) Instance

func (p *Plugin) Instance(roomId string, broker Broker) *Instance

Instance creates an instance of a plugin. It is *not* registered (and therefore not considered by the router until that is done).

func (*Plugin) Register

func (p *Plugin) Register() error

Register registers a plugin with the bot.

func (*Plugin) String

func (p *Plugin) String() string

func (*Plugin) Unregister

func (p *Plugin) Unregister() error

Unregister removes a plugin from the bot.

type Pref

type Pref struct {
	User    string `json:"user"`
	Plugin  string `json:"plugin"`
	Broker  string `json:"broker"`
	Room    string `json:"room"`
	Key     string `json:"key"`
	Value   string `json:"value"`
	Default string `json:"default"`
	Success bool   `json:"-"`
	Error   error  `json:"-"`
	Id      int    `json:"id"`
}

Pref is a key/value pair associated with a combination of user, plugin, borker, or room.

func GetPref

func GetPref(user, broker, room, plugin, key, def string) Pref

GetPref will retreive the most-specific preference from pref storage using the parameters provided. This is a bit like pattern matching. If no match is found, the provided default is returned. TODO: explain this better

func (*Pref) Delete

func (in *Pref) Delete() error

Set writes the value and returns a new struct with the new value.

func (Pref) Find

func (p Pref) Find() Prefs

Find retrieves all preferences from the database that match any field in the handle's fields. If the Key field is set, it is matched first. The resulting list is sorted before it is returned. Unlike Get(), empty string fields are not included in the (generated) query so it can potentially match a lot of rows. Returns an empty list and logs upon errors.

func (Pref) FindKey

func (p Pref) FindKey(key string) Prefs

func (*Pref) Get

func (in *Pref) Get() Pref

Get retrieves a value from the database. If the database returns an error, Success will be false and the Error field will be populated.

func (*Pref) GetPrefs

func (in *Pref) GetPrefs() Prefs

GetPrefs returns all preferences that match the fields set in the handle.

func (*Pref) Set

func (in *Pref) Set() error

Set writes the value and returns a new struct with the new value.

func (Pref) SetBroker

func (pref Pref) SetBroker(broker string) Pref

SetBroker returns a copy of the pref with the Broker set to the provided string.

func (Pref) SetKey

func (pref Pref) SetKey(key string) Pref

SetKey returns a copy of the pref with the key set to the provided string. Useful for chaining e.g. fooPrefs := p.SetKey("foo").Find().

func (Pref) SetUser

func (pref Pref) SetUser(user string) Pref

SetUser returns a copy of the pref with the User set to the provided string.

func (*Pref) String

func (p *Pref) String() string

type Prefs

type Prefs []Pref

func FindKey

func FindKey(key string) Prefs

FindKey is like Find() but the provide key is required.

func FindPrefs

func FindPrefs(user, broker, room, plugin, key string) Prefs

FindPrefs gets all records that match any of the inputs that are not empty strings. (hint: user="x", broker="y"; WHERE user=? OR broker=?)

func GetPrefs

func GetPrefs(user, broker, room, plugin string) Prefs

GetPrefs retrieves a set of preferences from the database. The settings are matched exactly on user,broker,room,plugin. e.g. GetPrefs("", "", "", "uptime") would get only records that have user/broker/room set to the empty string and room set to "uptime". A record with user "pford" and plugin "uptime" would not be included.

func (Prefs) Broker

func (prefs Prefs) Broker(broker string) Prefs

Broker filters the preference list by broker, returning a new Prefs

func (Prefs) Clone

func (prefs Prefs) Clone() Prefs

Clone returns a full/deep copy of the Prefs list.

func (Prefs) Key

func (prefs Prefs) Key(key string) Prefs

Key filters the preference list by key, returning a new Prefs

func (Prefs) Len

func (ps Prefs) Len() int

func (Prefs) Less

func (ps Prefs) Less(i, j int) bool

func (Prefs) One

func (prefs Prefs) One() Pref

One returns the most-specific preference from the Prefs according to the precedence order of user>room>broker>plugin>global.

func (Prefs) Plugin

func (prefs Prefs) Plugin(plugin string) Prefs

Plugin filters the preference list by plugin, returning a new Prefs

func (Prefs) Room

func (prefs Prefs) Room(room string) Prefs

Room filters the preference list by room, returning a new Prefs e.g. instprefs = prefs.Room("magrathea").Plugin("uptime").Broker("slack")

func (*Prefs) String

func (p *Prefs) String() string

func (Prefs) Swap

func (ps Prefs) Swap(i, j int)

func (Prefs) Table

func (prefs Prefs) Table() [][]string

Table returns Prefs as a 2d list ready to hand off to e.g. hal.AsciiTable()

func (Prefs) User

func (prefs Prefs) User(user string) Prefs

User filters the preference list by user, returning a new Prefs e.g. uprefs = prefs.User("adent")

func (Prefs) Value

func (prefs Prefs) Value(value string) Prefs

Value filters the preference list by key, returning a new Prefs

type RequiredParamNotFound

type RequiredParamNotFound struct {
	Param NamedParam
}

RequiredParamNotFound is returned when a parameter has Required=true and a method was used to access the value but no value was set in the command.

func (RequiredParamNotFound) Error

func (e RequiredParamNotFound) Error() string

Error fulfills the Error interface.

type RouterCTX

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

RouterCTX holds the router's context, including input/output chans.

func Router

func Router() *RouterCTX

Router returns the singleton router context. The router is initialized on the first call to this function.

func (*RouterCTX) AddBroker

func (r *RouterCTX) AddBroker(b Broker)

AddBroker adds a broker to the router and starts forwarding events between it and the router.

func (*RouterCTX) Brokers

func (r *RouterCTX) Brokers() []Broker

Brokers returns all brokers that have been added to the router. The returned list is not in any particular order.

func (*RouterCTX) GetBroker

func (r *RouterCTX) GetBroker(name string) Broker

GetBroker retrieves a broker handle by name.

func (*RouterCTX) Quit

func (r *RouterCTX) Quit()

func (*RouterCTX) Route

func (r *RouterCTX) Route()

Route is the main method for the router. It blocks and should be run in a goroutine exactly once. Running more than one router in the same process will result in shenanigans.

func (*RouterCTX) Send

func (r *RouterCTX) Send(evt Evt)

type SecretStore

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

secrets stores a plaintext key/value store for sensitive data that the bot and plugins need to operate along with methods for persisting encrypted copies to the database

func Secrets

func Secrets() *SecretStore

Secrets returns a handle for accessing secrets managed by hal.

func (*SecretStore) Delete

func (ss *SecretStore) Delete(key string)

Delete removes the key from the in-memory secret store. This is not persisted.

func (*SecretStore) Dump

func (ss *SecretStore) Dump() map[string]string

Dump returns a copy of the kv store. DO NOT USE IN PLUGINS. This returns an UNENCRYPTED copy of the kv store for CLI tools and debugging. This might go away.

func (*SecretStore) Exists

func (ss *SecretStore) Exists(key string) bool

Exists checks to see if the provided key exists in the secret store.

func (*SecretStore) Get

func (ss *SecretStore) Get(key string) string

Get returns the value of a key from the secret store. If the key doesn't exist, empty string is returned. To check existence, use Exists(string).

func (*SecretStore) InitDB

func (ss *SecretStore) InitDB()

func (*SecretStore) LoadFromDB

func (ss *SecretStore) LoadFromDB()

Load secrets from the database and decrypt them into hal's in-memory secret store. The database-side secrets will be added to the existing store, overwriting on conflict (e.g. the database secrets). Any errors during this process are fatal.

func (*SecretStore) Put

func (ss *SecretStore) Put(key, value string)

Put is an alias for Set

func (*SecretStore) SaveToDB

func (ss *SecretStore) SaveToDB()

Serialize the secret store, encrypt it, and store it in the database. Any errors during this process are fatal.

func (*SecretStore) Set

func (ss *SecretStore) Set(key, value string)

Put adds a key/value to the in-memory secret store. Put'ing a key that already exists overwrites the previous value. The secret store is not persisted at this point, an additional call to Save() is required.

func (*SecretStore) SetEncryptionKey

func (ss *SecretStore) SetEncryptionKey(in []byte)

SetEncryptionKey sets the key used to encrypt/decrypt credentials stored in the database. This needs to be called before anything will work.

func (*SecretStore) WipeDB

func (ss *SecretStore) WipeDB()

type SubCmd

type SubCmd struct {
	Cmd
	// contains filtered or unexported fields
}

func (*SubCmd) AddAlias

func (s *SubCmd) AddAlias(alias string) *SubCmd

func (*SubCmd) AddBoolParam

func (c *SubCmd) AddBoolParam(key string, required bool) *BoolParam

AddBoolParam adds a boolean/flag parameter to the subcommand and returns the new parameter.

func (*SubCmd) AddIdxParam

func (c *SubCmd) AddIdxParam(position int, name string, required bool) *IdxParam

AddIdxParam adds a positional parameter to the subcommand and returns the new parameter.

func (*SubCmd) AddKVParam

func (c *SubCmd) AddKVParam(key string, required bool) *KVParam

AddKVParam creates and adds a key/value parameter to the subcommand and returns the new parameter.

func (*SubCmd) SetUsage

func (s *SubCmd) SetUsage(usage string) *SubCmd

SetUsage sets the subcommand's usage string.

func (*SubCmd) SubCmd

func (s *SubCmd) SubCmd() *SubCmd

type SubCmdInst

type SubCmdInst struct {
	CmdInst
	// contains filtered or unexported fields
}

func (*SubCmdInst) GetBoolParam

func (c *SubCmdInst) GetBoolParam(key string) *BoolParam

func (*SubCmdInst) GetBoolParamInst

func (c *SubCmdInst) GetBoolParamInst(key string) *BoolParamInst

GetBoolParamInst gets a key/value parameter instance by its key.

func (*SubCmdInst) GetIdxParam

func (c *SubCmdInst) GetIdxParam(idx int) *IdxParam

func (*SubCmdInst) GetIdxParamInst

func (c *SubCmdInst) GetIdxParamInst(idx int) *IdxParamInst

GetIdxParamInst gets an indexed parameter instance by its index.

func (*SubCmdInst) GetIdxParamInstByName

func (c *SubCmdInst) GetIdxParamInstByName(name string) *IdxParamInst

GetIdxParamInstByName gets an indexed parameter instance by its name.

func (*SubCmdInst) GetKVParam

func (c *SubCmdInst) GetKVParam(key string) *KVParam

func (*SubCmdInst) GetKVParamInst

func (c *SubCmdInst) GetKVParamInst(key string) *KVParamInst

GetKVParamInst gets a key/value parameter instance by its key.

func (*SubCmdInst) HasIdxParam

func (c *SubCmdInst) HasIdxParam(idx int) bool

func (*SubCmdInst) HasKVParam

func (c *SubCmdInst) HasKVParam(key string) bool

func (*SubCmdInst) SubCmdToken

func (c *SubCmdInst) SubCmdToken() string

type SubCmdNotFound

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

func (SubCmdNotFound) Error

func (e SubCmdNotFound) Error() string

type UnsupportedTimeFormatError

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

UnsupportedTimeFormatError is returned when a provided time string cannot be parsed with one of the pre-defined time formats.

func (UnsupportedTimeFormatError) Error

Error fulfills the Error interface for UnsupportedTimeFormatError.

Jump to

Keyboard shortcuts

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