gumi

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2026 License: MIT Imports: 14 Imported by: 2 modules, 14 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

gumi

A DiscordGo command framework. You declare a command once and it runs as a slash command (or context menu command) and, optionally, as a classic prefixed message command. Handlers read ctx.Options and never care how they were invoked.

go get github.com/VTGare/gumi

Example

r := gumi.New(gumi.Config{
	Prefixes:              []string{"!"},
	DisablePrefixCommands: false, // set true for a slash-only bot
	OwnerIDs:              []string{"123456789012345678"},
})

r.Use(
	middleware.Logging(slog.Default()),
	middleware.Recover(),
	middleware.Timeout(time.Minute),
)

r.MustRegister(&gumi.Command{
	Name:        "greet",
	Description: "Say hello",
	Options: []*gumi.Option{
		gumi.String("name", "Who to greet").Require().WithAutocomplete(
			func(ctx *gumi.AutocompleteContext) ([]gumi.Choice, error) {
				return []gumi.Choice{{Name: "World", Value: "World"}}, nil
			},
		),
	},
	Handler: func(ctx *gumi.Context) error {
		return ctx.Replyf("Hello, %s!", ctx.Options.String("name"))
	},
})

unbind := r.Bind(session) // after discordgo.New
defer unbind()

// After session.Open():
if err := r.Sync(session); err != nil {
	log.Fatal(err)
}

Features

  • Slash, message context and user context commands. Prefix invocation can be turned off.
  • Subcommands and groups (two levels deep), with a default subcommand for prefix invocations.
  • Typed options with choices, ranges, lengths, channel types, greedy strings and slash-only options.
  • Autocomplete for string, integer and number options. The command's checks gate suggestions.
  • Middleware (middleware.Logging, Recover, Timeout), checks (GuildOnly, OwnerOnly, HasPermissions, BotHasPermissions, NSFW, Any, Not) and cooldowns.
  • Stateless components and modals that route back to their command via ComponentID.
  • Built-in help command.
  • One reply API for both invocation kinds: Reply, Defer, Edit, Followup, ephemeral replies.
  • Sync bulk-overwrites application commands, globally or to a development guild.

History

v0.x was the original 2020–2021 framework. v1 is a rewrite that grew out of boe-tea-go's router.

Documentation

Overview

Package gumi declares a Discord command once and runs it both as a slash (or context menu) command and as a classic prefixed message command. Handlers read ctx.Options and never care how they were invoked.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrMissingOption     = errors.New("missing required option")
	ErrMissingSubcommand = errors.New("missing subcommand")
	ErrUnknownSubcommand = errors.New("unknown subcommand")
	ErrNoHandler         = errors.New("command has no handler")
	ErrNoResponse        = errors.New("no response has been sent yet")
	ErrAlreadyResponded  = errors.New("interaction already responded to")
	ErrMissingTarget     = errors.New("missing command target")
)

Sentinel errors returned by the router.

Functions

func ComponentID added in v1.0.0

func ComponentID(cmd *Command, args ...string) string

ComponentID builds a custom ID that routes back to cmd's Components handler with args. It returns "" when the ID would exceed Discord's 100-character limit; args must not contain ':'.

func DefaultErrorHandler added in v1.0.0

func DefaultErrorHandler(ctx *Context, err error)

DefaultErrorHandler replies with the user-facing message, if any, and a generic one otherwise. Silent check failures get no reply.

func UserMessageOf added in v1.0.0

func UserMessageOf(err error) (string, bool)

Types

type AutocompleteContext added in v1.0.0

type AutocompleteContext struct {
	Session     *discordgo.Session
	Router      *Router
	Command     *Command
	Interaction *discordgo.InteractionCreate
	// Option is the declaration of the focused option.
	Option *Option
	// Value is what has been typed into the focused option so far.
	Value string
	// Options holds every option filled in so far, the focused one included.
	Options *Options
	// contains filtered or unexported fields
}

AutocompleteContext is one keystroke's worth of an option being typed.

func (*AutocompleteContext) ChannelID added in v1.0.0

func (c *AutocompleteContext) ChannelID() string

func (*AutocompleteContext) Context added in v1.0.0

func (c *AutocompleteContext) Context() context.Context

Context expires shortly before Discord stops waiting for suggestions.

func (*AutocompleteContext) GuildID added in v1.0.0

