gateway

package
v0.101.0 Latest Latest
Warning

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

Go to latest
Published: Sep 8, 2023 License: Apache-2.0 Imports: 17 Imported by: 1

Documentation

Index

Constants

View Source
const Version = 10

Version defines which discord API version disgo should use to connect to discord.

Variables

View Source
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 ActivityOpt added in v0.5.1

type ActivityOpt func(activity discord.Activity)

ActivityOpt is a type alias for a function that sets optional data for an Activity

func WithActivityState added in v0.5.1

func WithActivityState(state string) ActivityOpt

WithActivityState sets the Activity.State

type AddedThreadMember

type AddedThreadMember struct {
	discord.ThreadMember
	Member   discord.Member    `json:"member"`
	Presence *discord.Presence `json:"presence"`
}

type CloseEventCode

type CloseEventCode struct {
	Code        int
	Description string
	Explanation string
	Reconnect   bool
}

func CloseEventCodeByCode

func CloseEventCodeByCode(code int) CloseEventCode

type CloseHandlerFunc

type CloseHandlerFunc func(gateway Gateway, err error)

CloseHandlerFunc is a function that is called when the Gateway is closed.

type Config

type Config struct {
	// Logger is the logger of the Gateway. Defaults to log.Default().
	Logger log.Logger
	// Dialer is the websocket.Dialer of the Gateway. Defaults to websocket.DefaultDialer.
	Dialer *websocket.Dialer
	// LargeThreshold is the threshold for the Gateway. Defaults to 50
	// See here for more information: https://discord.com/developers/docs/topics/gateway-events#identify-identify-structure.
	LargeThreshold int
	// Intents is the Intents for the Gateway. Defaults to IntentsNone.
	Intents Intents
	// 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
	// ShardID is the shardID of the Gateway. Defaults to 0.
	ShardID int
	// ShardCount is the shardCount of the Gateway. Defaults to 1.
	ShardCount int
	// 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 or call the CloseHandlerFunc. 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
	// RateRateLimiterConfigOpts is the RateLimiterConfigOpts of the Gateway. Defaults to nil.
	RateRateLimiterConfigOpts []RateLimiterConfigOpt
	// Presence is the presence it should send on login. Defaults to nil.
	Presence *MessageDataPresenceUpdate
	// OS is the OS it should send on login. Defaults to runtime.GOOS.
	OS string
	// Browser is the Browser it should send on login. Defaults to "disgo".
	Browser string
	// Device is the Device it should send on login. Defaults to "disgo".
	Device string
}

Config lets you configure your Gateway instance.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a Config with sensible defaults.

func (*Config) Apply

func (c *Config) Apply(opts []ConfigOpt)

Apply applies the given ConfigOpt(s) to the Config

type ConfigOpt

type ConfigOpt func(config *Config)

ConfigOpt is a type alias for a function that takes a Config and is used to configure your Server.

func WithAutoReconnect

func WithAutoReconnect(autoReconnect bool) ConfigOpt

WithAutoReconnect sets whether the Gateway should automatically reconnect to Discord.

func WithBrowser

func WithBrowser(browser string) ConfigOpt

WithBrowser sets the browser the bot is running on. See here for more information: https://discord.com/developers/docs/topics/gateway#identify-identify-connection-properties

func WithCompress

func WithCompress(compress bool) ConfigOpt

WithCompress sets whether this Gateway supports compression. See here for more information: https://discord.com/developers/docs/topics/gateway#encoding-and-compression

func WithDevice

func WithDevice(device string) ConfigOpt

WithDevice sets the device the bot is running on. See here for more information: https://discord.com/developers/docs/topics/gateway#identify-identify-connection-properties

func WithDialer

func WithDialer(dialer *websocket.Dialer) ConfigOpt

WithDialer sets the websocket.Dialer for the Gateway.

func WithEnableRawEvents

func WithEnableRawEvents(enableRawEventEvents bool) ConfigOpt

WithEnableRawEvents enables/disables the EventTypeRaw.

func WithEnableResumeURL

func WithEnableResumeURL(enableResumeURL bool) ConfigOpt

WithEnableResumeURL enables/disables usage of resume URLs sent by Discord.

func WithIntents

func WithIntents(intents ...Intents) ConfigOpt

WithIntents sets the Intents for the Gateway. See here for more information: https://discord.com/developers/docs/topics/gateway#gateway-intents

func WithLargeThreshold

func WithLargeThreshold(largeThreshold int) ConfigOpt

