discordkit

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 17, 2026 License: MIT Imports: 15 Imported by: ? modules, 0 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

DiscordKit

DiscordKit is an ergonomic framework layer built on top of discordgo. It keeps discordgo as the transport and data-model layer and adds the pieces application developers write by hand over and over: a unified interaction router, typed command and option builders, a Components V2 DSL, modal forms, and a response lifecycle that turns easy-to-miss API rules into compile-time and run-time guarantees.

DiscordKit never wraps discordgo's domain types. A user is a *discordgo.User, a guild is a *discordgo.Guild, and every builder finalizes into plain discordgo structs, so you can always drop down to the underlying library.

Installation

go get github.com/freitaseric/discordkit

DiscordKit requires Go 1.26+ and a recent discordgo (Components V2, modal labels and file uploads rely on discordgo master; the exact minimum commit is pinned in go.mod).

Quick start

package main

import (
	"log"
	"os"
	"os/signal"

	"github.com/bwmarrin/discordgo"
	"github.com/freitaseric/discordkit"
)

func main() {
	s, err := discordgo.New("Bot " + os.Getenv("DISCORD_TOKEN"))
	if err != nil {
		log.Fatal(err)
	}

	r := discordkit.NewRouter(discordkit.Recovery(), discordkit.Logging(nil))
	r.Command("ping", func(c *discordkit.Context) error {
		return c.ReplyText("Pong!")
	})
	s.AddHandler(r.Handle)

	if err := s.Open(); err != nil {
		log.Fatal(err)
	}
	defer s.Close()

	// Register the slash command with Discord.
	cmds, _ := discordkit.BuildCommands(discordkit.Command("ping", "Check I am alive"))
	if _, err := discordkit.SyncCommands(s, s.State.User.ID, cmds, discordkit.SyncOptions{}); err != nil {
		log.Fatal(err)
	}

	stop := make(chan os.Signal, 1)
	signal.Notify(stop, os.Interrupt)
	<-stop
}

Commands and synchronization

Build commands with typed option builders. Validation (name/length limits, the 25-option cap, unique names, required-before-optional ordering, and choices/autocomplete mutual exclusion) happens at Build:

cmd := discordkit.Command("greet", "Greet a member",
	discordkit.UserOption("who", "Who to greet").Required(),
	discordkit.StringOption("tone", "How to greet").
		Choices(discordkit.Choice("Formal", "formal"), discordkit.Choice("Casual", "casual")),
)

sub := discordkit.Command("config", "Server config",
	discordkit.SubCommandGroup("channel", "Channel settings",
		discordkit.SubCommand("set", "Set the channel",
			discordkit.ChannelOption("target", "Channel").Required(),
		),
	),
)

SyncCommands diffs your declared commands against what is registered with Discord and only issues the create/update/delete calls that are actually needed. The diff is exposed as a pure, testable function:

plan := discordkit.DiffCommands(remote, desired, true) // deleteObsolete = true
fmt.Println(len(plan.Create), len(plan.Update), len(plan.Delete))

Set SyncOptions.GuildID to scope to a single guild and SyncOptions.Delete to control whether obsolete commands are removed.

Context

Every handler receives a *Context for exactly one interaction. It exposes typed, network-free option accessors that read from the interaction's resolved data:

name, _ := c.String("tone")           // (string, bool)
who, _ := c.UserOption("who")         // *discordgo.User
count := c.MustInt("count")           // panics if missing/invalid
target, err := c.RequireChannel("target")

Session and Interaction are exported escape hatches; the raw discordgo API is always one field away.

Routing, groups and middleware

Router dispatches command, component, modal and autocomplete interactions through a single tree. Component and modal routes match on custom-ID patterns with named parameters:

r := discordkit.NewRouter(discordkit.Recovery())

r.Command("greet", greetHandler)
r.Component("/jobs/:jobID/cancel", cancelHandler)  // matches custom_id built with Route
r.Autocomplete("greet", "tone", toneSuggestions)

admin := r.Group("admin", discordkit.RequirePermissions(discordgo.PermissionManageServer))
admin.Command("ban", banHandler)

Built-in middleware: Recovery() (turns panics into a *PanicError), Logging(*slog.Logger), RequireGuild(), and RequirePermissions(bitmask). Middleware is func(Handler) Handler, so custom middleware is trivial.

Custom IDs

Build and parse component custom IDs safely instead of using fmt.Sprintf and strings.Split:

id, err := discordkit.Route("/jobs/:jobID/cancel").Param("jobID", job.ID).Build()
btn := discordkit.Button("Cancel", string(id))
// In the handler registered at "/jobs/:jobID/cancel":
jobID, _ := c.Param("jobID")

Values are escaped exactly once and the final ID is validated against Discord's 100-character limit.

Components V2

The component DSL finalizes into discordgo components and is validated as a tree. When any Components V2 component is present, DiscordKit sets the IS_COMPONENTS_V2 message flag, moves Content into a leading TextDisplay, and rejects the combinations Discord forbids (legacy embeds and polls alongside V2):

msg := discordkit.MessageSpec{
	Components: discordkit.Components(
		discordkit.Container(
			discordkit.Text("## Deploy finished"),
			discordkit.Separator().Divider(true),
			discordkit.Section(discordkit.Text("Logs are ready.")).
				Accessory(discordkit.Button("Open", "logs:open")),
		),
	),
}
c.Reply(msg)

Available builders include Text, Row, Button/LinkButton/PremiumButton, StringSelect, UserSelect/RoleSelect/MentionableSelect, ChannelSelect, Section, Thumbnail, Gallery/MediaItem, File, Separator and Container. Raw(...) drops any discordgo component straight into the tree as an escape hatch.

Validation rules enforced by ValidateMessageComponents include: interactive components must live in an action row, a select is alone in its row, buttons need a custom ID (link buttons need a URL, premium buttons neither), sections have 1-3 text displays plus an accessory, thumbnails appear only as section accessories, containers do not nest, and the overall component budget is capped.