func (c *AutocompleteContext) GuildID() string

func (*AutocompleteContext) Locale added in v1.0.0

func (c *AutocompleteContext) Locale() discordgo.Locale

func (*AutocompleteContext) UserID added in v1.0.0

func (c *AutocompleteContext) UserID() string

UserID returns the ID of the user who is typing.

type AutocompleteErrorHandler added in v1.0.0

type AutocompleteErrorHandler func(ctx *AutocompleteContext, err error)

AutocompleteErrorHandler receives errors and recovered panics from autocomplete handlers. The user just sees no suggestions.

type AutocompleteHandler added in v1.0.0

type AutocompleteHandler func(ctx *AutocompleteContext) ([]Choice, error)

AutocompleteHandler suggests values for the option being typed. At most 25 choices are shown; names over 100 characters are trimmed and string values over 100 characters dropped.

type Check added in v1.0.0

type Check func(ctx *Context) error

Check gates a command: it runs after middleware, before cooldowns. Reject with a UserFacing error to tell the user why.

var DMOnly Check = func(ctx *Context) error {
	if ctx.GuildID() != "" {
		return &CheckError{Check: "dm_only", Message: "This command can only be used in DMs."}
	}

	return nil
}

DMOnly rejects invocations inside guilds.

var GuildOnly Check = func(ctx *Context) error {
	if ctx.GuildID() == "" {
		return &CheckError{Check: "guild_only", Message: "This command can only be used in a server."}
	}

	return nil
}

GuildOnly rejects invocations outside of guilds.

var NSFW Check = func(ctx *Context) error {
	if ctx.GuildID() == "" {
		return nil
	}

	ch, err := ctx.Channel()
	if err != nil {
		return err
	}

	if ch.IsThread() && ch.ParentID != "" {
		if ch, err = ctx.channel(ch.ParentID); err != nil {
			return err
		}
	}

	if !ch.NSFW {
		return &CheckError{Check: "nsfw", Message: "This command can only be used in NSFW channels."}
	}

	return nil
}

NSFW rejects invocations in non-NSFW guild channels. DMs are allowed. Threads inherit the flag from their parent channel.

var OwnerOnly Check = func(ctx *Context) error {
	if !ctx.Router.IsOwner(ctx.AuthorID()) {
		return &CheckError{Check: "owner_only", Message: "This command is restricted to the bot owner.", Silent: true}
	}

	return nil
}

OwnerOnly silently rejects everyone except Config.OwnerIDs.

func Any added in v1.0.0

func Any(checks ...Check) Check

Any passes if at least one of the checks passes. If all fail, the error of the last check is returned.

func BotHasPermissions added in v1.0.0

func BotHasPermissions(permissions int64) Check

BotHasPermissions needs all the given channel permissions for the bot. Outside guilds it passes.

func HasPermissions added in v1.0.0

func HasPermissions(permissions int64) Check

HasPermissions needs all the given channel permissions (admins pass). Outside guilds it passes.

func Not added in v1.0.0

func Not(check Check, message string) Check

Not inverts a check, using message as the rejection reason.

type CheckError added in v1.0.0

type CheckError struct {
	Check   string
	Message string

	// Silent sends no reply, for commands whose existence shouldn't be
	// revealed.
	Silent bool
}

func (*CheckError) Error added in v1.0.0

func (e *CheckError) Error() string

func (*CheckError) UserMessage added in v1.0.0

func (e *CheckError) UserMessage() string

type Choice added in v1.0.0

type Choice struct {
	Name  string
	Value any
}

type Command

