bcr

package module
v0.16.0 Latest Latest
Warning

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

Go to latest
Published: May 25, 2021 License: BSD-3-Clause Imports: 22 Imported by: 64

README

bcr

A command handler based on arikawa. Mostly for personal use, but feel free to use it elsewhere 🙂

Package bot contains a basic wrapper around bcr, for a categorized help command.

Example

(replace "token" with your bot's token, and the user ID with your own ID)

// create a router
router, err := bcr.NewWithState("token", []discord.UserID{0}, []string{"~"})

// make sure to add the message create handler
router.State.AddHandler(router.MessageCreate)

// add a command
router.AddCommand(&bcr.Command{
    Name:    "ping",
    Summary: "Ping pong!",

    Command: func(ctx *bcr.Context) (err error) {
        _, err = ctx.Send("Pong!", nil)
        return
    },
})

// connect to discord
if err := bot.Router.State.Open(); err != nil {
    log.Fatalln("Failed to connect:", err)
}

Documentation

Index

Constants

View Source
const (
	ColourTeal        = 0x1abc9c
	ColourDarkTeal    = 0x11806a
	ColourGreen       = 0x2ecc71
	ColourDarkGreen   = 0x1f8b4c
	ColourBlue        = 0x3498db
	ColourDarkBlue    = 0x206694
	ColourPurple      = 0x9b59b6
	ColourDarkPurple  = 0x71368a
	ColourMagenta     = 0xe91e63
	ColourDarkMagenta = 0xad1457
	ColourGold        = 0xf1c40f
	ColourDarkGold    = 0xc27c0e
	ColourOrange      = 0xe67e22
	ColourDarkOrange  = 0xa84300
	ColourRed         = 0xe74c3c
	ColourDarkRed     = 0x992d22
	ColourLighterGrey = 0x95a5a6
	ColourDarkGrey    = 0x607d8b
	ColourLightGrey   = 0x979c9f
	ColourDarkerGrey  = 0x546e7a
	ColourBlurple     = 0x7289da
	ColourGreyple     = 0x99aab5
	ColourDarkTheme   = 0x36393F
)

Common colours, yoinked from discord.py

View Source
const (
	PermissionViewServerInsights = 1 << 19
	PermissionUseSlashCommands   = 1 << 31
	PermissionRequestToSpeak     = 1 << 32
)

Permission constants that Arikawa is missing

RequiredIntents are the intents required for the command handler

Variables

View Source
var (
	ErrNoPath     = errors.New("alias: no path supplied")
	ErrNilCommand = errors.New("alias: command was nil")
)

Errors related to creating aliases

View Source
var (
	ErrorNotEnoughArgs = errors.New("not enough arguments")
	ErrorTooManyArgs   = errors.New("too many arguments")
)

Errors

View Source
var (
	ErrChannel   = errors.New("context: couldn't get channel")
	ErrNoBotUser = errors.New("context: couldn't get bot user")

	ErrEmptyMessage = errors.New("context: message was empty")
)

Errors related to getting the context

View Source
var (
	// ErrorTimedOut is returned when WaitForReaction times out
	ErrorTimedOut = errors.New("context: timed out waiting for reaction")
	// ErrorFailedConversion is returned when WaitForReaction can't convert the interface{} to a MessageReactionAddEvent
	ErrorFailedConversion = errors.New("context: failed conversion in WaitForReaction")
)
View Source
var (
	ErrInvalidMention  = errors.New("invalid mention")
	ErrChannelNotFound = errors.New("channel not found")
	ErrMemberNotFound  = errors.New("member not found")
	ErrUserNotFound    = errors.New("user not found")
	ErrRoleNotFound    = errors.New("role not found")
	ErrMessageNotFound = errors.New("message not found")
)

Errors related to parsing

View Source
var (
	MajorPerms = []Perm{
		{discord.PermissionAdministrator, "Administrator"},
		{discord.PermissionManageGuild, "Manage Server"},
		{discord.PermissionManageWebhooks, "Manage Webhooks"},
		{discord.PermissionManageChannels, "Manage Channels"},

		{discord.PermissionBanMembers, "Ban Members"},
		{discord.PermissionKickMembers, "Kick Members"},

		{discord.PermissionManageRoles, "Manage Roles"},
		{discord.PermissionManageNicknames, "Manage Nicknames"},
		{discord.PermissionManageEmojis, "Manage Emojis"},
		{discord.PermissionManageMessages, "Manage Messages"},

		{discord.PermissionMentionEveryone, "Mention Everyone"},

		{discord.PermissionMuteMembers, "Voice Mute Members"},
		{discord.PermissionDeafenMembers, "Voice Deafen Members"},
		{discord.PermissionMoveMembers, "Voice Move Members"},
	}

	NotablePerms = []Perm{
		{discord.PermissionViewAuditLog, "View Audit Log"},
		{PermissionViewServerInsights, "View Server Insights"},

		{discord.PermissionPrioritySpeaker, "Priority Speaker"},
		{discord.PermissionSendTTSMessages, "Send TTS Messages"},

		{discord.PermissionCreateInstantInvite, "Create Invite"},
	}

	MinorPerms = []Perm{
		{discord.PermissionStream, "Video"},
		{discord.PermissionUseVAD, "Use Voice Activity"},
		{discord.PermissionSpeak, "Speak"},
		{discord.PermissionConnect, "Connect"},
		{PermissionRequestToSpeak, "Request to Speak"},

		{discord.PermissionAttachFiles, "Attach Files"},
		{discord.PermissionEmbedLinks, "Embed Links"},

		{discord.PermissionAddReactions, "Add Reactions"},
		{discord.PermissionSendMessages, "Send Messages"},

		{discord.PermissionReadMessageHistory, "Read Message History"},
		{discord.PermissionViewChannel, "View Channel"},

		{PermissionUseSlashCommands, "Use Slash Commands"},

		{discord.PermissionChangeNickname, "Change Nickname"},
		{discord.PermissionUseExternalEmojis, "Use External Emojis"},
	}

	AllPerms = append(MajorPerms, append(NotablePerms, MinorPerms...)...)
)

All permissions

View Source
var (
	ErrBotMissingPermissions = errors.New("bot is missing permissions")
)

Errors related to sending messages

View Source
var ErrNoEmbeds = errors.New("PagedEmbed: no embeds")

ErrNoEmbeds is returned if PagedEmbed() is called without any embeds

Functions

func AsCode

func AsCode(s string) string

AsCode returns the given string as code, correctly escaped

func DefaultValue

func DefaultValue(s, def string) string

DefaultValue returns the second value if the first is empty

func EscapeBackticks

func EscapeBackticks(s string) string

EscapeBackticks escapes backticks in strings

func FieldPaginator added in v0.15.1

func FieldPaginator(title, description string, colour discord.Color, fields []discord.EmbedField, perPage int) []discord.Embed

FieldPaginator paginates embed fields, for use in ctx.PagedEmbed

func HasAnyPrefix

func HasAnyPrefix(s string, prefixes ...string) bool

HasAnyPrefix checks if the string has *any* of the given prefixes

func HasAnySuffix

func HasAnySuffix(s string, suffixes ...string) bool

HasAnySuffix checks if the string has *any* of the given suffixes

func HumanizeDuration added in v0.14.0

func HumanizeDuration(precision DurationFormatPrecision, in time.Duration) string

HumanizeDuration ...

func HumanizeTime added in v0.14.0

func HumanizeTime(precision DurationFormatPrecision, in time.Time) string

HumanizeTime ...

func PermStrings

func PermStrings(p discord.Permissions) []string

PermStrings gives permission strings for all Discord permissions

func PermStringsFor added in v0.14.0

func PermStringsFor(m []Perm, p discord.Permissions) []string

PermStringsFor gives permission strings for the given Perm slice

func SprintfAll

func SprintfAll(template string, in []string) []string

SprintfAll takes a slice of strings and uses them as input for Sprintf, returning a slice of strings

func TrimPrefixesSpace

func TrimPrefixesSpace(s string, prefixes ...string) string

TrimPrefixesSpace trims all given prefixes as well as whitespace from the given string

func Version

func Version() string

Version returns the current brc version

Types

type ArgTransformer

type ArgTransformer func(string) string

ArgTransformer is used in Alias, passing in the context's RawArgs, which are then split again.

func DefaultArgTransformer

func DefaultArgTransformer(prefix, suffix string) ArgTransformer

DefaultArgTransformer adds a prefix or suffix (or both!) to the current args

type Args added in v0.8.0

type Args [2]int

Args is a minimum/maximum argument count. If either is -1, it's treated as "no minimum" or "no maximum". This replaces the Check* functions in Context.

func ArgRange added in v0.8.0

func ArgRange(i, j int) *Args

ArgRange returns an *Args with both a minimum and maximum number of arguments.

func ExactArgs added in v0.8.0

func ExactArgs(i int) *Args

ExactArgs returns an *Args with an exact number of required arguments.

func MaxArgs added in v0.8.0

func MaxArgs(i int) *Args

MaxArgs returns an *Args with only a maximum number of arguments.

func MinArgs added in v0.8.0

func MinArgs(i int) *Args

MinArgs returns an *Args with only a minimum number of arguments.

type Command

type Command struct {
	Name    string
	Aliases []string

	// Blacklistable commands use the router's blacklist function to check if they can be run
	Blacklistable bool

	// Summary is used in the command list
	Summary string
	// Description is used in the help command
	Description string
	// Usage is appended to the command name in help commands
	Usage string

	// Hidden commands are not returned from (*Router).Commands()
	Hidden bool

	Args *Args

	CustomPermissions CustomPerms

	// Flags is used to create a new flag set, which is then parsed before the command is run.
	// These can then be retrieved with the (*FlagSet).Get*() methods.
	Flags func(fs *pflag.FlagSet) *pflag.FlagSet

	Permissions discord.Permissions
	Command     func(*Context) error

	GuildOnly bool
	OwnerOnly bool
	Cooldown  time.Duration
	// contains filtered or unexported fields
}

Command is a single command, or a group

func (*Command) AddSubcommand

func (c *Command) AddSubcommand(sub *Command) *Command

AddSubcommand adds a subcommand to a command

func (*Command) GetCommand

func (c *Command) GetCommand(name string) *Command

GetCommand gets a command by name

type Commands added in v0.8.0

type Commands []*Command

Commands is a sortable slice of Command

func (Commands) Len added in v0.8.0

func (c Commands) Len() int

func (Commands) Less added in v0.8.0

func (c Commands) Less(i, j int) bool

func (Commands) Swap added in v0.8.0

func (c Commands) Swap(i, j int)

type Context

type Context struct {
	// Command and Prefix contain the invoked command's name and prefix, respectively.
	// Note that Command won't be accurate if the invoked command was a subcommand, use FullCommandPath for that.
	Command string
	Prefix  string

	FullCommandPath []string

	Args    []string
	RawArgs string

	Flags *pflag.FlagSet

	InternalArgs []string

	State *state.State
	Bot   *discord.User

	// Info about the message
	Message discord.Message
	Channel *discord.Channel
	Author  discord.User

	// Note: Member is nil for non-guild messages
	Member *discord.Member

	// The command and the router used
	Cmd    *Command
	Router *Router

	AdditionalParams map[string]interface{}
	// contains filtered or unexported fields
}

Context is a command context

func (*Context) AddMessageHandler

func (ctx *Context) AddMessageHandler(
	c discord.ChannelID,
	user discord.UserID,
	fn func(*Context, discord.Message),
)

AddMessageHandler adds a message handler for the given user/channel

func (*Context) AddReactionHandler

func (ctx *Context) AddReactionHandler(
	msg discord.MessageID,
	user discord.UserID,
	reaction string,
	deleteOnTrigger, deleteReaction bool,
	fn func(*Context),
)

AddReactionHandler adds a reaction handler for the given message

func (*Context) AddReactionHandlerWithTimeout added in v0.16.0

func (ctx *Context) AddReactionHandlerWithTimeout(
	msg discord.MessageID,
	user discord.UserID,
	reaction string,
	deleteOnTrigger, deleteReaction bool,
	timeout time.Duration,
	fn func(*Context),
)

AddReactionHandlerWithTimeout is like AddReactionHandler but accepts a timeout

func (*Context) CheckArgRange

func (ctx *Context) CheckArgRange(min, max int) (err error)

CheckArgRange checks if the number of arguments is within the given range

func (*Context) CheckBotPerms

func (ctx *Context) CheckBotPerms(p discord.Permissions) (err error)

CheckBotPerms checks the bot's permissions in the current channel

func (*Context) CheckMinArgs

func (ctx *Context) CheckMinArgs(c int) (err error)

CheckMinArgs checks if the argument count is less than the given count

func (*Context) CheckPerms

func (ctx *Context) CheckPerms() (err error)

CheckPerms checks the user's permissions in the current channel

func (*Context) CheckRequiredArgs

func (ctx *Context) CheckRequiredArgs(c int) (err error)

CheckRequiredArgs checks if the arg count is exactly the given count

func (*Context) Confirm added in v0.14.0

func (ctx *Context) Confirm(s string) (yes bool)

Confirm confirms the given string to the context user

func (*Context) DisplayName added in v0.14.0

func (ctx *Context) DisplayName() string

DisplayName returns the context user's displayed name (either username without discriminator, or nickname)

func (*Context) Edit

func (ctx *Context) Edit(m *discord.Message, c string, embed *discord.Embed) (msg *discord.Message, err error)

Edit the given message

func (*Context) GreedyChannelParser

func (ctx *Context) GreedyChannelParser(args []string) (channels []*discord.Channel, n int)

GreedyChannelParser parses all arguments until it finds an error. Returns the parsed channels and the position at which it stopped. If all arguments were parsed as channels, returns -1.

func (*Context) GreedyMemberParser

func (ctx *Context) GreedyMemberParser(args []string) (members []*discord.Member, n int)

GreedyMemberParser parses all arguments until it finds an error. Returns the parsed members and the position at which it stopped. If all arguments were parsed as members, returns -1.

func (*Context) GreedyRoleParser

func (ctx *Context) GreedyRoleParser(args []string) (roles []*discord.Role, n int)

GreedyRoleParser parses all arguments until it finds an error. Returns the parsed roles and the position at which it stopped. If all arguments were parsed as roles, returns -1.

func (*Context) GreedyUserParser

func (ctx *Context) GreedyUserParser(args []string) (users []*discord.User, n int)

GreedyUserParser parses all arguments until it finds an error. Returns the parsed users and the position at which it stopped. If all arguments were parsed as users, returns -1.

func (*Context) Help

func (ctx *Context) Help(path []string) (err error)

Help sends a help embed for the command

func (*Context) NewDM added in v0.9.1

func (ctx *Context) NewDM(user discord.UserID) *MessageSend

NewDM creates a new MessageSend object for the given user. If the user has closed DMs, this will not error until the Send() call.

func (*Context) NewLog added in v0.16.0

func (ctx *Context) NewLog(title string) *Log

NewLog creates a new Log

func (*Context) NewMessage added in v0.9.0

func (ctx *Context) NewMessage(channel ...discord.ChannelID) *MessageSend

NewMessage creates a new MessageSend object. Only the *first* channel argument is used, if omitted it's set to the current channel.

func (*Context) PagedEmbed

func (ctx *Context) PagedEmbed(embeds []discord.Embed, extendedReactions bool) (msg *discord.Message, err error)

PagedEmbed sends a slice of embeds, and attaches reaction handlers to flip through them. if extendedReactions is true, also add delete, first page, and last page reactions.

func (*Context) PagedEmbedTimeout added in v0.16.0

func (ctx *Context) PagedEmbedTimeout(embeds []discord.Embed, extendedReactions bool, timeout time.Duration) (msg *discord.Message, timer *time.Timer, err error)

PagedEmbedTimeout creates a paged embed (see PagedEmbed) that times out after the given time. It also returns a timer that can be used to cancel the attached reaction-clearing timer.

func (*Context) ParseChannel

func (ctx *Context) ParseChannel(s string) (c *discord.Channel, err error)

ParseChannel parses a channel mention/id/name

func (*Context) ParseMember

func (ctx *Context) ParseMember(s string) (c *discord.Member, err error)

ParseMember parses a member mention/id/name

func (*Context) ParseMessage added in v0.14.0

func (ctx *Context) ParseMessage(s string) (m *discord.Message, err error)

ParseMessage parses a message link or ID. Either in channelID-messageID format (obtained by shift right-clicking on the "copy ID" button in the desktop client), or the message link obtained with the "copy message link" button. Will error if the bot does not have access to the channel the message is in.

func (*Context) ParseRole

func (ctx *Context) ParseRole(s string) (c *discord.Role, err error)

ParseRole parses a role mention/id/name

func (*Context) ParseUser

func (ctx *Context) ParseUser(s string) (u *discord.User, err error)

ParseUser finds a user by mention or ID

func (*Context) Peek added in v0.10.0

func (ctx *Context) Peek() string

Peek gets the next argument from the context's Args without removing it

func (*Context) Pop added in v0.10.0

func (ctx *Context) Pop() string

Pop gets the next argument from the context's Args and removes it from the slice

func (*Context) Reply

func (ctx *Context) Reply(content string, embed *discord.Embed) (m *discord.Message, err error)

Reply *replies* to the original message in the context channel

func (*Context) Send

func (ctx *Context) Send(content string, embed *discord.Embed) (m *discord.Message, err error)

Send sends a message to the context channel

func (*Context) SendEmbed added in v0.16.0

func (ctx *Context) SendEmbed(data SendEmbedData) (m *discord.Message, err error)

SendEmbed sends a message, formatted as an embed.

func (*Context) Sendf

func (ctx *Context) Sendf(template string, args ...interface{}) (m *discord.Message, err error)

Sendf sends a message with Printf-like syntax

func (*Context) WaitForMessage added in v0.16.0

func (ctx *Context) WaitForMessage(ch discord.ChannelID, user discord.UserID, timeout time.Duration, filter func(*gateway.MessageCreateEvent) bool) (msg *gateway.MessageCreateEvent, timedOut bool)

WaitForMessage waits for a message that matches the given channel ID, user ID, and filter function. If filter is nil, only checks for the channel and user matching.

func (*Context) WaitForReaction added in v0.14.0

func (ctx *Context) WaitForReaction(msg discord.Message, user discord.UserID) (ev *gateway.MessageReactionAddEvent, err error)

WaitForReaction calls WaitForReactionWithTimeout with a 3-minute timeout

func (*Context) WaitForReactionWithTimeout added in v0.14.0

func (ctx *Context) WaitForReactionWithTimeout(msg discord.Message, user discord.UserID, timeout time.Duration) (ev *gateway.MessageReactionAddEvent, err error)

WaitForReactionWithTimeout waits for a reaction with a user-given timeout

func (*Context) YesNoHandler added in v0.12.0

func (ctx *Context) YesNoHandler(msg discord.Message, user discord.UserID) (yes, timeout bool)

YesNoHandler adds a reaction handler for the given message. This handler times out after one minute. If it timed out, `false` and `true` are returned, respectively.

func (*Context) YesNoHandlerWithTimeout added in v0.14.0

func (ctx *Context) YesNoHandlerWithTimeout(msg discord.Message, user discord.UserID, t time.Duration) (yes, timeout bool)

YesNoHandlerWithTimeout is like YesNoHandler but lets you specify your own timeout.

type CooldownCache

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

CooldownCache holds cooldowns for commands

func (*CooldownCache) Get

func (c *CooldownCache) Get(cmdName string, userID discord.UserID, channelID discord.ChannelID) bool

Get returns true if the command is on cooldown

func (*CooldownCache) Set

func (c *CooldownCache) Set(cmdName string, userID discord.UserID, channelID discord.ChannelID, cooldown time.Duration)

Set sets a cooldown for a command

type CustomPerms

type CustomPerms interface {
	// The string used for the permissions if the check fails
	String() string

	// Returns true if the user has permission to run the command
	Check(*Context) (bool, error)
}

CustomPerms is a custom permission checker

type DurationFormatPrecision added in v0.14.0

type DurationFormatPrecision int

DurationFormatPrecision ...

const (
	DurationPrecisionSeconds DurationFormatPrecision = iota
	DurationPrecisionMinutes
	DurationPrecisionHours
	DurationPrecisionDays
	DurationPrecisionWeeks
	DurationPrecisionYears
)

...

func (DurationFormatPrecision) FromSeconds added in v0.14.0

func (d DurationFormatPrecision) FromSeconds(in int64) int64

FromSeconds ...

func (DurationFormatPrecision) String added in v0.14.0

func (d DurationFormatPrecision) String() string

type Log added in v0.16.0

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

Log is an updateable log message

func (*Log) Error added in v0.16.0

func (log *Log) Error(msg string)

Error logs an error message

func (*Log) Log added in v0.16.0

func (log *Log) Log(msg string)

Log logs a normal message

func (*Log) Replace added in v0.16.0

func (log *Log) Replace(msg string)

Replace replaces the latest message

func (*Log) Send added in v0.16.0

func (log *Log) Send()

Send ...

func (*Log) SetColor added in v0.16.0

func (log *Log) SetColor(color discord.Color)

SetColor ...

func (*Log) SetTitle added in v0.16.0

func (log *Log) SetTitle(title string)

SetTitle ...

type LogFunc added in v0.15.1

type LogFunc func(template string, args ...interface{})

LogFunc is a function used for logging

type Logger added in v0.15.1

type Logger struct {
	Debug LogFunc
	Info  LogFunc
	Error LogFunc
}

Logger is a basic logger

func NewNoopLogger added in v0.15.1

func NewNoopLogger() *Logger

NewNoopLogger returns a Logger that does nothing when its functions are called

func NewStdlibLogger added in v0.15.1

func NewStdlibLogger(debug bool) *Logger

NewStdlibLogger returns a Logger that wraps the standard library's "log" package

func NewZapLogger added in v0.15.1

func NewZapLogger(s *zap.SugaredLogger) *Logger

NewZapLogger returns a Logger that wraps a SugaredLogger from go.uber.org/zap

type MessageSend added in v0.9.0

type MessageSend struct {
	Data api.SendMessageData
	// contains filtered or unexported fields
}

MessageSend is a helper struct for sending messages. By default, it will send a message to the current channel, and check permissions (unless the target channel is the current channel and is a DM channel). These can be overridden with the Channel(id) and TogglePermCheck() methods. Alternatively, you can get the base SendMessageData struct and use that manually.

func (*MessageSend) AddFile added in v0.9.1

func (m *MessageSend) AddFile(name string, reader io.Reader) *MessageSend

AddFile adds a file to the message

func (*MessageSend) AllowedMentions added in v0.9.0

func (m *MessageSend) AllowedMentions(a *api.AllowedMentions) *MessageSend

AllowedMentions sets the message's allowed mentions

func (*MessageSend) BlockMentions added in v0.9.0

func (m *MessageSend) BlockMentions() *MessageSend

BlockMentions blocks all mentions from this message

func (*MessageSend) Channel added in v0.9.0

func (m *MessageSend) Channel(c discord.ChannelID) *MessageSend

Channel sets the channel to send the message to

func (*MessageSend) Content added in v0.9.0

func (m *MessageSend) Content(c string) *MessageSend

Content sets the message content

func (*MessageSend) Embed added in v0.9.0

func (m *MessageSend) Embed(e *discord.Embed) *MessageSend

Embed sets the message embed

func (*MessageSend) Reference added in v0.9.0

func (m *MessageSend) Reference(id discord.MessageID) *MessageSend

Reference sets the message this message will reply to

func (*MessageSend) Send added in v0.9.0

func (m *MessageSend) Send() (msg *discord.Message, err error)

Send sends the message

func (*MessageSend) TogglePermCheck added in v0.9.0

func (m *MessageSend) TogglePermCheck() *MessageSend

TogglePermCheck toggles whether or not to check permissions for the destination channel

type Perm added in v0.14.2

type Perm struct {
	Permission discord.Permissions
	Name       string
}

Perm is a single permission

type PermError

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

PermError is a permission error

func (*PermError) Error

func (p *PermError) Error() string

type Prefixer added in v0.11.0

type Prefixer func(m discord.Message) int

Prefixer returns the prefix used and the length. If the message doesn't start with a valid prefix, it returns -1. Note that this function should still use the built-in r.Prefixes for mention prefixes

type Roles added in v0.14.0

type Roles []discord.Role

Roles are a sortable collection of discord.Role

func (Roles) Len added in v0.14.0

func (r Roles) Len() int

func (Roles) Less added in v0.14.0

func (r Roles) Less(i, j int) bool

func (Roles) Swap added in v0.14.0

func (r Roles) Swap(i, j int)

type Router

type Router struct {
	BotOwners []string

	Prefixes []string
	Prefixer Prefixer

	State  *state.State
	Bot    *discord.User
	Logger *Logger

	BlacklistFunc   func(*Context) bool
	HelpCommand     func(*Context) error
	DefaultMentions *api.AllowedMentions
	EmbedColor      discord.Color

	ReactTimeout time.Duration
	// contains filtered or unexported fields
}

Router is the command router

func New added in v0.10.0

func New(s *state.State, owners, prefixes []string) *Router

New creates a new router object

func NewWithIntents added in v0.10.0

func NewWithIntents(token string, owners []discord.UserID, prefixes []string, intents gateway.Intents) (*Router, error)

NewWithIntents creates a new router with a state, with the specified intents. The token is automatically prefixed with `Bot `.

func NewWithState

func NewWithState(token string, owners []discord.UserID, prefixes []string) (*Router, error)

NewWithState creates a new router with a state. The token is automatically prefixed with `Bot `.

func (*Router) AddCommand

func (r *Router) AddCommand(c *Command) *Command

AddCommand adds a command to the router

func (*Router) Alias

func (r *Router) Alias(name string, aliases, path []string, argTransform ArgTransformer) (*Command, error)

Alias creates an alias to the command `path`, and transforms the arguments according to argTransform. argTransform is called with the context's RawArgs.

func (*Router) AliasMust

func (r *Router) AliasMust(name string, aliases, path []string, argTransform ArgTransformer) *Command

AliasMust is a wrapper around Alias that panics if err is non-nil

func (*Router) Commands

func (r *Router) Commands() []*Command

Commands returns a list of commands

func (*Router) DefaultPrefixer added in v0.11.0

func (r *Router) DefaultPrefixer(m discord.Message) int

DefaultPrefixer ...

func (*Router) DeleteReactions

func (r *Router) DeleteReactions(m discord.MessageID)

DeleteReactions deletes all reactions for a message

func (*Router) Execute

func (r *Router) Execute(ctx *Context) (err error)

Execute executes the command router

func (*Router) GetCommand

func (r *Router) GetCommand(name string) *Command

GetCommand gets a command by name

func (*Router) MatchPrefix

func (r *Router) MatchPrefix(m discord.Message) bool

MatchPrefix returns true if the message content contains any of the prefixes

func (*Router) MessageCreate

func (r *Router) MessageCreate(m *gateway.MessageCreateEvent)

MessageCreate gets called on new messages - makes sure the router has a bot user - checks if the message matches a prefix - runs commands

func (*Router) MsgHandlerCreate

func (r *Router) MsgHandlerCreate(e *gateway.MessageCreateEvent)

MsgHandlerCreate runs when a new message is sent

func (*Router) NewContext

func (r *Router) NewContext(m *gateway.MessageCreateEvent) (ctx *Context, err error)

NewContext returns a new message context

func (*Router) ReactionAdd

func (r *Router) ReactionAdd(e *gateway.MessageReactionAddEvent)

ReactionAdd runs when a reaction is added to a message

func (*Router) ReactionMessageDelete

func (r *Router) ReactionMessageDelete(m *gateway.MessageDeleteEvent)

ReactionMessageDelete cleans up old handlers on deleted messages

func (*Router) SetBotUser

func (r *Router) SetBotUser() error

SetBotUser sets the router's bot user, returning any errors

type SED added in v0.16.0

type SED = SendEmbedData

SED is an alias for SendEmbedData

type SendEmbedData added in v0.16.0

type SendEmbedData struct {
	Title   string
	Message string
	Footer  string

	Color discord.Color
}

SendEmbedData is data for SendEmbed. All these fields can be kept empty.

Directories

Path Synopsis
Package bot provides a basic embeddable Bot struct for more easily handling commands
Package bot provides a basic embeddable Bot struct for more easily handling commands

Jump to

Keyboard shortcuts

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