Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/disgoorg/disgo/llms.txt

Use this file to discover all available pages before exploring further.

The gateway package provides WebSocket connectivity to Discord’s real-time Gateway API. It handles connection management, heartbeats, reconnection, and event dispatching.

Gateway interface

The main Gateway interface for connecting to Discord.
type Gateway interface {
    ShardID() int
    ShardCount() int
    SessionID() *string
    LastSequenceReceived() *int
    ResumeURL() *string
    Intents() Intents
    Open(ctx context.Context) error
    Close(ctx context.Context)
    CloseWithCode(ctx context.Context, code int, message string)
    Status() Status
    Send(ctx context.Context, op Opcode, data MessageData) error
    Latency() time.Duration
    Presence() *MessageDataPresenceUpdate
}

Methods

Open

func (g Gateway) Open(ctx context.Context) error
Connects to the Discord Gateway. Handles identification, resumption, and heartbeating automatically.

Close

func (g Gateway) Close(ctx context.Context)
Gracefully closes the gateway connection with normal closure code.

CloseWithCode

func (g Gateway) CloseWithCode(ctx context.Context, code int, message string)
Closes the gateway connection with a custom close code and message.

Send

func (g Gateway) Send(ctx context.Context, op Opcode, data MessageData) error
Sends a message to the Gateway. Only works when Status is StatusReady.
ctx
context.Context
Context for the send operation
op
Opcode
Gateway opcode (e.g., OpcodeVoiceStateUpdate)
data
MessageData
Message payload data

Latency

func (g Gateway) Latency() time.Duration
Returns the current latency calculated from heartbeat round-trip time.

ShardID / ShardCount

func (g Gateway) ShardID() int
func (g Gateway) ShardCount() int
Returns the shard ID and total shard count for this gateway connection.

Creating a gateway

New

func New(token string, eventHandlerFunc EventHandlerFunc, opts ...ConfigOpt) Gateway
Creates a new Gateway instance.
token
string
Bot token for authentication
eventHandlerFunc
EventHandlerFunc
Function called when events are received
opts
...ConfigOpt
Configuration options

Configuration

ConfigOpt

type ConfigOpt func(config *config)
Functional option for configuring the Gateway.

Configuration options

WithIntents

func WithIntents(intents ...Intents) ConfigOpt
Sets the Gateway intents (what events you want to receive).

WithShardID / WithShardCount

func WithShardID(shardID int) ConfigOpt
func WithShardCount(shardCount int) ConfigOpt
Configures sharding for large bots.

WithCompression

func WithCompression(compression CompressionType) ConfigOpt
Sets the compression type. Default is CompressionZstdStream.
const (
    CompressionNone
    CompressionZlibStream
    CompressionZstdStream
)

WithPresenceOpts

func WithPresenceOpts(opts ...PresenceOpt) ConfigOpt
Sets the initial presence (status and activities) when connecting.

WithAutoReconnect

func WithAutoReconnect(autoReconnect bool) ConfigOpt
Enables or disables automatic reconnection on disconnect. Default is true.

WithLogger

func WithLogger(logger *slog.Logger) ConfigOpt
Sets a custom logger for the Gateway.

WithURL

func WithURL(url string) ConfigOpt
Sets a custom Gateway URL. Default is fetched from Discord’s API.

Gateway status

type Status int
Indicates the connection state of the Gateway.
const (
    StatusUnconnected Status = iota
    StatusConnecting
    StatusWaitingForHello
    StatusIdentifying
    StatusResuming
    StatusWaitingForReady
    StatusReady
    StatusDisconnected
)
Methods:
func (s Status) IsConnected() bool
Returns true if the status indicates an active connection.
func (s Status) String() string
Returns a string representation of the status.

Intents

Gateway intents control which events your bot receives.
type Intents int64

Available intents

const (
    IntentGuilds Intents = 1 << iota
    IntentGuildMembers
    IntentGuildModeration
    IntentGuildExpressions
    IntentGuildIntegrations
    IntentGuildWebhooks
    IntentGuildInvites
    IntentGuildVoiceStates
    IntentGuildPresences
    IntentGuildMessages
    IntentGuildMessageReactions
    IntentGuildMessageTyping
    IntentDirectMessages
    IntentDirectMessageReactions
    IntentDirectMessageTyping
    IntentMessageContent
    IntentGuildScheduledEvents
    IntentAutoModerationConfiguration
    IntentAutoModerationExecution
    IntentGuildMessagePolls
    IntentDirectMessagePolls
)

Intent groups

const (
    IntentsGuild           // All guild-related intents
    IntentsDirectMessage   // All DM-related intents
    IntentsNonPrivileged   // All non-privileged intents
    IntentsPrivileged      // Privileged intents (requires approval)
    IntentsAll             // All intents
    IntentsNone            // No intents
)
Privileged intents (IntentGuildMembers, IntentGuildPresences, IntentMessageContent) require approval from Discord for verified bots with 100+ servers.

Intent methods

func (i Intents) Add(bits ...Intents) Intents
func (i Intents) Remove(bits ...Intents) Intents
func (i Intents) Has(bits ...Intents) bool
func (i Intents) Missing(bits ...Intents) bool
Example:
intents := gateway.IntentGuilds.Add(
    gateway.IntentGuildMessages,
    gateway.IntentMessageContent,
)

if intents.Has(gateway.IntentMessageContent) {
    // Can access message content
}

Event handling

EventHandlerFunc

type EventHandlerFunc func(
    gateway Gateway,
    eventType EventType,
    sequenceNumber int,
    event EventData,
)
Function called when the Gateway receives an event.

EventType

type EventType string
Represents the type of event received from Discord. Common event types include:
  • EventTypeReady
  • EventTypeMessageCreate
  • EventTypeMessageUpdate
  • EventTypeMessageDelete
  • EventTypeGuildCreate
  • EventTypeGuildUpdate
  • EventTypeInteractionCreate
  • And many more…

Opcodes

type Opcode int
Gateway operation codes.
const (
    OpcodeDispatch Opcode = iota
    OpcodeHeartbeat
    OpcodeIdentify
    OpcodePresenceUpdate
    OpcodeVoiceStateUpdate
    OpcodeResume
    OpcodeReconnect
    OpcodeRequestGuildMembers
    OpcodeInvalidSession
    OpcodeHello
    OpcodeHeartbeatACK
)

Rate limiting

The Gateway automatically handles rate limiting for sent messages.

RateLimiter

type RateLimiter interface {
    Wait(ctx context.Context, commandType RateLimiterCommandType) error
    Unlock()
    Reset()
    Close(ctx context.Context)
}

Example usage

package main

import (
    "context"
    "log"
    
    "github.com/disgoorg/disgo/gateway"
)

func main() {
    token := "Bot YOUR_TOKEN"
    
    eventHandler := func(
        gw gateway.Gateway,
        eventType gateway.EventType,
        sequenceNumber int,
        event gateway.EventData,
    ) {
        log.Printf("Event: %s", eventType)
    }
    
    gw := gateway.New(
        token,
        eventHandler,
        gateway.WithIntents(
            gateway.IntentGuilds,
            gateway.IntentGuildMessages,
            gateway.IntentMessageContent,
        ),
    )
    
    if err := gw.Open(context.Background()); err != nil {
        log.Fatal(err)
    }
    
    defer gw.Close(context.Background())
    
    // Keep running...
    select {}
}