type Command struct {
	// Chat input names: 1-32 lowercase chars, no spaces. Context menu
	// names are free-form.
	Name string
	// Shown in Discord and in help (1-100 chars). Discord ignores it for
	// context menu commands.
	Description string
	// Defaults to ChatInput.
	Type     CommandType
	Category string
	// Extra prefix names; slash ignores them.
	Aliases []string
	// Parsed positionally in declaration order over prefix.
	Options []*Option
	// Subcommands turn this into a group: no options or handler allowed,
	// at most two levels deep (command > group > sub).
	Subcommands []*Command
	// Default is the subcommand a prefix invocation runs when no
	// subcommand is given, e.g. "bt!groups" runs "bt!groups list". If the
	// next word isn't a subcommand, it's passed to the default as an
	// argument: "bt!bookmarks popularity" runs "bt!bookmarks list popularity".
	Default string
	// Required for non-group commands.
	Handler Handler
	// Group checks also guard its subcommands.
	Checks     []Check
	Middleware []Middleware
	// Set on a group to cover its subcommands too.
	Cooldown *Cooldown
	// Acknowledge first ("thinking…", or typing over prefix), giving the
	// handler up to 15 minutes.
	Defer bool
	// Invoker-only replies. No effect over prefix.
	Ephemeral bool
	// Age-restricts the slash command. This alone changes nothing at runtime;
	// add NSFW to Checks to gate prefix invocations too.
	NSFW bool
	// Hides the slash command by default (admins can override). Also not a
	// runtime check; use HasPermissions for that.
	DefaultMemberPermissions *int64
	// Where the slash command shows up; empty means Discord's default.
	Contexts         []discordgo.InteractionContextType
	IntegrationTypes []discordgo.ApplicationIntegrationType
	// Register the slash command only here instead of globally.
	GuildIDs      []string
	DisableSlash  bool
	DisablePrefix bool
	Hidden        bool
	// Shown in help; write without prefix, e.g. "set prefix !".
	Examples []string

	// Components handles interactions on components built with
	// ComponentID. Only root commands receive them.
	Components ComponentHandler
	// contains filtered or unexported fields
}

Command is declared once and works as both a slash command and a prefix command.

func HelpCommand added in v1.0.0

func HelpCommand(cfg HelpConfig) *Command

HelpCommand documents every command on the router it runs in:

/help            – overview with a category menu
/help set prefix – details, usage, options, cooldown

The menus are stateless: each custom ID carries the invoker, the syntax mode and the target, so they keep working across restarts.

func (*Command) IsGroup added in v1.0.0

func (c *Command) IsGroup() bool

func (*Command) Parent added in v1.0.0

func (c *Command) Parent() *Command

func (*Command) Path added in v1.0.0

func (c *Command) Path() []string

func (*Command) QualifiedName added in v1.0.0

func (c *Command) QualifiedName() string

func (*Command) Root added in v1.0.0

func (c *Command) Root() *Command

func (*Command) Subcommand added in v1.0.0

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

Subcommand finds a direct subcommand by name or alias, ignoring case.

func (*Command) Usage added in v0.3.0

func (c *Command) Usage(lead string) string

Usage renders e.g. "/set prefix <value>" for lead "/", "bt!set prefix <value>" for lead "bt!".

func (*Command) Walk added in v1.0.0

func (c *Command) Walk(fn func(*Command))

type CommandType added in v1.0.0

type CommandType int

CommandType mirrors Discord application command types.

const (
	ChatInput CommandType = iota
	// MessageContext runs on a message: right-click it, or reply to it
	// (or pass a link / ID) over prefix.
	MessageContext
	// UserContext runs on a user: right-click them, or pass a mention / ID
	// over prefix (defaults to the author).
	UserContext
)

func (CommandType) String added in v1.0.0

func (t CommandType) String() string

type ComponentContext added in v1.0.0

type ComponentContext struct {
	Session     *discordgo.Session
	Router      *Router
	Command     *Command
	Interaction *discordgo.InteractionCreate
	// Args are the custom ID's parts after the command name.
	Args []string
	// contains filtered or unexported fields
}

ComponentContext is a button click, select or modal submit.

func (*ComponentContext) Arg added in v1.0.0

func (c *ComponentContext) Arg(i int) string

Arg returns the i-th arg, or "" when absent.

func (*ComponentContext) ChannelID added in v1.0.0

func (c *ComponentContext) ChannelID() string

func (*ComponentContext) GuildID added in v1.0.0

func (c *ComponentContext) GuildID() string

func (*ComponentContext) IsModal added in v1.0.0

func (c *ComponentContext) IsModal() bool

IsModal reports whether this is a modal submit.

func (*ComponentContext) Modal added in v1.0.0

func (c *ComponentContext) Modal(customID, title string, inputs ...discordgo.TextInput) error

Modal opens a modal whose submit routes back with the given custom ID.

func (*ComponentContext) Permissions added in v1.0.0

func (c *ComponentContext) Permissions() int64

Permissions are the user's channel permissions (all of them in DMs).

func (*ComponentContext) Reply added in v1.0.0

func (c *ComponentContext) Reply(r *Response) error