Forms and modals

Modals are built from Label-wrapped fields and validated on build:

modal, _ := discordkit.Form("feedback:new", "Send feedback",
	discordkit.Field("Subject", discordkit.TextInput("subject")),
	discordkit.Field("Details", discordkit.TextInput("body").Paragraph()),
	discordkit.Field("Attachment", discordkit.FileUpload("file").FileTypes("png", "pdf")),
).Build()
c.ShowModal(modal)

FileUpload().FileTypes(...) is a DiscordKit request-only extension: discordgo does not model file_types, so DiscordKit marshals it for you while submissions still decode into discordgo.FileUpload.

Read submissions without reflection through Context.Form():

f := c.Form()
subject, _ := f.String("subject")
files, _ := f.Files("file")   // resolved []*discordgo.MessageAttachment

Responses, followups and autocomplete

Context tracks the response lifecycle so an accidental double-acknowledge fails loudly with a sentinel error instead of a confusing Discord API error:

Method Purpose
Reply / ReplyText Initial message response
Ephemeral / EphemeralText Initial response only the caller sees
Defer(ephemeral) Acknowledge a command, edit later
DeferUpdate Acknowledge a component without changing the message
Update Replace a component's message
Edit Edit the original response after Reply/Defer
Followup / FollowupEdit Additional messages
DeleteResponse Delete the original response
Autocomplete(...ChoiceValue) Reply to an autocomplete interaction
ShowModal(Modal) Open a modal

Calling an initial response twice returns ErrAlreadyResponded; calling Edit/Followup before acknowledging returns ErrNotResponded; Autocomplete and ShowModal guard against the wrong interaction type.

Error handling

DiscordKit exposes sentinel errors for use with errors.Is: ErrRouteNotFound, ErrRouteConflict, ErrInvalidCustomID, ErrAlreadyResponded, ErrNotResponded, ErrInvalidInteraction, ErrInvalidComponent, ErrInvalidMessage, ErrMissingOption, and ErrInvalidCommand. Register a router-wide handler with Router.OnError.

discordgo interop

DiscordKit is additive. You keep your existing *discordgo.Session, add router.Handle with Session.AddHandler, and use discordgo types everywhere. Every builder has a Build/component/conversion method that returns plain discordgo structs, and Raw / the exported Context.Session and Context.Interaction fields give you a full escape hatch at any time.

Compatibility

See docs/compatibility.md for the mapping between Discord API features, discordgo support, and DiscordKit coverage, including the components DiscordKit intentionally does not build (Radio Group, Checkbox Group and Checkbox, which discordgo cannot yet decode).

License

MIT. See LICENSE.

Documentation

Overview

Package discordkit provides an interaction framework built on top of discordgo. discordgo owns Discord models and transport; DiscordKit provides routing, typed command options, component validation, forms and response lifecycle.

Register routes before connecting a discordgo.Session. Attach a Router with Session.AddHandler(router.Handle). Handlers return errors to Router.OnError. Recovery is enabled by default. Access Context.Session for raw discordgo APIs.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrRouteNotFound      = errors.New("discordkit: route not found")
	ErrRouteConflict      = errors.New("discordkit: route conflict")
	ErrInvalidCustomID    = errors.New("discordkit: invalid custom ID")
	ErrAlreadyResponded   = errors.New("discordkit: interaction already acknowledged")
	ErrNotResponded       = errors.New("discordkit: interaction has not been acknowledged")
	ErrInvalidInteraction = errors.New("discordkit: operation is invalid for this interaction")
	ErrInvalidComponent   = errors.New("discordkit: invalid component")
	ErrInvalidMessage     = errors.New("discordkit: invalid message")
	ErrMissingOption      = errors.New("discordkit: option missing or invalid")
	ErrInvalidCommand     = errors.New("discordkit: invalid command")
)

Sentinel errors identify failures that callers can handle with errors.Is.

Functions

func AttachmentOption

func AttachmentOption(name, description string) *simpleOptionBuilder

AttachmentOption starts an attachment option builder.

func BooleanOption

func BooleanOption(name, description string) *simpleOptionBuilder

BooleanOption starts a boolean option builder.

func BuildCommands

func BuildCommands(builders ...*CommandBuilder) ([]*discordgo.ApplicationCommand, error)

BuildCommands builds a set of command builders, returning the first error.

func Components

func Components(nodes ...Component) []discordgo.MessageComponent

Components finalizes DSL nodes into a discordgo component slice, ready for a MessageSpec. Validation happens when the MessageSpec is resolved.

func MentionableOption

func MentionableOption(name, description string) *simpleOptionBuilder

MentionableOption starts a mentionable (user or role) option builder.

func RoleOption

func RoleOption(name, description string) *simpleOptionBuilder

RoleOption starts a role option builder.

func UserOption

func UserOption(name, description string) *simpleOptionBuilder

UserOption starts a user option builder.

func ValidateMessageComponents

func ValidateMessageComponents(components []discordgo.MessageComponent) error

ValidateMessageComponents checks a message component tree against Discord's structural rules and the 40-component limit. It returns ErrInvalidComponent.

func ValidateModalComponents

func ValidateModalComponents(components []discordgo.MessageComponent) error

ValidateModalComponents checks a modal component tree. Modern modals use Label wrappers around a single text input, string select or file upload.

Types

type ButtonBuilder

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

ButtonBuilder builds an interactive, link or premium button.

func Button

func Button(label, customID string) *ButtonBuilder

Button creates an interactive button with the given custom ID.

func LinkButton

func LinkButton(label, url string) *ButtonBuilder

LinkButton creates a link button that opens a URL.

func PremiumButton

func PremiumButton(skuID string) *ButtonBuilder

PremiumButton creates a premium upsell button for a SKU.

func (*ButtonBuilder) Danger

func (b *ButtonBuilder) Danger() *ButtonBuilder

