Documentation ¶
Index ¶
- Constants
- Variables
- type ClientState
- type CloseEventCode
- type Config
- type CreateFunc
- type EventData
- type EventHandlerFunc
- type EventMessage
- type EventModalCreate
- type EventRaw
- type EventReady
- type EventType
- type EventUnknown
- type Gateway
- type IdentifyCommandDataProperties
- type LogType
- type Message
- type MessageData
- type MessageDataHeartbeat
- type MessageDataHello
- type MessageDataIdentify
- type MessageDataInvalidSession
- type MessageDataPresenceUpdate
- type MessageDataResume
- type MessageDataUnknown
- type Opcode
- type RateLimiter
- type RateLimiterConfig
- type RateLimiterConfigOpt
- type Status
Constants ¶
const CommandsPerMinute = 120
CommandsPerMinute is the default number of commands per minute that the Gateway will allow.
const Version = 9
Version defines which discord API version should be used to connect to discord.
Variables ¶
var ( CloseEventCodeUnknownError = CloseEventCode{ Code: 4000, Description: "Unknown error", Explanation: "We're not sure what went wrong. Try reconnecting?", Reconnect: true, } CloseEventCodeUnknownOpcode = CloseEventCode{ Code: 4001, Description: "Unknown opcode", Explanation: "You sent an invalid Gateway opcode or an invalid payload for an opcode. Don't do that!", Reconnect: true, } CloseEventCodeDecodeError = CloseEventCode{ Code: 4002, Description: "Decode error", Explanation: "You sent an invalid payload to Discord. Don't do that!", Reconnect: true, } CloseEventCodeNotAuthenticated = CloseEventCode{ Code: 4003, Description: "Not authenticated", Explanation: "You sent us a payload prior to identifying.", Reconnect: true, } CloseEventCodeAuthenticationFailed = CloseEventCode{ Code: 4004, Description: "Authentication failed", Explanation: "The account token sent with your identify payload is incorrect.", Reconnect: false, } CloseEventCodeAlreadyAuthenticated = CloseEventCode{ Code: 4005, Description: "Already authenticated", Explanation: "You sent more than one identify payload. Don't do that!", Reconnect: true, } CloseEventCodeInvalidSeq = CloseEventCode{ Code: 4007, Description: "Invalid seq", Explanation: "The sequence sent when resuming the session was invalid. Reconnect and start a new session.", Reconnect: true, } CloseEventCodeRateLimited = CloseEventCode{ Code: 4008, Description: "Rate limited.", Explanation: "You're sending payloads to us too quickly. Slow it down! You will be disconnected on receiving this.", Reconnect: true, } CloseEventCodeSessionTimed = CloseEventCode{ Code: 4009, Description: "Session timed out", Explanation: "Your session timed out. Reconnect and start a new one.", Reconnect: true, } CloseEventCodeInvalidShard = CloseEventCode{ Code: 4010, Description: "Invalid shard", Explanation: "You sent us an invalid shard when identifying.", Reconnect: false, } CloseEventCodeShardingRequired = CloseEventCode{ Code: 4011, Description: "Sharding required", Explanation: "The session would have handled too many guilds - you are required to shard your connection in order to connect.", Reconnect: false, } CloseEventCodeInvalidAPIVersion = CloseEventCode{ Code: 4012, Description: "Invalid API version", Explanation: "You sent an invalid version for the gateway.", Reconnect: false, } CloseEventCodeInvalidIntent = CloseEventCode{ Code: 4013, Description: "Invalid intent(s)", Explanation: "You sent an invalid intent for a Gateway Intent. You may have incorrectly calculated the bitwise value.", Reconnect: false, } CloseEventCodeDisallowedIntent = CloseEventCode{ Code: 4014, Description: "Disallowed intent(s)", Explanation: "You sent a disallowed intent for a Gateway Intent. You may have tried to specify an intent that you have not enabled or are not approved for.", Reconnect: false, } CloseEventCodeUnknown = CloseEventCode{ Code: 0, Description: "Unknown", Explanation: "Unknown Gateway Close Event Code", Reconnect: true, } CloseEventCodes = map[int]CloseEventCode{ CloseEventCodeUnknownError.Code: CloseEventCodeUnknownError, CloseEventCodeUnknownOpcode.Code: CloseEventCodeUnknownOpcode, CloseEventCodeDecodeError.Code: CloseEventCodeDecodeError, CloseEventCodeNotAuthenticated.Code: CloseEventCodeNotAuthenticated, CloseEventCodeAuthenticationFailed.Code: CloseEventCodeAuthenticationFailed, CloseEventCodeAlreadyAuthenticated.Code: CloseEventCodeAlreadyAuthenticated, CloseEventCodeInvalidSeq.Code: CloseEventCodeInvalidSeq, CloseEventCodeRateLimited.Code: CloseEventCodeRateLimited, CloseEventCodeSessionTimed.Code: CloseEventCodeSessionTimed, CloseEventCodeInvalidShard.Code: CloseEventCodeInvalidShard, CloseEventCodeInvalidAPIVersion.Code: CloseEventCodeInvalidAPIVersion, CloseEventCodeInvalidIntent.Code: CloseEventCodeInvalidIntent, CloseEventCodeDisallowedIntent.Code: CloseEventCodeDisallowedIntent, } )
Functions ¶
This section is empty.
Types ¶
type ClientState ¶
type ClientState struct {
GuildVersions struct{} `json:"guild_versions"`
}
type CloseEventCode ¶
func CloseEventCodeByCode ¶
func CloseEventCodeByCode(code int) CloseEventCode
type Config ¶
type Config struct { // Dialer is the websocket.Dialer of the Gateway. Defaults to websocket.DefaultDialer. Dialer *websocket.Dialer // Compress is whether the Gateway should compress payloads. Defaults to true. Compress bool // URL is the URL of the Gateway. Defaults to fetch from Discord. URL string // SessionID is the last sessionID of the Gateway. Defaults to nil (no resume). SessionID *string // ResumeURL is the last resumeURL of the Gateway. Defaults to nil (no resume). ResumeURL *string // LastSequenceReceived is the last sequence received by the Gateway. Defaults to nil (no resume). LastSequenceReceived *int // AutoReconnect is whether the Gateway should automatically reconnect. Defaults to true. AutoReconnect bool // EnableRawEvents is whether the Gateway should emit EventRaw. Defaults to false. EnableRawEvents bool // EnableResumeURL is whether the Gateway should enable the resumeURL. Defaults to true. EnableResumeURL bool // RateLimiter is the RateLimiter of the Gateway. Defaults to NewRateLimiter(). RateLimiter RateLimiter // RateLimiterConfigOpts is the RateLimiterConfigOpts of the Gateway. Defaults to nil. RateLimiterConfigOpts []RateLimiterConfigOpt // Presence is the presence it should send on login. Defaults to config value. Presence *MessageDataPresenceUpdate // UserAgent is the UserAgent it should send on login and on api requests UserAgent string }
Config lets you configure your Gateway instance.
func DefaultConfig ¶
func DefaultConfig() *Config
DefaultConfig returns a Config with sensible defaults.
type CreateFunc ¶
CreateFunc is a type that is used to create a new Gateway(s).
type EventData ¶
type EventData interface { MessageData // contains filtered or unexported methods }
type EventHandlerFunc ¶
EventHandlerFunc is a function that is called when an event is received.
type EventMessage ¶
type EventMessage struct {
types.MessageData
}
type EventModalCreate ¶
type EventReady ¶
type EventReady struct {
types.ReadyEventData
}
EventReady is the event sent by discord when you successfully Identify
type EventUnknown ¶
type EventUnknown json.RawMessage
EventUnknown is an event that is not known
func (EventUnknown) MarshalJSON ¶
func (e EventUnknown) MarshalJSON() ([]byte, error)
func (*EventUnknown) UnmarshalJSON ¶
func (e *EventUnknown) UnmarshalJSON(data []byte) error
type Gateway ¶
type Gateway interface { // SessionID returns the session ID that is used by this Gateway. // This may be nil if the Gateway was never connected to Discord, was gracefully closed with websocket.CloseNormalClosure or websocket.CloseGoingAway. SessionID() *string User() *types.User UserAgent() string // LastSequenceReceived returns the last sequence number that was received by the Gateway. // This may be nil if the Gateway was never connected to Discord, was gracefully closed with websocket.CloseNormalClosure or websocket.CloseGoingAway. LastSequenceReceived() *int // Open connects this Gateway to the Discord API. Open(ctx context.Context) error // Close gracefully closes the Gateway with the websocket.CloseNormalClosure code. // If the context is done, the Gateway connection will be killed. Close(ctx context.Context) // CloseWithCode closes the Gateway with the given code & message. // If the context is done, the Gateway connection will be killed. CloseWithCode(ctx context.Context, code int, message string) // Send sends a message to the Discord gateway with the opCode and data. // If context is deadline exceeds, the message sending will be aborted. Send(ctx context.Context, op Opcode, data MessageData) error // Latency returns the latency of the Gateway. // This is calculated by the time it takes to send a heartbeat and receive a heartbeat ack by discord. Latency() time.Duration // Presence returns the current presence of the Gateway. Presence() *MessageDataPresenceUpdate // StatusUpdates returns a channel that will be updated with the status of the gateway. StatusUpdates() <-chan Status }
Gateway is what is used to connect to discord.
type IdentifyCommandDataProperties ¶
type IdentifyCommandDataProperties struct { Browser string `json:"browser"` BrowserUserAgent string `json:"browser_user_agent"` BrowserVersion string `json:"browser_version"` ClientBuildNumber string `json:"client_build_number"` DesignID int `json:"design_id"` OS string `json:"os"` OSVersion string `json:"os_version"` ReleaseChannel string `json:"release_channel"` Device string `json:"device"` SystemLocale string `json:"system_locale"` }
IdentifyCommandDataProperties is used for specifying to discord which library and OS the bot is using, is automatically handled by the library and should rarely be used.
type Message ¶
type Message struct { Op Opcode `json:"op"` S int `json:"s,omitempty"` T EventType `json:"t,omitempty"` D MessageData `json:"d,omitempty"` RawD json.RawMessage `json:"-"` }
Message raw Message type
func (*Message) UnmarshalJSON ¶
type MessageData ¶
type MessageData interface {
// contains filtered or unexported methods
}
type MessageDataHeartbeat ¶
type MessageDataHeartbeat int
MessageDataHeartbeat is used to ensure the websocket connection remains open, and disconnect if not.
type MessageDataHello ¶
type MessageDataHello struct {
HeartbeatInterval int `json:"heartbeat_interval"`
}
type MessageDataIdentify ¶
type MessageDataIdentify struct { Capabilities int64 `json:"capabilities"` Token string `json:"token"` Properties IdentifyCommandDataProperties `json:"properties"` ClientState ClientState `json:"client_state"` Compress bool `json:"compress,omitempty"` Presence *MessageDataPresenceUpdate `json:"presence,omitempty"` }
MessageDataIdentify is the data used in IdentifyCommandData
type MessageDataInvalidSession ¶
type MessageDataInvalidSession bool
type MessageDataPresenceUpdate ¶
type MessageDataPresenceUpdate struct { Since *int64 `json:"since"` Activities []map[string]interface{} `json:"activities"` Status types.OnlineStatus `json:"status"` AFK bool `json:"afk"` }
MessageDataPresenceUpdate is used for updating Client's presence
type MessageDataResume ¶
type MessageDataResume struct { Token string `json:"token"` SessionID string `json:"session_id"` Seq int `json:"seq"` }
MessageDataResume is used to resume a connection to discord in the case that you are disconnected. Is automatically handled by the library and should rarely be used.
type MessageDataUnknown ¶
type MessageDataUnknown json.RawMessage
type Opcode ¶
type Opcode int
Opcode are opcodes used by discord
const ( OpcodeDispatch Opcode = iota OpcodeHeartbeat OpcodeIdentify OpcodePresenceUpdate OpcodeVoiceStateUpdate OpcodeResume OpcodeReconnect OpcodeRequestGuildMembers OpcodeInvalidSession OpcodeHello OpcodeHeartbeatACK )
https://discord.com/developers/docs/topics/opcodes-and-status-codes#gateway-gateway-opcodes
type RateLimiter ¶
type RateLimiter interface { // Close gracefully closes the RateLimiter. // If the context deadline is exceeded, the RateLimiter will be closed immediately. Close(ctx context.Context) // Reset resets the RateLimiter to its initial state. Reset() // Wait waits for the RateLimiter to be ready to send a new message. // If the context deadline is exceeded, Wait will return immediately and no message will be sent. Wait(ctx context.Context) error // Unlock unlocks the RateLimiter and allows the next message to be sent. Unlock() }
RateLimiter provides handles the rate limiting logic for connecting to Discord's Gateway.
func NewRateLimiter ¶
func NewRateLimiter(opts ...RateLimiterConfigOpt) RateLimiter
NewRateLimiter creates a new default RateLimiter with the given RateLimiterConfigOpt(s).
type RateLimiterConfig ¶
RateLimiterConfig lets you configure your Gateway instance.
func DefaultRateLimiterConfig ¶
func DefaultRateLimiterConfig() *RateLimiterConfig
DefaultRateLimiterConfig returns a RateLimiterConfig with sensible defaults.
func (*RateLimiterConfig) Apply ¶
func (c *RateLimiterConfig) Apply(opts []RateLimiterConfigOpt)
Apply applies the given RateLimiterConfigOpt(s) to the RateLimiterConfig
type RateLimiterConfigOpt ¶
type RateLimiterConfigOpt func(config *RateLimiterConfig)
RateLimiterConfigOpt is a type alias for a function that takes a RateLimiterConfig and is used to configure your Server.
func WithCommandsPerMinute ¶
func WithCommandsPerMinute(commandsPerMinute int) RateLimiterConfigOpt
WithCommandsPerMinute sets the number of commands per minute that the Gateway will allow.
func WithRateLimiterLogger ¶
func WithRateLimiterLogger(logger *slog.Logger) RateLimiterConfigOpt
WithRateLimiterLogger sets the Logger for the Gateway.
type Status ¶
type Status int
Status is the state that the client is currently in.
const ( // StatusUnconnected is the initial state when a new Gateway is created. StatusUnconnected Status = iota // StatusConnecting is the state when the client is connecting to the Discord gateway. StatusConnecting // StatusWaitingForHello is the state when the Gateway is waiting for the first OpcodeHello packet. StatusWaitingForHello // StatusIdentifying is the state when the Gateway received its first OpcodeHello packet and now sends a OpcodeIdentify packet. StatusIdentifying // StatusResuming is the state when the Gateway received its first OpcodeHello packet and now sends a OpcodeResume packet. StatusResuming // StatusWaitingForReady is the state when the Gateway received sent a OpcodeIdentify or OpcodeResume packet and now waits for a OpcodeDispatch with EventTypeReady packet. StatusWaitingForReady // StatusReady is the state when the Gateway received a OpcodeDispatch with EventTypeReady packet. StatusReady // StatusDisconnected is the state when the Gateway is disconnected. // Either due to an error or because the Gateway was closed gracefully. StatusDisconnected // StatusInvalidToken is the state when the Gateway is disconnected due to an invalid token. StatusInvalidToken )
Indicates how far along the client is too connecting.
func (Status) IsConnected ¶
IsConnected returns whether the Gateway is connected.