Reply sends a new message; set Ephemeral for an invoker-only one.

func (*ComponentContext) ResolvedChannels added in v1.0.0

func (c *ComponentContext) ResolvedChannels() map[string]*discordgo.Channel

ResolvedChannels are the channels picked in a channel select, by ID.

func (*ComponentContext) TextInput added in v1.0.0

func (c *ComponentContext) TextInput(customID string) string

TextInput is a modal text input's submitted value, or "".

func (*ComponentContext) Update added in v1.0.0

func (c *ComponentContext) Update(r *Response) error

Update edits the message the component is on.

func (*ComponentContext) UserID added in v1.0.0

func (c *ComponentContext) UserID() string

UserID returns the ID of the user who clicked.

func (*ComponentContext) Values added in v1.0.0

func (c *ComponentContext) Values() []string

Values are a select menu's chosen values.

type ComponentHandler added in v1.0.0

type ComponentHandler func(ctx *ComponentContext) error

ComponentHandler handles clicks, selects and modal submits on components whose custom IDs came from ComponentID.

type Config added in v1.0.0

type Config struct {
	// Prefixes accepted everywhere. Ignored if PrefixResolver is set.
	Prefixes []string

	// PrefixResolver returns per-guild prefixes.
	PrefixResolver PrefixResolver

	// DisableMentionPrefix turns off "@Bot command" invocation.
	DisableMentionPrefix bool

	// DisablePrefixCommands turns off prefix invocation entirely.
	DisablePrefixCommands bool

	// DisableSlashCommands turns off interaction handling and Sync.
	DisableSlashCommands bool

	// DevGuildID registers every slash command to this guild instead of
	// globally (instant propagation, useful for development).
	DevGuildID string

	// ApplicationID used for Sync. Fetched from the API if empty.
	ApplicationID string

	OwnerIDs []string

	// ErrorHandler replaces the default error handler.
	ErrorHandler ErrorHandler

	// AutocompleteErrorHandler receives autocomplete handler errors, which
	// are otherwise dropped.
	AutocompleteErrorHandler AutocompleteErrorHandler

	// Fallback is called for messages that were not commands.
	Fallback FallbackHandler

	// AllowedMentions applied to prefix replies that don't set their own.
	AllowedMentions *discordgo.MessageAllowedMentions

	// DisableReplyReference stops prefix replies from quoting the invoking
	// message.
	DisableReplyReference bool

	// BaseContext produces the root context.Context for each invocation.
	BaseContext func() context.Context
}

type Context added in v1.0.0

type Context struct {
	Session       *discordgo.Session
	Router        *Router
	Command       *Command
	Source        Source
	Prefix        string
	Message       *discordgo.Message
	Interaction   *discordgo.InteractionCreate
	Options       *Options
	TargetMessage *discordgo.Message
	TargetUser    *discordgo.User
	// Guilds only; nil in DMs.
	TargetMember *discordgo.Member
	StartedAt    time.Time
	// contains filtered or unexported fields
}

Context is a single command invocation. Replies work the same whether it came from a slash command or a message. Exactly one of Message and Interaction is set.

func (*Context) Author added in v1.0.0

func (c *Context) Author() *discordgo.User

func (*Context) AuthorID added in v1.0.0

func (c *Context) AuthorID() string

func (*Context) BotPermissions added in v1.0.0

func (c *Context) BotPermissions() (int64, error)

func (*Context) Channel added in v1.0.0

func (c *Context) Channel() (*discordgo.Channel, error)

Channel fetches the invoking channel (state cache first, then REST).

func (*Context) ChannelID added in v1.0.0

func (c *Context) ChannelID() string

func (*Context) Context added in v1.0.0

func (c *Context) Context() context.Context

Context carries cancellation and deadlines; see middleware.Timeout.

func (*Context) Defer added in v1.0.0

func (c *Context) Defer() error

Defer gives the handler up to 15 minutes by showing "thinking…" (or typing, over prefix). Calling it twice does nothing.

func (*Context) Delete added in v1.0.0

func (c *Context) Delete() error

Delete removes the original response (interactions) or the last reply.

func (*Context) DisplayPrefix added in v1.0.0

func (c *Context) DisplayPrefix() string

DisplayPrefix is the used prefix, falling back to the guild's first one.

func (*Context) Edit added in v1.0.0