func (*ButtonBuilder) Disabled

func (b *ButtonBuilder) Disabled() *ButtonBuilder

Disabled disables the button.

func (*ButtonBuilder) Emoji

Emoji sets a button emoji.

func (*ButtonBuilder) Primary

func (b *ButtonBuilder) Primary() *ButtonBuilder

Primary, Secondary, Success and Danger set an interactive button's style.

func (*ButtonBuilder) Secondary

func (b *ButtonBuilder) Secondary() *ButtonBuilder

func (*ButtonBuilder) Success

func (b *ButtonBuilder) Success() *ButtonBuilder

type ChannelOptionBuilder

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

ChannelOptionBuilder builds a channel command option with channel type limits.

func ChannelOption

func ChannelOption(name, description string) *ChannelOptionBuilder

ChannelOption starts a channel option builder.

func (*ChannelOptionBuilder) ChannelTypes

ChannelTypes restricts selectable channel types.

func (*ChannelOptionBuilder) NameLocalizations

func (b *ChannelOptionBuilder) NameLocalizations(m map[discordgo.Locale]string) *ChannelOptionBuilder

NameLocalizations sets localized names.

func (*ChannelOptionBuilder) Required

Required marks the option as required.

type ChannelSelectBuilder

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

ChannelSelectBuilder builds a channel select menu.

func ChannelSelect

func ChannelSelect(customID string) *ChannelSelectBuilder

ChannelSelect creates a channel select menu.

func (*ChannelSelectBuilder) ChannelTypes

ChannelTypes restricts selectable channel types.

func (*ChannelSelectBuilder) DefaultValues

DefaultValues sets auto-populated default channels.

func (*ChannelSelectBuilder) Disabled

Disabled disables the select menu.

func (*ChannelSelectBuilder) MaxValues

MaxValues sets the maximum number of selections.

func (*ChannelSelectBuilder) MinValues

MinValues sets the minimum number of selections.

func (*ChannelSelectBuilder) Placeholder

Placeholder sets placeholder text.

type ChoiceValue

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

ChoiceValue is a single predefined choice for a command option or an autocomplete response. Build one with Choice.

func Choice

func Choice(name string, value any) ChoiceValue

Choice creates a named choice. The value must be a string, integer or float.

func (ChoiceValue) Localized

func (c ChoiceValue) Localized(localizations map[discordgo.Locale]string) ChoiceValue

Localized attaches name localizations to a choice.

type CommandBuilder

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

CommandBuilder builds a *discordgo.ApplicationCommand with compile-time typed option builders and validation deferred to Build.

func Command

func Command(name, description string, options ...Option) *CommandBuilder

Command starts a chat (slash) command builder. Options may also be added with Options for readability.

func MessageCommand

func MessageCommand(name string) *CommandBuilder

MessageCommand starts a message context menu command builder.

func UserCommand

func UserCommand(name string) *CommandBuilder

UserCommand starts a user context menu command builder.

func (*CommandBuilder) Build

Build validates and returns the discordgo command.

func (*CommandBuilder) Contexts

Contexts sets the interaction contexts where the command is available.

func (*CommandBuilder) DefaultMemberPermissions

func (b *CommandBuilder) DefaultMemberPermissions(perms int64) *CommandBuilder

DefaultMemberPermissions sets the default member permission bitmask required to see and use the command.

func (*CommandBuilder) DescriptionLocalizations

func (b *CommandBuilder) DescriptionLocalizations(m map[discordgo.Locale]string) *CommandBuilder

DescriptionLocalizations sets localized command descriptions.

func (*CommandBuilder) IntegrationTypes

func (b *CommandBuilder) IntegrationTypes(types ...discordgo.ApplicationIntegrationType) *CommandBuilder

IntegrationTypes sets the installation contexts for the command.

func (*CommandBuilder) MustBuild

MustBuild is Build with panic on error, for static command declarations.

func (*CommandBuilder) NSFW

func (b *CommandBuilder) NSFW() *CommandBuilder

NSFW marks the command as age-restricted.

func (*CommandBuilder) NameLocalizations

func (b *CommandBuilder) NameLocalizations(m map[discordgo.Locale]string) *CommandBuilder

NameLocalizations sets localized command names.

func (*CommandBuilder) Options

func (b *CommandBuilder) Options(options ...Option) *CommandBuilder

Options appends command options.

type Component

type Component interface {
	// contains filtered or unexported methods
}

Component is a DSL node that finalizes into a concrete discordgo component. Every builder in this package implements it, and Raw wraps an existing discordgo component as an escape hatch.

func Raw

Raw lets callers drop a discordgo component directly into the DSL, so an unsupported Discord feature never blocks use of DiscordKit.

type ContainerBuilder

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

ContainerBuilder builds a container with an optional accent color.

func Container

func Container(children ...Component) *ContainerBuilder

Container groups components with a colored side bar.

func (*ContainerBuilder) AccentColor

func (b *ContainerBuilder) AccentColor(color int) *ContainerBuilder

AccentColor sets the container accent color.

func (*ContainerBuilder) Spoiler

func (b *ContainerBuilder) Spoiler() *ContainerBuilder

Spoiler marks the container as a spoiler.

type Context

type Context struct {
	Session     *discordgo.Session
	Interaction *discordgo.InteractionCreate
	// contains filtered or unexported fields
}

Context represents one interaction. Session and Interaction are escape hatches. Do not copy Context after use. Raw response calls bypass its lifecycle tracking.

func NewContext

NewContext creates a pending interaction context. Router normally calls this.

func (*Context) Attachment

func (c *Context) Attachment(name string) (*discordgo.MessageAttachment, bool)

Attachment returns a resolved attachment option.

func (*Context) Autocomplete

func (c *Context) Autocomplete(choices ...ChoiceValue) error

Autocomplete responds to an autocomplete interaction with up to 25 choices.

func (*Context) Bool

