discord

package module
v0.32.1 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: MIT Imports: 24 Imported by: 2

README

comms-discord

The Discord provider for comms — read channels, reply in threads, moderate and run slash commands

Go Reference Pipeline phpboyscout Go toolkit

Part of the phpboyscout Go toolkit — small, framework-free Go modules. Docs: comms.go.phpboyscout.uk


Import it for its side effect and reach it by name. Your code never mentions Discord again.

import _ "gitlab.com/phpboyscout/go/comms-discord"

// One client is one gateway. Declare what you will use: the provider asks
// Discord for that and nothing more.
c, _ := comms.NewClient(ctx, "discord", comms.ClientConfig{
    Token: os.Getenv("DISCORD_TOKEN"),
    Needs: []comms.Need{comms.NeedMessages, comms.NeedInteractions},
})
defer c.Close()

// One provider is one guild. Serving several means several of these, over the
// same connection.
p, _ := c.Provider(ctx, guildID, comms.WithAllowedChannels(channelID))

if err := p.Reader.Connect(ctx); err != nil {
    return err
}

for msg := range p.Reader.Messages() {
    p.Actor.ReplyInThread(ctx, msg.Ref(), "help", answer)
}

Capabilities

All ten optional interfaces are implemented, found by type assertion through the core module's As* helpers, and only when the matching need was declared.

Capability What it adds
Moderator delete a message, time a member out
MemberInspector a member's roles, and when they joined
Author replace or delete a message the bot posted
Interactive prompts with buttons, forms, replies, and replacing a card once it has been actioned
Commands guild-scoped slash commands, with subcommands, groups and typed options
Indicator set the bot's nickname in the guild
VoiceParticipants who is in a voice channel now, without joining it
ReactionObserver reactions landing on and leaving messages
VoiceReceiver join a voice channel and receive decrypted Opus
VoiceSender send Opus into the channel joined

VoiceReceiver and VoiceSender exist only in a build with CGO, because DAVE needs libdave. Without it the two are absent rather than failing, and AsVoiceReceiver answers false exactly as it does for a platform with no voice at all.

A read-only provider has no Actor at all, so it yields none of these but VoiceParticipants and ReactionObserver, which hang off the Reader.

Voice without a gateway

voicenode is a second comms.Client in this module: audio only, no gateway, no REST and no token. It joins voice channels through a Control link to whichever process holds the gateway session, and the two gateway events a join waits on come back through voicenode.Events. It refuses NeedMessages at construction, its Actor answers ErrUnsupported to anything textual, and it is deliberately not registered, because a ClientConfig carries a token a node must never hold.

node, err := voicenode.New(voicenode.Config{
    Control: link,          // your side of spec 0023's control channel
    Self:    botUserID,     // the node cannot ask Discord who it is
    Needs:   []comms.Need{comms.NeedVoiceReceive, comms.NeedVoiceSend},
})

It needs CGO, as the provider's own voice does. Without it the package is a doc comment and nothing else.

voicenode/link and voicenode/broker are that Control, over a messaging.Bus. Neither needs CGO: a control link is a bus client with no audio in it.

A worker holds nodes and no token:

l, _ := link.New(link.Config{Bot: botID, Self: botID, Worker: "capture-1"})
bus, _ := messaging.New(backend, messaging.Settings{
    Subscriptions: l.Subscriptions(), Source: source,
})
l.Bind(bus)
node, _ := voicenode.New(voicenode.Config{Control: l, Self: botID, Needs: needs})
_ = l.Attach(node)

A broker holds the gateway and no voice:

b, _ := broker.New(store, broker.Config{Bot: botID})
bus, _ := messaging.New(backend, messaging.Settings{
    Subscriptions: b.Subscriptions(), Source: source,
})
b.Bind(bus)
rs, _ := b.ResumeState(ctx)
c, _ := discord.NewClient(cfg, discord.WithControl(b), discord.WithResumeState(rs.SessionID, rs.Sequence, rs.ResumeURL))
go func() { errs <- b.Run(ctx) }()
_ = bus.Start(ctx)
_ = discord.ConnectControl(ctx, c)