func (c *Context) Edit(r *Response) error

Edit rewrites the original response, or the last reply over prefix. Replies instead if nothing was sent yet.

func (*Context) Followup added in v1.0.0

func (c *Context) Followup(r *Response) (*discordgo.Message, error)

Followup sends an extra message, responding first if it has to.

func (*Context) Get added in v1.0.0

func (c *Context) Get(key string) (any, bool)

func (*Context) Guild added in v1.0.0

func (c *Context) Guild() (*discordgo.Guild, error)

Guild fetches the invoking guild (state cache first, then REST).

func (*Context) GuildID added in v1.0.0

func (c *Context) GuildID() string

func (*Context) IsInteraction added in v1.0.0

func (c *Context) IsInteraction() bool

func (*Context) IsMessage added in v1.0.0

func (c *Context) IsMessage() bool

func (*Context) Locale added in v1.0.0

func (c *Context) Locale() discordgo.Locale

func (*Context) Member added in v1.0.0

func (c *Context) Member() *discordgo.Member

func (*Context) OriginalResponse added in v1.0.0

func (c *Context) OriginalResponse() (*discordgo.Message, error)

func (*Context) Permissions added in v1.0.0

func (c *Context) Permissions() (int64, error)

Permissions are the invoker's channel permissions (all of them outside guilds).

func (*Context) Reply added in v1.0.0

func (c *Context) Reply(r *Response) error

Reply answers once over interactions (editing the deferred placeholder if there is one, else following up), or replies to the message.

func (*Context) ReplyEmbed added in v1.0.0

func (c *Context) ReplyEmbed(embed *discordgo.MessageEmbed) error

func (*Context) ReplyEphemeral added in v1.0.0

func (c *Context) ReplyEphemeral(content string) error

func (*Context) ReplyText added in v1.0.0

func (c *Context) ReplyText(content string) error

func (*Context) Replyf added in v1.0.0

func (c *Context) Replyf(format string, args ...any) error

func (*Context) Responded added in v1.0.0

func (c *Context) Responded() bool

Responded reports whether an initial response (or Defer) has been sent.

func (*Context) Set added in v1.0.0

func (c *Context) Set(key string, value any)

Set stashes a value for middleware and handlers to share.

func (*Context) SetContext added in v1.0.0

func (c *Context) SetContext(ctx context.Context)

func (*Context) SetEphemeral added in v1.0.0

func (c *Context) SetEphemeral(on bool)

SetEphemeral decides at runtime whether replies are invoker-only, e.g. from an option. Discord fixes it with the first response (including Defer), so call it before that. No effect over prefix.

type Cooldown added in v1.0.0

type Cooldown struct {
	Scope CooldownScope
	Uses  int
	Per   time.Duration
	// contains filtered or unexported fields
}

Cooldown is a fixed-window rate limiter: Uses invocations per Per for every key in Scope (Uses defaults to 1). Safe for concurrent use. Set it on a group to cover its subcommands:

Cooldown: &gumi.Cooldown{Uses: 2, Per: 10 * time.Second}

func NewCooldown added in v1.0.0

func NewCooldown(scope CooldownScope, uses int, per time.Duration) *Cooldown

func (*Cooldown) Key added in v1.0.0

func (c *Cooldown) Key(ctx *Context) string

func (*Cooldown) Reset added in v1.0.0

func (c *Cooldown) Reset(key string)

func (*Cooldown) String added in v1.0.0

func (c *Cooldown) String() string

func (*Cooldown) Take added in v1.0.0

func (c *Cooldown) Take(key string) (time.Duration, bool)

Take spends one use; it reports how long to wait when limited.

type CooldownError added in v1.0.0

type CooldownError struct {
	Remaining time.Duration
	Scope     CooldownScope
}

func (*CooldownError) Error added in v1.0.0

func (e *CooldownError) Error() string

func (*CooldownError) UserMessage added in v1.0.0

func (e *CooldownError) UserMessage() string

type CooldownScope added in v1.0.0

type CooldownScope int

CooldownScope determines which key a cooldown bucket is tied to.

const (
	// CooldownUser limits each user independently (default).
	CooldownUser CooldownScope = iota
	// CooldownChannel limits each channel independently.
	CooldownChannel
	// CooldownGuild limits each guild independently (DMs are keyed by channel).
	CooldownGuild
	// CooldownGlobal limits the command for everyone.
	CooldownGlobal
)

