gdiscordbot

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 14, 2026 License: MIT Imports: 10 Imported by: 1 module, 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

gdiscordbot

A high-level Go framework over bwmarrin/discordgo for building Discord bots.

  • Module path: github.com/grontis/gdiscordbot
  • Go: 1.24+
  • discordgo: pinned at v0.29.0

What you get

  • Slash commands with typed option builders (String/Int/Bool/Number/User/Channel/Role) and per-option autocomplete, returned as Option Handles — no reflection, no struct tags.
  • Router over all four interaction kinds (command, component, modal, autocomplete) with a CustomID pattern grammar that mints and matches from the same source.
  • Middleware (RequirePermissions, Cooldown, Recover) composed global → module → route.
  • Modules with Setup/Teardown lifecycle and reverse-order shutdown.
  • Sync that diffs your declared command tree against Discord and bulk-overwrites only on change.
  • Capability errors detected via errors.As — return UserFacing from a handler and the default error middleware replies for you.
  • The full *discordgo.Session is always one method call away (ctx.Session()) — no leaky escape.

Install

go get github.com/grontis/gdiscordbot@latest

Minimal bot

package main

import (
    "log"
    "os"

    gdiscordbot "github.com/grontis/gdiscordbot"
    "github.com/grontis/gdiscordbot/command"
    "github.com/grontis/gdiscordbot/event"
    "github.com/grontis/gdiscordbot/gdctx"
    "github.com/grontis/gdiscordbot/router"
)

type PingModule struct{}

func (m *PingModule) Register(r *router.Router) {
    cmd := command.New("ping", "Replies pong")
    r.Command(cmd, func(ctx *gdctx.Context) error {
        return ctx.Reply("pong")
    })
}

func (m *PingModule) Listeners() []event.Listener { return nil }
func (m *PingModule) Setup(*gdiscordbot.Bot) error    { return nil }
func (m *PingModule) Teardown(*gdiscordbot.Bot) error { return nil }

func main() {
    bot, err := gdiscordbot.New(os.Getenv("DISCORD_TOKEN"),
        gdiscordbot.WithModule(&PingModule{}),
    )
    if err != nil { log.Fatal(err) }
    if err := bot.Run(); err != nil { log.Fatal(err) }
}

Running the example

The repo ships a kitchensink example — a multi-module bot that exercises essentially the entire v1 surface: all option types, autocomplete, subcommands, cooldown and permission middleware, components, a modal, event listeners, and custom UserFacing/Presenter errors:

DISCORD_TOKEN=<your-bot-token> go run ./examples/kitchensink

Source: examples/kitchensink/ — see its README and TESTING.md.

Build & test

go build ./...
go test -race ./...

Further reading

Documentation

Overview

Package gdiscordbot is a high-level framework over github.com/bwmarrin/discordgo for building Discord bots. It provides a Router for interactions, typed Option Handles for Command options, middleware, diff-then-bulk Command syncing, Modules, Event listeners, and capability-based error handling. See the docs/ directory for the full design.

Package gdiscordbot is the root framework package. It provides the Bot type, lifecycle management (New, Run, Start, Close), functional options, and re-exports the interaction Context so bot authors import only this package in their handlers.

Usage: create a Bot with New, register Modules via WithModule, then call Run (blocking) or Start + Close (non-blocking). See SPEC §2.1, §2.6 and CONTEXT.md for terminology.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Bot

type Bot struct {
	*discordgo.Session
	// contains filtered or unexported fields
}

Bot is the top-level framework object. It wires Modules onto the Router, manages the Discord gateway lifecycle, and synchronizes the application command catalog at startup.

Embed or compose Bot to build your application. Always use Bot.Session as the escape hatch for discordgo capabilities not exposed by this framework (ADR 0001).

func New

func New(token string, opts ...Option) (*Bot, error)

New creates a Bot with the given token and options. It validates the token, creates the discordgo session, applies global middleware, and wires the router's Dispatch handler. It does NOT connect to the Discord gateway — call Run or Start for that.

Returns an error if token is empty or if discordgo session creation fails.

func (*Bot) Close

func (b *Bot) Close() error

Close closes the Discord gateway session. Call after cancelling the context passed to Start to ensure a clean shutdown.

func (*Bot) Run

func (b *Bot) Run(ctx context.Context) error

Run opens the Discord gateway, runs the full lifecycle, and blocks until ctx is cancelled. It returns after all modules' Teardown completes.

Lifecycle: Open gateway → Register modules → Sync commands → Setup modules (in order) → block on ctx → Teardown modules (reverse order).

func (*Bot) Start

func (b *Bot) Start(ctx context.Context) error

Start opens the Discord gateway and launches the lifecycle in a goroutine. It returns once the gateway is open, or on error. The goroutine exits (after Teardown) when ctx is cancelled. Call Close after cancelling ctx for a clean shutdown. Use Wait to observe the lifecycle goroutine's error after it exits.