WithControl takes this provider's own voice away, because a process serving voice workers must not compete with them for the one voice connection per guild Discord allows. ConnectControl opens that client's gateway: a broker holds no space, and Connect belongs to a scope.

The Store is where claims live. broker.NewMemoryStore is the test carrier; anything else must pass broker/storetest.

Spec 0023 on the wiki is the decision record for all of it.

Why disgo

disgoorg/disgo, chosen over discordgo and arikawa for one reason: it implements resume_gateway_url.

When a connection drops, Discord expects the client to reconnect to the endpoint it nominated for resuming. Reconnect anywhere else and the resume may be refused, which degrades to a fresh IDENTIFY — and every event buffered during the gap is gone. For a support bot those are questions nobody will ever answer, lost with no error and no trace.

That property is invisible in ordinary use, so it is covered by a regression test that cuts a live connection and asserts the session resumed (just test-integration). Reader.State().LastReconnectLostEvents reports the answer at runtime: Discord sends RESUMED when the gap was replayed and a second READY when it was not, and nothing else distinguishes them — the session id is reissued either way.

Setting up the application

Enable only the intents your declared needs require. NeedMessages asks for Message Content and NeedMemberLookup asks for Server Members; both are privileged and both must be enabled in the Developer Portal, or the identify is refused. Below 10,000 installs each is a toggle rather than an application.

A consumer that declares neither — voice, participants, reactions and slash commands, say — needs no privileged intent at all. NeedReactions asks for Guild Message Reactions, which is not privileged and is separate from message content: a consumer that only wants to hear reactions never requests the privileged intent messages cost.

Nobody can check that from the authorisation screen, and an earlier version of this file said they could. Intents are not part of the OAuth2 authorisation request, so no consent screen discloses them; the screen shows OAuth scopes, and it will happily show Read Message History ticked beside a line saying the app cannot read your messages. The same claim was made in chat-platform and withdrawn in v0.7.4 for this reason. What is checkable is the code: intentsFor derives every intent from a declared need, and its test asserts the mapping.

Leave the Interactions Endpoint URL blank. Setting it switches Discord to HTTP delivery, and this provider receives interactions over the gateway.

Contributing

Conformance is the bar: RunProviderConformance from the core module's test package runs offline and checks the behaviour the compiler cannot. Tests are written first and run with the race detector on; the root package sits at about 88% coverage, voiceengine lower.

just          # tidy, lint, test
just ci       # tidy, test, test-nocgo, race, lint

Licence

MIT © Matt Cockayne

Documentation

Overview

Package discord implements the comms contract on Discord, using disgoorg/disgo.

Register it with a blank import:

import _ "gitlab.com/phpboyscout/go/comms-discord"

c, err := comms.NewClient(ctx, "discord", comms.ClientConfig{
    Token: tok,
    Needs: []comms.Need{comms.NeedMessages},
})
p, err := c.Provider(ctx, guild, comms.WithAllowedChannels(chans...))

Why disgo

It is the only candidate Go Discord library that implements resume_gateway_url, the endpoint Discord supplies for resuming a session. Reconnecting elsewhere risks the resume being rejected, which degrades to a fresh identify and drops every event buffered during the outage. For a bot that answers questions, those are questions nobody will answer — a failure with no error and no trace.

Index

Constants

View Source
const Name = "discord"

Name is the key this provider registers under.

Variables

View Source
var ErrFormWindowClosed = errors.NewSentinel("comms-discord.form_window_closed", "discord: form window closed; the interaction was already acknowledged")

ErrFormWindowClosed reports that a form can no longer be opened for an interaction, because the acknowledgement has already been sent.

Distinct from ErrUnsupported: the capability exists, the moment passed. A caller that cannot tell those apart will retry something that can never succeed.

View Source
var ErrTooManyChoices = errors.NewSentinel("comms-discord.too_many_choices", "discord: too many choices for one message")

ErrTooManyChoices reports that a prompt offers more choices than Discord can render on one message.

Functions

func ConnectControl

func ConnectControl(ctx context.Context, c comms.Client) error

ConnectControl opens the gateway of a client built for a control hook.