func (c *Context) Bool(name string) (bool, bool)

Bool reads a boolean option, preserving a supplied false value.

func (*Context) Channel

func (c *Context) Channel(name string) (*discordgo.Channel, bool)

Channel returns a resolved channel option.

func (*Context) ChannelID

func (c *Context) ChannelID() string

ChannelID returns the interaction's channel ID.

func (*Context) Context

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

Context returns the standard context used by DiscordKit's REST requests.

func (*Context) Defer

func (c *Context) Defer(ephemeral bool) error

Defer acknowledges a command interaction and shows a loading state. Edit the original response later with Edit. Pass ephemeral to hide the loading state.

func (*Context) DeferUpdate

func (c *Context) DeferUpdate() error

DeferUpdate acknowledges a component interaction without changing the message. Edit the message later with Edit. Only valid for component interactions.

func (*Context) DeleteResponse

func (c *Context) DeleteResponse() error

DeleteResponse deletes the original interaction response.

func (*Context) Edit

func (c *Context) Edit(spec MessageSpec) (*discordgo.Message, error)

Edit edits the original interaction response after Reply or Defer.

func (*Context) Ephemeral

func (c *Context) Ephemeral(spec MessageSpec) error

Ephemeral sends an initial response visible only to the invoking user.

func (*Context) EphemeralText

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

EphemeralText is a convenience for a plain text ephemeral response.

func (*Context) Float

func (c *Context) Float(name string) (float64, bool)

Float reads a finite number option.

func (*Context) FocusedOption

FocusedOption returns the currently focused autocomplete option.

func (*Context) Followup

func (c *Context) Followup(spec MessageSpec) (*discordgo.Message, error)

Followup sends an additional message after the interaction is acknowledged.

func (*Context) FollowupEdit

func (c *Context) FollowupEdit(messageID string, spec MessageSpec) (*discordgo.Message, error)

FollowupEdit edits a previously sent followup message by ID.

func (*Context) Form

func (c *Context) Form() *FormData

Form parses the modal submission attached to the context. It returns an empty FormData for non-modal interactions.

func (*Context) GuildID

func (c *Context) GuildID() string

GuildID returns the guild ID, or an empty string in DMs.

func (*Context) Int

func (c *Context) Int(name string) (int64, bool)

Int reads an integer option without truncation or precision loss.

func (*Context) IsDM

func (c *Context) IsDM() bool

IsDM reports whether a non-nil interaction was invoked outside a guild.

func (*Context) IsGuild

func (c *Context) IsGuild() bool

IsGuild reports whether the interaction was invoked in a guild.

func (*Context) Locale

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

Locale returns the invoking user's locale.

func (*Context) Member

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

Member returns the invoking guild member, or nil in DMs.

func (*Context) MemberOption

func (c *Context) MemberOption(name string) (*discordgo.Member, bool)

MemberOption joins a resolved member with its user without mutating discordgo data.

func (*Context) Mentionable

func (c *Context) Mentionable(name string) (Mentionable, bool)

Mentionable returns a resolved mentionable without assuming it is a user.

func (*Context) MustAttachment

func (c *Context) MustAttachment(name string) *discordgo.MessageAttachment

MustAttachment panics when the value is absent or invalid.

func (*Context) MustBool

func (c *Context) MustBool(name string) bool

MustBool panics when the value is absent or invalid.

func (*Context) MustChannel

func (c *Context) MustChannel(name string) *discordgo.Channel

MustChannel panics when the value is absent or invalid.

func (*Context) MustFloat

func (c *Context) MustFloat(name string) float64

MustFloat panics when the value is absent or invalid.

func (*Context) MustInt

func (c *Context) MustInt(name string) int64

MustInt panics when the value is absent or invalid.

func (*Context) MustMemberOption

func (c *Context) MustMemberOption(name string) *discordgo.Member

MustMemberOption panics when the value is absent or invalid.

func (*Context) MustMentionable

func (c *Context) MustMentionable(name string) Mentionable

MustMentionable panics when the value is absent or invalid.

func (*Context) MustParam

func (c *Context) MustParam(name string) string

MustParam panics when the value is absent or invalid.

func (*Context) MustRole

func (c *Context) MustRole(name string) *discordgo.Role

MustRole panics when the value is absent or invalid.

func (*Context) MustString

func (c *Context) MustString(name string) string

MustString panics when the value is absent or invalid.

func (*Context) MustUserOption

func (c *Context) MustUserOption(name string) *discordgo.User

MustUserOption panics when the value is absent or invalid.

func (*Context) Option

Option returns a leaf option from the selected subcommand, without fetching data.

func (*Context) Param

func (c *Context) Param(name string) (string, bool)

Param returns a decoded route parameter.

func (*Context) Reply

func (c *Context) Reply(spec MessageSpec) error

Reply sends an initial response as a new message. It fails with ErrAlreadyResponded if the interaction was already acknowledged.

func (*Context) ReplyText

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

ReplyText is a convenience for a plain text initial response.

func (*Context) RequireAttachment

func (c *Context) RequireAttachment(name string) (*discordgo.MessageAttachment, error)

RequireAttachment returns an error when the value is absent or invalid.

func (*Context) RequireBool

func (c *Context) RequireBool(name string) (bool, error)

RequireBool returns an error when the value is absent or invalid.

func (*Context) RequireChannel

func (c *Context) RequireChannel(name string) (*discordgo.Channel, error)

RequireChannel returns an error when the value is absent or invalid.

func (*Context) RequireFloat

func (c *Context) RequireFloat(name string) (float64, error)

RequireFloat returns an error when the value is absent or invalid.

func (*Context) RequireInt

func (c *Context) RequireInt(name string) (int64, error)

RequireInt returns an error when the value is absent or invalid.

func (*Context) RequireMemberOption

func (c *Context) RequireMemberOption(name string) (*discordgo.Member, error)

RequireMemberOption returns an error when the value is absent or invalid.

