keybasebot

package module
v1.8.0 Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2021 License: MIT Imports: 8 Imported by: 1

README

* keybasebot
keybasebot is a framework for easily creating interactive chat bots for Keybase

** Helpful Links
- [[https://pkg.go.dev/github.com/kf5grd/keybasebot][GoDoc]] - Documentation for this package on the [[https://pkg.go.dev/][pkg.go.dev]] website
- [[https://pkg.go.dev/samhofi.us/x/keybase/v2][Keybase Library]] - This framework is written around a Keybase library I wrote, and you'll likely need to use this along with this bot framework
- [[https://keybase.io/team/mkbot][mkbot]] - Keybase bot community. Come say "Hi" and show off your bots, or ask for help

** Usage
For a full example of a bot written with this framework, see the examples folder.

*** A Basic Bot
**** Create a bot instance
#+BEGIN_SRC go
  // The bot name will show up next to your bot's username in conversations
  botName := "Example Bot"
  b := bot.New(botName)
  b.LogWriter = os.Stdout
#+END_SRC

**** BotCommands
BotCommands consist of 3 fields:
- =Name=: The name of the command, mostly for logging purposes
- =Ad=: The [[https://pkg.go.dev/samhofi.us/x/keybase/v2/types/chat1#UserBotCommandInput][advertisement]] that displays in the Keybase client when a user starts to type the command
- =Run=: The [[https://pkg.go.dev/github.com/kf5grd/keybasebot#BotAction][BotAction]] that gets called when the command is triggered
  - BotActions can also be modified on the fly by [[https://pkg.go.dev/github.com/kf5grd/keybasebot#Adapter][Adapters]], which are basically middleware for your bot commands

#+BEGIN_SRC go
    // Advertisements for cmdPing
    var cmdPingAd = chat1.UserBotCommandInput{
            Name:        "ping", // the command's trigger
            Description: "I will reply with `Pong!`",
    }

    // cmdPing is a BotAction that replies with "Pong!"
    func cmdPing(m chat1.MsgSummary, b *bot.Bot) (bool, error) {
            b.KB.ReplyByConvID(m.ConvID, m.Id, "Pong!")

            // 'true' tells the bot not to look for any more commands, and 'nil' means there were no
            // errors
            return true, nil
    }

    b.Commands = append(b.Commands,
            bot.BotCommand{
                    Name: "Ping",
                    Ad:   &cmdPingAd,
                  
                    // By using the bot.Adapt() function in our Run field, we're allowing the
                    // cmdPing BotAction to be modified by any adapters we pass to this
                    // command. In this case, we're using the MessageType adapter, which
                    // checks that the recieved message was of a specific message type, and
                    // the CommandPrefix adapter, which checks that the incoming message
                    // (which must have a "text" message type) begins with a certain string.
                    // If either of these adapters fail (that is, if the message does not
                    // have a message type of "text", or the message text does not begin
                    // with the string "!ping"), they will return an error and the bot will
                    // try to run the next command in the b.Commands slice. As long as both
                    // adapters are successful, the cmdPing BotAction will be executed.
                    Run: bot.Adapt(cmdPing, 
                                  bot.MessageType("text"),
                                  bot.CommandPrefix("!ping"),
                    ),
            },
    }
#+END_SRC

**** Running the bot
Once your bot instance is set up, call the =Run()= command
#+BEGIN_SRC go
  b.Run()
#+END_SRC

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Adapter

type Adapter func(BotAction) BotAction

Adapter can modify the behavior of a BotAction

func CommandPrefix

func CommandPrefix(prefix string) Adapter

CommandPrefix returns an Adapter that specifies the specific prefix that this command responds to. Note that this will often require that MessageType is called _before_ this adapter to avoid a panic.

func Contains added in v1.1.0

func Contains(s string, ignoreCase bool, ignoreWhiteSpace bool) Adapter

Contains returns an Adapter that only runs a command when the message contains a specific string. This will also make sure the received message has a type of 'text' or 'edit'

func FromUser added in v1.1.0

func FromUser(user string) Adapter

FromUser returns an Adapter that only runs a command when sent by a specific user

func FromUsers added in v1.1.0

func FromUsers(users []string) Adapter

FromUsers returns an Adapter that only runs a command when sent by one of a list of specific users

func MessageType

func MessageType(typeName string) Adapter

MessageType returns an Adapter that restricts a command to a specific message type

func MinRole

func MinRole(kb *keybase.Keybase, role string) Adapter

MinRole returns an Adapter that restricts a command to users with _at least_ the specified role. Note that this _must_ be called _after_ CommandPrefix because this assumes that we already know we're executing the provided command.

func ReactionTrigger

func ReactionTrigger(trigger string) Adapter

ReactionTrigger returns an Adapter that specifies the specific reaction that this command responds to. Note that you do not need to use the MessageType adapter when using this as we will already be checking to make sure the message type is a reaction.

type Bot

type Bot struct {
	// The Name string will show up next to the bot's username in chat messages. Setting this
	// to empty will cause it to be ignored
	Name string

	// If CommandPrefix is set, any messages that are received with a TypeName of "text," and
	// do not have this string prefix will be discarded. This can be useful if all of your
	// commands start with the same prefix.
	CommandPrefix string

	// The Keybase instance
	KB *keybase.Keybase

	// The logr instance
	Logger *logr.Logger

	// Where you want log messages written to
	LogWriter io.Writer

	// If LogConv is not empty, log messages will be sent to this conversation, in addition to
	// the LogWriter
	LogConv chat1.ConvIDStr

	// Whether log messages should be in JSON format
	JSON bool

	// Whether to show debug messages in log output
	Debug bool

	// Message handlers. You probably should leave the Chat handler alone
	Handlers keybase.Handlers

	// Custom run options for the message listener
	Opts keybase.RunOptions

	// A slice holding all of you BotCommands. Be sure to populate this prior to calling Run()
	Commands []BotCommand

	// You can use this to store custom info in order to pass it around to your bot commands
	Meta map[string]interface{}

	// Setting this to true allows the bot to react to its own messages. You'll need to be
	// careful with your commands when enabling this to make sure your bot doesn't get stuck
	// in a loop attempting to verify its own message, then sending an error, then trying to
	// verify, etc.
	AllowSelfMessages bool
	// contains filtered or unexported fields
}

Bot is where we'll hold the necessary information for the bot to run

func New

func New(name string, opts ...keybase.KeybaseOpt) *Bot

New returns a new Bot instance. name will set the Bot.Name and will show up next to the bot's username in chat messages. You can set name to an empty string. You can also pass in any keybase.KeybaseOpt options and they will be passed to keybase.New()

func (*Bot) AdvertiseCommands

func (b *Bot) AdvertiseCommands()

AdvertiseCommands loops through all the bot's commands and sends their advertisements to the Keybase service

func (*Bot) ClearCommands

func (b *Bot) ClearCommands()

ClearCommands clears the advertised commands from the Keybase service

func (*Bot) Run

func (b *Bot) Run() error

Run starts the bot listening for new messages

func (*Bot) Running added in v1.8.0

func (b *Bot) Running() bool

Running indicates whether the bot is currently running

type BotAction

type BotAction func(chat1.MsgSummary, *Bot) (bool, error)

BotAction is a function that's run when a command is received by the bot. If the boolean return is true, the bot will not attempt to execute any other commands after this one. If an error is returned, it will be sent to the logger. If an error is returned and the boolean is also set to true, the returned error will be sent back to the chat as a reply to the message that triggered the command.

func Adapt

func Adapt(b BotAction, adapters ...Adapter) BotAction

Adapt loops through a set of Adapters and runs them on a given BotAction in the order that they're provided. It's important to make sure you're passing adapters in the correct order as some things will need to be checked before others. As an example, the Contains adapter assumes that the incoming message has a MessageType of "text." If we pass that adapter prior to passing the MessageType adapter, then we will end up with a panic any time a message comes through with a MessageType other than "text."

type BotCommand

type BotCommand struct {
	// Name of the command for use in the logs
	Name string

	// This will show in your chat channels when someone starts typing a command in the
	// message box. Set this to nil if you don't want the command advertised
	Ad *chat1.UserBotCommandInput

	// AdType can be one of "public", "conv", "teamconvs", and "teammembers". If AdType is empty or
	// unknown, it will default to "public". If AdType is one of "teamconvs" or "teammembers",
	// be sure to specify the corresponding team name in AdTeamName. If AdType is "conv", be
	// sure to specify the corresponding conversation id in AdConv. Note: These settings only
	// restrict where the advertisements will show. You will still need to either use
	// appropriate Adapters, or write your BotAction in a way that limits where the commands
	// can be called from if that is your intention
	AdType string

	// If AdType is one of "teamconvs" or "teammembers", be sure to enter a team name in
	// AdTeamName, which will restrict your command to either be advertised in this team, or
	// only be advertised to members of this team
	AdTeamName string

	// If AdType is "conv", be sure to enter a conversation id in AdConv, which will restrict
	// your command to being advertised only in this conversation
	AdConv chat1.ConvIDStr

	// The function to run when the command is triggered
	Run BotAction
}

BotCommand holds information regarding a command and its advertisements

type JobAction added in v1.7.1

type JobAction func(b *Bot) error

JobAction is a function that can be run by the JobQueue

Directories

Path Synopsis
examples
meta-getset
This is a very simple bot that has 2 commands: set, and get.
This is a very simple bot that has 2 commands: set, and get.
pkg

Jump to

Keyboard shortcuts

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