func (CooldownScope) String added in v1.0.0

func (s CooldownScope) String() string

type ErrorHandler

type ErrorHandler func(ctx *Context, err error)

ErrorHandler receives every error returned from the command pipeline.

type FallbackHandler added in v1.0.0

type FallbackHandler func(s *discordgo.Session, m *discordgo.MessageCreate)

FallbackHandler receives messages (from non-bot users) that were not dispatched as a command.

type Handler added in v1.0.0

type Handler func(ctx *Context) error

type HelpConfig added in v1.0.0

type HelpConfig struct {
	// Name of the command (default "help").
	Name string
	// Description (default "Shows the list of commands or details about one").
	Description string
	// Category the help command itself is listed under (default "General").
	Category string
	// Aliases for prefix invocation.
	Aliases []string
	// Title of the overview embed (default "Commands").
	Title string
	// Color of the embeds.
	Color int
	// Footer appended to the overview embed.
	Footer string
	// ShowHidden lists hidden commands too.
	ShowHidden bool
	// Public makes help replies visible to everyone (default: ephemeral).
	Public bool
	// Uncategorized is the category name for commands without one (default "Other").
	Uncategorized string
	// CategoryOrder lists categories first, in this order; the rest follow
	// alphabetically.
	CategoryOrder []string
}

HelpConfig customises the built-in help command.

type Middleware added in v1.0.0

type Middleware func(next Handler) Handler

Middleware wraps a Handler. Router middleware runs first, then the command chain's, outermost first.

type Option

type Option struct {
	Type        OptionType
	Name        string
	Description string
	Required    bool
	Choices     []Choice
	// ChannelTypes restricts channel options to the given types.
	ChannelTypes []discordgo.ChannelType
	// MinValue / MaxValue apply to integer and number options.
	MinValue *float64
	MaxValue *float64
	// MinLength / MaxLength apply to string options.
	MinLength *int
	MaxLength *int
	// Consume the rest of the message over prefix (string only). Only
	// attachments and slash-only options may follow it. Ignored by slash
	// commands.
	Rest bool
	// Skip the option over prefix, where it keeps its zero value. Lets a
	// slash command take extra options without breaking the positional
	// prefix syntax. Cannot be required.
	NoPrefix bool
	// Autocomplete suggests values while the user types (string, integer
	// and number options only; not with Choices). Ignored by prefix
	// commands.
	Autocomplete AutocompleteHandler
}

Option is one command argument; the same declaration feeds the slash definition and the prefix parser.

func Attachment added in v1.0.0

func Attachment(name, description string) *Option

func Boolean added in v1.0.0

func Boolean(name, description string) *Option

func Channel added in v1.0.0

func Channel(name, description string) *Option

func Integer added in v1.0.0

func Integer(name, description string) *Option

func Mentionable added in v1.0.0

func Mentionable(name, description string) *Option

func Number added in v1.0.0

func Number(name, description string) *Option

func Role added in v1.0.0

func Role(name, description string) *Option

func String added in v1.0.0

func String(name, description string) *Option

func User added in v1.0.0

func User(name, description string) *Option

func (*Option) Greedy added in v1.0.0

func (o *Option) Greedy() *Option

func (*Option) Require added in v1.0.0

func (o *Option) Require() *Option

func (*Option) SlashOnly added in v1.0.0

func (o *Option) SlashOnly() *Option

func (*Option) WithAutocomplete added in v1.0.0

func (o *Option) WithAutocomplete(h AutocompleteHandler) *Option

func (*Option) WithChannelTypes added in v1.0.0

func (o *Option) WithChannelTypes(types ...discordgo.ChannelType) *Option

func (*Option) WithChoices added in v1.0.0

func (o *Option) WithChoices(choices ...Choice) *Option

func (*Option) WithLength added in v1.0.0

func (o *Option) WithLength(minLength, maxLength int) *Option

func (*Option) WithRange added in v1.0.0

func (o *Option) WithRange(minValue, maxValue float64) *Option

type OptionError added in v1.0.0

type OptionError struct {
	Option *Option
	Value  string
	Err    error
}

func (*OptionError) Error added in v1.0.0

func (e *OptionError) Error() string

func (*OptionError) Unwrap added in v1.0.0

func (e *OptionError) Unwrap() error