WithLargeThreshold sets the threshold for the Gateway. See here for more information: https://discord.com/developers/docs/topics/gateway#identify-identify-structure

func WithLogger

func WithLogger(logger log.Logger) ConfigOpt

WithLogger sets the Logger for the Gateway.

func WithOS

func WithOS(os string) ConfigOpt

WithOS sets the operating system the bot is running on. See here for more information: https://discord.com/developers/docs/topics/gateway#identify-identify-connection-properties

func WithPresenceOpts

func WithPresenceOpts(opts ...PresenceOpt) ConfigOpt

WithPresenceOpts allows to pass initial presence data the bot should display.

func WithRateLimiter

func WithRateLimiter(rateLimiter RateLimiter) ConfigOpt

WithRateLimiter sets the grate.RateLimiter for the Gateway.

func WithRateRateLimiterConfigOpts

func WithRateRateLimiterConfigOpts(opts ...RateLimiterConfigOpt) ConfigOpt

WithRateRateLimiterConfigOpts lets you configure the default RateLimiter.

func WithSequence

func WithSequence(sequence int) ConfigOpt

WithSequence sets the last sequence received for the Gateway. If sessionID and lastSequence is present while connecting, the Gateway will try to resume the session.

func WithSessionID

func WithSessionID(sessionID string) ConfigOpt

WithSessionID sets the Session ID for the Gateway. If sessionID and lastSequence is present while connecting, the Gateway will try to resume the session.

func WithShardCount

func WithShardCount(shardCount int) ConfigOpt

WithShardCount sets the shard count for the Gateway. See here for more information on sharding: https://discord.com/developers/docs/topics/gateway#sharding

func WithShardID

func WithShardID(shardID int) ConfigOpt

WithShardID sets the shard ID for the Gateway. See here for more information on sharding: https://discord.com/developers/docs/topics/gateway#sharding

func WithURL

func WithURL(url string) ConfigOpt

WithURL sets the Gateway URL for the Gateway.

type CreateFunc

type CreateFunc func(token string, eventHandlerFunc EventHandlerFunc, closeHandlerFUnc CloseHandlerFunc, opts ...ConfigOpt) Gateway

CreateFunc is a type that is used to create a new Gateway(s).

type EventApplicationCommandPermissionsUpdate

type EventApplicationCommandPermissionsUpdate struct {
	discord.ApplicationCommandPermissions
}

type EventAutoModerationActionExecution

type EventAutoModerationActionExecution struct {
	GuildID              snowflake.ID                      `json:"guild_id"`
	Action               discord.AutoModerationAction      `json:"action"`
	RuleID               snowflake.ID                      `json:"rule_id"`
	RuleTriggerType      discord.AutoModerationTriggerType `json:"rule_trigger_type"`
	UserID               snowflake.ID                      `json:"user_id"`
	ChannelID            *snowflake.ID                     `json:"channel_id,omitempty"`
	MessageID            *snowflake.ID                     `json:"message_id,omitempty"`
	AlertSystemMessageID snowflake.ID                      `json:"alert_system_message_id"`
	Content              string                            `json:"content"`
	MatchedKeywords      *string                           `json:"matched_keywords"`
	MatchedContent       *string                           `json:"matched_content"`
}

type EventAutoModerationRuleCreate

type EventAutoModerationRuleCreate struct {
	discord.AutoModerationRule
}

type EventAutoModerationRuleDelete

type EventAutoModerationRuleDelete struct {
	discord.AutoModerationRule
}

type EventAutoModerationRuleUpdate

type EventAutoModerationRuleUpdate struct {
	discord.AutoModerationRule
}

type EventChannelCreate

type EventChannelCreate struct {
	discord.GuildChannel
}

func (*EventChannelCreate) UnmarshalJSON

func (e *EventChannelCreate) UnmarshalJSON(data []byte) error

type EventChannelDelete

type EventChannelDelete struct {
	discord.GuildChannel
}

func (*EventChannelDelete) UnmarshalJSON

func (e *EventChannelDelete) UnmarshalJSON(data []byte) error

type EventChannelPinsUpdate

type EventChannelPinsUpdate struct {
	GuildID          *snowflake.ID `json:"guild_id"`
	ChannelID        snowflake.ID  `json:"channel_id"`
	LastPinTimestamp *time.Time    `json:"last_pin_timestamp"`
}

type EventChannelUpdate

type EventChannelUpdate struct {
	discord.GuildChannel
}

func (*EventChannelUpdate) UnmarshalJSON

