Documentation
¶
Overview ¶
Package plugin provides abstractions for commands and modules and all types associated with them.
Index ¶
- Constants
- Variables
- type ArgConfig
- type ArgKind
- type ArgParser
- type ArgType
- type Args
- func (a Args) APIEmoji(i int) discord.APIEmoji
- func (a Args) APIEmojis(i int) []discord.APIEmoji
- func (a Args) Bool(i int) bool
- func (a Args) Channel(i int) *discord.Channel
- func (a Args) Channels(i int) []*discord.Channel
- func (a Args) Command(i int) *ResolvedCommand
- func (a Args) Commands(i int) []*ResolvedCommand
- func (a Args) Duration(i int) time.Duration
- func (a Args) Durations(i int) []time.Duration
- func (a Args) Emoji(i int) *discord.Emoji
- func (a Args) Emojis(i int) []*discord.Emoji
- func (a Args) Float32(i int) float32
- func (a Args) Float32s(i int) []float32
- func (a Args) Float64(i int) float64
- func (a Args) Float64s(i int) []float64
- func (a Args) Int(i int) int
- func (a Args) Int64(i int) int64
- func (a Args) Int64s(i int) []int64
- func (a Args) Ints(i int) []int
- func (a Args) Location(i int) *time.Location
- func (a Args) Locations(i int) []*time.Location
- func (a Args) Member(i int) *discord.Member
- func (a Args) Members(i int) []*discord.Member
- func (a Args) Module(i int) *ResolvedModule
- func (a Args) Modules(i int) []*ResolvedModule
- func (a Args) Regexp(i int) *regexp.Regexp
- func (a Args) Regexps(i int) []*regexp.Regexp
- func (a Args) Role(i int) *discord.Role
- func (a Args) Roles(i int) []*discord.Role
- func (a Args) String(i int) string
- func (a Args) Strings(i int) []string
- func (a Args) Time(i int) time.Time
- func (a Args) Times(i int) []time.Time
- func (a Args) Uint(i int) uint
- func (a Args) Uint64(i int) uint64
- func (a Args) Uint64s(i int) []uint64
- func (a Args) Uints(i int) []uint
- func (a Args) User(i int) *discord.User
- func (a Args) Users(i int) []*discord.User
- type ArgumentError
- type BotPermissionsError
- func (e *BotPermissionsError) Description(l *i18n.Localizer) (desc string)
- func (e *BotPermissionsError) Error() string
- func (e *BotPermissionsError) Handle(s *state.State, ctx *Context) error
- func (e *BotPermissionsError) Is(target error) bool
- func (e *BotPermissionsError) IsSinglePermission() bool
- func (e *BotPermissionsError) PermissionList(l *i18n.Localizer) string
- type ChannelTypeError
- type ChannelTypes
- type Command
- type CommandMeta
- type Context
- func (ctx *Context) Channel() (*discord.Channel, error)
- func (ctx *Context) Edit(messageID discord.MessageID, content ...interface{}) (*discord.Message, error)
- func (ctx *Context) EditDM(messageID discord.MessageID, content ...interface{}) (*discord.Message, error)
- func (ctx *Context) EditEmbeds(messageID discord.MessageID, embeds ...discord.Embed) (*discord.Message, error)
- func (ctx *Context) EditEmbedsDM(messageID discord.MessageID, embeds ...discord.Embed) (*discord.Message, error)
- func (ctx *Context) EditMessage(messageID discord.MessageID, data api.EditMessageData) (*discord.Message, error)
- func (ctx *Context) EditMessageDM(messageID discord.MessageID, data api.EditMessageData) (*discord.Message, error)
- func (ctx *Context) Editf(messageID discord.MessageID, format string, a ...interface{}) (*discord.Message, error)
- func (ctx *Context) EditfDM(messageID discord.MessageID, format string, a ...interface{}) (*discord.Message, error)
- func (ctx *Context) Editl(messageID discord.MessageID, c *i18n.Config) (*discord.Message, error)
- func (ctx *Context) EditlDM(messageID discord.MessageID, c *i18n.Config) (*discord.Message, error)
- func (ctx *Context) EditltDM(messageID discord.MessageID, term i18n.Term) (*discord.Message, error)
- func (ctx *Context) Guild() (*discord.Guild, error)
- func (ctx *Context) IsBotOwner() bool
- func (ctx *Context) ParentChannel() (*discord.Channel, error)
- func (ctx *Context) RawArgs() string
- func (ctx *Context) RawInvoke() string
- func (ctx *Context) Reply(content ...interface{}) (*discord.Message, error)
- func (ctx *Context) ReplyDM(content ...interface{}) (*discord.Message, error)
- func (ctx *Context) ReplyEmbeds(embeds ...discord.Embed) (*discord.Message, error)
- func (ctx *Context) ReplyEmbedsDM(embeds ...discord.Embed) (*discord.Message, error)
- func (ctx *Context) ReplyMessage(data api.SendMessageData) (*discord.Message, error)
- func (ctx *Context) ReplyMessageDM(data api.SendMessageData) (msg *discord.Message, err error)
- func (ctx *Context) Replyf(format string, a ...interface{}) (*discord.Message, error)
- func (ctx *Context) ReplyfDM(format string, a ...interface{}) (*discord.Message, error)
- func (ctx *Context) Replyl(c *i18n.Config) (*discord.Message, error)
- func (ctx *Context) ReplylDM(c *i18n.Config) (*discord.Message, error)
- func (ctx *Context) Self() (*discord.Member, error)
- func (ctx *Context) SelfPermissions() (discord.Permissions, error)
- func (ctx *Context) UsedPrefix() string
- func (ctx *Context) UserPermissions() (discord.Permissions, error)
- type DiscordDataProvider
- type ErrorHandler
- type ExampleArgs
- type Flag
- type Flags
- func (f Flags) APIEmoji(name string) discord.APIEmoji
- func (f Flags) APIEmojis(name string) []discord.APIEmoji
- func (f Flags) Bool(name string) bool
- func (f Flags) Channel(name string) *discord.Channel
- func (f Flags) Channels(name string) []*discord.Channel
- func (f Flags) Command(name string) *ResolvedCommand
- func (f Flags) Commands(name string) []*ResolvedCommand
- func (f Flags) Duration(name string) time.Duration
- func (f Flags) Durations(name string) []time.Duration
- func (f Flags) Emoji(name string) *discord.Emoji
- func (f Flags) Emojis(name string) []*discord.Emoji
- func (f Flags) Float32(name string) float32
- func (f Flags) Float32s(name string) []float32
- func (f Flags) Float64(name string) float64
- func (f Flags) Float64s(name string) []float64
- func (f Flags) Int(name string) int
- func (f Flags) Int64(name string) int64
- func (f Flags) Int64s(name string) []int64
- func (f Flags) Ints(name string) []int
- func (f Flags) Location(name string) *time.Location
- func (f Flags) Locations(name string) []*time.Location
- func (f Flags) Member(name string) *discord.Member
- func (f Flags) Members(name string) []*discord.Member
- func (f Flags) Module(name string) *ResolvedModule
- func (f Flags) Modules(name string) []*ResolvedModule
- func (f Flags) Regexp(name string) *regexp.Regexp
- func (f Flags) Regexps(name string) []*regexp.Regexp
- func (f Flags) Role(name string) *discord.Role
- func (f Flags) Roles(name string) []*discord.Role
- func (f Flags) String(name string) string
- func (f Flags) Strings(name string) []string
- func (f Flags) Time(name string) time.Time
- func (f Flags) Times(name string) []time.Time
- func (f Flags) Uint(name string) uint
- func (f Flags) Uint64(name string) uint64
- func (f Flags) Uint64s(name string) []uint64
- func (f Flags) Uints(name string) []uint
- func (f Flags) User(name string) *discord.User
- func (f Flags) Users(name string) []*discord.User
- type ID
- type Module
- type ModuleMeta
- type OptionalArg
- type ParseContext
- type Provider
- type Replier
- type RequiredArg
- type ResolvedCommand
- type ResolvedModule
- type RestrictionError
- type RestrictionFunc
- type Source
- type SourceModule
- type Throttler
- type ThrottlingError
- type UnavailableSource
Examples ¶
Constants ¶
const ( // KindArg is the Kind used for argument. KindArg = "arg" // KindFlag is the Kind used for flags. KindFlag = "flag" )
const ( // GuildTextChannels is the ChannelTypes of a regular guild text channel // (0). GuildTextChannels ChannelTypes = 1 << iota // GuildNewsChannels is the ChannelTypes of a news channel (5). GuildNewsChannels // Threads is the ChannelTypes of a thread (10, 11, 12). Threads // DirectMessages is the ChannelTypes of a private chat (1). DirectMessages // AllChannels is a combination of all ChannelTypes. AllChannels = DirectMessages | GuildChannels // GuildChannels is a combination of all ChannelTypes used in guilds, i.e. // GuildTextChannels, GuildNewsChannels, and Threads. GuildChannels = PersistentGuildChannels | Threads // PersistentGuildChannels are all non-thread guild channels. PersistentGuildChannels = GuildTextChannels | GuildNewsChannels )
const BuiltInSource = "built_in"
BuiltInSource is the name of the built-in plugin source.
Variables ¶
var ( // DefaultRestrictionError is a restriction error with a default, generic // description. DefaultRestrictionError = NewRestrictionErrorl(defaultRestrictionDesc) // DefaultFatalRestrictionError is a restriction error with a default, // generic description and Fatal set to true. DefaultFatalRestrictionError = NewFatalRestrictionErrorl(defaultRestrictionDesc) )
var DefaultBotPermissionsError = new(BotPermissionsError)
DefaultBotPermissionsError is an *BotPermissionsError that displays a generic "missing permissions" error message, instead of listing the missing permissions.
var HandleArgumentError = func(_ *state.State, ctx *Context, aerr *ArgumentError) error { desc, err := aerr.Description(ctx.Localizer) if err != nil { return err } e := shared.ErrorEmbedTemplate(ctx.Localizer) e.Description = desc _, err = ctx.ReplyEmbeds(e) return err }
var HandleBotPermissionsError = func(_ *state.State, ctx *Context, perr *BotPermissionsError) error { if perr.Missing.Has(discord.PermissionSendMessages) { return nil } e := shared.ErrorEmbedTemplate(ctx.Localizer) e.Description = perr.Description(ctx.Localizer) if !perr.IsSinglePermission() { permsName, err := ctx.Localize(botPermissionsMissingPermissionsFieldName) if err != nil { return err } e.Fields = append(e.Fields, discord.EmbedField{ Name: permsName, Value: perr.PermissionList(ctx.Localizer), }) } _, err := ctx.ReplyEmbeds(e) return err }
var HandleChannelTypeError = func(s *state.State, ctx *Context, cerr *ChannelTypeError) error { e := shared.ErrorEmbedTemplate(ctx.Localizer) e.Description = cerr.Description(ctx.Localizer) _, err := ctx.ReplyEmbeds(e) return err }
var HandleRestrictionError = func(s *state.State, ctx *Context, rerr *RestrictionError) error { desc, err := rerr.Description(ctx.Localizer) if err != nil { return err } e := shared.ErrorEmbedTemplate(ctx.Localizer) e.Description = desc if err != nil { return err } _, err = ctx.ReplyEmbeds(e) return err }
var HandleThrottlingError = func(s *state.State, ctx *Context, terr *ThrottlingError) error { desc, err := terr.Description(ctx.Localizer) if err != nil { return err } e := shared.InfoEmbedTemplate(ctx.Localizer) e.Description = desc _, err = ctx.ReplyEmbeds(e) return err }
Functions ¶
This section is empty.
Types ¶
type ArgConfig ¶
type ArgConfig interface { // GetRequiredArgs returns the required arguments of the command. GetRequiredArgs() []RequiredArg // GetOptionalArgs returns the optional arguments of the command. GetOptionalArgs() []OptionalArg // IsVariadic returns whether the last argument is variadic, i.e. that // it may be specified multiple times. IsVariadic() bool // GetFlags returns the flags of the command. GetFlags() []Flag }
ArgConfig is the abstraction of the commands argument and flag configuration.
Default implementations can be found in impl/arg.
type ArgParser ¶
type ArgParser interface { // Parse parses the passed arguments and stores them in the passed // *plugin.Context. // args is the trimmed message, with prefix and command stripped. Parse(args string, argConfig ArgConfig, s *state.State, ctx *Context) error // FormatArgs formats the passed arguments and flags so that they would // present a valid input for the passed ArgConfig by properly escaping // and delimiting the individual arguments and flags. // // It is guaranteed that the passed args and flags are valid in // themselves, i.e. that they fulfil the requirements defined by their // config. // // See package arg for example implementations. FormatArgs(argConfig ArgConfig, args []string, flags map[string]string) string // FormatUsage formats the passed arguments and flags so that they are // properly separated. // It should ignore the need for escapes, as the produced output is // solely intended to be used for usage illustrations such as // <Required Argument 1>, <Required Argument 2>, [Optional Argument 1] // The above output would be produced if the args slice contained // {"<Required Argument 1>", "<Required Argument 2>", // "[Optional Argument 1"} and the ArgParser uses arg.DelimiterParser. // // The passed args must always correspond to the arguments specified // in the passed ArgConfig, which implementing parsers can use if they // need to infer further information. FormatUsage(argConfig ArgConfig, args []string) string // FormatFlag formats the passed name of a flag as it would be required // if using that flag. // For example "my-flag" could become "-my-flag" if using a // shellword-like flag notation. FormatFlag(name string) string }
ArgParser is the abstraction of a parser that uses the information provided by the ArgConfig to parse the arguments and flags supplied to a command.
Every bot instance defines a global ArgParser that can be overridden by the individual commands.
type ArgType ¶
type ArgType interface { // GetName returns the name of the type. // The name should be a noun. GetName(*i18n.Localizer) string // GetDescription returns the description of the type. GetDescription(*i18n.Localizer) string // Parse parses the argument or flag using the passed Context. // // The first return value must always be of the same type. Parse(s *state.State, ctx *ParseContext) (interface{}, error) // GetDefault returns the default value for the type. // See Flag.Default or OptionalArg.Default for more info. // // It must return a value that is of the type returned by Parse. GetDefault() interface{} }
ArgType contains information about a flag or arg type. The returned name and description must be the same for all arguments of the guild.
type Args ¶
type Args []interface{}
Args are the parsed arguments of a command.
func (Args) Command ¶
func (a Args) Command(i int) *ResolvedCommand
Command returns the argument with the passed index as *ResolvedCommand.
func (Args) Commands ¶
func (a Args) Commands(i int) []*ResolvedCommand
Commands returns the argument with the passed index as []*ResolvedCommand.
func (Args) Module ¶
func (a Args) Module(i int) *ResolvedModule
Module returns the argument with the passed index as *RegisteredRegexp.
func (Args) Modules ¶
func (a Args) Modules(i int) []*ResolvedModule
Modules returns the argument with the passed index as []*ResolvedModule.
type ArgumentError ¶
type ArgumentError struct {
// contains filtered or unexported fields
}
ArgumentError is the error used if an argument or flag a user supplied is invalid.
func NewArgumentError ¶
func NewArgumentError(description string) *ArgumentError
NewArgumentError returns a new *ArgumentError with the passed description. The description mustn't be empty for this error to be handled properly.
func NewArgumentErrorl ¶
func NewArgumentErrorl(description *i18n.Config) *ArgumentError
NewArgumentErrorl returns a new *ArgumentError using the passed *i18n.Config to generate a description.
func (*ArgumentError) Description ¶
func (e *ArgumentError) Description(l *i18n.Localizer) (string, error)
Description returns the description of the error and localizes it, if possible.
func (*ArgumentError) Error ¶
func (e *ArgumentError) Error() string
type BotPermissionsError ¶
type BotPermissionsError struct { // Missing are the missing permissions. Missing discord.Permissions }
BotPermissionsError is the error returned if the bot does not have sufficient permissions to execute a command.
func NewBotPermissionsError ¶
func NewBotPermissionsError(missing discord.Permissions) *BotPermissionsError
NewBotPermissionsError creates a new *BotPermissionsError with the passed missing permissions.
If the missing permissions contains discord.PermissionAdministrator, all other permissions will be discarded, as they are included in Administrator.
If missing is 0 or invalid, a generic error message will be used.
func (*BotPermissionsError) Description ¶
func (e *BotPermissionsError) Description(l *i18n.Localizer) (desc string)
Description returns the description of the error and localizes it, if possible. Note that if IsSinglePermission returns true, the description will already contain the missing permissions, which otherwise would need to be retrieved via PermissionList.
func (*BotPermissionsError) Error ¶
func (e *BotPermissionsError) Error() string
func (*BotPermissionsError) Handle ¶
func (e *BotPermissionsError) Handle(s *state.State, ctx *Context) error
Handle handles the BotPermissionsError. By default, it sends an error Embed stating the missing permissions.
func (*BotPermissionsError) Is ¶
func (e *BotPermissionsError) Is(target error) bool
func (*BotPermissionsError) IsSinglePermission ¶
func (e *BotPermissionsError) IsSinglePermission() bool
IsSinglePermission checks if only a single permission is missing.
func (*BotPermissionsError) PermissionList ¶
func (e *BotPermissionsError) PermissionList(l *i18n.Localizer) string
PermissionList returns a written bullet point list of the missing permissions, as used if multiple permissions are missing.
type ChannelTypeError ¶
type ChannelTypeError struct { // Allowed are the plugin.ChannelTypes that the command supports. Allowed ChannelTypes }
ChannelTypeError is the error returned if a command is invoked in a channel that is not supported by that command.
func NewChannelTypeError ¶
func NewChannelTypeError(allowed ChannelTypes) *ChannelTypeError
NewChannelTypeError creates a new *ChannelTypeError with the passed allowed plugin.ChannelTypes.
func (*ChannelTypeError) Description ¶
func (e *ChannelTypeError) Description(l *i18n.Localizer) (desc string)
Description returns the description containing the types of channels this command may be used in.
func (*ChannelTypeError) Error ¶
func (e *ChannelTypeError) Error() string
func (*ChannelTypeError) Handle ¶
func (e *ChannelTypeError) Handle(s *state.State, ctx *Context) error
Handle handles the ChannelTypeError. By default, it sends an error message stating the allowed channel types.
func (*ChannelTypeError) Is ¶
func (e *ChannelTypeError) Is(target error) bool
type ChannelTypes ¶
type ChannelTypes uint8
ChannelTypes is an enum used to specify in which channel types the command may be executed. It is bit-shifted to allow for combinations of different channel types.
func (ChannelTypes) Check ¶
func (t ChannelTypes) Check(ctx *Context) (bool, error)
Check checks if the ChannelTypes match the channel type of the invoking channel. It tries to avoid a call to Context.Channel.
func (ChannelTypes) Has ¶
func (t ChannelTypes) Has(target discord.ChannelType) bool
Has checks if the passed discord.ChannelType is found in the ChannelTypes.
func (ChannelTypes) String ¶
func (t ChannelTypes) String() string
type Command ¶
type Command interface { CommandMeta // Invoke calls the command. // The first return value is the reply sent to the user in the channel // they invoked the command in. // // Possible first return values are: // • uint, uint8, uint16, uint32, uint64 // • int, int8, int16, int32, int64 // • float32, float64 // • string // • discord.Embed, *discord.Embed // • *msgbuilder.Builder // • api.SendMessageData // • i18n.Term // • *i18n.Config // • any type implementing Reply // • nil for no reply // // All other values will be captured through a *bot.ReplyTypeError. // // Error Handling // // If Invoke returns an error it will be handed down the middleware // chain until it reaches the bot's ErrorHandler. // // Panic Handling // // Similarly, if Invoke panics the panic will be handled by the // PanicHandler of the executing bot. Invoke(s *state.State, ctx *Context) (interface{}, error) }
Command is the abstraction of a command.
Defaults for simple commands can be found in impl/command.
type CommandMeta ¶
type CommandMeta interface { // GetName gets the name of the command. // It may not contain whitespace or dots. GetName() string // GetAliases returns the optional aliases of the command.\ // They may not contain whitespace or dots. GetAliases() []string // GetShortDescription returns an optional short description // of the command. GetShortDescription(l *i18n.Localizer) string // GetLongDescription returns an optional long description of the // command. GetLongDescription(l *i18n.Localizer) string // GetArgs returns the ArgConfig of the command. // // If this is nil, the command will accept no arguments and flags. GetArgs() ArgConfig // GetArgParser returns the optional custom ArgParser of the command. GetArgParser() ArgParser // GetExampleArgs returns optional example arguments of the command. GetExampleArgs(l *i18n.Localizer) ExampleArgs // IsHidden specifies whether this command will be hidden in the help // page. IsHidden() bool // GetChannelTypes returns the ChannelTypes this command may be invoked // in. // If this is 0, AllChannels will be used. GetChannelTypes() ChannelTypes // GetBotPermissions gets the permissions the bot needs to execute this // command. // If the bot lacks one ore more permissions command execution will // stop with an errors.InsufficientPermissionsError. // // Note that that direct messages may also pass this, if the passed // permissions only require permutil.DMPermissions. GetBotPermissions() discord.Permissions // IsRestricted checks if the user is restricted from using the // command. // // If they are restricted, a *plugin.RestrictionError should be // returned. IsRestricted(s *state.State, ctx *Context) error // GetThrottler returns the Throttler for the command. GetThrottler() Throttler }
CommandMeta is the abstraction of the Command's meta data.
Default implementations can be found in impl/command.
type Context ¶
type Context struct { // Message is the invoking message. discord.Message // Member is the invoking member, or nil if the command was invoked in a // direct message. *discord.Member // Base is the *event.Base of the MessageCreateEvent or MessageUpdateEvent // that triggered the invoke. *event.Base // Localizer is the localizer set to the guild's or user's language. *i18n.Localizer // InvokeIndex is the starting index of the invoke as found in Content. // The invoke ends at ArgsIndex-1 and is trailed by whitespace (' ', '\n'). InvokeIndex int // ArgsIndex is the starting index of the argument as found in Content. ArgsIndex int // Args contains the arguments supplied to the bot. // They are guaranteed to be valid and parsed according to the type spec. Args Args // Flags contains the flags supplied to the bot. // They are guaranteed to be valid and parsed according to the type spec. Flags Flags // InvokedCommand is the ResolvedCommand that is being invoked. InvokedCommand ResolvedCommand // Prefixes contains the prefixes of the bot as defined for the invoking // guild or user. // It does not include the bot's mention, which is always a valid // prefix. // It may be empty, in which case the command was invoked using the bot's // mention. // // Note that direct messages do not require prefixes. // However, the bot's mention or any other prefix returned by the bot's // bot.SettingsProvider (as stored in this variable), will be stripped if // the message starts with such. Prefixes []string // BotOwnerIDs contains the ids of the bot owners, as defined in the bot's // bot.Options. BotOwnerIDs []discord.UserID // Replier is the interface used to send replies to a command. // // Defaults to replier.WrapState, as found in impl/replier. Replier Replier // Provider is an embedded interface that provides access to the commands // and Modules of the Bot, as well as the runtime commands and modules // for the guild. Provider // ErrorHandler is an embedded interface that provides error handling // capabilities to the command. ErrorHandler // DiscordDataProvider is an embedded interface that gives direct access to // common data types needed during execution. // Its asynchronous methods are supplemented by blocking methods provided // by the context. DiscordDataProvider }
Context contains context information about a command.
func (*Context) Edit ¶
func (ctx *Context) Edit(messageID discord.MessageID, content ...interface{}) (*discord.Message, error)
Edit edits the message with the passed id in the invoking channel. The message will be formatted as fmt.Sprint(content...).
func (*Context) EditDM ¶
func (ctx *Context) EditDM(messageID discord.MessageID, content ...interface{}) (*discord.Message, error)
EditDM edits the message with the passed id in the direct message channel with the invoking user. The message will be formatted as fmt.Sprint(content...).
func (*Context) EditEmbeds ¶
func (ctx *Context) EditEmbeds(messageID discord.MessageID, embeds ...discord.Embed) (*discord.Message, error)
EditEmbeds replaces the embeds of the message with the passed id in the invoking channel.
func (*Context) EditEmbedsDM ¶
func (ctx *Context) EditEmbedsDM(messageID discord.MessageID, embeds ...discord.Embed) (*discord.Message, error)
EditEmbedsDM replaces the embeds of the message with the passed id in the invoking channel.
func (*Context) EditMessage ¶
func (ctx *Context) EditMessage(messageID discord.MessageID, data api.EditMessageData) (*discord.Message, error)
EditMessage sends the passed api.EditMessageData to the channel the command was originally sent in.
func (*Context) EditMessageDM ¶
func (ctx *Context) EditMessageDM(messageID discord.MessageID, data api.EditMessageData) (*discord.Message, error)
EditMessageDM sends the passed api.EditMessageData to the direct message channel with the invoking user.
func (*Context) Editf ¶
func (ctx *Context) Editf(messageID discord.MessageID, format string, a ...interface{}) (*discord.Message, error)
Editf edits the message with the passed id in the invoking channel. The message will be formatted as fmt.Sprintf(format, a...).
func (*Context) EditfDM ¶
func (ctx *Context) EditfDM(messageID discord.MessageID, format string, a ...interface{}) (*discord.Message, error)
EditfDM edits the message with the passed id in the direct message channel with the invoking user. The message will be formatted as fmt.Sprintf(format, a...).
func (*Context) Editl ¶
Editl edits the message with passed id in the invoking channel, by replacing it with the text generated from the passed *i18n.Config.
func (*Context) EditlDM ¶
EditlDM edits the message with passed id in the direct message channel with the invoking user, by replacing it with the text generated from the passed *i18n.Config.
func (*Context) EditltDM ¶
EditltDM edits the message with the passed id in the direct message channel with the invoking user, by replacing it with the text generated from the passed i18n.Term.
func (*Context) IsBotOwner ¶
IsBotOwner checks if the invoking user is a bot owner.
func (*Context) ParentChannel ¶
ParentChannel returns the parent *discord.Channel the command was invoked in.
func (*Context) RawInvoke ¶
RawInvoke returns the raw invoke stripped of prefix and args as the user typed it.
func (*Context) Reply ¶
Reply replies with the passed message in the channel the command was originally sent in. The message will be formatted as fmt.Sprint(content...).
func (*Context) ReplyDM ¶
ReplyDM replies with the passed message in a direct message to the invoking user. The message will be formatted as fmt.Sprint(content...).
func (*Context) ReplyEmbeds ¶
ReplyEmbeds replies with the passed discord.Embeds in the channel the command was originally sent in.
func (*Context) ReplyEmbedsDM ¶
ReplyEmbedsDM replies with the passed discord.Embeds in a direct message to the invoking user.
func (*Context) ReplyMessage ¶
ReplyMessage sends the passed api.SendMessageData to the channel the command was originally sent in.
func (*Context) ReplyMessageDM ¶
ReplyMessageDM sends the passed api.SendMessageData in a direct message to the invoking user.
func (*Context) Replyf ¶
Replyf replies with the passed message in the channel the command was originally sent in. The message will be formatted as fmt.Sprintf(format, a...).
func (*Context) ReplyfDM ¶
ReplyfDM replies with the passed message in the channel the command was originally sent in. The message will be formatted as fmt.Sprintf(format, a...).
func (*Context) Replyl ¶
Replyl replies with the message generated from the passed *i18n.Config in the channel the command was originally sent in.
func (*Context) ReplylDM ¶
ReplylDM replies with the message translated from the passed *i18n.Config in a direct message to the invoking user.
func (*Context) Self ¶
Self returns the *discord.Member that belongs to the bot. It will return (nil, nil) if the command was not invoked in a guild.
func (*Context) SelfPermissions ¶
func (ctx *Context) SelfPermissions() (discord.Permissions, error)
SelfPermissions returns the discord.Permissions the bot has in the invoking channel. If the command is executed in a direct message, permutil.DMPermissions will be returned instead.
func (*Context) UsedPrefix ¶
UsedPrefix returns the prefix used to invoke the command.
func (*Context) UserPermissions ¶
func (ctx *Context) UserPermissions() (discord.Permissions, error)
UserPermissions returns the permissions of the invoking user in the channel. If this command is executed in a direct message, permutil.DMPermissions will be returned instead.
type DiscordDataProvider ¶
type DiscordDataProvider interface { // GuildAsync returns a callback returning guild the message was sent // in. // If the command was invoked in a private channel, Guild will return // (nil, nil). GuildAsync() func() (*discord.Guild, error) // ChannelAsync returns a callback returning the Channel the message // was sent in. ChannelAsync() func() (*discord.Channel, error) // ParentChannelAsync returns a callback returning the parent of the // Channel the message was sent in. ParentChannelAsync() func() (*discord.Channel, error) // SelfAsync returns a callback returning the member object of the bot // in the calling guild. // If the command was used in a private channel, SelfAsync will return // (nil, nil). SelfAsync() func() (*discord.Member, error) }
DiscordDataProvider is an embeddable interface used to extend a Context with additional information.
type ErrorHandler ¶
type ErrorHandler interface { // HandleError hands the error to the bot's error handler. HandleError(err error) // HandleErrorSilently wraps the error using errors.Silent and hands it // to the bot's error handler. HandleErrorSilently(err error) }
ErrorHandler is an embedded interface used to provide error handling capabilities through a Context.
type ExampleArgs ¶
type ExampleArgs []struct { // Args contains the example arguments. Args []string // Flags is a map of exemplary flags. Flags map[string]string }
ExampleArgs is a struct containing a set of exemplary arguments and flags. They are formatted using their ArgParser's FormatArgs method.
func (ExampleArgs) BaseType ¶
func (a ExampleArgs) BaseType(*i18n.Localizer) ExampleArgs
type Flag ¶
type Flag interface { // GetName returns the name of the flag. GetName() string // GetAliases returns the optional aliases of the flag. GetAliases() []string // GetType returns information about the type of the flag. GetType() ArgType // GetDefault is the default value of the flag. // // If Default is (interface{})(nil), ArgType.Default() will be used. GetDefault() interface{} // GetDescription returns the optional description of the flag. GetDescription(*i18n.Localizer) string // IsMulti returns whether the flag may be used multiple times. IsMulti() bool }
Flag contains information about a flag.
type Flags ¶
type Flags map[string]interface{}
Flags are the parsed flags of a command.
func (Flags) Command ¶
func (f Flags) Command(name string) *ResolvedCommand
Command returns the flag with the passed name as *ResolvedCommand.
func (Flags) Commands ¶
func (f Flags) Commands(name string) []*ResolvedCommand
Commands returns the flag with the passed name as []*ResolvedCommand.
func (Flags) Module ¶
func (f Flags) Module(name string) *ResolvedModule
Module returns the flag with the passed name as *ResolvedModule.
func (Flags) Modules ¶
func (f Flags) Modules(name string) []*ResolvedModule
Modules returns the flag with the passed name as []*ResolvedModule.
type ID ¶
type ID string
ID is the unique identifier of a plugin. The root/base is '.'. All plugins are dot-separated, e.g. '.mod.ban'.
const RootID ID = "."
RootID is the ID representing root, i.e. the parent of all plugins.
func NewIDFromInvoke ¶
NewIDFromInvoke creates a new ID from the passed invoke.
func (ID) All ¶
All returns a slice of all parents including root and the identifier itself starting with root.
If the ID is invalid, All returns nil.
func (ID) AsInvoke ¶
AsInvoke returns the identifier as a prefixless command invoke.
Returns "" if the ID is root or invalid.
Example ¶
var id ID = ".mod.ban" fmt.Println(id.AsInvoke())
Output: mod ban
func (ID) IsParentOf ¶
IsParentOf checks if the this ID is a parent of target.
func (ID) NumParents ¶
NumParents returns the number of parents the plugin has.
Returns a negative number, if the ID is invalid.
type Module ¶
type Module interface { ModuleMeta // GetCommands returns the subcommands of the module. GetCommands() []Command // GetModules returns the submodules of the module. GetModules() []Module }
Module is the abstraction of a module.
A default for a simple module can be found in impl/module.
type ModuleMeta ¶
type ModuleMeta interface { // GetName returns the name of the module. // It may not contain whitespace or dots. GetName() string // GetShortDescription returns an optional one-sentence description of // the module. GetShortDescription(l *i18n.Localizer) string // GetLongDescription returns an option long description of the module. GetLongDescription(l *i18n.Localizer) string }
ModuleMeta is the abstraction of the Module's meta data.
Default implementations can be found in impl/module.
type OptionalArg ¶
type OptionalArg interface { // GetName returns the name of the argument. GetName(*i18n.Localizer) string // GetType returns the ArgType of the argument. GetType() ArgType // GetDefault is the default value of the argument. // // If Default is (interface{})(nil), ArgType.Default() will be used. GetDefault() interface{} // GetDescription returns the optional description of the argument. GetDescription(*i18n.Localizer) string }
OptionalArg is the interface used to access information about a single optional argument.
type ParseContext ¶
type ParseContext struct { *Context // Raw is the raw argument or flag. Raw string // Name is the name of the argument or flag. // It includes possible prefixes such as minuses. Name string // UsedName is the alias of the flag the Context represents. // If the name of the flag was used, or the context represents an // argument, UsedName will be equal to Name. // It includes possible prefixes such as minuses. UsedName string // Index contains the index of the argument, if the context represents // an argument. Index int // Kind specifies whether a flag or an argument is being parsed. Kind ArgKind }
ParseContext is the context passed to ArgType.Parse.
type Provider ¶
type Provider interface { // PluginSources returns a slice of Sources containing all commands and // modules of the bot. // PluginSources()[0] contains the built-in plugins of the bot, and is // named BuiltInSource. // // To check if any runtime plugin sources returned an error, call // UnavailablePluginSources. PluginSources() []Source // Commands returns all top-level commands sorted in ascending order by // name. // // To check if any of the plugin sources returned an error, call // UnavailablePluginProviders. // If that is the case, the data returned might be incomplete. Commands() []ResolvedCommand // Modules returns all top-level modules sorted in ascending order by // name. // // To check if any of the plugin sources returned an error, call // UnavailablePluginProviders. // If that is the case, the data returned might be incomplete. Modules() []ResolvedModule // Command returns the ResolvedCommand with the passed ID. // // Note that Identifiers may only consist of the command's name, not // their alias. // // It will return nil if no command matching the identifier was found. // // To check if any of the runtime plugin sources returned an error, // call UnavailablePluginProviders. Command(ID) ResolvedCommand // Module returns the ResolvedModule with the passed ID. // // It will return nil if no module matching the identifier was found. // // To check if any of the plugin sources returned an error, call // UnavailablePluginProviders. // If that is the case, the module's description might not be available // or differ from the description that is used if all plugin sources // function properly. Module(ID) ResolvedModule // FindCommand returns the ResolvedCommand with the passed invoke. // // It will return nil if no command matching the passed invoke was // found. // // To check if any of the plugin sources returned an error, call // UnavailablePluginProviders. FindCommand(invoke string) ResolvedCommand // FindCommandWithArgs is the same as FindCommand, but allows invoke // to contain trailing arguments. // // If a command is found, it is returned alongside the arguments. // Otherwise, (nil, "") will be returned. FindCommandWithArgs(invoke string) (cmd ResolvedCommand, args string) // FindModule returns the ResolvedModule with the passed invoke. // // It will return nil if no module matching the passed invoke was // found. // // To check if any of the plugin sources returned an error, call // UnavailablePluginProviders. // If that is the case, the module's description might not be available // or differ from the description that is used if all plugin sources // function properly. FindModule(invoke string) ResolvedModule // sources. // If no runtime plugins were requested yet, it will request them and // return the list of unavailable ones. // // If the length of the returned slice is 0, all plugin sources are // available. UnavailablePluginSources() []UnavailableSource }
Provider provides copies of the plugins of the bot. The returned slices can therefore be freely modified.
Copies are only created on call of one of the methods.
type Replier ¶
type Replier interface { // Reply sends a message in the invoking channel. Reply(ctx *Context, data api.SendMessageData) (*discord.Message, error) // ReplyDM sends the passed message in a direct message to the user. ReplyDM(ctx *Context, data api.SendMessageData) (*discord.Message, error) // Edit edits a message in the invoking channel Edit(ctx *Context, messageID discord.MessageID, data api.EditMessageData) (*discord.Message, error) // EditDM edits a message sent in the direct message channel with the // invoking user. EditDM(ctx *Context, messageID discord.MessageID, data api.EditMessageData) (*discord.Message, error) }
Replier is the interface used to send replies to a command.
This allows the user to define special behavior for commands, such as the ability to delete answers after a set amount of time, after the bot responds.
type RequiredArg ¶
type RequiredArg interface { // GetName returns the name of the argument. GetName(*i18n.Localizer) string // GetType returns the ArgType of the argument. GetType() ArgType // GetDescription returns the optional description of the argument. GetDescription(*i18n.Localizer) string }
RequiredArg is the interface used to access information about a single required argument.
type ResolvedCommand ¶
type ResolvedCommand interface { // Parent returns the parent of this command. // The returned ResolvedModule may not consists of all modules that share // the same namespace, if some plugin sources are unavailable. // Check PluginProvider.UnavailableProviders() to check if that is the // case. // // In any case the module will contain the built-in module and the module // that provides the command. Parent() ResolvedModule // SourceName returns the name of the plugin source that provides the // command. // // If the command is built-in, ProviderName will be set to BuiltInSource. SourceName() string // Source returns the original Command this command is based on. Source() Command // SourceParents returns the original parent Modules in ascending order // from the most distant to the closest parent. // // If the command is top-level, SourceParents will return nil. SourceParents() []Module // ID returns the identifier of the command. ID() ID // Name returns the name of the command. Name() string // Aliases returns the optional aliases of the command. Aliases() []string // ShortDescription returns an optional brief description of the command. ShortDescription(*i18n.Localizer) string // LongDescription returns an optional long description of the command. // // If the command only provides a short description, it will be returned // instead. LongDescription(*i18n.Localizer) string // Args returns the argument configuration of the command. // // If this is nil, the command accepts no arguments. Args() ArgConfig // ArgParser returns ArgParser of the command. // In contrast to Command's GetArgParser equivalent, ArgParser will return // the global ArgParser if the command did not define one. ArgParser() ArgParser // ExampleArgs returns optional example arguments of the command. ExampleArgs(*i18n.Localizer) ExampleArgs // Examples returns the command's example arguments prefixed with their // invoke. // Invoke and example arguments are separated by a space. Examples(*i18n.Localizer) []string // IsHidden returns whether to show this command in the help. IsHidden() bool // ChannelTypes are the ChannelTypes this command can be run in. // // If the command itself did not define some, ChannelTypes will be // AllChannels. ChannelTypes() ChannelTypes // BotPermissions returns the permissions the command needs to execute. BotPermissions() discord.Permissions // IsRestricted checks whether or not this command is restricted. // // If the RestrictionFunc returns an error that implements // RestrictionErrorWrapper, it will be wrapped accordingly. IsRestricted(*state.State, *Context) error // Throttler returns the Throttler of this command. Throttler() Throttler // Invoke invokes the command. // See Command.Invoke for more details. Invoke(*state.State, *Context) (interface{}, error) }
ResolvedCommand is a resolved command as returned by a Provider.
type ResolvedModule ¶
type ResolvedModule interface { // Parent is the parent of this module. // If the module is top-level Parent will be nil. Parent() ResolvedModule // Sources contains the Modules this module is based upon. // If the module is top-level, this will be empty. Sources() []SourceModule // ID is the identifier of the module. ID() ID // Name is the name of the module. Name() string // ShortDescription returns an optional one-sentence description of the // module. ShortDescription(l *i18n.Localizer) string // LongDescription returns an option thorough description of the // module. // // If the module only provides a short description, it will be returned // instead. LongDescription(l *i18n.Localizer) string // IsHidden specifies if all Sources are hidden. // A source module is considered hidden if all of it's commands and // modules are hidden as well. IsHidden() bool // Commands are the subcommands of the module. // They are sorted in ascending order by name. Commands() []ResolvedCommand // Modules are the submodules of the module. // They are sorted in ascending order by name. Modules() []ResolvedModule // FindCommand finds the command with the given name or alias inside // this module. // // If there is no command with the given name or alias, nil will be // returned. FindCommand(name string) ResolvedCommand // FindModule finds the module with the given name inside the module. // // If there is no module with the given name, nil will be returned. FindModule(name string) ResolvedModule }
ResolvedModule is a resolved module as returned by a Provider. In contrast to the regular Module abstraction, ResolvedModule's plugins reflect the plugins provided by all modules with the same ID, i.e. a plugin with the same name provided through different bot.PluginProvider.
type RestrictionError ¶
type RestrictionError struct { // Fatal defines if the RestrictionError is fatal. // A RestrictionError is fatal, if the user cannot prevent the error from // occurring again, without the action of another user, e.g. getting a // permission. Fatal bool // contains filtered or unexported fields }
RestrictionError is the error returned if a restriction fails. It contains a description stating the conditions that need to be fulfilled for a command to execute.
Note that the description might contain mentions, which are intended not to ping anyone, e.g. "You need @role to use this command.". This means you should use allowed mentions if you are custom handling this error and not using an Embed, which suppresses mentions by default.
func NewFatalRestrictionError ¶
func NewFatalRestrictionError(description string) *RestrictionError
NewFatalRestrictionError creates a new fatal *RestrictionError with the passed description.
func NewFatalRestrictionErrorl ¶
func NewFatalRestrictionErrorl(description *i18n.Config) *RestrictionError
NewFatalRestrictionErrorl creates a new fatal *RestrictionError using the message generated from the passed *i18n.Config as description.
func NewRestrictionError ¶
func NewRestrictionError(description string) *RestrictionError
NewRestrictionError creates a new *RestrictionError with the passed description.
func NewRestrictionErrorl ¶
func NewRestrictionErrorl(description *i18n.Config) *RestrictionError
NewRestrictionErrorl creates a new *RestrictionError using the message generated from the passed *i18n.Config as description.
func (*RestrictionError) Description ¶
func (e *RestrictionError) Description(l *i18n.Localizer) (string, error)
Description returns the description of the error and localizes it, if possible.
func (*RestrictionError) Error ¶
func (e *RestrictionError) Error() string
type RestrictionFunc ¶
RestrictionFunc is the function used to determine if a user is authorized to use a command or module.
Implementations can be found in impl/restriction.
type Source ¶
type Source struct { // Name is the name of the source that provides these plugins. Name string // Commands are the top-level commands of the repository. Commands []Command // Modules are the top-level modules of the repository. Modules []Module }
Source is the struct returned by Provider.PluginSources. It contains the top-level plugins of a single repository.
type SourceModule ¶
type SourceModule struct { // SourceName is the name of the plugin source that // provided the module. SourceName string // Modules contains the parents of the ResolvedModule. // They are sorted in ascending order from the most distant to the // closest parent. Modules []Module }
SourceModule contains the parent Modules of a ResolvedModule.
type Throttler ¶
type Throttler interface { // Check checks if the command may be executed and increments the counter // if so. // It returns non-nil, nil if the command may be executed and nil, non-nil // if the command is throttled. // The returned error should be of type *plugin.ThrottlingError. // // If the returned function gets called, the command invoke should not be // counted, e.g. if a Command returns with an error. // This will be the case, if the ThrottlerCancelChecker function in the // bot's Options returns true. // // Note that the Throttler will be called before non-default bot // middlewares are run. // Therefore, only context data set through event handlers will be // available. Check(*state.State, *Context) (func(), error) }
Throttler is used to create cooldowns for commands.
Implementations can be found in impl/throttler.
type ThrottlingError ¶
type ThrottlingError struct {
// contains filtered or unexported fields
}
ThrottlingError is the error returned if a command gets throttled. It contains a description about when the command will become available again.
func NewThrottlingError ¶
func NewThrottlingError(description string) *ThrottlingError
NewThrottlingError creates a new *ThrottlingError with the passed description.
func NewThrottlingErrorl ¶
func NewThrottlingErrorl(description *i18n.Config) *ThrottlingError
NewThrottlingErrorl creates a new *ThrottlingError using the message generated from the passed *i18n.Config as description.
func (*ThrottlingError) Description ¶
func (e *ThrottlingError) Description(l *i18n.Localizer) (string, error)
Description returns the description of the error and localizes it, if possible.
func (*ThrottlingError) Error ¶
func (e *ThrottlingError) Error() string
type UnavailableSource ¶
UnavailableSource contains information about an unavailable plugin source.