It exists because a broker holds no space. NewClient returns a comms.Client, whose surface is Provider and Close; Connect belongs to a Reader, and a Reader is reached only through a scope. A broker wants no scope and no message feed -- minting one to open a transport would allocate a feed nobody reads and say the wrong thing about what a broker is.

It refuses a client built without WithControl: on that client a scope is the way in, and connecting behind the scopes' backs would leave them thinking they were disconnected.

func NewClient

func NewClient(cfg comms.ClientConfig, opts ...Option) (comms.Client, error)

NewClient builds a Discord client from a consumer's declared configuration.

It opens NOTHING. disgo derives the application id from the token, so constructing eagerly would make this fail without live credentials — and a client that cannot be built without secrets cannot be inspected for its capabilities or exercised by the conformance harness, which runs without a network by design.

The connection is dialled by the first comms.Reader.Connect across the scopes this mints. A Client owns the transport's LIFETIME, not its construction.

A missing token is therefore NOT an error here. Construction validates configuration; Connect reaches out, and that is where a credential is needed and where its absence is reported.

Types

type ControlHook

type ControlHook interface {
	// Attach is called with every client this provider builds, BEFORE that
	// client's gateway is opened, so the hook's listeners are installed before
	// a resume replays anything.
	//
	// An error here fails the construction or the connection that caused it: a
	// broker that cannot attach cannot serve, and a provider that carried on
	// would hold a session nothing was listening to.
	Attach(client *bot.Client) error
}

ControlHook is what WithControl attaches. The broker implements it.

type Option

type Option func(*options)

Option configures a provider.

func WithBotMessages

func WithBotMessages() Option

WithBotMessages stops the provider filtering bot-authored messages.

Test affordance only. Testing a chat bot needs either a second identity or a deliberate bypass, since a bot ignores its own messages by contract. It is an Option rather than a Config field so no production configuration file can reach it.

func WithClient

func WithClient(c *bot.Client) Option

WithClient supplies a pre-built disgo client. Intended for tests, which drive the provider through a fake gateway rather than a live connection.

func WithControl

func WithControl(h ControlHook) Option

WithControl gives the gateway to a control hook and takes voice away from this provider.

The two halves are one option because they are one decision. A process serving voice workers must not also join channels itself: it would be competing with them for the one voice connection per guild that Discord allows, and the failure would appear in whichever of them lost.

func WithResumeState

func WithResumeState(sessionID string, sequence int, resumeURL string) Option

WithResumeState gives the gateway a session to resume rather than a fresh identify.

A zero state sets nothing, so a first start identifies. An empty ResumeURL selects no URL rather than an empty one, because disgo dials whatever the pointer holds and an empty string would dial nothing.

Directories

Path Synopsis
internal
voiceengine
Package voiceengine is the join and session engine shared by the Discord provider and the Discord voice node.
Package voiceengine is the join and session engine shared by the Discord provider and the Discord voice node.
Package voicenode is a comms.Client that holds a Discord voice channel and nothing else: no gateway, no REST, no bot token.
Package voicenode is a comms.Client that holds a Discord voice channel and nothing else: no gateway, no REST, no bot token.
broker
Package broker is the gateway holder's side of the control link: it owns every guild the bot is in, one worker at a time, and turns requests from a bus into Opcode 4 on a Discord gateway it already holds.
Package broker is the gateway holder's side of the control link: it owns every guild the bot is in, one worker at a time, and turns requests from a bus into Opcode 4 on a Discord gateway it already holds.
broker/storetest
Package storetest is the suite any broker.Store must pass.
Package storetest is the suite any broker.Store must pass.
internal/lossy
Package lossy is a messaging.Backend decorator that drops the sends a test names.
Package lossy is a messaging.Backend decorator that drops the sends a test names.
internal/wire
Package wire is the control link's payloads and subjects, shared by the link and the broker so the two cannot drift.
Package wire is the control link's payloads and subjects, shared by the link and the broker so the two cannot drift.
link
Package link is the worker's side of the control link: a voicenode.Control that proxies Opcode 4 over a messaging bus and hands back the two gateway events a voice join needs.
Package link is the worker's side of the control link: a voicenode.Control that proxies Opcode 4 over a messaging bus and hands back the two gateway events a voice join needs.

Jump to

Keyboard shortcuts

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