func (e *EventChannelUpdate) UnmarshalJSON(data []byte) error

type EventData

type EventData interface {
	MessageData
	// contains filtered or unexported methods
}

func UnmarshalEventData

func UnmarshalEventData(data []byte, eventType EventType) (EventData, error)

type EventGuildAuditLogEntryCreate

type EventGuildAuditLogEntryCreate struct {
	discord.AuditLogEntry
	GuildID snowflake.ID `json:"guild_id"`
}

type EventGuildBanAdd

type EventGuildBanAdd struct {
	GuildID snowflake.ID `json:"guild_id"`
	User    discord.User `json:"user"`
}

type EventGuildBanRemove

type EventGuildBanRemove struct {
	GuildID snowflake.ID `json:"guild_id"`
	User    discord.User `json:"user"`
}

type EventGuildCreate

type EventGuildCreate struct {
	discord.GatewayGuild
}

type EventGuildDelete

type EventGuildDelete struct {
	discord.GatewayGuild
}

type EventGuildEmojisUpdate

type EventGuildEmojisUpdate struct {
	GuildID snowflake.ID    `json:"guild_id"`
	Emojis  []discord.Emoji `json:"emojis"`
}

func (*EventGuildEmojisUpdate) UnmarshalJSON

func (e *EventGuildEmojisUpdate) UnmarshalJSON(data []byte) error

type EventGuildIntegrationsUpdate

type EventGuildIntegrationsUpdate struct {
	GuildID snowflake.ID `json:"guild_id"`
}

type EventGuildMemberAdd

type EventGuildMemberAdd struct {
	discord.Member
}

type EventGuildMemberRemove

type EventGuildMemberRemove struct {
	GuildID snowflake.ID `json:"guild_id"`
	User    discord.User `json:"user"`
}

type EventGuildMemberUpdate

type EventGuildMemberUpdate struct {
	discord.Member
}

type EventGuildMembersChunk

type EventGuildMembersChunk struct {
	GuildID    snowflake.ID       `json:"guild_id"`
	Members    []discord.Member   `json:"members"`
	ChunkIndex int                `json:"chunk_index"`
	ChunkCount int                `json:"chunk_count"`
	NotFound   []snowflake.ID     `json:"not_found"`
	Presences  []discord.Presence `json:"presences"`
	Nonce      string             `json:"nonce"`
}

type EventGuildRoleCreate

type EventGuildRoleCreate struct {
	GuildID snowflake.ID `json:"guild_id"`
	Role    discord.Role `json:"role"`
}

func (*EventGuildRoleCreate) MarshalJSON

func (e *EventGuildRoleCreate) MarshalJSON() ([]byte, error)

func (*EventGuildRoleCreate) UnmarshalJSON

func (e *EventGuildRoleCreate) UnmarshalJSON(data []byte) error

type EventGuildRoleDelete

type EventGuildRoleDelete struct {
	GuildID snowflake.ID `json:"guild_id"`
	RoleID  snowflake.ID `json:"role_id"`
}

type EventGuildRoleUpdate

type EventGuildRoleUpdate struct {
	GuildID snowflake.ID `json:"guild_id"`
	Role    discord.Role `json:"role"`
}

func (*EventGuildRoleUpdate) MarshalJSON

func (e *EventGuildRoleUpdate) MarshalJSON() ([]byte, error)

func (*EventGuildRoleUpdate) UnmarshalJSON

func (e *EventGuildRoleUpdate) UnmarshalJSON(data []byte) error

type EventGuildScheduledEventCreate

type EventGuildScheduledEventCreate struct {
	discord.GuildScheduledEvent
}

type EventGuildScheduledEventDelete

type EventGuildScheduledEventDelete struct {
	discord.GuildScheduledEvent
}

type EventGuildScheduledEventUpdate

type EventGuildScheduledEventUpdate struct {
	discord.GuildScheduledEvent
}

type EventGuildScheduledEventUserAdd

type EventGuildScheduledEventUserAdd struct {
	GuildScheduledEventID snowflake.ID `json:"guild_scheduled_event_id"`
	UserID                snowflake.ID `json:"user_id"`
	GuildID               snowflake.ID `json:"guild_id"`
}

type EventGuildScheduledEventUserRemove

type EventGuildScheduledEventUserRemove struct {
	GuildScheduledEventID snowflake.ID `json:"guild_scheduled_event_id"`
	UserID                snowflake.ID `json:"user_id"`
	GuildID               snowflake.ID `json:"guild_id"`
}

