gokord

package module
v0.33.1 Latest Latest
Warning

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

Go to latest
Published: Jan 22, 2026 License: BSD-3-Clause Imports: 40 Imported by: 2 modules, 1 package

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

gokord

Go Reference CI

gokord is a Go package that provides low level bindings to the Discord chat client API. gokord has nearly complete support for all the Discord API endpoints, and websocket interface. We have decided to remove the really outdated voice API, because our maintainers do not use it. Feel free to open a PR to add it!

gokord is a hard fork of DiscordGo because:

Check the ROADMAP for more information.

See below for the main differences between gokord and DiscordGo.

Getting Started

Installing

This assumes you already have a working Go environment.

go get will always pull the latest tagged release from the main branch.

go get -u github.com/nyttikord/gokord
Usage

Import the package into your project.

import "github.com/nyttikord/gokord"

Construct a new Discord client which can be used to access the variety of Discord API functions and to set callback functions for Discord events.

dg := gokord.New("Bot " + "authentication token")
// do some config things, like setting the intents or the sharding
err := dg.Open() // this starts the websocket and connect it to the Discord API.

See Documentation and Examples below for more detailed information.

Why should you use gokord instead of DiscordGo?

We have completely refactored the code base to clean it and to update it.

What you can see

We have:

  • recoded the websocket to follow Discord documentations;
  • modified how goroutines were managed to avoid data races with Mutex (this actually leads to a faster code :D);
  • fixed lot of bugs related to invalid handling of rate limits;
  • updated the documentation;
  • added missing features.

With gokord, you can also choose where you state is stored: you can stay with maps, or you can go with in-memory key-value database like Valkey or Redis.

You can use our powerful logger based on log/slog!

What you will see

We are currently simplifying how data is shared between goroutines using context package to build a more seamless development experience.

We are going to refactor how interactions are handled and we will create helpful structs to achieve the same goal.

Check the ROADMAP to have the details ;D

What you cannot see

Everything were stored in huge files (restapi.go, websocket.go, structs.go...) located in the package discordgo. We have decided to split these to increase the readability and the ease of maintenance of our code.

We also have:

  • changed the websocket API to use a well-maintained one;
  • refactored how data are handled internally to avoid data races and to be faster;
  • modified how the code is written to fit with what we think that are the best practices.

Migrating to gokord from DiscordGo

Due to its nature as a hard fork, migrating to gokord is equivalent to rewriting your application. Take a look at our examples to see the major differences. You can also check the documentation which is nearly complete.

Documentation

NOTICE: This library and the Discord API are unfinished. We are following the Semantic Versioning and we plan to release the 1.0.0 after cleaning the library. Next major breaking changes will only be introduced when the major version is increased.

Currently, we are using Discord API v10. When we will switch to Discord API v11 with its breaking changes, we will increase the major version. We can also increase it if we introduce breaking changes in our library. We will not increase it if Discord introduces breaking changes in the current supported API version.

The gokord code is fairly well documented at this point and this is currently the only documentation available. Go reference (below) presents that information in a nice format.

  • Go Reference

Examples

Below is a list of examples and other projects using Gokord.

  • gokord examples — A collection of example programs written with gokord (really outdated)

If you want real world example, you can check our bots or Les Copaings Bot.

Contributing

Contributions are very welcomed, however please follow the below guidelines.

  • First open an issue describing the bug or enhancement so it can be discussed.
  • Try to match current naming conventions as closely as possible.
  • This package is intended to be a low level direct mapping of the Discord API, so please avoid adding enhancements outside of that scope without first discussing it.
  • Create a Pull Request with your changes against the main branch.

Check CONTRIBUTING.md for more information.

Documentation

Index

Constants

View Source
const FailedHeartbeatAcks = 5

FailedHeartbeatAcks is the Number of heartbeat intervals to wait until forcing a connection restart.

View Source
const VERSION = "0.33.1"

