Documentation
¶
Overview ¶
Sapphire is a complete discord bot framework for Golang with discordgo
Index ¶
- Constants
- Variables
- func CommandHandlerMonitor(bot *Bot, ctx *MonitorContext)
- func Escape(input string) string
- func HumanizeUsage(usage string) string
- type Argument
- func (arg *Argument) AsBool() bool
- func (arg *Argument) AsFloat() float64
- func (arg *Argument) AsGuild() *discordgo.Guild
- func (arg *Argument) AsInt() int
- func (arg *Argument) AsMember() *discordgo.Member
- func (arg *Argument) AsMessage() *discordgo.Message
- func (arg *Argument) AsRole() *discordgo.Role
- func (arg *Argument) AsString() string
- func (arg *Argument) AsUser() *discordgo.User
- func (arg *Argument) IsProvided() bool
- type Bot
- func (bot *Bot) AddCommand(cmd *Command) *Bot
- func (bot *Bot) AddLanguage(lang *Language) *Bot
- func (bot *Bot) AddMonitor(m *Monitor) *Bot
- func (bot *Bot) CheckCooldown(userID, command string, cooldownSec int) (bool, int)
- func (bot *Bot) Connect() error
- func (bot *Bot) GetCommand(name string) *Command
- func (bot *Bot) LoadBuiltins() *Bot
- func (bot *Bot) MustConnect()
- func (bot *Bot) SetDefaultLocale(locale string) *Bot
- func (bot *Bot) SetErrorHandler(fn ErrorHandler) *Bot
- func (bot *Bot) SetInvitePerms(bits int) *Bot
- func (bot *Bot) SetLocaleHandler(handler LocaleHandler) *Bot
- func (bot *Bot) SetMentionPrefix(toggle bool) *Bot
- func (bot *Bot) SetPrefix(prefix string) *Bot
- func (bot *Bot) SetPrefixHandler(prefix PrefixHandler) *Bot
- func (bot *Bot) Wait()
- type Command
- func (c *Command) AddAliases(aliases ...string) *Command
- func (c *Command) Disable() *Command
- func (c *Command) Enable() *Command
- func (c *Command) SetCooldown(cooldown int) *Command
- func (c *Command) SetDescription(description string) *Command
- func (c *Command) SetEditable(toggle bool) *Command
- func (c *Command) SetGuildOnly(toggle bool) *Command
- func (c *Command) SetOwnerOnly(toggle bool) *Command
- func (c *Command) SetUsage(usage string) *Command
- type CommandContext
- func (ctx *CommandContext) Arg(idx int) *Argument
- func (ctx *CommandContext) BuildEmbed(embed *Embed) (*discordgo.Message, error)
- func (ctx *CommandContext) BuildEmbedNoEdit(embed *Embed) (*discordgo.Message, error)
- func (ctx *CommandContext) CodeBlock(lang, content string, args ...interface{}) (*discordgo.Message, error)
- func (ctx *CommandContext) Edit(msg *discordgo.Message, content string, args ...interface{}) (*discordgo.Message, error)
- func (ctx *CommandContext) EditLocale(msg *discordgo.Message, key string, args ...interface{}) (*discordgo.Message, error)
- func (ctx *CommandContext) Error(err interface{}, args ...interface{})
- func (ctx *CommandContext) FetchUser(id string) (*discordgo.User, error)
- func (ctx *CommandContext) Flag(flag string) string
- func (ctx *CommandContext) GetFirstMentionedUser() *discordgo.User
- func (ctx *CommandContext) HasArgs() bool
- func (ctx *CommandContext) HasFlag(flag string) bool
- func (ctx *CommandContext) JoinedArgs(sliced ...int) string
- func (ctx *CommandContext) Member(id string) *discordgo.Member
- func (ctx *CommandContext) ParseArgs() bool
- func (ctx *CommandContext) React(emoji string) error
- func (ctx *CommandContext) Reply(content string, args ...interface{}) (*discordgo.Message, error)
- func (ctx *CommandContext) ReplyEmbed(embed *discordgo.MessageEmbed) (*discordgo.Message, error)
- func (ctx *CommandContext) ReplyEmbedNoEdit(embed *discordgo.MessageEmbed) (*discordgo.Message, error)
- func (ctx *CommandContext) ReplyLocale(key string, args ...interface{}) (*discordgo.Message, error)
- func (ctx *CommandContext) ReplyNoEdit(content string, args ...interface{}) (*discordgo.Message, error)
- func (ctx *CommandContext) SendFile(name string, file io.Reader) (*discordgo.Message, error)
- func (ctx *CommandContext) User(id string) *discordgo.User
- type CommandError
- type CommandHandler
- type Embed
- func (e *Embed) AddField(name, value string) *Embed
- func (e *Embed) AddInlineField(name, value string) *Embed
- func (e *Embed) Build() *discordgo.MessageEmbed
- func (e *Embed) InlineAllFields() *Embed
- func (e *Embed) SetAuthor(args ...string) *Embed
- func (e *Embed) SetColor(clr int) *Embed
- func (e *Embed) SetDescription(description string) *Embed
- func (e *Embed) SetFooter(args ...string) *Embed
- func (e *Embed) SetImage(args ...string) *Embed
- func (e *Embed) SetThumbnail(args ...string) *Embed
- func (e *Embed) SetTitle(name string) *Embed
- func (e *Embed) SetURL(URL string) *Embed
- func (e *Embed) Truncate() *Embed
- func (e *Embed) TruncateDescription() *Embed
- func (e *Embed) TruncateFields() *Embed
- func (e *Embed) TruncateFooter() *Embed
- func (e *Embed) TruncateTitle() *Embed
- type ErrorHandler
- type Language
- type LocaleHandler
- type Monitor
- type MonitorContext
- type MonitorHandler
- type Paginator
- func (p *Paginator) AddPage(fn func(em *Embed) *Embed)
- func (p *Paginator) AddPageString(str string)
- func (p *Paginator) GetIndex() int
- func (p *Paginator) Goto(index int)
- func (p *Paginator) NextPage()
- func (p *Paginator) PreviousPage()
- func (p *Paginator) Run()
- func (p *Paginator) SetFooter()
- func (p *Paginator) SetTemplate(em func() *Embed)
- func (p *Paginator) Stop()
- type Permissions
- type PrefixHandler
- type UsageTag
Constants ¶
const ( EmbedLimitTitle = 256 EmbedLimitDescription = 2048 EmbedLimitFieldValue = 1024 EmbedLimitFieldName = 256 EmbedLimitField = 25 EmbedLimit = 4000 )
Constants for message embed character limits
const ( EmojiLeft = "◀️" // Go left, -1 page. EmojiRight = "▶️" // Go right, +1 page. EmojiFirst = "⏪" // Go to first page. EmojiLast = "⏩" // Go to last page. EmojiStop = "⏹️" // Stop the paginator. )
Emoji constants.
const COLOR = 0x7F139E
COLOR is the color for sapphire's embed colors.
const VERSION = "1.0.0"
VERSION is a constant representing the current version of the framework.
Variables ¶
var ChannelMentionRegex = regexp.MustCompile("^(?:<#)?(\\d{17,19})>?$")
The Regexp used for matching channel mentions.
var English = NewLanguage("en-US").
Set("LOCALE_NO_KEY", "No localization found for the key \"%s\" Please report this to the developers.").
Set("COMMAND_ERROR", "Something went wrong, please try again later.").
Set("COMMAND_PING", "Pong!").
Set("COMMAND_PING_PONG", "Pong! Latency: **%d**ms, API Latency: **%d**ms").
Set("COMMAND_ENABLE_ALREADY", "That command is already enabled!").
Set("COMMAND_DISABLE_ALREADY", "That command is already disabled!").
Set("COMMAND_ENABLE_SUCCESS", "Successfully enabled the command **%s**").
Set("COMMAND_DISABLE_SUCCESS", "Successfully disabled the command **%s**").
Set("COMMAND_NOT_FOUND", "Command '%s' not found.").
Set("COMMAND_INVITE", "To invite me to your server: <%s>").
Set("COMMAND_OWNER_ONLY", "This command is for the bot owner only!").
Set("COMMAND_GUILD_ONLY", "This command can only be used in a server!").
Set("COMMAND_COOLDOWN", "You can use this command again in %d seconds.").
Set("COMMAND_DISABLED", "This command has been disabled globally by the bot owner.")
var HumanizeUsageRegex = regexp.MustCompile("(<|\\[)(\\w+):[^.]+?(\\.\\.\\.)?(>|\\])")
HumanizeUsageRegex is the regexp used for HuamnizeUsage
var MentionRegex = regexp.MustCompile("^(?:<@!?)?(\\d{17,19})>?$")
The Regexp used for matching user mentions.
Functions ¶
func CommandHandlerMonitor ¶
func CommandHandlerMonitor(bot *Bot, ctx *MonitorContext)
This is the builtin monitor responsible for running commands.
func Escape ¶
Escape escapes @everyone/@here mentions by adding an invisible character to avoid the ping.
func HumanizeUsage ¶
HumanizeUsage removes the unneccessary types and shows only the names. e.g <hello:string> <user:user> [rest:int...] => <hello> <user> [rest...]
Types ¶
type Argument ¶
type Argument struct {
// contains filtered or unexported fields
}
Argument represents an argument, it has methods to grab the right type.
func ParseArgument ¶
func ParseArgument(ctx *CommandContext, tag *UsageTag, raw string) (*Argument, error)
Parses the raw argument as specified in tag in context of ctx
func (*Argument) IsProvided ¶
IsProvided checks if this argument is provided, for optional arguments you must use this before casting.
type Bot ¶
type Bot struct { Session *discordgo.Session // The discordgo session. Prefix PrefixHandler // The handler called to get the prefix. (default: !) Language LocaleHandler // The handler called to get the language (default: en-US) Commands map[string]*Command // Map of commands. CommandsRan int // Commands ran. Monitors map[string]*Monitor // Map of monitors. CommandCooldowns map[string]map[string]time.Time CommandEdits map[string]string OwnerID string // Bot owner's ID (default: fetched from application info) InvitePerms int // Permissions bits to use for the invite link. (default: 3072) Languages map[string]*Language // Map of languages. DefaultLocale *Language // Default locale to fallback. (default: en-US) CommandTyping bool // Wether to start typing when a command is being ran. (default: true) ErrorHandler ErrorHandler // The handler to catch panics in monitors (which includes commands). MentionPrefix bool // Wether to allow @mention of the bot to be used as a prefix too. (default: true) Application *discordgo.Application // The bot's application. Uptime time.Time // The time the bot hit ready event. Color int // The color used in builtin commands's embeds. // contains filtered or unexported fields }
Bot represents a bot with sapphire framework features.
func (*Bot) AddCommand ¶
func (*Bot) AddLanguage ¶
AddLanguage adds the specified language.
func (*Bot) AddMonitor ¶
func (*Bot) CheckCooldown ¶
CheckCooldown checks the cooldown for userID for a command the first return is a bool indicating if the user can run the command. The second value is if user can't run then it will be the amount of seconds to wait before being able to. Note this function assumes the user will run the command and will place the user on cooldown if it isn't already.
func (*Bot) GetCommand ¶
GetCommand returns a command by name, it also searches by aliases, returns nil if not found.
func (*Bot) LoadBuiltins ¶
LoadBuiltins loads the default set of builtin command, they are: ping, help, stats, invite, enable, disable, gc Some of the must have commands. (or rather commands that i feel good to have.)
func (*Bot) MustConnect ¶
func (bot *Bot) MustConnect()
MustConnect is like Connect but panics if there is an error.
func (*Bot) SetDefaultLocale ¶
Sets the default locale to fallback when the bot can't find a key in the current locale. Panics if locale isn't registered.
func (*Bot) SetErrorHandler ¶
func (bot *Bot) SetErrorHandler(fn ErrorHandler) *Bot
SetErrorHandler sets the function to handle panics that happens in monitors (which includes commands)
func (*Bot) SetInvitePerms ¶
SetInvitePerms sets the permissions to request for in the bot invite link. The default is 3072 which is [VIEW_CHANNEL, SEND_MESSAGES]
func (*Bot) SetLocaleHandler ¶
func (bot *Bot) SetLocaleHandler(handler LocaleHandler) *Bot
func (*Bot) SetMentionPrefix ¶
SetMentionPrefix toggles the usage of the bot's @mention as a prefix.
func (*Bot) SetPrefix ¶
SetPrefix sets a constant string as the prefix, use SetPrefixHandler if you need dynamic per-guild prefixes.
func (*Bot) SetPrefixHandler ¶
func (bot *Bot) SetPrefixHandler(prefix PrefixHandler) *Bot
SetPrefixHandler sets the prefix handler, the function is responsible to return the right prefix for the command call. Use this for dynamic prefixes, e.g fetch prefix from database.
type Command ¶
type Command struct { Name string // The command's name. (default: required) Aliases []string // Aliases that point to this command. (default: []) Run CommandHandler // The handler that actually runs the command. (default: required) Enabled bool // Wether this command is enabled. (default: true) Description string // The command's brief description. (default: "No Description Provided.") Category string // The category this command belongs to. (default: required) OwnerOnly bool // Wether this command can only be used by the owner. (default: false) GuildOnly bool // Wether this command can only be ran on a guild. (default: false) UsageString string // Usage string for this command. (default: "") Usage []*UsageTag // Parsed usage tags for this command. Cooldown int // Command cooldown in seconds. (default: 0) Editable bool // Wether this command's response will be editable. (default: true) RequiredPermissions int // Permissions the user needs to run this command. (default: 0) BotPermissions int // Permissions the bot needs to perform this command. (default: 0) }
Command represents a command in the sapphire framework.
func NewCommand ¶
func NewCommand(name string, category string, run CommandHandler) *Command
func (*Command) AddAliases ¶
AddAliases adds aliases to this command.
func (*Command) SetCooldown ¶
SetCooldown sets the command's cooldown in seconds.
func (*Command) SetDescription ¶
SetDescription sets the command's description
func (*Command) SetEditable ¶
SetEditable toggles wether this command will be respondable to edits.
func (*Command) SetGuildOnly ¶
SetGuildOnly toggles if this command can only be used on a guild.
func (*Command) SetOwnerOnly ¶
SetOwnerOnly toggles wether the command can only be used by the bot owner.
type CommandContext ¶
type CommandContext struct { Command *Command // The currently executing command. Message *discordgo.Message // The message of this command. Session *discordgo.Session // The discordgo session. Bot *Bot // The sapphire Bot. Channel *discordgo.Channel // The channel this command was ran on. Author *discordgo.User // Alias of Context.Message.Author Args []*Argument // List of arguments. Prefix string // The prefix used to invoke this command. Guild *discordgo.Guild // The guild this command was ran on. Flags map[string]string // Map of flags passed to the command. e.g --flag=yo Locale *Language // The current language. RawArgs []string // The raw args that may not match the usage string. InvokedName string // The name this command was invoked as, this includes the used alias. }
CommandContext represents an execution context of a command.
func (*CommandContext) Arg ¶
func (ctx *CommandContext) Arg(idx int) *Argument
Arg returns the argument at index idx, it returns an empty arg if the index doesn't exist, useful for optional arguments.
func (*CommandContext) BuildEmbed ¶
func (ctx *CommandContext) BuildEmbed(embed *Embed) (*discordgo.Message, error)
BuildEmbed calls ReplyEmbed(embed.Build())
func (*CommandContext) BuildEmbedNoEdit ¶
func (ctx *CommandContext) BuildEmbedNoEdit(embed *Embed) (*discordgo.Message, error)
BuildEmbedNoEdit calls ReplyEmbedNoEdit(embed.Build())
func (*CommandContext) CodeBlock ¶
func (ctx *CommandContext) CodeBlock(lang, content string, args ...interface{}) (*discordgo.Message, error)
func (*CommandContext) Edit ¶
func (ctx *CommandContext) Edit(msg *discordgo.Message, content string, args ...interface{}) (*discordgo.Message, error)
Edit edits msg's content It will call Sprintf() on the content if atleast one vararg is passed.
func (*CommandContext) EditLocale ¶
func (ctx *CommandContext) EditLocale(msg *discordgo.Message, key string, args ...interface{}) (*discordgo.Message, error)
EditLocale edits msg with a localized key
func (*CommandContext) Error ¶
func (ctx *CommandContext) Error(err interface{}, args ...interface{})
Error invokes the bot's error handler, see bot.SetErrorHandler It also replies with a message indicating an unexpected error.
func (*CommandContext) FetchUser ¶
func (ctx *CommandContext) FetchUser(id string) (*discordgo.User, error)
FetchUser searches the cache for the given user id and if not found, attempts to fetch it from the API.
func (*CommandContext) Flag ¶
func (ctx *CommandContext) Flag(flag string) string
Flag returns the value of a commmnd flag, if it is a bool-flag use HasFlag() instead.
func (*CommandContext) GetFirstMentionedUser ¶
func (ctx *CommandContext) GetFirstMentionedUser() *discordgo.User
GetFirstMentionedUser returns the first user mentioned in the message.
func (*CommandContext) HasArgs ¶
func (ctx *CommandContext) HasArgs() bool
HasArgs returns true if there is atleast one argument in the raw args.
func (*CommandContext) HasFlag ¶
func (ctx *CommandContext) HasFlag(flag string) bool
HasFlag returns a bool of wether the flag exists.
func (*CommandContext) JoinedArgs ¶
func (ctx *CommandContext) JoinedArgs(sliced ...int) string
Get the joined arguments as a string If sliced is provided then arguments are sliced by that before joining Examples ["hello", "example", "test"] JoinedArgs() => "hello example test" JoinedArgs(1) => "example test" This uses the raw arguments so arguments of different types are also shown in their raw form. This also means invalid arguments are also included but strings can never be invalid so this is useful for getting the rest strings.
func (*CommandContext) Member ¶
func (ctx *CommandContext) Member(id string) *discordgo.Member
Member gets a member by id from the current guild, returns nil if not found.
func (*CommandContext) ParseArgs ¶
func (ctx *CommandContext) ParseArgs() bool
Parses the raw args and fills in ctx.Args and returns true on success and on failure it replies with the error and returns false This is called in the command handler to process the arguments, it shouldn't be used in normal code It is exported to allow modification of the command handler in your own bot and avoid this line from giving errors.
func (*CommandContext) React ¶
func (ctx *CommandContext) React(emoji string) error
React adds the reaction emoji to the message that triggered the command.
func (*CommandContext) Reply ¶
func (ctx *CommandContext) Reply(content string, args ...interface{}) (*discordgo.Message, error)
Reply replies with a string. It will call Sprintf() on the content if atleast one vararg is passed.
func (*CommandContext) ReplyEmbed ¶
func (ctx *CommandContext) ReplyEmbed(embed *discordgo.MessageEmbed) (*discordgo.Message, error)
ReplyEmbed replies with an embed.
func (*CommandContext) ReplyEmbedNoEdit ¶
func (ctx *CommandContext) ReplyEmbedNoEdit(embed *discordgo.MessageEmbed) (*discordgo.Message, error)
ReplyEmbedNoEdits replies with an embed but not considering the editable option of the command.
func (*CommandContext) ReplyLocale ¶
func (ctx *CommandContext) ReplyLocale(key string, args ...interface{}) (*discordgo.Message, error)
ReplyLocale sends a localized key for the current context's locale.
func (*CommandContext) ReplyNoEdit ¶
func (ctx *CommandContext) ReplyNoEdit(content string, args ...interface{}) (*discordgo.Message, error)
ReplyNoEdit replies with content but does not consider editable option of the command.
type CommandError ¶
type CommandError struct { Err interface{} // The value passed to panic() Context *CommandContext // The context of the command, use this to e.g get the command's name etc. }
CommandError represents a panic that occured during a command execution. You can type assert this in bot.SetErrorHandler's callback to get more context about the error. Implements the error interface
func (*CommandError) Error ¶
func (err *CommandError) Error() string
Error implements the error interface, it simply calls fmt.Sprint on the panicked value.
type CommandHandler ¶
type CommandHandler func(ctx *CommandContext)
type Embed ¶
type Embed struct {
*discordgo.MessageEmbed
}
Embed ...
func (*Embed) AddInlineField ¶
func (*Embed) Build ¶
func (e *Embed) Build() *discordgo.MessageEmbed
func (*Embed) InlineAllFields ¶
InlineAllFields sets all fields in the embed to be inline
func (*Embed) SetDescription ¶
SetDescription [desc]
func (*Embed) TruncateDescription ¶
TruncateDescription ...
func (*Embed) TruncateFields ¶
TruncateFields truncates fields that are too long
type ErrorHandler ¶
type ErrorHandler func(b *Bot, err interface{})
type Language ¶
func NewLanguage ¶
NewLanguage creates a new language with the specified name.
func (*Language) GetDefault ¶
type Monitor ¶
type Monitor struct { Name string // Name of the monitor Enabled bool // Wether the monitor is enabled. Run MonitorHandler // The actual handler function. GuildOnly bool // Wether this monitor should only run on guilds. (default: false) IgnoreWebhooks bool // Wether to ignore messages sent by webhooks (default: true) IgnoreBots bool // Wether to ignore messages sent by bots (default: true) IgnoreSelf bool // Wether to ignore the bot itself. (default: true) IgnoreEdits bool // Wether to ignore edited messages. (default: true) }
func NewMonitor ¶
func NewMonitor(name string, monitor MonitorHandler) *Monitor
func (*Monitor) AllowEdits ¶
func (*Monitor) AllowWebhooks ¶
func (*Monitor) SetGuildOnly ¶
type MonitorContext ¶
type MonitorHandler ¶
type MonitorHandler func(bot *Bot, ctx *MonitorContext)
type Paginator ¶
type Paginator struct { Running bool // If we are running or not. Session *discordgo.Session // The discordgo session. ChannelID string // The ID of the channel we are on. Template func() *Embed // Base template that is passed to AddPage calls. Pages []*discordgo.MessageEmbed // Embeds for all pages. Message *discordgo.Message // The sent message to be edited as we go AuthorID string // The user that can control this paginator. StopChan chan bool // Stop paginator by sending to this channel. Timeout time.Duration // Duration of when the paginator expires. (default: 5minutes) // contains filtered or unexported fields }
func NewPaginator ¶
NewPaginator creates a new paginator and returns it. This is the raw one if you have special needs, it's preferred to use NewPaginatorForContext Session is the discordgo sesssion, channel is the ID of the channel to start the paginator. Author is the id of the user to listen to everyone else's reaction is ignored, pass "" to allow everyone.
func NewPaginatorForContext ¶
func NewPaginatorForContext(ctx *CommandContext) *Paginator
NewPaginatorForContext creates a new paginator for this command context
func (*Paginator) AddPage ¶
Adds a page, takes a function that recieves the copy of embed template inside you can modify the embed as needed then return it back.
func (*Paginator) AddPageString ¶
Adds a page as string, this calls the regular AddPage with the callback as a simple function that only sets the description to the given string.
func (*Paginator) Goto ¶
Switches pages, index is assumed to be a valid index. (can panic if it's not) Edits the current message to the given page and updates the index.
func (*Paginator) NextPage ¶
func (p *Paginator) NextPage()
Switches to next page, this is safer than raw Goto as it compares indices and switch to first page if we are already on last one.
func (*Paginator) PreviousPage ¶
func (p *Paginator) PreviousPage()
Switches to the previous page, this is safer than raw Goto as it compares indices and switch to last page if we are already on the first one.
func (*Paginator) SetFooter ¶
func (p *Paginator) SetFooter()
Sets the footers of all pages to their page number out of total pages. Called by Run to initialize.
func (*Paginator) SetTemplate ¶
SetTemplate sets the base template.
type Permissions ¶
type Permissions int
Permissions represent permission bits for a discord entity.
func PermissionsForMember ¶
func PermissionsForMember(guild *discordgo.Guild, member *discordgo.Member) Permissions
PermissionsForMember returns a permissions instance for a member.
func PermissionsForRole ¶
func PermissionsForRole(role *discordgo.Role) Permissions
PermissionsForRole returns a permissions instance for a role.
func (Permissions) Has ¶
func (perms Permissions) Has(bits int) bool
type UsageTag ¶
type UsageTag struct { Name string // Name of the tag, e.g for <reason:string> the name is reason. Type string // Type of the tag, e.g for <reason:string> the type is string. Rest bool // If this is rest of the arguments, e.g for <reason:string...> it is true. Required bool // If this argument is required, e.g <name> is required but [name] is not. }
func ParseUsage ¶
Parse a usage string into tags.