type EventGuildStickersUpdate

type EventGuildStickersUpdate struct {
	GuildID  snowflake.ID      `json:"guild_id"`
	Stickers []discord.Sticker `json:"stickers"`
}

type EventGuildUpdate

type EventGuildUpdate struct {
	discord.GatewayGuild
}

type EventHandlerFunc

type EventHandlerFunc func(gatewayEventType EventType, sequenceNumber int, shardID int, event EventData)

EventHandlerFunc is a function that is called when an event is received.

type EventHeartbeatAck

type EventHeartbeatAck struct {
	LastHeartbeat time.Time
	NewHeartbeat  time.Time
}

type EventIntegrationCreate

type EventIntegrationCreate struct {
	discord.Integration
	GuildID snowflake.ID `json:"guild_id"`
}

func (*EventIntegrationCreate) UnmarshalJSON

func (e *EventIntegrationCreate) UnmarshalJSON(data []byte) error

type EventIntegrationDelete

type EventIntegrationDelete struct {
	ID            snowflake.ID  `json:"id"`
	GuildID       snowflake.ID  `json:"guild_id"`
	ApplicationID *snowflake.ID `json:"application_id"`
}

type EventIntegrationUpdate

type EventIntegrationUpdate struct {
	discord.Integration
	GuildID snowflake.ID `json:"guild_id"`
}

func (*EventIntegrationUpdate) UnmarshalJSON

func (e *EventIntegrationUpdate) UnmarshalJSON(data []byte) error

type EventInteractionCreate

type EventInteractionCreate struct {
	discord.Interaction
}

func (EventInteractionCreate) MarshalJSON

func (e EventInteractionCreate) MarshalJSON() ([]byte, error)

func (*EventInteractionCreate) UnmarshalJSON

func (e *EventInteractionCreate) UnmarshalJSON(data []byte) error

type EventInviteCreate

type EventInviteCreate struct {
	discord.Invite
}

type EventInviteDelete

type EventInviteDelete struct {
	ChannelID snowflake.ID  `json:"channel_id"`
	GuildID   *snowflake.ID `json:"guild_id"`
	Code      string        `json:"code"`
}

type EventMessageCreate

type EventMessageCreate struct {
	discord.Message
}

type EventMessageDelete

type EventMessageDelete struct {
	ID        snowflake.ID  `json:"id"`
	ChannelID snowflake.ID  `json:"channel_id"`
	GuildID   *snowflake.ID `json:"guild_id,omitempty"`
}

type EventMessageDeleteBulk

type EventMessageDeleteBulk struct {
	IDs       []snowflake.ID `json:"id"`
	ChannelID snowflake.ID   `json:"channel_id"`
	GuildID   *snowflake.ID  `json:"guild_id,omitempty"`
}

type EventMessageReactionAdd

type EventMessageReactionAdd struct {
	UserID          snowflake.ID         `json:"user_id"`
	ChannelID       snowflake.ID         `json:"channel_id"`
	MessageID       snowflake.ID         `json:"message_id"`
	GuildID         *snowflake.ID        `json:"guild_id"`
	Member          *discord.Member      `json:"member"`
	Emoji           discord.PartialEmoji `json:"emoji"`
	MessageAuthorID *snowflake.ID        `json:"message_author_id"`
	BurstColors     []string             `json:"burst_colors"`
	Burst           bool                 `json:"burst"`
}

func (*EventMessageReactionAdd) UnmarshalJSON

func (e *EventMessageReactionAdd) UnmarshalJSON(data []byte) error

type EventMessageReactionRemove

type EventMessageReactionRemove struct {
	UserID      snowflake.ID         `json:"user_id"`
	ChannelID   snowflake.ID         `json:"channel_id"`
	MessageID   snowflake.ID         `json:"message_id"`
	GuildID     *snowflake.ID        `json:"guild_id"`
	Emoji       discord.PartialEmoji `json:"emoji"`
	BurstColors []string             `json:"burst_colors"`
	Burst       bool                 `json:"burst"`
}

type EventMessageReactionRemoveAll

type EventMessageReactionRemoveAll struct {
	ChannelID snowflake.ID  `json:"channel_id"`
	MessageID snowflake.ID  `json:"message_id"`
	GuildID   *snowflake.ID `json:"guild_id"`
}

type EventMessageReactionRemoveEmoji

type EventMessageReactionRemoveEmoji struct {
	ChannelID snowflake.ID         `json:"channel_id"`
	MessageID snowflake.ID         `json:"message_id"`
	GuildID   *snowflake.ID        `json:"guild_id"`
	Emoji     discord.PartialEmoji `json:"emoji"`
}