func (*OptionError) UserMessage added in v1.0.0

func (e *OptionError) UserMessage() string

type Options added in v1.0.0

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

func (*Options) Attachment added in v1.0.0

func (o *Options) Attachment(name string) *discordgo.MessageAttachment

func (*Options) Bool added in v1.0.0

func (o *Options) Bool(name string) bool

func (*Options) BoolOr added in v1.0.0

func (o *Options) BoolOr(name string, def bool) bool

func (*Options) Channel added in v1.0.0

func (o *Options) Channel(name string) *discordgo.Channel

func (*Options) Float added in v1.0.0

func (o *Options) Float(name string) float64

func (*Options) Get added in v1.0.0

func (o *Options) Get(name string) *Value

func (*Options) Has added in v1.0.0

func (o *Options) Has(name string) bool

func (*Options) ID added in v1.0.0

func (o *Options) ID(name string) string

func (*Options) Int added in v1.0.0

func (o *Options) Int(name string) int64

func (*Options) IntOr added in v1.0.0

func (o *Options) IntOr(name string, def int64) int64

func (*Options) Len added in v1.0.0

func (o *Options) Len() int

func (*Options) Member added in v1.0.0

func (o *Options) Member(name string) *discordgo.Member

func (*Options) Role added in v1.0.0

func (o *Options) Role(name string) *discordgo.Role

func (*Options) String added in v1.0.0

func (o *Options) String(name string) string

func (*Options) StringOr added in v1.0.0

func (o *Options) StringOr(name, def string) string

func (*Options) User added in v1.0.0

func (o *Options) User(name string) *discordgo.User

type PanicError added in v1.0.0

type PanicError struct {
	Value any
	Stack []byte
}

func (*PanicError) Error added in v1.0.0

func (e *PanicError) Error() string

type PrefixResolver

type PrefixResolver func(s *discordgo.Session, guildID, channelID string) []string

PrefixResolver returns the prefixes accepted in the given guild/channel.

type Response added in v1.0.0

type Response struct {
	Content         string
	Embeds          []*discordgo.MessageEmbed
	Components      []discordgo.MessageComponent
	Files           []*discordgo.File
	AllowedMentions *discordgo.MessageAllowedMentions
	// Invoker-only for interactions; ignored over prefix.
	Ephemeral bool
	TTS       bool
	Flags     discordgo.MessageFlags
}

func Embed added in v1.0.0

func Embed(embed *discordgo.MessageEmbed) *Response

func Text added in v1.0.0

func Text(content string) *Response

func Textf added in v1.0.0

func Textf(format string, args ...any) *Response

func (*Response) Private added in v1.0.0

func (r *Response) Private() *Response

type Router added in v0.3.0

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

func New added in v1.0.0

func New(cfg Config) *Router

func (*Router) AddCheck added in v1.0.0

func (r *Router) AddCheck(checks ...Check)

AddCheck appends router-wide checks that run before every command.

func (*Router) ApplicationCommands added in v1.0.0

func (r *Router) ApplicationCommands() (global []*discordgo.ApplicationCommand, byGuild map[string][]*discordgo.ApplicationCommand)

ApplicationCommands builds the Discord definitions, split into global and per-guild commands. DevGuildID is not applied here; see Sync.

func (*Router) Bind added in v1.0.0

func (r *Router) Bind(s *discordgo.Session) func()

Bind hooks the router into the session; the result unbinds it.

func (*Router) ClearCommands added in v1.0.0

func (r *Router) ClearCommands(s *discordgo.Session, guildID string) error

ClearCommands wipes global (guildID == "") or guild commands.

func (*Router) Commands added in v0.3.0

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

func (*Router) Config added in v1.0.0

func (r *Router) Config() Config

func (*Router) HandleInteraction added in v1.0.0

func (r *Router) HandleInteraction(s *discordgo.Session, i *discordgo.InteractionCreate)

HandleInteraction runs application commands, their autocomplete, and the components and modals built with ComponentID. It ignores everything else, so it can share a session with your own component and modal handlers.

func (*Router) HandleMessage added in v1.0.0

func (r *Router) HandleMessage(s *discordgo.Session, m *discordgo.MessageCreate)

func (*Router) IsOwner added in v1.0.0

func (r *Router) IsOwner(userID string) bool

func (*Router) Lookup added in v1.0.0

func (r *Router) Lookup(path ...string) *Command