func (*Context) RequireMentionable

func (c *Context) RequireMentionable(name string) (Mentionable, error)

RequireMentionable returns an error when the value is absent or invalid.

func (*Context) RequireParam

func (c *Context) RequireParam(name string) (string, error)

RequireParam returns an error when the value is absent or invalid.

func (*Context) RequireRole

func (c *Context) RequireRole(name string) (*discordgo.Role, error)

RequireRole returns an error when the value is absent or invalid.

func (*Context) RequireString

func (c *Context) RequireString(name string) (string, error)

RequireString returns an error when the value is absent or invalid.

func (*Context) RequireUserOption

func (c *Context) RequireUserOption(name string) (*discordgo.User, error)

RequireUserOption returns an error when the value is absent or invalid.

func (*Context) Role

func (c *Context) Role(name string) (*discordgo.Role, bool)

Role returns a resolved role option.

func (*Context) SetContext

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

SetContext sets the request context before response operations; nil means Background.

func (*Context) ShowModal

func (c *Context) ShowModal(m Modal) error

ShowModal opens a modal as the initial response. Not valid for modal submit or autocomplete interactions.

func (*Context) String

func (c *Context) String(name string) (string, bool)

String reads a string option, including a supplied empty string.

func (*Context) Update

func (c *Context) Update(spec MessageSpec) error

Update replaces the message a component belongs to. Only valid as the initial response to a component interaction.

func (*Context) User

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

User returns the invoking user, in guilds or DMs, without network access.

func (*Context) UserOption

func (c *Context) UserOption(name string) (*discordgo.User, bool)

UserOption returns a resolved user, never performing an implicit REST request.

type CustomID

type CustomID string

CustomID identifies an interactive component or modal. Validate before sending.

func (CustomID) Validate

func (id CustomID) Validate() error

Validate checks Discord's 1–100 character limit and excludes control characters.

type EntitySelectBuilder

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

EntitySelectBuilder builds a user, role or mentionable auto-populated select.

func MentionableSelect

func MentionableSelect(customID string) *EntitySelectBuilder

MentionableSelect creates a mentionable (user or role) select menu.

func RoleSelect

func RoleSelect(customID string) *EntitySelectBuilder

RoleSelect creates a role select menu.

func UserSelect

func UserSelect(customID string) *EntitySelectBuilder

UserSelect creates a user select menu.

func (*EntitySelectBuilder) DefaultValues

DefaultValues sets auto-populated default values.

func (*EntitySelectBuilder) Disabled

Disabled disables the select menu.

func (*EntitySelectBuilder) MaxValues

func (b *EntitySelectBuilder) MaxValues(n int) *EntitySelectBuilder

MaxValues sets the maximum number of selections.

func (*EntitySelectBuilder) MinValues

func (b *EntitySelectBuilder) MinValues(n int) *EntitySelectBuilder

MinValues sets the minimum number of selections.

func (*EntitySelectBuilder) Placeholder

func (b *EntitySelectBuilder) Placeholder(p string) *EntitySelectBuilder

Placeholder sets placeholder text.

type FieldBuilder

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

FieldBuilder wraps a single modal input in a Label.

func Field

func Field(label string, input Component) *FieldBuilder

Field wraps a modal input (text input, string select or file upload) with a visible label, producing a discordgo.Label.

func (*FieldBuilder) Description

func (b *FieldBuilder) Description(d string) *FieldBuilder

Description adds helper text below the label.

type FileBuilder

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

FileBuilder builds a file display component.

func File

func File(url string) *FileBuilder

File displays an uploaded file referenced by attachment://name.

func (*FileBuilder) Spoiler

func (b *FileBuilder) Spoiler() *FileBuilder

Spoiler marks the file as a spoiler.

type FileUploadBuilder

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

FileUploadBuilder builds a file upload input for a modal field.

func FileUpload

func FileUpload(customID string) *FileUploadBuilder

FileUpload creates a file upload input for a modal field.

func (*FileUploadBuilder) FileTypes

func (b *FileUploadBuilder) FileTypes(types ...string) *FileUploadBuilder

FileTypes restricts accepted uploads by extension, e.g. "png", "pdf". This is a DiscordKit request-only extension over discordgo's FileUpload.

func (*FileUploadBuilder) MaxValues

func (b *FileUploadBuilder) MaxValues(n int) *FileUploadBuilder

MaxValues sets the maximum number of files.

func (*FileUploadBuilder) MinValues

func (b *FileUploadBuilder) MinValues(n int) *FileUploadBuilder

MinValues sets the minimum number of files.

func (*FileUploadBuilder) Required

func (b *FileUploadBuilder) Required(required bool) *FileUploadBuilder

Required sets whether at least one file must be uploaded.

type FormData

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

FormData provides typed, reflection-free access to a modal submission.

func (*FormData) Files

func (f *FormData) Files(customID string) ([]*discordgo.MessageAttachment, bool)

Files returns the resolved attachments uploaded to a file upload input.

func (*FormData) MustString

func (f *FormData) MustString(customID string) string

MustString panics when the field is absent.

func (*FormData) RequireFiles

func (f *FormData) RequireFiles(customID string) ([]*discordgo.MessageAttachment, error)

RequireFiles returns an error when the field is absent.

func (*FormData) RequireString

func (f *FormData) RequireString(customID string) (string, error)

RequireString returns an error when the field is absent.

func (*FormData) RequireStrings

func (f *FormData) RequireStrings(customID string) ([]string, error)

RequireStrings returns an error when the field is absent.

func (*FormData) String

func (f *FormData) String(customID string) (string, bool)

String returns a text input value, or the first value of a single-value select.

func (*FormData) Strings

func (f *FormData) Strings(customID string) ([]string, bool)

Strings returns all selected values for a select or file upload input.

type GalleryBuilder

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

GalleryBuilder builds a media gallery.

func Gallery(items ...GalleryItem) *GalleryBuilder