type EventMessageUpdate

type EventMessageUpdate struct {
	discord.Message
}

type EventPresenceUpdate

type EventPresenceUpdate struct {
	discord.Presence
}

type EventRaw

type EventRaw struct {
	EventType EventType
	Payload   io.Reader
}

type EventReady

type EventReady struct {
	Version          int                        `json:"v"`
	User             discord.OAuth2User         `json:"user"`
	Guilds           []discord.UnavailableGuild `json:"guilds"`
	SessionID        string                     `json:"session_id"`
	ResumeGatewayURL string                     `json:"resume_gateway_url"`
	Shard            [2]int                     `json:"shard,omitempty"`
	Application      discord.PartialApplication `json:"application"`
}

EventReady is the event sent by discord when you successfully Identify

type EventStageInstanceCreate

type EventStageInstanceCreate struct {
	discord.StageInstance
}

type EventStageInstanceDelete

type EventStageInstanceDelete struct {
	discord.StageInstance
}

type EventStageInstanceUpdate

type EventStageInstanceUpdate struct {
	discord.StageInstance
}

type EventThreadCreate

type EventThreadCreate struct {
	discord.GuildThread
	ThreadMember discord.ThreadMember `json:"thread_member"`
}

type EventThreadDelete

type EventThreadDelete struct {
	ID       snowflake.ID        `json:"id"`
	GuildID  snowflake.ID        `json:"guild_id"`
	ParentID snowflake.ID        `json:"parent_id"`
	Type     discord.ChannelType `json:"type"`
}

type EventThreadListSync

type EventThreadListSync struct {
	GuildID    snowflake.ID           `json:"guild_id"`
	ChannelIDs []snowflake.ID         `json:"channel_ids"`
	Threads    []discord.GuildThread  `json:"threads"`
	Members    []discord.ThreadMember `json:"members"`
}

type EventThreadMemberUpdate

type EventThreadMemberUpdate struct {
	discord.ThreadMember
}

type EventThreadMembersUpdate

type EventThreadMembersUpdate struct {
	ID               snowflake.ID        `json:"id"`
	GuildID          snowflake.ID        `json:"guild_id"`
	MemberCount      int                 `json:"member_count"`
	AddedMembers     []AddedThreadMember `json:"added_members"`
	RemovedMemberIDs []snowflake.ID      `json:"removed_member_ids"`
}

type EventThreadUpdate

type EventThreadUpdate struct {
	discord.GuildThread
}

type EventType

type EventType string

EventType wraps all EventType types