VERSION of Gokord, follows Semantic Versioning. (http://semver.org/)

Variables

View Source
var (
	ErrShouldNotReconnect   = errors.New("session should not reconnect")
	ErrSendingResumePacket  = errors.New("cannot send resume packet")
	ErrHandlingMissedEvents = errors.New("cannot handle missed events")
	ErrInvalidSession       = errors.New("invalid session")
)
View Source
var (
	ErrReadingReadyPacket = errors.New("cannot read READY packet")
	ErrIdentifying        = errors.New("cannot identify")
)
View Source
var (
	ErrJSONUnmarshal = errors.New("json unmarshal")
	ErrStatusOffline = errors.New("you can't set your Status to offline")
	ErrUnauthorized  = errors.New("HTTP request was unauthorized. This could be because the provided token was not a bot token. Please add \"Bot \" to the start of your token. https://discord.com/developers/docs/reference#authentication-example-bot-token-authorization-header")
)

All error constants

View Source
var (
	// ErrWSAlreadyOpen is thrown when you attempt to open a websocket that already is open.
	ErrWSAlreadyOpen = errors.New("web socket already opened")
	// ErrWSNotFound is thrown when you attempt to use a websocket that doesn't exist
	ErrWSNotFound = errors.New("no websocket connection exists")
	// ErrWSShardBounds is thrown when you try to use a shard ID that is more than the total shard count
	ErrWSShardBounds = errors.New("ShardID must be less than ShardCount")
)

Functions

func NewState

func NewState(s *Session) state.State

NewState creates an empty state.State.

Types

type GatewayBotResponse

type GatewayBotResponse struct {
	URL               string             `json:"url"`
	Shards            int                `json:"shards"`
	SessionStartLimit SessionInformation `json:"session_start_limit"`
}

GatewayBotResponse stores the data for the gateway/bot response.

type GatewayStatusUpdate

type GatewayStatusUpdate struct {
	Since  int             `json:"since"`
	Game   status.Activity `json:"game"`
	Status string          `json:"status"`
	AFK    bool            `json:"afk"`
}

GatewayStatusUpdate is sent by the client to indicate a presence or status update. https://discord.com/developers/docs/topics/gateway#update-status-gateway-status-update-structure

type Identify

type Identify struct {
	Token          string              `json:"token"`
	Properties     IdentifyProperties  `json:"properties"`
	Compress       bool                `json:"compress"`
	LargeThreshold int                 `json:"large_threshold"`
	Shard          *[2]int             `json:"shard,omitempty"`
	Presence       GatewayStatusUpdate `json:"presence"`
	Intents        discord.Intent      `json:"intents"`
}

Identify is sent during initial handshake with the discord gateway. https://discord.com/developers/docs/topics/gateway#identify

type IdentifyProperties

type IdentifyProperties struct {
	OS              string `json:"$os"`
	Browser         string `json:"$browser"`
	Device          string `json:"$device"`
	Referer         string `json:"$referer"`
	ReferringDomain string `json:"$referring_domain"`
}

IdentifyProperties contains the "properties" portion of an Identify packet. https://discord.com/developers/docs/topics/gateway#identify-identify-connection-properties

type RESTError

type RESTError struct {
	Request      *http.Request
	Response     *http.Response
	ResponseBody []byte

	// Message may be nil.
	Message *discord.APIErrorMessage
}

RESTError stores error information about a request with a bad response code. Message is not always present, there are cases where api calls can fail without returning a json message.

func (RESTError) Error

func (r RESTError) Error() string

Error returns a Rest API Error with its status code and body.

type RESTSession added in v0.33.0

type RESTSession struct {

	// Should the session retry requests when rate limited.
	Options *bot.Options

	// The http.Client used for REST requests.
	Client *http.Client
	// The UserAgent used for REST APIs.
	UserAgent string
	// Used to deal with rate limits.
	RateLimiter *discord.RateLimiter
	// contains filtered or unexported fields
}

RESTSession is the part of the Session responsible for the REST API.

func (*RESTSession) Logger added in v0.33.0

func (s *RESTSession) Logger() *slog.Logger

func (*RESTSession) Request added in v0.33.0

func (s *RESTSession) Request(method, urlStr string, data any, options ...discord.RequestOption) ([]byte, error)

func (*RESTSession) RequestRaw added in v0.33.0

func (s *RESTSession) RequestRaw(method, urlStr, contentType string, b []byte, bucketID string, sequence int, options ...discord.RequestOption) ([]byte, error)

func (*RESTSession) RequestWithBucketID added in v0.33.0

func (s *RESTSession) RequestWithBucketID(method, urlStr string, data any, bucketID string, options ...discord.RequestOption) ([]byte, error)

func (*RESTSession) RequestWithLockedBucket added in v0.33.0

func (s *RESTSession) RequestWithLockedBucket(method, urlStr, contentType string, b []byte, bucket *discord.Bucket, sequence int, options ...discord.RequestOption) ([]byte, error)

func (*RESTSession) Unmarshal added in v0.33.0

func (s *RESTSession) Unmarshal(bytes []byte, i any) error

type RateLimitError

type RateLimitError struct {
	*event.RateLimit
}

RateLimitError is returned when a request exceeds a rate limit and Session.ShouldRetryOnRateLimit is false. The request may be manually retried after waiting the duration specified by RetryAfter.

func (RateLimitError) Error

func (e RateLimitError) Error() string

Error returns a rate limit error with rate limited endpoint and retry time.

type Session

type Session struct {
	MFA bool

	// Options of the Session.
	Options bot.Options

	// Identify is sent during initial handshake with the discord gateway.
	// https://discord.com/developers/docs/topics/gateway#identify
	Identify Identify

	// REST contains the Session interacting with the REST API.
	REST *RESTSession

	UserStorage    state.Storage // UserStorage is the state.Storage used for the UserAPI
	ChannelStorage state.Storage // ChannelStorage is the state.Storage used for the ChannelAPI
	GuildStorage   state.Storage // GuildStorage is the state.Storage used for the GuildAPI
	// contains filtered or unexported fields
}

Session represents a connection to the Discord API.

func New

func New(token string) *Session

New creates a new Discord session with provided token. If the token is for a bot, it must be prefixed with "Bot "

e.g. "Bot ..."

Or if it is an OAuth2 token, it must be prefixed with "Bearer "

e.g. "Bearer ..."

See NewWithLogLevel to modify the default slog.Level. See NewWithLoggerOptions to set the logger.Options for the logger. See NewWithLogger to set the default slog.Logger.

func NewWithLogLevel added in v0.32.0

func NewWithLogLevel(token string, logLevel slog.Level) *Session

NewWithLogLevel creates a new Discord session with provided token and set the slog.Level of the logger.

See New for the full documentation. See NewWithLoggerOptions to set the logger.Options for the logger. See NewWithLogger to set the default slog.Logger.

func NewWithLogger added in v0.32.0

func NewWithLogger(token string, logger *slog.Logger) *Session

NewWithLogger creates a new Discord session with provided token and set the logger.

See New for the full documentation. See NewWithLogLevel to modify the default slog.Level. See NewWithLoggerOptions to set the logger.Options for the logger.

func NewWithLoggerOptions added in v0.33.0

func NewWithLoggerOptions(token string, opt *logger.Options) *Session

NewWithLoggerOptions creates a new Discord session with provided token and options for the logger.

See New for the full documentation. See NewWithLogLevel to set the slog.Level without providing other logger.Options. See NewWithLogger to set the default slog.Logger.

func (*Session) ApplicationAPI added in v0.31.0

func (s *Session) ApplicationAPI() *applicationapi.Requester

ApplicationAPI returns an applicationapi.Requester to interact with the application package.

func (*Session) BotAPI added in v0.32.0

func (s *Session) BotAPI() *botapi.Requester

BotAPI returns a botapi.Requester to interact with the bot package.

func (*Session) ChannelAPI added in v0.31.0

func (s *Session) ChannelAPI() *channelapi.Requester

ChannelAPI returns a channelapi.Requester to interact with the channel package.

func (*Session) Close

func (s *Session) Close(ctx context.Context) error

Close closes a websocket and stops all listening/heartbeat goroutines. If it returns an error, the session is not closed.

func (*Session) CloseWithCode

func (s *Session) CloseWithCode(ctx context.Context, closeCode websocket.StatusCode) error

CloseWithCode closes a websocket using the provided closeCode and stops all listening/heartbeat goroutines. If it returns an error, the session is not closed. TODO: Add support for Voice WS/UDP connections

func (*Session) EventManager added in v0.32.0

func (s *Session) EventManager() bot.EventManager

EventManager returns the event.Manager used by the Session.

func (*Session) ForceClose added in v0.32.0

func (s *Session) ForceClose() error

ForceClose the connection. Use Close or CloseWithCode before to have a better closing process.

It doesn't send an event.Disconnect, unlike Close or CloseWithCode.

func (*Session) Gateway

func (s *Session) Gateway(options ...discord.RequestOption) (string, error)

Gateway returns the websocket Gateway address

func (*Session) GatewayBot

func (s *Session) GatewayBot(options ...discord.RequestOption) (*GatewayBotResponse, error)

GatewayBot returns the websocket Gateway address and the recommended number of shards

func (*Session) GatewayDial added in v0.32.0

func (s *Session) GatewayDial(ctx context.Context, urlString string, headers http.Header) (*websocket.Conn, *http.Response, error)

func (*Session) GatewayWriteStruct

func (s *Session) GatewayWriteStruct(ctx context.Context, v any) error

func (*Session) GuildAPI added in v0.31.0

func (s *Session) GuildAPI() *guildapi.Requester

GuildAPI returns a guildapi.Requester to interact with the guild package.

func (*Session) HeartbeatLatency

func (s *Session) HeartbeatLatency() time.Duration

HeartbeatLatency returns the latency between heartbeat acknowledgement and heartbeat send.

func (*Session) InteractionAPI added in v0.31.0

func (s *Session) InteractionAPI() *interactionapi.Requester

InteractionAPI returns an interactionapi.Requester to interact with the interaction package.

func (*Session) InviteAPI added in v0.31.0

func (s *Session) InviteAPI() *inviteapi.Requester

InviteAPI returns an inviteapi.Requester to interact with the invite package.

func (*Session) LastHeartbeatAck

func (s *Session) LastHeartbeatAck() time.Time

LastHeartbeatAck returns the time.Time of the last heartbeat ack received.

func (*Session) LastHeartbeatSent

func (s *Session) LastHeartbeatSent() time.Time

LastHeartbeatAck returns the time.Time of the last heartbeat sent.

func (*Session) Logger added in v0.32.0

func (s *Session) Logger() *slog.Logger

func (*Session) Open

func (s *Session) Open(ctx context.Context) error

Open creates a websocket connection to Discord. https://discord.com/developers/docs/topics/gateway#connecting

func (*Session) OpenAndBlock added in v0.32.1

func (s *Session) OpenAndBlock(ctx context.Context) error

OpenAndBlock calls Session.Open and block the program until an OS signal is received. It returns an error if Session.Open or Session.Close return an error. When this function returns, the session is already disconnected.

func (*Session) SessionState added in v0.32.0

func (s *Session) SessionState() state.Bot

SessionState returns the state.Bot of the Session.

func (*Session) SetStateParams added in v0.32.0

func (s *Session) SetStateParams(params state.Params)

SetStateParams sets the state.Params for the state.State

func (*Session) UserAPI added in v0.31.0

func (s *Session) UserAPI() *userapi.Requester

UserAPI returns an userapi.Requester to interact with the user package.

func (*Session) VoiceAPI added in v0.32.0

func (s *Session) VoiceAPI() *voice.Requester

VoiceAPI returns a voice.Requester to interact with the voice package.

type SessionInformation

type SessionInformation struct {
	Total          int `json:"total,omitempty"`
	Remaining      int `json:"remaining,omitempty"`
	ResetAfter     int `json:"reset_after,omitempty"`
	MaxConcurrency int `json:"max_concurrency,omitempty"`
}

SessionInformation provides the information for max concurrency sharding.

Directories

Path Synopsis
Package application handles everything related with Discord's Application and Team.
Package application handles everything related with Discord's Application and Team.
applicationapi
Package applicationapi contains everything to interact with everything located in the application package.
Package applicationapi contains everything to interact with everything located in the application package.
bot
Package bot contains everything related to the bot.
Package bot contains everything related to the bot.
Package channel contains every data structures linked with channels like...
Package channel contains every data structures linked with channels like...
channelapi
Package channelapi contains everything to interact with everything located in the channel package.
Package channelapi contains everything to interact with everything located in the channel package.
Package component contains everything related to Component including Modal component and Message component.
Package component contains everything related to Component including Modal component and Message component.
Package discord contains every object used to interact with the Discord API.
Package discord contains every object used to interact with the Discord API.
types
Package types contains every type constant documented in the Discord API.
Package types contains every type constant documented in the Discord API.
Package emoji contains every thing related to emoji and stickers.
Package emoji contains every thing related to emoji and stickers.
Package event contains everything related to events emmitted by Discord.
Package event contains everything related to events emmitted by Discord.
examples
airhorn command
auto_moderation command
autocomplete command
avatar command
components command
context_menus command
dm_pingpong command
echo command
modals command
pingpong command
slash_commands command
stage_instance command
threads command
Package guild contains every data structures linked to guilds like...
Package guild contains every data structures linked to guilds like...
guildapi
Package guildapi contains everything to interact with everything located in the guild package.
Package guildapi contains everything to interact with everything located in the guild package.
Package interaction contains everything linked with interactions like...
Package interaction contains everything linked with interactions like...
interactionapi
Package interactionapi contains everything to interact with everything located in the interaction package.
Package interactionapi contains everything to interact with everything located in the interaction package.
Package logger contains the structures used by gokord's custom slog.Logger.
Package logger contains the structures used by gokord's custom slog.Logger.
Package premium contains everything related with premium things in your application.Application.
Package premium contains everything related with premium things in your application.Application.
premiumapi
Package premiumapi contains everything to interact with everything located in the premium package.
Package premiumapi contains everything to interact with everything located in the premium package.
Package state contains interfaces and variables used by every State.
Package state contains interfaces and variables used by every State.
tools
cmd/session command
Package user contains everything related to Discord User, guild.Guild Member and Integration.
Package user contains everything related to Discord User, guild.Guild Member and Integration.
invite
Package invite contains the Invite...
Package invite contains the Invite...
invite/inviteapi
Package inviteapi contains everything to interact with everything located in the invite package.
Package inviteapi contains everything to interact with everything located in the invite package.
userapi
Package userapi contains everything to interact with everything located in the user package.
Package userapi contains everything to interact with everything located in the user package.
Package voice contains everything related to Discord voice Connection.
Package voice contains everything related to Discord voice Connection.

Jump to

Keyboard shortcuts

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