func (*Bot) Wait

func (b *Bot) Wait() error

Wait blocks until the lifecycle goroutine (started by Start) exits and returns its error. Must be called at most once after Start. If Run was used instead of Start, Wait returns immediately with the same error Run returned.

type Context

type Context = gdctx.Context

Context is the per-interaction object handed to every handler. It is a type alias for gdctx.Context so that bot authors import only this root package. See SPEC §2.2 and Q1.

type Handler

type Handler = gdctx.Handler

Handler is the interaction handler function signature. Type alias for gdctx.Handler.

type Middleware

type Middleware = middleware.Middleware

Middleware is the middleware function signature. Type alias for middleware.Middleware.

type Option

type Option func(*config)

Option is a functional option for configuring a Bot. Pass Options to New.

func WithDevGuild

func WithDevGuild(guildID string) Option

WithDevGuild configures a guild ID for instant command sync during development. When set, commands sync exclusively to that guild (instant propagation) instead of the global scope. Use for development iteration; remove or leave empty to sync globally in production. An empty guildID is a no-op.

func WithErrorMiddleware

func WithErrorMiddleware(mw ...middleware.Middleware) Option

WithErrorMiddleware prepends middleware in front of the default error-handling middleware (Phase 7). The prepended middleware runs before the framework's built-in error resolution logic. Repeatable — each call appends to the error middleware list.

func WithIntents

func WithIntents(i discordgo.Intent) Option

WithIntents overrides the default Discord gateway intents. The default is discordgo.IntentsGuilds | discordgo.IntentsGuildMessages (non-privileged baseline). Provide all required intents; this call replaces (does not append to) the default.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger sets the logger used by the Bot, Router, and event listeners. The default is slog.Default().

func WithMiddleware

func WithMiddleware(mw ...middleware.Middleware) Option

WithMiddleware appends global interaction middleware. Applied to all handlers registered after New returns, in global → module → route composition order. Repeatable — each call appends to the global middleware stack.

func WithModule

func WithModule(m module.Module) Option

WithModule registers a Module with the Bot. Modules are initialized in registration order (Setup) and torn down in reverse order (Teardown). Repeatable — each call appends the module to the list.

func WithModules

func WithModules(mods ...module.Module) Option

WithModules registers multiple Modules at once. Equivalent to calling WithModule for each module in order.

func WithSyncer

func WithSyncer(s syncdiscord.Syncer) Option

WithSyncer injects a custom Syncer. The default is sync.NewBulkSyncer(). Inject a fake Syncer in tests to verify sync behavior without hitting Discord.

func WithoutAutoSync

func WithoutAutoSync() Option

WithoutAutoSync disables the automatic command sync that normally runs at startup. Use when you manage the command catalog yourself or want to skip it in tests.

Directories

Path Synopsis
Package command declares Commands and their typed Option Handles.
Package command declares Commands and their typed Option Handles.
Package errs defines the optional Error capability interfaces a domain error may implement to control how the framework presents it: UserFacing (supplies a user-safe message) and Presenter (renders its own response).
Package errs defines the optional Error capability interfaces a domain error may implement to control how the framework presents it: UserFacing (supplies a user-safe message) and Presenter (renders its own response).
Package event provides the Event listener family: typed handlers over raw discordgo gateway events (for example MessageCreate or GuildMemberAdd), bundled in a Module.
Package event provides the Event listener family: typed handlers over raw discordgo gateway events (for example MessageCreate or GuildMemberAdd), bundled in a Module.
examples
kitchensink command
Command kitchensink is a comprehensive tour of the gdiscordbot framework.
Command kitchensink is a comprehensive tour of the gdiscordbot framework.
Package gdctx defines the per-interaction Context handed to interaction Handlers.
Package gdctx defines the per-interaction Context handed to interaction Handlers.
Package middleware defines the Middleware type — func(next Handler) Handler — and the built-in middleware (RequirePermissions, Cooldown, Recover).
Package middleware defines the Middleware type — func(next Handler) Handler — and the built-in middleware (RequirePermissions, Cooldown, Recover).
Package module defines the Module interface — a compile-time unit that bundles related Commands, Component and Modal Routes, and Event listeners, with optional Setup and Teardown hooks.
Package module defines the Module interface — a compile-time unit that bundles related Commands, Component and Modal Routes, and Event listeners, with optional Setup and Teardown hooks.
Package router provides the Router: the single component that dispatches every incoming interaction — Commands, Component and Modal Routes, and autocomplete — to a Handler, through one unified API and middleware model.
Package router provides the Router: the single component that dispatches every incoming interaction — Commands, Component and Modal Routes, and autocomplete — to a Handler, through one unified API and middleware model.
Package sync reconciles the bot's declared Command set with what Discord has registered.
Package sync reconciles the bot's declared Command set with what Discord has registered.

Jump to

Keyboard shortcuts

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