const (
	// EventTypeRaw is not a real event type, but is used to pass raw payloads to the bot.EventManager
	EventTypeRaw                                 EventType = "__RAW__"
	EventTypeHeartbeatAck                        EventType = "__HEARTBEAT_ACK__"
	EventTypeReady                               EventType = "READY"
	EventTypeResumed                             EventType = "RESUMED"
	EventTypeApplicationCommandPermissionsUpdate EventType = "APPLICATION_COMMAND_PERMISSIONS_UPDATE"
	EventTypeAutoModerationRuleCreate            EventType = "AUTO_MODERATION_RULE_CREATE"
	EventTypeAutoModerationRuleUpdate            EventType = "AUTO_MODERATION_RULE_UPDATE"
	EventTypeAutoModerationRuleDelete            EventType = "AUTO_MODERATION_RULE_DELETE"
	EventTypeAutoModerationActionExecution       EventType = "AUTO_MODERATION_ACTION_EXECUTION"
	EventTypeChannelCreate                       EventType = "CHANNEL_CREATE"
	EventTypeChannelUpdate                       EventType = "CHANNEL_UPDATE"
	EventTypeChannelDelete                       EventType = "CHANNEL_DELETE"
	EventTypeChannelPinsUpdate                   EventType = "CHANNEL_PINS_UPDATE"
	EventTypeThreadCreate                        EventType = "THREAD_CREATE"
	EventTypeThreadUpdate                        EventType = "THREAD_UPDATE"
	EventTypeThreadDelete                        EventType = "THREAD_DELETE"
	EventTypeThreadListSync                      EventType = "THREAD_LIST_SYNC"
	EventTypeThreadMemberUpdate                  EventType = "THREAD_MEMBER_UPDATE"
	EventTypeThreadMembersUpdate                 EventType = "THREAD_MEMBERS_UPDATE"
	EventTypeGuildCreate                         EventType = "GUILD_CREATE"
	EventTypeGuildUpdate                         EventType = "GUILD_UPDATE"
	EventTypeGuildDelete                         EventType = "GUILD_DELETE"
	EventTypeGuildAuditLogEntryCreate            EventType = "GUILD_AUDIT_LOG_ENTRY_CREATE"
	EventTypeGuildBanAdd                         EventType = "GUILD_BAN_ADD"
	EventTypeGuildBanRemove                      EventType = "GUILD_BAN_REMOVE"
	EventTypeGuildEmojisUpdate                   EventType = "GUILD_EMOJIS_UPDATE"
	EventTypeGuildStickersUpdate                 EventType = "GUILD_STICKERS_UPDATE"
	EventTypeGuildIntegrationsUpdate             EventType = "GUILD_INTEGRATIONS_UPDATE"
	EventTypeGuildMemberAdd                      EventType = "GUILD_MEMBER_ADD"
	EventTypeGuildMemberRemove                   EventType = "GUILD_MEMBER_REMOVE"
	EventTypeGuildMemberUpdate                   EventType = "GUILD_MEMBER_UPDATE"
	EventTypeGuildMembersChunk                   EventType = "GUILD_MEMBERS_CHUNK"
	EventTypeGuildRoleCreate                     EventType = "GUILD_ROLE_CREATE"
	EventTypeGuildRoleUpdate                     EventType = "GUILD_ROLE_UPDATE"
	EventTypeGuildRoleDelete                     EventType = "GUILD_ROLE_DELETE"
	EventTypeGuildScheduledEventCreate           EventType = "GUILD_SCHEDULED_EVENT_CREATE"
	EventTypeGuildScheduledEventUpdate           EventType = "GUILD_SCHEDULED_EVENT_UPDATE"
	EventTypeGuildScheduledEventDelete           EventType = "GUILD_SCHEDULED_EVENT_DELETE"
	EventTypeGuildScheduledEventUserAdd          EventType = "GUILD_SCHEDULED_EVENT_USER_ADD"
	EventTypeGuildScheduledEventUserRemove       EventType = "GUILD_SCHEDULED_EVENT_USER_REMOVE"
	EventTypeIntegrationCreate                   EventType = "INTEGRATION_CREATE"
	EventTypeIntegrationUpdate                   EventType = "INTEGRATION_UPDATE"
	EventTypeIntegrationDelete                   EventType = "INTEGRATION_DELETE"
	EventTypeInteractionCreate                   EventType = "INTERACTION_CREATE"
	EventTypeInviteCreate                        EventType = "INVITE_CREATE"
	EventTypeInviteDelete                        EventType = "INVITE_DELETE"
	EventTypeMessageCreate                       EventType = "MESSAGE_CREATE"
	EventTypeMessageUpdate                       EventType = "MESSAGE_UPDATE"
	EventTypeMessageDelete                       EventType = "MESSAGE_DELETE"
	EventTypeMessageDeleteBulk                   EventType = "MESSAGE_DELETE_BULK"
	EventTypeMessageReactionAdd                  EventType = "MESSAGE_REACTION_ADD"
	EventTypeMessageReactionRemove               EventType = "MESSAGE_REACTION_REMOVE"
	EventTypeMessageReactionRemoveAll            EventType = "MESSAGE_REACTION_REMOVE_ALL"
	EventTypeMessageReactionRemoveEmoji          EventType = "MESSAGE_REACTION_REMOVE_EMOJI"
	EventTypePresenceUpdate                      EventType = "PRESENCE_UPDATE"
	EventTypeStageInstanceCreate                 EventType = "STAGE_INSTANCE_CREATE"
	EventTypeStageInstanceDelete                 EventType = "STAGE_INSTANCE_DELETE"
	EventTypeStageInstanceUpdate                 EventType = "STAGE_INSTANCE_UPDATE"
	EventTypeTypingStart                         EventType = "TYPING_START"
	EventTypeUserUpdate                          EventType = "USER_UPDATE"
	EventTypeVoiceStateUpdate                    EventType = "VOICE_STATE_UPDATE"
	EventTypeVoiceServerUpdate                   EventType = "VOICE_SERVER_UPDATE"
	EventTypeWebhooksUpdate                      EventType = "WEBHOOKS_UPDATE"
)

Constants for the gateway events

type EventTypingStart