Gallery creates a media gallery of 1-10 items.

type GalleryItem

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

GalleryItem is a single media gallery entry.

func MediaItem

func MediaItem(url string) GalleryItem

MediaItem creates a gallery item from a media URL.

func (GalleryItem) Description

func (g GalleryItem) Description(d string) GalleryItem

Description sets alt text on a gallery item.

func (GalleryItem) Spoiler

func (g GalleryItem) Spoiler() GalleryItem

Spoiler marks a gallery item as a spoiler.

type Group

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

Group shares a route prefix and middleware. Command prefixes use spaces; custom ID prefixes use slashes. A group does not create a separate router.

func (*Group) Autocomplete

func (g *Group) Autocomplete(p, o string, h Handler, m ...Middleware) error

Autocomplete registers an autocomplete handler in the group.

func (*Group) Command

func (g *Group) Command(p string, h Handler, m ...Middleware) error

Command registers a command in the group.

func (*Group) Component

func (g *Group) Component(p string, h Handler, m ...Middleware) error

Component registers a component in the group.

func (*Group) Modal

func (g *Group) Modal(p string, h Handler, m ...Middleware) error

Modal registers a modal in the group.

type Handler

type Handler func(*Context) error

Handler handles a single interaction.

type IntegerOptionBuilder

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

IntegerOptionBuilder builds an integer command option.

func IntegerOption

func IntegerOption(name, description string) *IntegerOptionBuilder

IntegerOption starts an integer option builder.

func (*IntegerOptionBuilder) Autocomplete

func (b *IntegerOptionBuilder) Autocomplete() *IntegerOptionBuilder

Autocomplete enables dynamic autocomplete. Mutually exclusive with Choices.

func (*IntegerOptionBuilder) Choices

func (b *IntegerOptionBuilder) Choices(choices ...ChoiceValue) *IntegerOptionBuilder

Choices restricts the option to a predefined set. Mutually exclusive with Autocomplete.

func (*IntegerOptionBuilder) Max

Max sets the maximum value.

func (*IntegerOptionBuilder) Min

Min sets the minimum value.

func (*IntegerOptionBuilder) NameLocalizations

func (b *IntegerOptionBuilder) NameLocalizations(m map[discordgo.Locale]string) *IntegerOptionBuilder

NameLocalizations sets localized names.

func (*IntegerOptionBuilder) Required

Required marks the option as required.

type Mentionable

type Mentionable struct {
	User *discordgo.User
	Role *discordgo.Role
}

Mentionable is a resolved user-or-role union. Valid reports its invariant.

func (Mentionable) Valid

func (m Mentionable) Valid() bool

Valid reports whether exactly one of User and Role is present.

type MessageSpec

type MessageSpec struct {
	Content         string
	Components      []discordgo.MessageComponent
	Embeds          []*discordgo.MessageEmbed
	Files           []*discordgo.File
	Attachments     []*discordgo.MessageAttachment
	AllowedMentions *discordgo.MessageAllowedMentions
	Poll            *discordgo.Poll
	Ephemeral       bool
}

MessageSpec is the single source of truth for an outgoing message or interaction response. It converts, without duplicating rules, into every discordgo payload shape used across the response lifecycle.

When Components contains Components V2 layout components, MessageSpec applies the IS_COMPONENTS_V2 flag, converts Content into a leading TextDisplay, and rejects payloads that Discord forbids (legacy embeds and polls).

func (MessageSpec) InteractionResponseData

func (m MessageSpec) InteractionResponseData() (*discordgo.InteractionResponseData, error)

InteractionResponseData converts the spec into interaction response data, applying Components V2 normalization and flags.

func (MessageSpec) MessageEdit

func (m MessageSpec) MessageEdit(channelID, messageID string) (*discordgo.MessageEdit, error)

MessageEdit converts the spec into a channel message edit for the given channel and message IDs.

func (MessageSpec) WebhookEdit

func (m MessageSpec) WebhookEdit() (*discordgo.WebhookEdit, error)

WebhookEdit converts the spec into a webhook edit payload used to edit the original interaction response or a followup message.

func (MessageSpec) WebhookParams

func (m MessageSpec) WebhookParams() (*discordgo.WebhookParams, error)

WebhookParams converts the spec into followup webhook params. Discord's webhook create endpoint has no poll field, so a poll is rejected here.

type Middleware

type Middleware func(Handler) Handler

Middleware wraps a Handler. The first middleware registered runs outermost.

func Logging

func Logging(logger *slog.Logger) Middleware

Logging logs latency and errors without interaction tokens, content or options.

func Recovery

func Recovery() Middleware

Recovery converts handler panics to PanicError; it never replies to a user. Router applies Recovery automatically, outside all configured middleware.

func RequireGuild

func RequireGuild() Middleware

RequireGuild rejects interactions outside a guild.

func RequirePermissions

func RequirePermissions(permissions int64) Middleware

RequirePermissions checks the invoking member's interaction permissions. Administrator bypasses the bit check. This does not check the bot's permissions.

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

Modal is a validated modal ready to be shown with Context.ShowModal.

func ModalOf

func ModalOf(customID, title string, components ...discordgo.MessageComponent) Modal

ModalOf constructs a modal from raw discordgo components as a low-level escape hatch when the Form DSL is insufficient.

type ModalBuilder

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

ModalBuilder builds a modal from field components.

func Form

func Form(customID, title string, fields ...Component) *ModalBuilder

Form starts a modal builder using modern Label-wrapped fields.

func (*ModalBuilder) Build

func (b *ModalBuilder) Build() (Modal, error)

Build validates and returns the modal.

func (*ModalBuilder) Fields

func (b *ModalBuilder) Fields(fields ...Component) *ModalBuilder

Fields appends additional fields to the form.

func (*ModalBuilder) MustBuild

func (b *ModalBuilder) MustBuild() Modal

MustBuild is Build with panic on error, for static modal declarations.