Lookup resolves a command by prefix path, e.g. Lookup("set", "prefix"). Names and aliases both match; nil if not found.

func (*Router) Mention added in v1.0.0

func (r *Router) Mention(c *Command) string

Mention renders a chat command as a clickable </name:id> mention, or "" before Sync or for commands Discord cannot mention.

func (*Router) MustRegister added in v1.0.0

func (r *Router) MustRegister(cmds ...*Command)

MustRegister is Register but panics on error.

func (*Router) Prefixes added in v1.0.0

func (r *Router) Prefixes(s *discordgo.Session, guildID, channelID string) []string

func (*Router) Register added in v1.0.0

func (r *Router) Register(cmds ...*Command) error

Register validates and adds top-level commands. Either all commands are registered or none.

func (*Router) Sync added in v1.0.0

func (r *Router) Sync(s *discordgo.Session) error

Sync bulk-overwrites the application commands. With DevGuildID set, everything lands in that guild instead (globals are left alone). Call it after the session is open.

func (*Router) Use added in v1.0.0

func (r *Router) Use(mw ...Middleware)

Use appends router-wide middleware. Middleware runs in registration order.

type Source added in v1.0.0

type Source int
const (
	SourceMessage Source = iota
	SourceInteraction
)

func (Source) String added in v1.0.0

func (s Source) String() string

type SubcommandError added in v1.0.0

type SubcommandError struct {
	Command *Command
	Given   string
}

func (*SubcommandError) Error added in v1.0.0

func (e *SubcommandError) Error() string

func (*SubcommandError) Unwrap added in v1.0.0

func (e *SubcommandError) Unwrap() error

Unwrap matches ErrUnknownSubcommand or ErrMissingSubcommand.

func (*SubcommandError) UserMessage added in v1.0.0

func (e *SubcommandError) UserMessage() string

type UserError added in v1.0.0

type UserError struct {
	Message string
	Err     error
}

UserError is for when the user did something wrong (bad input, nothing found).

func Errorf added in v1.0.0

func Errorf(format string, args ...any) *UserError

func NewUserError added in v1.0.0

func NewUserError(message string) *UserError

func WrapUserError added in v1.0.0

func WrapUserError(message string, err error) *UserError

func (*UserError) Error added in v1.0.0

func (e *UserError) Error() string

func (*UserError) Unwrap added in v1.0.0

func (e *UserError) Unwrap() error

func (*UserError) UserMessage added in v1.0.0

func (e *UserError) UserMessage() string

type UserFacing added in v1.0.0

type UserFacing interface {
	error
	UserMessage() string
}

UserFacing errors are safe to show the invoker; anything else gets a generic "something went wrong" reply.

type Value added in v1.0.0

type Value struct {
	Type OptionType
	// contains filtered or unexported fields
}

Value is one parsed argument. Entities resolve lazily (state cache, then REST) for prefix invocations; slash uses Discord's resolved data.

func (*Value) Attachment added in v1.0.0

func (v *Value) Attachment() *discordgo.MessageAttachment

func (*Value) Bool added in v1.0.0

func (v *Value) Bool() bool

func (*Value) Channel added in v1.0.0

func (v *Value) Channel() (*discordgo.Channel, error)

func (*Value) Float added in v1.0.0

func (v *Value) Float() float64

func (*Value) ID added in v1.0.0

func (v *Value) ID() string

func (*Value) Int added in v1.0.0

func (v *Value) Int() int64

func (*Value) IsRole added in v1.0.0

func (v *Value) IsRole() bool

func (*Value) IsUser added in v1.0.0

func (v *Value) IsUser() bool

func (*Value) Member added in v1.0.0

func (v *Value) Member() (*discordgo.Member, error)

func (*Value) Raw added in v1.0.0

func (v *Value) Raw() string

Raw is the value as typed over prefix, or its string form from slash.

func (*Value) Role added in v1.0.0

func (v *Value) Role() (*discordgo.Role, error)

func (*Value) String added in v1.0.0

func (v *Value) String() string

String is the string value, or Raw() for anything else.

func (*Value) User added in v1.0.0

func (v *Value) User() (*discordgo.User, error)

Directories

Path Synopsis
Package middleware provides common middleware for gumi.Router.
Package middleware provides common middleware for gumi.Router.

Jump to

Keyboard shortcuts

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