type EventTypingStart struct {
	ChannelID snowflake.ID    `json:"channel_id"`
	GuildID   *snowflake.ID   `json:"guild_id,omitempty"`
	UserID    snowflake.ID    `json:"user_id"`
	Timestamp time.Time       `json:"timestamp"`
	Member    *discord.Member `json:"member,omitempty"`
	User      discord.User    `json:"user"`
}

func (*EventTypingStart) UnmarshalJSON

func (e *EventTypingStart) UnmarshalJSON(data []byte) error

type EventUnknown

type EventUnknown json.RawMessage

EventUnknown is an event that is not known to disgo

func (EventUnknown) MarshalJSON

func (e EventUnknown) MarshalJSON() ([]byte, error)

func (*EventUnknown) UnmarshalJSON

func (e *EventUnknown) UnmarshalJSON(data []byte) error

type EventUserUpdate

type EventUserUpdate struct {
	discord.OAuth2User
}

type EventVoiceServerUpdate

type EventVoiceServerUpdate struct {
	Token    string       `json:"token"`
	GuildID  snowflake.ID `json:"guild_id"`
	Endpoint *string      `json:"endpoint"`
}

type EventVoiceStateUpdate

type EventVoiceStateUpdate struct {
	discord.VoiceState
	Member discord.Member `json:"member"`
}

type EventWebhooksUpdate

type EventWebhooksUpdate struct {
	GuildID   snowflake.ID `json:"guild_id"`
	ChannelID snowflake.ID `json:"channel_id"`
}

type Gateway

type Gateway interface {
	// ShardID returns the shard ID that this Gateway is configured to use.
	ShardID() int

	// ShardCount returns the total number of shards that this Gateway is configured to use.
	ShardCount() int

	// 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

	// 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

	// Intents returns the Intents that are used by this Gateway.
	Intents() Intents

	// 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)

	// Status returns the Status of the Gateway.
	Status() Status

	// 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
}

Gateway is what is used to connect to discord.

func New

func New(token string, eventHandlerFunc EventHandlerFunc, closeHandlerFunc CloseHandlerFunc, opts ...ConfigOpt) Gateway

New creates a new Gateway instance with the provided token, eventHandlerFunc, closeHandlerFunc and ConfigOpt(s).

type IdentifyCommandDataProperties

type IdentifyCommandDataProperties struct {
	OS      string `json:"os"`      // user OS
	Browser string `json:"browser"` // library name
	Device  string `json:"device"`  // library name
}

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 Intents

type Intents int64

Intents is an extension of the Bit structure used when identifying with discord

const (
	IntentGuilds Intents = 1 << iota
	IntentGuildMembers
	IntentGuildModeration
	IntentGuildEmojisAndStickers
	IntentGuildIntegrations
	IntentGuildWebhooks
	IntentGuildInvites
	IntentGuildVoiceStates
	IntentGuildPresences
	IntentGuildMessages
	IntentGuildMessageReactions
	IntentGuildMessageTyping
	IntentDirectMessages
	IntentDirectMessageReactions
	IntentDirectMessageTyping
	IntentMessageContent
	IntentGuildScheduledEvents

	IntentAutoModerationConfiguration
	IntentAutoModerationExecution

	IntentsGuild = IntentGuilds |
		IntentGuildMembers |
		IntentGuildModeration |
		IntentGuildEmojisAndStickers |
		IntentGuildIntegrations |
		IntentGuildWebhooks |
		IntentGuildInvites |
		IntentGuildVoiceStates |
		IntentGuildPresences |
		IntentGuildMessages |
		IntentGuildMessageReactions |
		IntentGuildMessageTyping |
		IntentGuildScheduledEvents

	IntentsDirectMessage = IntentDirectMessages |
		IntentDirectMessageReactions |
		IntentDirectMessageTyping

	IntentsNonPrivileged = IntentGuilds |
		IntentGuildModeration |
		IntentGuildEmojisAndStickers |
		IntentGuildIntegrations |
		IntentGuildWebhooks |
		IntentGuildInvites |
		IntentGuildVoiceStates |
		IntentGuildMessages |
		IntentGuildMessageReactions |
		IntentGuildMessageTyping |
		IntentDirectMessages |
		IntentDirectMessageReactions |
		IntentDirectMessageTyping |
		IntentGuildScheduledEvents |
		IntentAutoModerationConfiguration |
		IntentAutoModerationExecution

	IntentsPrivileged = IntentGuildMembers |
		IntentGuildPresences | IntentMessageContent

	IntentsAll = IntentsNonPrivileged |
		IntentsPrivileged

	IntentsDefault = IntentsNone

	IntentsNone Intents = 0
)