type NumberOptionBuilder

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

NumberOptionBuilder builds a floating-point command option.

func NumberOption

func NumberOption(name, description string) *NumberOptionBuilder

NumberOption starts a number (float) option builder.

func (*NumberOptionBuilder) Autocomplete

func (b *NumberOptionBuilder) Autocomplete() *NumberOptionBuilder

Autocomplete enables dynamic autocomplete. Mutually exclusive with Choices.

func (*NumberOptionBuilder) Choices

func (b *NumberOptionBuilder) Choices(choices ...ChoiceValue) *NumberOptionBuilder

Choices restricts the option to a predefined set. Mutually exclusive with Autocomplete.

func (*NumberOptionBuilder) Max

Max sets the maximum value.

func (*NumberOptionBuilder) Min

Min sets the minimum value.

func (*NumberOptionBuilder) NameLocalizations

func (b *NumberOptionBuilder) NameLocalizations(m map[discordgo.Locale]string) *NumberOptionBuilder

NameLocalizations sets localized names.

func (*NumberOptionBuilder) Required

Required marks the option as required.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option is a command option builder that produces a discordgo option.

type PanicError

type PanicError struct {
	Value any
	Stack []byte
}

PanicError describes a recovered panic. Stack is only for server-side logging. Error intentionally excludes the panic value, which might contain secrets.

func (*PanicError) Error

func (e *PanicError) Error() string

func (*PanicError) Unwrap

func (e *PanicError) Unwrap() error

Unwrap exposes a panic error to errors.Is and errors.As.

type RouteBuilder

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

RouteBuilder binds named path parameters without treating parameter values as paths.

func Route

func Route(pattern string) *RouteBuilder

Route starts a custom ID from a pattern such as /jobs/:jobID/save.

func (*RouteBuilder) Build

func (b *RouteBuilder) Build() (CustomID, error)

Build validates the pattern and all bindings, and enforces the final ID limit.

func (*RouteBuilder) MustBuild

func (b *RouteBuilder) MustBuild() CustomID

MustBuild is Build with panic on error, for static application configuration.

func (*RouteBuilder) Param

func (b *RouteBuilder) Param(name, value string) *RouteBuilder

Param sets a raw, unescaped parameter. Build escapes each value exactly once.

type Router

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

Router is a shared routing core for commands, components, modals and autocomplete. Recovery is always outermost. Registration and dispatch are concurrency safe.

func NewRouter

func NewRouter(middleware ...Middleware) *Router

NewRouter creates a router. Middleware executes in the order supplied.

func (*Router) Autocomplete

func (r *Router) Autocomplete(path, option string, h Handler, m ...Middleware) error

Autocomplete registers a command path and focused option name.

func (*Router) Command

func (r *Router) Command(path string, h Handler, m ...Middleware) error

Command registers a slash or context command path, e.g. "jobs search".

func (*Router) Component

func (r *Router) Component(path string, h Handler, m ...Middleware) error

Component registers a custom ID route, with optional named path parameters.

func (*Router) Dispatch

func (r *Router) Dispatch(c *Context) error

Dispatch routes an interaction and returns handler errors. It does not call OnError.

func (*Router) Group

func (r *Router) Group(prefix string, m ...Middleware) *Group

Group creates a group whose registrations share this router.

func (*Router) Handle

Handle is a discordgo InteractionCreate handler. Attach using Session.AddHandler.

func (*Router) Modal

func (r *Router) Modal(path string, h Handler, m ...Middleware) error

Modal registers a modal submission route.

func (*Router) OnError

func (r *Router) OnError(h func(*Context, error))

OnError sets the error hook. A nil hook uses structured server-side logging. Error hooks should not panic. No stack trace or automatic error reply is sent.

func (*Router) Use

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

Use appends global middleware, including for previously registered routes.

type RowBuilder

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

RowBuilder builds an action row.

func Row

func Row(children ...Component) *RowBuilder

Row groups interactive components. A row with a select must contain only it.

type SectionBuilder

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

SectionBuilder builds a section: 1-3 text displays plus an accessory.

func Section

func Section(texts ...Component) *SectionBuilder

Section groups text displays with a button or thumbnail accessory.

func (*SectionBuilder) Accessory

func (b *SectionBuilder) Accessory(a Component) *SectionBuilder

Accessory sets the section accessory (a button or thumbnail).

type SelectOptionBuilder

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

SelectOptionBuilder builds a string select option.

func SelectOption

func SelectOption(label, value string) *SelectOptionBuilder

SelectOption creates a string select option.

func (*SelectOptionBuilder) Default

Default marks the option selected by default.

func (*SelectOptionBuilder) Description

func (b *SelectOptionBuilder) Description(d string) *SelectOptionBuilder

Description sets the option description.

func (*SelectOptionBuilder) Emoji

Emoji sets the option emoji.

type SeparatorBuilder

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

SeparatorBuilder builds a separator.

func Separator

func Separator() *SeparatorBuilder

Separator creates a visual separator.

func (*SeparatorBuilder) Divider

func (b *SeparatorBuilder) Divider(on bool) *SeparatorBuilder

Divider toggles the visible divider line.

func (*SeparatorBuilder) Large

func (b *SeparatorBuilder) Large() *SeparatorBuilder

Large sets large spacing; the default spacing is small.

type StringOptionBuilder

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

StringOptionBuilder builds a string command option.

func StringOption

func StringOption(name, description string) *StringOptionBuilder

StringOption starts a string option builder.

func (*StringOptionBuilder) Autocomplete

func (b *StringOptionBuilder) Autocomplete() *StringOptionBuilder

Autocomplete enables dynamic autocomplete. Mutually exclusive with Choices.

func (*StringOptionBuilder) Choices

func (b *StringOptionBuilder) Choices(choices ...ChoiceValue) *StringOptionBuilder

Choices restricts the option to a predefined set. Mutually exclusive with Autocomplete.