Constants for the different bit offsets of Intents

func (Intents) Add

func (i Intents) Add(bits ...Intents) Intents

Add allows you to add multiple bits together, producing a new bit

func (Intents) Has

func (i Intents) Has(bits ...Intents) bool

Has will ensure that the bit includes all the bits entered

func (Intents) Missing

func (i Intents) Missing(bits ...Intents) bool

Missing will check whether the bit is missing any one of the bits

func (Intents) Remove

func (i Intents) Remove(bits ...Intents) Intents

Remove allows you to subtract multiple bits from the first, producing a new bit

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

func (e *Message) UnmarshalJSON(data []byte) error

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 {
	Token          string                        `json:"token"`
	Properties     IdentifyCommandDataProperties `json:"properties"`
	Compress       bool                          `json:"compress,omitempty"`
	LargeThreshold int                           `json:"large_threshold,omitempty"`
	Shard          *[2]int                       `json:"shard,omitempty"`
	Intents        Intents                       `json:"intents"`
	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 []discord.Activity   `json:"activities"`
	Status     discord.OnlineStatus `json:"status"`
	AFK        bool                 `json:"afk"`
}

MessageDataPresenceUpdate is used for updating Client's presence

type MessageDataRequestGuildMembers

type MessageDataRequestGuildMembers struct {
	GuildID   snowflake.ID   `json:"guild_id"`
	Query     *string        `json:"query,omitempty"` //If specified, user_ids must not be entered
	Limit     *int           `json:"limit,omitempty"` //Must be >=1 if query/user_ids is used, otherwise 0
	Presences bool           `json:"presences,omitempty"`
	UserIDs   []snowflake.ID `json:"user_ids,omitempty"` //If specified, query must not be entered
	Nonce     string         `json:"nonce,omitempty"`    //All responses are hashed with this nonce, optional
}

MessageDataRequestGuildMembers is used for fetching all the members of a guild_events. It is recommended you have a strict member caching policy when using this.

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 MessageDataVoiceStateUpdate

type MessageDataVoiceStateUpdate struct {
	GuildID   snowflake.ID  `json:"guild_id"`
	ChannelID *snowflake.ID `json:"channel_id"`
	SelfMute  bool          `json:"self_mute"`
	SelfDeaf  bool          `json:"self_deaf"`
}

MessageDataVoiceStateUpdate is used for updating the bots voice state in a guild

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 PresenceOpt

type PresenceOpt func(presenceUpdate *MessageDataPresenceUpdate)

func WithAfk

func WithAfk(afk bool) PresenceOpt

WithAfk sets whether the session is afk

func WithCompetingActivity

func WithCompetingActivity(name string, opts ...ActivityOpt) PresenceOpt

WithCompetingActivity creates a new "Competing in ..." activity of type discord.ActivityTypeCompeting

func WithCustomActivity added in v0.5.1

func WithCustomActivity(status string, opts ...ActivityOpt) PresenceOpt

WithCustomActivity creates a new activity of type discord.ActivityTypeCustom

func WithListeningActivity

func WithListeningActivity(name string, opts ...ActivityOpt) PresenceOpt

WithListeningActivity creates a new "Listening to ..." activity of type discord.ActivityTypeListening

func WithOnlineStatus

func WithOnlineStatus(status discord.OnlineStatus) PresenceOpt

WithOnlineStatus sets the online status to the provided discord.OnlineStatus

func WithPlayingActivity

func WithPlayingActivity(name string, opts ...ActivityOpt) PresenceOpt

WithPlayingActivity creates a new "Playing ..." activity of type discord.ActivityTypeGame

func WithSince

func WithSince(since *int64) PresenceOpt

WithSince sets when the session has gone afk

func WithStreamingActivity

func WithStreamingActivity(name string, url string, opts ...ActivityOpt) PresenceOpt

WithStreamingActivity creates a new "Streaming ..." activity of type discord.ActivityTypeStreaming

func WithWatchingActivity

func WithWatchingActivity(name string, opts ...ActivityOpt) PresenceOpt

WithWatchingActivity creates a new "Watching ..." activity of type discord.ActivityTypeWatching

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

type RateLimiterConfig struct {
	Logger            log.Logger
	CommandsPerMinute int
}

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 log.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
)

Indicates how far along the client is too connecting.

func (Status) IsConnected

func (s Status) IsConnected() bool

IsConnected returns whether the Gateway is connected.

Jump to

Keyboard shortcuts

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