func (*StringOptionBuilder) MaxLen

MaxLen sets the maximum string length.

func (*StringOptionBuilder) MinLen

MinLen sets the minimum string length.

func (*StringOptionBuilder) NameLocalizations

func (b *StringOptionBuilder) NameLocalizations(m map[discordgo.Locale]string) *StringOptionBuilder

NameLocalizations sets localized names.

func (*StringOptionBuilder) Required

Required marks the option as required.

type StringSelectBuilder

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

StringSelectBuilder builds a string select menu with manual options.

func StringSelect

func StringSelect(customID string) *StringSelectBuilder

StringSelect creates a string select menu.

func (*StringSelectBuilder) Disabled

Disabled disables the select menu.

func (*StringSelectBuilder) MaxValues

func (b *StringSelectBuilder) MaxValues(n int) *StringSelectBuilder

MaxValues sets the maximum number of selections.

func (*StringSelectBuilder) MinValues

func (b *StringSelectBuilder) MinValues(n int) *StringSelectBuilder

MinValues sets the minimum number of selections.

func (*StringSelectBuilder) Options

Options sets the selectable options. Only string selects accept manual options.

func (*StringSelectBuilder) Placeholder

func (b *StringSelectBuilder) Placeholder(p string) *StringSelectBuilder

Placeholder sets placeholder text.

func (*StringSelectBuilder) Required

Required marks the select as required within a modal label.

type SubCommandBuilder

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

SubCommandBuilder builds a subcommand option.

func SubCommand

func SubCommand(name, description string, options ...Option) *SubCommandBuilder

SubCommand starts a subcommand with its own leaf options.

func (*SubCommandBuilder) NameLocalizations

func (b *SubCommandBuilder) NameLocalizations(m map[discordgo.Locale]string) *SubCommandBuilder

NameLocalizations sets localized names.

type SubCommandGroupBuilder

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

SubCommandGroupBuilder builds a subcommand group option.

func SubCommandGroup

func SubCommandGroup(name, description string, subcommands ...*SubCommandBuilder) *SubCommandGroupBuilder

SubCommandGroup starts a subcommand group containing subcommands.

func (*SubCommandGroupBuilder) NameLocalizations

NameLocalizations sets localized names.

type SyncOptions

type SyncOptions struct {
	// GuildID scopes synchronization to a guild. Empty means global commands.
	GuildID string
	// Delete removes remote commands that are no longer declared. When false,
	// obsolete commands are reported but left in place.
	Delete bool
}

SyncOptions configures command synchronization scope and deletion behavior.

type SyncPlan

type SyncPlan struct {
	Create    []*discordgo.ApplicationCommand
	Update    []*discordgo.ApplicationCommand
	Unchanged []*discordgo.ApplicationCommand
	Delete    []*discordgo.ApplicationCommand
}

SyncPlan is the result of diffing declared commands against remote commands. It is computed without any Discord API calls and is safe to inspect in tests.

func DiffCommands

func DiffCommands(remote, desired []*discordgo.ApplicationCommand, deleteObsolete bool) SyncPlan

DiffCommands computes the synchronization plan between remote and desired commands, matching by name and type. When deleteObsolete is false, obsolete remote commands are omitted from Delete. This function performs no I/O.

func SyncCommands

func SyncCommands(s *discordgo.Session, appID string, desired []*discordgo.ApplicationCommand, opts SyncOptions) (SyncPlan, error)

SyncCommands synchronizes declared commands with Discord: creating missing commands, updating divergent ones, and optionally deleting obsolete ones. It returns the plan that was applied. Commands with no diff are left untouched.

func (SyncPlan) Empty

func (p SyncPlan) Empty() bool

Empty reports whether the plan requires no create, update or delete actions.

type TextDisplayBuilder

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

TextDisplayBuilder builds a Components V2 text display.

func Text

func Text(content string) *TextDisplayBuilder

Text creates a text display component.

type TextInputBuilder

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

TextInputBuilder builds a text input for a modal field.

func TextInput

func TextInput(customID string) *TextInputBuilder

TextInput creates a short text input. The visible label belongs to the Field.

func (*TextInputBuilder) MaxLen

func (b *TextInputBuilder) MaxLen(n int) *TextInputBuilder

MaxLen sets the maximum length.

func (*TextInputBuilder) MinLen

func (b *TextInputBuilder) MinLen(n int) *TextInputBuilder

MinLen sets the minimum length.

func (*TextInputBuilder) Paragraph

func (b *TextInputBuilder) Paragraph() *TextInputBuilder

Paragraph switches to a multi-line paragraph style.

func (*TextInputBuilder) Placeholder

func (b *TextInputBuilder) Placeholder(p string) *TextInputBuilder

Placeholder sets placeholder text.

func (*TextInputBuilder) Required

func (b *TextInputBuilder) Required(required bool) *TextInputBuilder

Required sets whether the input must be filled.

func (*TextInputBuilder) Value

Value sets a prefilled value.

type ThumbnailBuilder

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

ThumbnailBuilder builds a thumbnail accessory.

func Thumbnail

func Thumbnail(url string) *ThumbnailBuilder

Thumbnail creates a thumbnail from a media URL.

func (*ThumbnailBuilder) Description

func (b *ThumbnailBuilder) Description(d string) *ThumbnailBuilder

Description sets alt text.

func (*ThumbnailBuilder) Spoiler

func (b *ThumbnailBuilder) Spoiler() *ThumbnailBuilder

Spoiler marks the thumbnail as a spoiler.

Directories

Path Synopsis
examples
basic command
Command basic is a minimal DiscordKit bot: one slash command, synced on start.
Command basic is a minimal DiscordKit bot: one slash command, synced on start.
components command
Command components shows a Components V2 message, a component route with a typed custom ID, and a modal form round-trip.
Command components shows a Components V2 message, a component route with a typed custom ID, and a modal form round-trip.

Jump to

Keyboard shortcuts

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