tempest

package module
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2026 License: BSD-3-Clause Imports: 21 Imported by: 4

README

Tempest library banner

Create lightning fast Discord Applications

Features - HTTP vs Gateway - Getting started - Troubleshooting - Contributing

Go Reference Go Report Go Version License Maintenance Status CodeQL Conventional Commits

Project: Tempest is a modern, minimal Discord library for building Discord Apps, written in Go. It aims to be extremely fast, stay very close to the Discord API, and include little to no caching - making it an excellent choice for small VPS or serverless architecture. In real-world projects using this lib, your bottlenecks will 9/10 cases be in the database or network bandwidth, not in app/bot itself.

It was created as a better alternative to discord-interactions-go, which is too low-level and outdated.

Features

  • Secure HTTPS-based communication with the Discord API using crypto/ed25519
  • Automatic dispatching of:
    • Application commands
    • Message components (buttons, select menu, text input)
    • Autocomplete interactions
    • Modal interactions
  • Built-in basic rate limit management that respects Discord’s HTTP limits
  • Full file upload support (message attachments) as stream (over x4 times faster than regular multipart creation)
  • Lightweight, fast command manager for auto handling slash commands, their auto complete and subcommands
  • Performance focused approach:
    • Structs only contain fields usable without a Gateway session
    • Essentially no caching for very low resource usage & easier hosting
  • Built-in helpers for component & modal interaction flow:
  • Helper structs and methods to manage:
    • Simple messages
    • Embeds
    • Components (buttons, string selects, sections, etc.)
    • Modals
    • Bitfields (flags, permissions, etc.)
    • Message Components v2
  • Exposed Rest client and all API structs which allows to easily extend library capabilities if needed
  • Basic support for Discord Monetization API (enough to get started)

HTTP vs Gateway

TL;DR: you probably should be using libraries like DiscordGo unless you know why you're here.

There are two ways for bots to receive events from Discord. Most API wrappers such as DiscordGo use a WebSocket connection called a "gateway" to receive events, but Tempest receives interaction events over HTTPS**. Using http hooks lets you scale code more easily & reduce resource usage at cost of greatly reduced number of events you can use. You can easily create bots for roles, minigames, custom messages or admin utils but it'll be very difficult / impossible to create music or moderation bots.

** Since v1.4 - Tempest can also run same code over gateway, simply swap HTTPClient to GatewayClient. Your existing bot/app code should be backward compatible. This option exists for large Discord Applications that outgrow initial plans and now require more reliable connection / lower latency for its users. Check usage at example/cmd/example-bot/main.go.

Getting started

  1. Install with: go get -u github.com/amatsagu/tempest
  2. Check example with few simple commands.
  3. (Experimental) Using AI coding assistants like Gemini, ChatGPT, or Claude? Check TEMPEST_AI.md for optimized documentation to help them understand the library better.

Troubleshooting

For help feel free to open an issue on github. You can also inivite to contact me on discord.

Contributing

All contributions are welcomed. Few rules before making a pull request:

FOSSA Status

Documentation

Index

Constants

View Source
const (
	DISCORD_EPOCH                      = 1420070400000 // Discord epoch in milliseconds
	USER_AGENT                         = "DiscordApp https://github.com/amatsagu/tempest"
	CONTENT_TYPE_JSON                  = "application/json"
	CONTENT_TYPE_OCTET_STREAM          = "application/octet-stream"
	CONTENT_MULTIPART_JSON_DESCRIPTION = `form-data; name="payload_json"`
	MAX_REQUEST_BODY_SIZE              = 1024 * 1024 // 1024 KB
	ROOT_PLACEHOLDER                   = "-"
)
View Source
const (
	SUPPRESS_JOIN_NOTIFICATIONS_SYSTEM_FLAG = 1 << iota
	SUPPRESS_PREMIUM_SUBSCRIPTIONS_SYSTEM_FLAG
	SUPPRESS_GUILD_REMINDER_NOTIFICATIONS_SYSTEM_FLAG
	SUPPRESS_JOIN_NOTIFICATION_REPLIES_SYSTEM_FLAG
	SUPPRESS_ROLE_SUBSCRIPTION_PURCHASE_NOTIFICATIONS_SYSTEM_FLAG
	SUPPRESS_ROLE_SUBSCRIPTION_PURCHASE_NOTIFICATION_REPLIES_SYSTEM_FLAG
)

Variables

This section is empty.

Functions

func DiscordAPIBaseURL added in v1.5.0

func DiscordAPIBaseURL() string

func DiscordCDNBaseURL added in v1.5.0

func DiscordCDNBaseURL() string

func FindInteractiveComponent added in v1.3.0

func FindInteractiveComponent[CC AnyComponent, T InteractiveComponent](components []CC, filter func(T) bool) (component T, found bool)

FindInteractiveComponent recursively scans the components array for the first interactive component that satisfies filter.

Warning - This function can traverse arbitrarily deep nested component trees & uses frequent type assertions, reducing overall performance. Prefer checking individual components for interactions with smaller numbers of components.

func UpdateDiscordAPIBaseURL added in v1.5.0

func UpdateDiscordAPIBaseURL(url string)

func UpdateDiscordCDNBaseURL added in v1.5.0

func UpdateDiscordCDNBaseURL(url string)

Types

type AccessoryComponent added in v1.3.0

type AccessoryComponent interface {
	AnyComponent
	// contains filtered or unexported methods
}

AccessoryComponent is a special subset of components that can be used as SectionComponent accessories. Only one accessory is allowed per section.

Currently valid types: ButtonComponent & ThumbnailComponent.

https://docs.discord.com/developers/components/reference#section-section-structure

type ActionRowChildComponent added in v1.5.0

type ActionRowChildComponent interface {
	AnyComponent
	// contains filtered or unexported methods
}

ActionRowChildComponent represents components that can be used inside an ActionRowComponent.

Currently valid types: ButtonComponent, StringSelectComponent and SelectComponent (user/role/mentionable/channel selects).

https://docs.discord.com/developers/components/reference#action-row-action-row-child-components

type ActionRowComponent added in v1.3.0

type ActionRowComponent struct {
	Type       ComponentType             `json:"type"` // Always = ACTION_ROW_COMPONENT_TYPE (1)
	ID         uint32                    `json:"id,omitempty"`
	Components []ActionRowChildComponent `json:"components,omitzero"` // Up to 5 interactive [ButtonComponent]s or a single [SelectComponent]
}

An ActionRowComponent groups other related components within a message or modal.

https://docs.discord.com/developers/components/reference#action-row-action-row-structure

func (*ActionRowComponent) UnmarshalJSON added in v1.3.0

func (c *ActionRowComponent) UnmarshalJSON(data []byte) error

type Activity added in v1.4.0

type Activity struct {
	Name string       `json:"name"`
	Type ActivityType `json:"type"`
	URL  string       `json:"url,omitempty"` // Stream URL, only for Streaming type
}

https://docs.discord.com/developers/events/gateway-events#activity-object

Activity only in context of Discord Bot Presence via Gateway.

type ActivityType added in v1.4.0

type ActivityType uint8

https://docs.discord.com/developers/events/gateway-events#activity-object-activity-types

const (
	PLAYING_ACTIVITY_TYPE   ActivityType = 0
	STREAMING_ACTIVITY_TYPE ActivityType = 1
	LISTENING_ACTIVITY_TYPE ActivityType = 2
	WATCHING_ACTIVITY_TYPE  ActivityType = 3
	CUSTOM_ACTIVITY_TYPE    ActivityType = 4
	COMPETING_ACTIVITY_TYPE ActivityType = 5
)

type AllowedMentions

type AllowedMentions struct {
	Parse       []AllowedMentionsType `json:"parse,omitzero"`
	Roles       []Snowflake           `json:"roles,omitzero"`
	Users       []Snowflake           `json:"users,omitzero"`
	RepliedUser bool                  `json:"replied_user"`
}

https://docs.discord.com/developers/resources/message#allowed-mentions-object

type AllowedMentionsType added in v1.2.3

type AllowedMentionsType string

https://docs.discord.com/developers/resources/message#allowed-mentions-object-allowed-mention-types

const (
	ALLOWED_ROLE_MENTION_TYPE     AllowedMentionsType = "roles"
	ALLOWED_USERS_MENTION_TYPE    AllowedMentionsType = "users"
	ALLOWED_EVERYONE_MENTION_TYPE AllowedMentionsType = "everyone"
)

type AnyComponent added in v1.3.0

type AnyComponent interface {
	// contains filtered or unexported methods
}

AnyComponent is a union interface representing all possible Discord components. All component types must implement this interface.

Avoid using this interface directly; instead look at its child interfaces - MessageComponent, ModalComponent, InteractiveComponent, LabelChildComponent, etc.

func UnmarshalComponent added in v1.3.0

func UnmarshalComponent(data []byte) (AnyComponent, error)

UnmarshalComponent inspects the "type" field and returns the proper component struct.

type Attachment

type Attachment struct {
	ID           Snowflake `json:"id"`
	FileName     string    `json:"filename"`
	Title        string    `json:"title,omitempty"`
	Description  string    `json:"description,omitempty"`
	ContentType  string    `json:"content_type,omitempty"`
	Size         uint64    `json:"size"`
	URL          string    `json:"url"`
	ProxyURL     string    `json:"proxy_url"`
	Height       uint32    `json:"height,omitempty"`
	Width        uint32    `json:"width,omitempty"`
	Ephemeral    bool      `json:"ephemeral"`
	DurationSecs float64   `json:"duration_secs,omitempty"`
	Waveform     string    `json:"waveform,omitempty"`
	Flags        uint64    `json:"flags,omitempty"`
}

https://docs.discord.com/developers/resources/channel#attachment-object

type AvatarDecoration added in v1.2.3

type AvatarDecoration struct {
	AssetHash string    `json:"avatar"` // Hash code used to access user's avatar decoration.
	SkuID     Snowflake `json:"sku_id"`
}

https://docs.discord.com/developers/resources/user#avatar-decoration-data-object-avatar-decoration-data-structure

func (*AvatarDecoration) DecorationURL added in v1.2.3

func (adc *AvatarDecoration) DecorationURL() string

Returns a direct url to targets's avatar decoration. It'll return empty string if target doesn't use avatar decoration.

type BaseClient added in v1.4.0

type BaseClient struct {
	ApplicationID Snowflake
	Rest          *Rest
	// contains filtered or unexported fields
}

BaseClient is the core tempest entrypoint. It's used to create either HTTP or Gateway clients. You should avoid using base version unless you know what you're doing.

func NewBaseClient added in v1.4.0

func NewBaseClient(opt BaseClientOptions) *BaseClient

func (*BaseClient) AwaitComponent added in v1.4.0

func (client *BaseClient) AwaitComponent(customIDs []string) (<-chan *ComponentInteraction, func(), error)

Makes client dynamically "listen" incoming component type interactions. When component custom id matches - it'll send back interaction through channel. Holder s responsible for calling cleanup function once done (check example app code for better understanding). You can use context to control timeout - Discord API allows to reply to interaction for max 15 minutes.

Warning! Components handled this way will already be acknowledged.

func (*BaseClient) AwaitModal added in v1.4.0

func (client *BaseClient) AwaitModal(customIDs []string) (<-chan *ModalInteraction, func(), error)

Mirror method to Client.AwaitComponent but for handling modal interactions. Look comment on Client.AwaitComponent and see example bot/app code for more.

func (*BaseClient) ConsumeEntitlement added in v1.4.0

func (client *BaseClient) ConsumeEntitlement(entitlementID Snowflake) error

For One-Time Purchase consumable SKUs, marks a given entitlement for the user as consumed. The entitlement will have consumed: true when using Client.FetchEntitlements.

https://docs.discord.com/developers/resources/entitlement#consume-an-entitlement

func (*BaseClient) CrosspostMessage added in v1.4.0

func (client *BaseClient) CrosspostMessage(channelID Snowflake, messageID Snowflake) error

func (*BaseClient) DeleteComponent added in v1.4.2

func (client *BaseClient) DeleteComponent(customIDs []string) error

Removes previously registered, static components that match any of provided custom IDs.

func (*BaseClient) DeleteMessage added in v1.4.0

func (client *BaseClient) DeleteMessage(channelID Snowflake, messageID Snowflake) error

func (*BaseClient) DeleteModal added in v1.4.2

func (client *BaseClient) DeleteModal(customIDs []string) error

Removes previously registered, static modals that match any of provided custom IDs.

func (*BaseClient) DeleteTestEntitlement added in v1.4.0

func (client *BaseClient) DeleteTestEntitlement(entitlementID Snowflake) error

https://docs.discord.com/developers/resources/entitlement#delete-test-entitlement

func (*BaseClient) EditMessage added in v1.4.0

func (client *BaseClient) EditMessage(channelID Snowflake, messageID Snowflake, content Message) error

func (*BaseClient) FetchEntitlement added in v1.4.0

func (client *BaseClient) FetchEntitlement(entitlementID Snowflake) (Entitlement, error)

https://docs.discord.com/developers/resources/entitlement#get-entitlement

func (*BaseClient) FetchEntitlementsPage added in v1.4.0

func (client *BaseClient) FetchEntitlementsPage(queryFilter string) ([]Entitlement, error)

Returns all entitlements for a given app, active and expired.

By default it will attempt to return all, existing entitlements - provide query filter to control this behavior.

https://docs.discord.com/developers/resources/entitlement#list-entitlements

func (*BaseClient) FetchMember added in v1.4.0

func (client *BaseClient) FetchMember(guildID Snowflake, memberID Snowflake) (Member, error)

func (*BaseClient) FetchUser added in v1.4.0

func (client *BaseClient) FetchUser(id Snowflake) (User, error)

func (*BaseClient) FindCommand added in v1.4.0

func (client *BaseClient) FindCommand(cmdName string) (Command, bool)

func (*BaseClient) RegisterCommand added in v1.4.0

func (client *BaseClient) RegisterCommand(cmd Command) error

func (*BaseClient) RegisterComponent added in v1.4.0

func (client *BaseClient) RegisterComponent(customIDs []string, fn func(ComponentInteraction)) error

Bind function to all components with matching custom ids. App will automatically run bound function whenever receiving component interaction with matching custom id.

func (*BaseClient) RegisterModal added in v1.4.0

func (client *BaseClient) RegisterModal(customID string, fn func(ModalInteraction)) error

Bind function to modal with matching custom id. App will automatically run bound function whenever receiving component interaction with matching custom id.

func (*BaseClient) RegisterSubCommand added in v1.4.0

func (client *BaseClient) RegisterSubCommand(subCommand Command, parentCommandName string) error

func (*BaseClient) SendLinearMessage added in v1.4.0

func (client *BaseClient) SendLinearMessage(channelID Snowflake, content string) (Message, error)

func (*BaseClient) SendMessage added in v1.4.0

func (client *BaseClient) SendMessage(channelID Snowflake, message Message, files []File) (Message, error)

func (*BaseClient) SendPrivateMessage added in v1.4.0

func (client *BaseClient) SendPrivateMessage(userID Snowflake, content Message, files []File) (Message, error)

Creates (or fetches if already exists) user's private text channel (DM) and tries to send message into it. Warning! Discord's user channels endpoint has huge rate limits so please reuse Message#ChannelID whenever possible.

func (*BaseClient) SyncCommandsWithDiscord added in v1.4.0

func (client *BaseClient) SyncCommandsWithDiscord(guildIDs []Snowflake, whitelist []string, reverseMode bool) error

type BaseClientOptions added in v1.4.0

type BaseClientOptions struct {
	Token                      string
	DefaultInteractionContexts []InteractionContextType

	PreCommandHook   func(cmd Command, itx *CommandInteraction) bool // Function that runs before each command. Return type signals whether to continue command execution (return with false to stop early).
	PostCommandHook  func(cmd Command, itx *CommandInteraction)      // Function that runs after each command.
	ComponentHandler func(itx *ComponentInteraction)                 // Function that runs for each unhandled component.
	ModalHandler     func(itx *ModalInteraction)                     // Function that runs for each unhandled modal.

	Logger *log.Logger // Optional custom logger. If tracing is enabled, this logger will be used for all internal messages. If none is provided, the default Stdout logger will be used instead.
}

type BitSet added in v1.2.3

type BitSet uint64

Represents combination of discord bit settings, flags, permissions, etc. For example all the user badges or member permissions.

func (BitSet) Add added in v1.2.3

func (f BitSet) Add(bits ...BitSet) BitSet

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

func (BitSet) Has added in v1.2.3

func (f BitSet) Has(bits ...BitSet) bool

Has will ensure that the bit set includes all the bits entered.

func (BitSet) Missing added in v1.2.3

func (f BitSet) Missing(bits ...BitSet) bool

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

func (BitSet) Remove added in v1.2.3

func (f BitSet) Remove(bits ...BitSet) BitSet

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

type ButtonComponent added in v1.3.0

type ButtonComponent struct {
	Type     ComponentType `json:"type"` // Always = BUTTON_COMPONENT_TYPE (2)
	ID       uint32        `json:"id,omitempty"`
	Style    ButtonStyle   `json:"style"`
	Label    string        `json:"label,omitempty"`
	Emoji    *Emoji        `json:"emoji,omitempty"` // It may only contain id, name, and animated from regular Emoji struct.
	CustomID string        `json:"custom_id,omitempty"`
	SkuID    Snowflake     `json:"sku_id,omitempty"` // Identifier for a purchasable SKU, only available when using premium-style buttons. Premium buttons do not send an interaction to your app when clicked.
	URL      string        `json:"url,omitempty"`
	Disabled bool          `json:"disabled"`
}

A ButtonComponent displays a clickable element that users can interact with, sending an interaction to your app when pressed.

They must be placed within an ActionRowComponent or a SectionComponent's accessory field, both of which are only valid inside messages.

https://docs.discord.com/developers/components/reference#button

type ButtonStyle

type ButtonStyle uint8

https://docs.discord.com/developers/components/reference#button-button-styles

const (
	PRIMARY_BUTTON_STYLE   ButtonStyle = iota + 1 // blurple (custom_id field is required)
	SECONDARY_BUTTON_STYLE                        // grey (custom_id field is required)
	SUCCESS_BUTTON_STYLE                          // green (custom_id field is required)
	DANGER_BUTTON_STYLE                           // red (custom_id field is required)
	LINK_BUTTON_STYLE                             // grey, navigate to URL (url field is required)
	PREMIUM_BUTTON_STYLE                          // By default same as primary but will automatically use SKU icon, name & price (sky_id field is required)
)

type ChannelMention

type ChannelMention struct {
	ID      Snowflake   `json:"id"`
	Name    string      `json:"name"`
	GuildID Snowflake   `json:"guild_id"`
	Type    ChannelType `json:"type"`
}

https://docs.discord.com/developers/resources/message#channel-mention-object

type ChannelType

type ChannelType uint8

https://docs.discord.com/developers/resources/channel#channel-object-channel-types

const (
	GUILD_TEXT_CHANNEL_TYPE ChannelType = iota
	DM_CHANNEL_TYPE
	GUILD_VOICE_CHANNEL_TYPE
	GROUP_DM_CHANNEL_TYPE
	GUILD_CATEGORY_CHANNEL_TYPE
	GUILD_ANNOUNCEMENT_CHANNEL_TYPE // Formerly news channel.

	GUILD_ANNOUNCEMENT_THREAD_CHANNEL_TYPE
	GUILD_PUBLIC_THREAD_CHANNEL_TYPE
	GUILD_PRIVATE_THREAD_CHANNEL_TYPE
	GUILD_STAGE_VOICE_CHANNEL_TYPE
	GUILD_DIRECTORY_CHANNEL_TYPE
	GUILD_FORUM_CHANNEL_TYPE
	GUILD_MEDIA_CHANNEL_TYPE
)

func (ChannelType) MarshalJSON

func (ct ChannelType) MarshalJSON() (p []byte, err error)

type CheckboxComponent added in v1.6.0

type CheckboxComponent struct {
	Type     ComponentType `json:"type"`         // Always = CHECKBOX_COMPONENT_TYPE (23)
	ID       uint32        `json:"id,omitempty"` // Optional identifier for component
	CustomID string        `json:"custom_id,omitempty"`
	Default  bool          `json:"default"` // Whether to render this option as selected by default.
}

A Checkbox is a single interactive component for simple yes/no style questions. Checkboxes are available in modals and must be placed inside a Label Component(s).

https://docs.discord.com/developers/components/reference#checkbox

type CheckboxGroupComponent added in v1.6.0

type CheckboxGroupComponent struct {
	Type      ComponentType         `json:"type"`         // Always = CHECKBOX_GROUP_COMPONENT_TYPE (22)
	ID        uint32                `json:"id,omitempty"` // Optional identifier for component
	CustomID  string                `json:"custom_id,omitempty"`
	Options   []CheckboxGroupOption `json:"options,omitzero"`
	MinValues uint8                 `json:"min_values,omitempty"`
	MaxValues uint8                 `json:"max_values,omitempty"`
	Required  bool                  `json:"required"`
}

A Checkbox Group is an interactive component for selecting one or many options via checkboxes. Checkbox Groups are available in modals and must be placed inside a Label Component(s).

https://docs.discord.com/developers/components/reference#checkbox-group

type CheckboxGroupOption added in v1.6.0

type CheckboxGroupOption struct {
	Value       string `json:"value"`
	Label       string `json:"label"`
	Description string `json:"description,omitempty"`
	Default     bool   `json:"default"` // Whether to render this option as selected by default.
}

https://docs.discord.com/developers/components/reference#checkbox-group-option-structure

type Command

type Command struct {
	ID                       Snowflake                    `json:"-"` // It's not needed on app side to work.
	Type                     CommandType                  `json:"type,omitempty"`
	ApplicationID            Snowflake                    `json:"application_id"`
	GuildID                  Snowflake                    `json:"guild_id,omitempty"`
	Name                     string                       `json:"name"`
	NameLocalizations        map[Language]string          `json:"name_localizations,omitzero"`
	Description              string                       `json:"description"`
	DescriptionLocalizations map[Language]string          `json:"description_localizations,omitzero"`
	Options                  []CommandOption              `json:"options,omitzero"`
	RequiredPermissions      PermissionFlags              `json:"default_member_permissions,string,omitempty"` // Set of permissions represented as a bit set that are required from user/member to use command. Set it to 0 to make command unavailable for regular members (guild administrators still can use it).
	IntegrationTypes         []ApplicationIntegrationType `json:"integration_types,omitzero"`
	Contexts                 []InteractionContextType     `json:"contexts,omitzero"` // Interaction context(s) where the command can be used, only for globally-scoped commands. By default, all interaction context types included for new commands.
	NSFW                     bool                         `json:"nsfw"`              // https://docs.discord.com/developers/interactions/application-commands#agerestricted-commands
	Version                  Snowflake                    `json:"version,omitempty"` // Autoincrementing version identifier updated during substantial record changes.
	Handler                  CommandHandlerType           `json:"handler,omitempty"`

	AutoCompleteHandler func(itx CommandInteraction) []CommandOptionChoice `json:"-"` // Custom handler for auto complete interactions. It's a Tempest specific field.
	SlashCommandHandler func(itx *CommandInteraction)                      `json:"-"` // Custom handler for slash command interactions. It's a Tempest specific field. It receives pointer to CommandInteraction as it's being used with pre & post client hooks.
}

https://docs.discord.com/developers/interactions/application-commands#application-command-object-application-command-structure

type CommandHandlerType added in v1.3.0

type CommandHandlerType uint8

https://docs.discord.com/developers/interactions/application-commands#application-command-object-entry-point-command-handler-types

const (
	APP_COMMAND_HANDLER CommandHandlerType = iota + 1
	DISCORD_LAUNCH_ACTIVITY_COMMAND_HANDLER
)

type CommandInteraction

type CommandInteraction struct {
	*Interaction
	Data CommandInteractionData `json:"data"`
}

https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-object

func (*CommandInteraction) Defer

func (itx *CommandInteraction) Defer(ephemeral bool) error

Use to let user/member know that bot is processing command. Make ephemeral = true to make notification visible only to target.

func (*CommandInteraction) DeleteFollowUp

func (itx *CommandInteraction) DeleteFollowUp(messageID Snowflake) error

func (*CommandInteraction) DeleteReply

func (itx *CommandInteraction) DeleteReply() error

func (*CommandInteraction) EditFollowUp

func (itx *CommandInteraction) EditFollowUp(messageID Snowflake, content ResponseMessageData) error

func (*CommandInteraction) EditLinearFollowUp added in v1.3.1

func (itx *CommandInteraction) EditLinearFollowUp(messageID Snowflake, content string) error

func (*CommandInteraction) EditLinearReply added in v1.3.1

func (itx *CommandInteraction) EditLinearReply(content string, ephemeral bool) error

func (*CommandInteraction) EditReply

func (itx *CommandInteraction) EditReply(content ResponseMessageData, ephemeral bool) error

func (*CommandInteraction) GetFocusedValue

func (itx *CommandInteraction) GetFocusedValue() (string, any)

Warning! This method is only for handling auto complete interaction which is a part of command logic. Returns option name and its value of triggered option. Option name is always of string type but you'll need to check type of value.

func (*CommandInteraction) GetOptionValue

func (itx *CommandInteraction) GetOptionValue(name string) (any, bool)

Returns value of any type. Check second value to check whether option was provided or not (true if yes).

func (*CommandInteraction) ResolveAttachment

func (itx *CommandInteraction) ResolveAttachment(id Snowflake) Attachment

Returns pointer to attachment if present in interaction.data.resolved. It'll return empty struct if there's no resolved attachment.

func (*CommandInteraction) ResolveChannel

func (itx *CommandInteraction) ResolveChannel(id Snowflake) PartialChannel

Returns pointer to partial channel if present in interaction.data.resolved. It'll return empty struct if there's no resolved partial channel.

func (*CommandInteraction) ResolveMember

func (itx *CommandInteraction) ResolveMember(id Snowflake) Member

Returns pointer to member if present in interaction.data.resolved and binds member.user. It'll return empty struct if there's no resolved member.

func (*CommandInteraction) ResolveMessage

func (itx *CommandInteraction) ResolveMessage(id Snowflake) Message

Returns pointer to message if present in interaction.data.resolved. It'll return empty struct if there's no resolved message.

func (*CommandInteraction) ResolveRole

func (itx *CommandInteraction) ResolveRole(id Snowflake) (Role, bool)

Returns pointer to guild role if present in interaction.data.resolved. It'll return empty struct if there's no resolved role.

func (*CommandInteraction) ResolveUser

func (itx *CommandInteraction) ResolveUser(id Snowflake) User

Returns pointer to user if present in interaction.data.resolved. It'll return empty struct if there's no resolved user.

func (*CommandInteraction) SendFollowUp

func (itx *CommandInteraction) SendFollowUp(content ResponseMessageData, ephemeral bool) (Message, error)

func (*CommandInteraction) SendFollowUpWithFiles added in v1.4.0

func (itx *CommandInteraction) SendFollowUpWithFiles(content ResponseMessageData, ephemeral bool, files []File) (Message, error)

func (*CommandInteraction) SendLinearFollowUp added in v1.3.1

func (itx *CommandInteraction) SendLinearFollowUp(content string, ephemeral bool) (Message, error)

func (*CommandInteraction) SendLinearFollowUpWithFiles added in v1.4.0

func (itx *CommandInteraction) SendLinearFollowUpWithFiles(content string, ephemeral bool, files []File) (Message, error)

func (*CommandInteraction) SendLinearReply

func (itx *CommandInteraction) SendLinearReply(content string, ephemeral bool) error

func (*CommandInteraction) SendModal

func (itx *CommandInteraction) SendModal(modal ResponseModalData) error

func (*CommandInteraction) SendReply

func (itx *CommandInteraction) SendReply(reply ResponseMessageData, ephemeral bool, files []File) error

Acknowledges the interaction with a message. Set ephemeral = true to make message visible only to target.

type CommandInteractionData

type CommandInteractionData struct {
	ID       Snowflake                  `json:"id"`
	Name     string                     `json:"name"`
	Type     CommandType                `json:"type"`
	Resolved *InteractionDataResolved   `json:"resolved,omitempty"`
	Options  []CommandInteractionOption `json:"options,omitzero"`
	GuildID  Snowflake                  `json:"guild_id,omitempty"`
	TargetID Snowflake                  `json:"target_id,omitempty"` // ID of either user or message targeted. Depends whether it was user command or message command.
}

https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-object-interaction-data

type CommandInteractionOption

type CommandInteractionOption struct {
	Name    string                     `json:"name"`
	Type    OptionType                 `json:"type"`
	Value   any                        `json:"value,omitempty"` // string, float64 (double or integer) or bool
	Options []CommandInteractionOption `json:"options,omitzero"`
	Focused bool                       `json:"focused"`
}

https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-object-application-command-interaction-data-option-structure

type CommandOption

type CommandOption struct {
	Type                     OptionType            `json:"type"`
	Name                     string                `json:"name"`
	NameLocalizations        map[Language]string   `json:"name_localizations,omitzero"`
	Description              string                `json:"description"`
	DescriptionLocalizations map[Language]string   `json:"description_localizations,omitzero"`
	Required                 bool                  `json:"required"`
	Choices                  []CommandOptionChoice `json:"choices,omitzero"`
	Options                  []CommandOption       `json:"options,omitzero"`
	ChannelTypes             []ChannelType         `json:"channel_types,omitzero"`
	MinValue                 float64               `json:"min_value,omitempty"`
	MaxValue                 float64               `json:"max_value,omitempty"`
	MinLength                uint16                `json:"min_length,omitempty"`
	MaxLength                uint16                `json:"max_length,omitempty"`
	AutoComplete             bool                  `json:"autocomplete"` // Required to be = true if you want to catch it later in auto complete handler.
}

https://docs.discord.com/developers/interactions/application-commands#application-command-object-application-command-option-structure

type CommandOptionChoice added in v1.3.0

type CommandOptionChoice struct {
	Name              string              `json:"name"`
	NameLocalizations map[Language]string `json:"name_localizations,omitzero"` // https://docs.discord.com/developers/reference#locales
	Value             any                 `json:"value"`                       // string, float64 (double or integer) or bool
}

https://docs.discord.com/developers/interactions/application-commands#application-command-object-application-command-option-choice-structure

type CommandType

type CommandType uint8

https://docs.discord.com/developers/interactions/application-commands#application-command-object-application-command-types

const (
	CHAT_INPUT_COMMAND_TYPE          CommandType = iota + 1 // Slash command (default option)
	USER_COMMAND_TYPE                                       // Mounted to user/member profile
	MESSAGE_COMMAND_TYPE                                    // Mounted to text message
	PRIMARY_ENTRY_POINT_COMMAND_TYPE                        // An UI-based command that represents the primary way to invoke an app's Activity
)

type ComponentInteraction

type ComponentInteraction struct {
	*Interaction
	Data ComponentInteractionData `json:"data"`
}

https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-object

func (*ComponentInteraction) Acknowledge

func (itx *ComponentInteraction) Acknowledge() error

Sends to discord info that this component was handled successfully without sending anything more.

func (*ComponentInteraction) AcknowledgeWithLinearMessage

func (itx *ComponentInteraction) AcknowledgeWithLinearMessage(content string, ephemeral bool) error

func (*ComponentInteraction) AcknowledgeWithMessage

func (itx *ComponentInteraction) AcknowledgeWithMessage(reply ResponseMessageData, ephemeral bool) error

func (*ComponentInteraction) AcknowledgeWithModal

func (itx *ComponentInteraction) AcknowledgeWithModal(modal ResponseModalData) error

type ComponentInteractionData

type ComponentInteractionData struct {
	CustomID string                   `json:"custom_id"`
	Type     ComponentType            `json:"component_type"`
	Values   []string                 `json:"values,omitzero"` // Values the user selected in a select menu component
	Resolved *InteractionDataResolved `json:"resolved,omitempty"`
}

https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-object-message-component-data-structure

type ComponentType

type ComponentType uint8
const (
	ACTION_ROW_COMPONENT_TYPE         ComponentType = iota + 1 // Layout component for Messages
	BUTTON_COMPONENT_TYPE                                      // Interactive component for Messages
	STRING_SELECT_COMPONENT_TYPE                               // Interactive component for Messages and Modals
	TEXT_INPUT_COMPONENT_TYPE                                  // Interactive component for Modals
	USER_SELECT_COMPONENT_TYPE                                 // Interactive component for Messages
	ROLE_SELECT_COMPONENT_TYPE                                 // Interactive component for Messages
	MENTIONABLE_SELECT_COMPONENT_TYPE                          // Interactive component for Messages
	CHANNEL_SELECT_COMPONENT_TYPE                              // Interactive component for Messages
	SECTION_COMPONENT_TYPE                                     // Layout component for Messages
	TEXT_DISPLAY_COMPONENT_TYPE                                // Content component for Messages
	THUMBNAIL_COMPONENT_TYPE                                   // Content component for Messages
	MEDIA_GALLERY_COMPONENT_TYPE                               // Content component for Messages
	FILE_COMPONENT_TYPE                                        // Content component for Messages
	SEPARATOR_COMPONENT_TYPE                                   // Layout component for Messages

	CONTAINER_COMPONENT_TYPE   // Layout component for Messages
	LABEL_COMPONENT_TYPE       // Layout component for Modals
	FILE_UPLOAD_COMPONENT_TYPE // Layout component for Modals

	RADIO_GROUP_COMPONENT_TYPE    // Interactive component for Modals
	CHECKBOX_GROUP_COMPONENT_TYPE // Interactive component for Modals
	CHECKBOX_COMPONENT_TYPE       // Interactive component for Modals
)

https://docs.discord.com/developers/components/reference#component-object

type ContainerChildComponent added in v1.5.0

type ContainerChildComponent interface {
	AnyComponent
	// contains filtered or unexported methods
}

ContainerChildComponent represents components that can be used as the child of a ContainerComponent.

Currently valid types: ActionRowComponent, TextDisplayComponent, SectionComponent, MediaGalleryComponent, SeparatorComponent and FileComponent.

https://docs.discord.com/developers/components/reference#container-container-child-components

type ContainerComponent added in v1.3.0

type ContainerComponent struct {
	Type        ComponentType             `json:"type"` // Always = CONTAINER_COMPONENT_TYPE (17)
	ID          uint32                    `json:"id,omitempty"`
	Components  []ContainerChildComponent `json:"components,omitzero"`    // Child components to nest within the container.
	AccentColor uint32                    `json:"accent_color,omitempty"` // The accent color of the container, as an RGB value from 0x000000 to 0xFFFFFF. (Write as a hex literal for best results.)
	Spoiler     bool                      `json:"spoiler"`                // Whether to mark the container as a spoiler.
}

A ContainerComponent visually encapsulates one or more components inside a message, alongside an optional accent color bar.

They can only be used inside messages.

https://docs.discord.com/developers/components/reference#container-container-structure

func (*ContainerComponent) UnmarshalJSON added in v1.3.0

func (c *ContainerComponent) UnmarshalJSON(data []byte) error

type ContentComponent added in v1.3.0

type ContentComponent interface {
	AnyComponent
	// contains filtered or unexported methods
}

ContentComponent represents non-interactive visual components such as text, media, or files. These are used to display static content in sections or containers.

type CreateGuildEventData added in v1.5.0

type CreateGuildEventData struct {
	*Guild

	JoinedAt    *time.Time `json:"joined_at"`
	Large       bool       `json:"large"`
	Unavailable bool       `json:"unavailable,omitempty"`
	MemberCount uint32     `json:"member_count"`

	Members  []Member         `json:"members"`
	Channels []PartialChannel `json:"channels"`
	Threads  []PartialChannel `json:"threads"`
}

Represents the payload for the GUILD_CREATE gateway event. It embeds the base Guild object and adds fields unique to this event.

https://docs.discord.com/developers/events/gateway-events#guild-create

type DefaultValueOption added in v1.3.0

type DefaultValueOption struct {
	ID   Snowflake        `json:"id"`   // Snowflake ID of a user, role, or channel
	Type DefaultValueType `json:"type"` // The type of value that the option represents. Should be consistent across all default value options.
}

https://docs.discord.com/developers/components/reference#user-select-select-default-value-structure

type DefaultValueType added in v1.3.0

type DefaultValueType string

https://docs.discord.com/developers/components/reference#user-select-select-default-value-structure

const (
	USER_DEFAULT_VALUE    DefaultValueType = "user"
	ROLE_DEFAULT_VALUE    DefaultValueType = "role"
	CHANNEL_DEFAULT_VALUE DefaultValueType = "channel"
)

type Embed

type Embed struct {
	Title       string          `json:"title,omitempty"`
	URL         string          `json:"url,omitempty"`
	Author      *EmbedAuthor    `json:"author,omitempty"`
	Color       uint32          `json:"color,omitempty"`
	Thumbnail   *EmbedThumbnail `json:"thumbnail,omitempty"`
	Description string          `json:"description,omitempty"`
	Fields      []EmbedField    `json:"fields,omitzero"`
	Footer      *EmbedFooter    `json:"footer,omitempty"`
	Image       *EmbedImage     `json:"image,omitempty"`
	Video       *EmbedVideo     `json:"video,omitempty"`
	Provider    *EmbedProvider  `json:"provider,omitempty"`
	Timestamp   *time.Time      `json:"timestamp,omitempty"`
}

https://docs.discord.com/developers/resources/channel#embed-object-embed-structure (always rich embed type)

type EmbedAuthor

type EmbedAuthor struct {
	Name         string `json:"name"`
	URL          string `json:"url,omitempty"`
	IconURL      string `json:"icon_url,omitempty"`
	ProxyIconURL string `json:"proxy_icon_url,omitempty"`
}

https://docs.discord.com/developers/resources/channel#embed-object-embed-author-structure

type EmbedField

type EmbedField struct {
	Name   string `json:"name"`
	Value  string `json:"value"`
	Inline bool   `json:"inline"`
}

https://docs.discord.com/developers/resources/channel#embed-object-embed-field-structure

type EmbedFooter

type EmbedFooter struct {
	Text         string `json:"text"`
	IconURL      string `json:"icon_url,omitempty"`
	ProxyIconURL string `json:"proxy_icon_url,omitempty"`
}

https://docs.discord.com/developers/resources/channel#embed-object-embed-footer-structure

type EmbedImage

type EmbedImage struct {
	URL      string `json:"url"`
	ProxyURL string `json:"proxy_url,omitempty"`
	Width    uint32 `json:"width,omitempty"`
	Height   uint32 `json:"height,omitempty"`
}

https://docs.discord.com/developers/resources/channel#embed-object-embed-image-structure

type EmbedProvider

type EmbedProvider struct {
	URL  string `json:"url,omitempty"`
	Name string `json:"name,omitempty"`
}

https://docs.discord.com/developers/resources/channel#embed-object-embed-provider-structure

type EmbedThumbnail

type EmbedThumbnail struct {
	URL      string `json:"url"`
	ProxyURL string `json:"proxy_url,omitempty"`
	Width    uint32 `json:"width,omitempty"`
	Height   uint32 `json:"height,omitempty"`
}

https://docs.discord.com/developers/resources/channel#embed-object-embed-thumbnail-structure

type EmbedVideo

type EmbedVideo struct {
	URL      string `json:"url,omitempty"`
	ProxyURL string `json:"proxy_url,omitempty"`
	Width    uint32 `json:"width,omitempty"`
	Height   uint32 `json:"height,omitempty"`
}

https://docs.discord.com/developers/resources/channel#embed-object-embed-video-structure

type Emoji

type Emoji struct {
	ID            Snowflake   `json:"id,omitempty"`
	Name          string      `json:"name,omitempty"` // Note: may be empty for deleted emojis.
	Roles         []Snowflake `json:"roles,omitzero"`
	User          *User       `json:"user,omitempty"`
	RequireColons bool        `json:"require_colons"`
	Managed       bool        `json:"managed"`
	Animated      bool        `json:"animated"`
	Available     bool        `json:"available"`
}

https://docs.discord.com/developers/resources/emoji#emoji-object-emoji-structure

type Entitlement added in v1.3.0

type Entitlement struct {
	ID            Snowflake       `json:"id"`
	SkuID         Snowflake       `json:"sku_id"`
	ApplicationID Snowflake       `json:"application_id"`
	UserID        Snowflake       `json:"user_id,omitempty"` // ID of the user that is granted access to the entitlement's sku
	Type          EntitlementType `json:"type"`
	Deleted       bool            `json:"deleted"` // Whether entitlement was deleted
	StartsAt      *time.Time      `json:"starts_at"`
	EndsAt        *time.Time      `json:"ends_at"`
	GuildID       Snowflake       `json:"guild_id,omitempty"`
	Consumed      bool            `json:"consumed"` // Whether entitlement was already used
}

Entitlements in Discord represent that a user or guild has access to a premium offering in your application.

Refer to the Monetization Overview for more information on how to use Entitlements in your app.

https://docs.discord.com/developers/resources/entitlement#entitlement-object

type EntitlementType added in v1.3.0

type EntitlementType uint8

https://docs.discord.com/developers/resources/entitlement#entitlement-object-entitlement-types

const (
	PURCHASE_ENTITLEMENT_TYPE EntitlementType = iota + 1
	PREMIUM_SUBSCRIPTION_ENTITLEMENT_TYPE
	DEVELOPER_GIFT_ENTITLEMENT_TYPE
	TEST_MODE_PURCHASE_ENTITLEMENT_TYPE
	FREE_PURCHASE_ENTITLEMENT_TYPE
	USER_GIFT_ENTITLEMENT_TYPE
	PREMIUM_PURCHASE_ENTITLEMENT_TYPE
	APPLICATION_SUBSCRIPTION_ENTITLEMENT_TYPE
)

type EventName added in v1.4.0

type EventName string

https://docs.discord.com/developers/events/gateway-events#receive-events

const (
	READY_EVENT               EventName = "READY"
	RESUMED_EVENT             EventName = "RESUMED"
	INTERACTION_CREATE_EVENT  EventName = "INTERACTION_CREATE"
	MESSAGE_CREATE_EVENT      EventName = "MESSAGE_CREATE"
	MESSAGE_UPDATE_EVENT      EventName = "MESSAGE_UPDATE"
	MESSAGE_DELETE_EVENT      EventName = "MESSAGE_DELETE"
	MESSAGE_DELETE_BULK_EVENT EventName = "MESSAGE_DELETE_BULK"
	GUILD_CREATE_EVENT        EventName = "GUILD_CREATE"
	GUILD_DELETE_EVENT        EventName = "GUILD_DELETE"
	ENTITLEMENT_CREATE_EVENT  EventName = "ENTITLEMENT_CREATE"
	ENTITLEMENT_UPDATE_EVENT  EventName = "ENTITLEMENT_UPDATE"
	ENTITLEMENT_DELETE_EVENT  EventName = "ENTITLEMENT_DELETE"
	INTEGRATION_CREATE_EVENT  EventName = "INTEGRATION_CREATE"
	INTEGRATION_UPDATE_EVENT  EventName = "INTEGRATION_UPDATE"
	INTEGRATION_DELETE_EVENT  EventName = "INTEGRATION_DELETE"
	VOICE_STATE_UPDATE_EVENT  EventName = "VOICE_STATE_UPDATE"
)

type EventPacket added in v1.4.0

type EventPacket struct {
	Opcode   Opcode          `json:"op"`
	Sequence uint32          `json:"s,omitempty"`
	Event    EventName       `json:"t,omitempty"`
	Data     json.RawMessage `json:"d"`
}

In modern discord docs - otherwise known as generic gateway event.

https://docs.discord.com/developers/events/gateway#gateway-events

type ExplicitContentFilter added in v1.3.5

type ExplicitContentFilter uint8

https://docs.discord.com/developers/resources/guild#guild-object-explicit-content-filter-level

const (
	DISABLED_CONTENT_FILTER ExplicitContentFilter = iota
	MEMBERS_WITHOUT_ROLES_CONTENT_FILTER
	ALL_MEMBERS_CONTENT_FILTER
)

type File added in v1.3.0

type File struct {
	Name   string // File's display name
	Reader io.Reader
}

Represents file you can attach to message on Discord.

type FileComponent added in v1.3.0

type FileComponent struct {
	Type    ComponentType     `json:"type"` // Always = FILE_COMPONENT_TYPE (13)
	ID      uint32            `json:"id,omitempty"`
	File    UnfurledMediaItem `json:"file"` // This unfurled media item is unique in that it only supports attachment references using the attachment://<filename> syntax.
	Spoiler bool              `json:"spoiler"`

	Name string `json:"name,omitempty"` // This field is ignored and provided by the API as part of the response.
	Size uint32 `json:"size,omitempty"` // The size of the file in bytes. This field is ignored and provided by the API as part of the response.
}

https://docs.discord.com/developers/components/reference#file-file-structure

type FileUploadComponent added in v1.6.0

type FileUploadComponent struct {
	Type      ComponentType `json:"type"`         // Always = FILE_UPLOAD_COMPONENT_TYPE (19)
	ID        uint32        `json:"id,omitempty"` // Optional identifier for component
	CustomID  string        `json:"custom_id,omitempty"`
	MinValues uint8         `json:"min_values,omitempty"`
	MaxValues uint8         `json:"max_values,omitempty"`
	Required  bool          `json:"required"`
}

File Upload is an interactive component that allows users to upload files in modals. File Uploads can be configured to have a minimum and maximum number of files between 0 and 10, along with required for if the upload is required to submit the modal. The max file size a user can upload is based on the user’s upload limit in that channel.

File Uploads are available on modals. They must be placed inside a Label Component(s).

https://docs.discord.com/developers/components/reference#file-upload

type GatewayBot added in v1.4.0

type GatewayBot struct {
	URL               string            `json:"url"`
	ShardCount        uint16            `json:"shards"`
	SessionStartLimit SessionStartLimit `json:"session_start_limit"`
}

https://docs.discord.com/developers/events/gateway#get-gateway-bot

type GatewayClient added in v1.4.0

type GatewayClient struct {
	*BaseClient
	Gateway *ShardManager
	// contains filtered or unexported fields
}

func NewGatewayClient added in v1.4.0

func NewGatewayClient(opt GatewayClientOptions) *GatewayClient

type GatewayClientOptions added in v1.4.0

type GatewayClientOptions struct {
	BaseClientOptions
	Trace              bool // Whether to enable detailed logging for shard manager and basic client actions.
	CustomEventHandler func(shardID uint16, packet EventPacket)
}

type Guild added in v1.3.5

type Guild struct {
	ID                          Snowflake                `json:"id"`
	Name                        string                   `json:"name"`
	IconHash                    string                   `json:"icon,omitempty"`             // Hash code used to access guild's icon. Call Guild.IconURL to get direct url.
	SplashHash                  string                   `json:"splash,omitempty"`           // Hash code used to access guild's splash background. Call Guild.SplashURL to get direct url.
	DiscoverySplashHash         string                   `json:"discovery_splash,omitempty"` // Hash code used to access guild's special discovery splash background (only available for "DISCOVERABLE" guilds). Call Guild.DiscoverySplashURL to get direct url.
	OwnerID                     Snowflake                `json:"owner_id"`
	AFKChannelID                Snowflake                `json:"afk_channel_id,omitempty"`
	AFKChannelTimeout           uint32                   `json:"afk_timeout"`                 // AFK timeout value in seconds.
	WidgetEnabled               bool                     `json:"widget_enabled"`              // Whether server uses widget.
	WidgetChannelID             Snowflake                `json:"widget_channel_id,omitempty"` // The channel ID that the widget will generate an invite to, or null if set to no invite.
	DefaultMessageNotifications MessageNotificationLevel `json:"default_message_notifications"`
	ExplicitContentFilter       ExplicitContentFilter    `json:"explicit_content_filter"`
	Roles                       []Role                   `json:"roles,omitzero"`
	Emojis                      []Emoji                  `json:"emojis,omitzero"`
	Features                    []string                 `json:"features,omitzero"` // // https://docs.discord.com/developers/resources/guild#guild-object-guild-features
	MFALevel                    MFALevel                 `json:"mfa_level"`
	ApplicationID               Snowflake                `json:"application_id,omitempty"` // Application id of the guild creator if it is bot-created (never seen it in use).
	SystemChannelID             Snowflake                `json:"system_channel_id,omitempty"`
	SystemChannelFlags          SystemChannelFlags       `json:"system_channel_flags"`
	RulesChannelID              Snowflake                `json:"rules_channel_id,omitempty"`
	MaxPresences                uint32                   `json:"max_presences,omitempty"` // The maximum number of presences for the guild (null is always returned, apart from the largest of guilds).
	MaxMembers                  uint32                   `json:"max_members,omitempty"`
	VanityURL                   string                   `json:"vanity_url_code,omitempty"`
	Description                 string                   `json:"description,omitempty"`
	BannerHash                  string                   `json:"banner,omitempty"` // Hash code used to access guild's icon. Call Guild.BannerURL to get direct url.
	PremiumTier                 PremiumTier              `json:"premium_tier"`
	PremiumSubscriptionCount    uint32                   `json:"premium_subscription_count,omitempty"` // The number of boosts this guild currently has.
	PrefferedLocale             string                   `json:"preferred_locale,omitempty"`

	ApproximateMemberCount    uint32 `json:"approximate_member_count,omitempty"`
	ApproximatePresenceCount  uint32 `json:"approximate_presence_count,omitempty"`
	PremiumProgressBarEnabled bool   `json:"premium_progress_bar_enabled"`
}

https://docs.discord.com/developers/resources/guild#guild-object-guild-structure

func (*Guild) BannerURL added in v1.3.5

func (guild *Guild) BannerURL() string

Returns a direct url to guild banner. It'll return empty string if there's no custom banner.

func (*Guild) DiscoverySplashURL added in v1.3.5

func (guild *Guild) DiscoverySplashURL() string

Returns a direct url to guild discovery splash background. It'll return empty string if there's no discovery splash bg.

func (*Guild) IconURL added in v1.3.5

func (guild *Guild) IconURL() string

Returns a direct url to guild icon. It'll return empty string if there's no custom icon.

func (*Guild) SplashURL added in v1.3.5

func (guild *Guild) SplashURL() string

Returns a direct url to guild splash background. It'll return empty string if there's no custom splash bg.

type HTTPClient added in v1.4.0

type HTTPClient struct {
	*BaseClient
	PublicKey ed25519.PublicKey
}

func NewHTTPClient added in v1.4.0

func NewHTTPClient(opt HTTPClientOptions) *HTTPClient

func (*HTTPClient) DiscordRequestHandler added in v1.4.0

func (client *HTTPClient) DiscordRequestHandler(w http.ResponseWriter, r *http.Request)

This handler already runs in dedicated goroutine (from std http server behavior). Due to default HTTP server behavior, this goroutine cannot block for more than 3s, to achieve that we use client interaction responder trick.

type HTTPClientOptions added in v1.4.0

type HTTPClientOptions struct {
	BaseClientOptions
	PublicKey string
	Trace     bool // Whether to enable basic logging for the client actions.
}

type HeartbeatEvent added in v1.4.0

type HeartbeatEvent struct {
	Opcode   Opcode `json:"op"`
	Sequence uint32 `json:"d"`
}

https://docs.discord.com/developers/events/gateway-events#heartbeat

type HelloEventData added in v1.4.0

type HelloEventData struct {
	HeartbeatInterval uint32 `json:"heartbeat_interval"`
}

https://docs.discord.com/developers/events/gateway-events#hello

type IdentifyEvent added in v1.4.0

type IdentifyEvent struct {
	Opcode Opcode              `json:"op"`
	Data   IdentifyPayloadData `json:"d"`
}

https://docs.discord.com/developers/events/gateway-events#identify

type IdentifyPayloadData added in v1.4.0

type IdentifyPayloadData struct {
	Token          string                        `json:"token"`
	Intents        uint32                        `json:"intents"`
	ShardOrder     [2]uint16                     `json:"shard"`           // [currentID, maxCount]
	LargeThreshold uint8                         `json:"large_threshold"` // 50 - 250
	Properties     IdentifyPayloadDataProperties `json:"properties"`
}

https://docs.discord.com/developers/events/gateway-events#identify-identify-structure

type IdentifyPayloadDataProperties added in v1.4.0

type IdentifyPayloadDataProperties struct {
	OS      string `json:"os"`
	Browser string `json:"browser"`
	Device  string `json:"device"`
}

https://docs.discord.com/developers/events/gateway-events#identify-identify-connection-properties

type Interaction added in v1.3.0

type Interaction struct {
	ID            Snowflake       `json:"id"`
	ApplicationID Snowflake       `json:"application_id"`
	Type          InteractionType `json:"type"`
	Data          json.RawMessage `json:"data"`

	GuildID Snowflake `json:"guild_id,omitempty"`

	ChannelID Snowflake `json:"channel_id,omitempty"`
	Member    *Member   `json:"member,omitempty"`
	User      *User     `json:"user,omitempty"`
	Token     string    `json:"token"` // Temporary token used for responding to the interaction. It's not the same as bot token.

	PermissionFlags PermissionFlags `json:"app_permissions,string"` // Bitwise set of permissions the app/bot has within the channel the interaction was sent from (guild text channel or DM channel).
	Locale          Language        `json:"locale,omitempty"`       // Selected language of the invoking user.
	GuildLocale     string          `json:"guild_locale,omitempty"` // Guild's preferred locale, available if invoked in a guild.
	Entitlements    []Entitlement   `json:"entitlements,omitzero"`  // For monetized apps, any entitlements for the invoking user, representing access to premium SKUs.

	BaseClient    *BaseClient    `json:"-"` // Always provided.
	HTTPClient    *HTTPClient    `json:"-"` // Only provided if using HTTP Client.
	GatewayClient *GatewayClient `json:"-"` // Only provided if using Gateway Client.
	ShardID       uint16         `json:"-"` // Only provided if using Gateway Client. Shard ID = 0 is also a valid ID.
	// contains filtered or unexported fields
}

Represents general interaction. Use Command/Component/Modal interaction to read Data field.

https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-object-interaction-structure

func (*Interaction) BaseUser added in v1.4.2

func (itx *Interaction) BaseUser() *User

Returns user data either from member or from user (depending if interaction was used in a server).

func (*Interaction) Responded added in v1.5.0

func (itx *Interaction) Responded() bool

Returns whether this interaction already was responded to.

type InteractionContextType added in v1.2.3

type InteractionContextType uint16 // use uint16 instead uint8 to avoid Go's json marshal logic that thinks of it as symbols.

https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-object-interaction-context-types

const (
	GUILD_CONTEXT_TYPE InteractionContextType = iota
	BOT_DM_CONTEXT_TYPE
	PRIVATE_CHANNEL_CONTEXT_TYPE
)

type InteractionDataResolved

type InteractionDataResolved struct {
	Users       map[Snowflake]User           `json:"users,omitzero"`
	Members     map[Snowflake]Member         `json:"members,omitzero"`
	Roles       map[Snowflake]Role           `json:"roles,omitzero"`
	Channels    map[Snowflake]PartialChannel `json:"channels,omitzero"`
	Messages    map[Snowflake]Message        `json:"messages,omitzero"`
	Attachments map[Snowflake]Attachment     `json:"attachments,omitzero"`
}

https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-object-resolved-data-structure

type InteractionType

type InteractionType uint8

https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-object-interaction-type

const (
	PING_INTERACTION_TYPE InteractionType = iota + 1
	APPLICATION_COMMAND_INTERACTION_TYPE
	MESSAGE_COMPONENT_INTERACTION_TYPE
	APPLICATION_COMMAND_AUTO_COMPLETE_INTERACTION_TYPE
	MODAL_SUBMIT_INTERACTION_TYPE
)

type InteractionTypeExtractor

type InteractionTypeExtractor struct {
	Type InteractionType `json:"type"`
}

Used only for partial JSON parsing.

type InteractiveComponent added in v1.3.0

type InteractiveComponent interface {
	AnyComponent
	// contains filtered or unexported methods
}

InteractiveComponent is a component that can trigger interactions, like buttons or select menus. These can be placed inside Action Rows or used as accessories in sections. Use when you need a component that triggers a callback or response.

type LabelChildComponent added in v1.3.2

type LabelChildComponent interface {
	AnyComponent
	// contains filtered or unexported methods
}

LabelChildComponent represents components that can be used as the child of a LabelComponent. Only one child component is allowed per label.

Currently valid types: TextInputComponent, StringSelectComponent, SelectComponent (user/role/mentionable/channel selects), FileUploadComponent, RadioGroupComponent, CheckboxGroupComponent and CheckboxComponent.

https://docs.discord.com/developers/components/reference#label-label-child-components

type LabelComponent added in v1.3.2

type LabelComponent struct {
	Type        ComponentType       `json:"type"`                  // Always = LABEL_COMPONENT_TYPE (18)
	ID          uint32              `json:"id,omitempty"`          // Optional identifier for component
	Label       string              `json:"label"`                 // The header text to show on the label; max 45 characters.
	Description string              `json:"description,omitempty"` // An additional description for the label; max 100 characters.
	Component   LabelChildComponent `json:"component"`             // The component nested within the label.
}

A LabelComponent wraps a child component with text and an optional description.

They can only be used inside modals.

https://docs.discord.com/developers/components/reference#label

func (*LabelComponent) UnmarshalJSON added in v1.3.2

func (c *LabelComponent) UnmarshalJSON(data []byte) error

type Language

type Language string

https://docs.discord.com/developers/reference#locales

const (
	DANISH_LANGUAGE         Language = "da"
	GERMAN_LANGUAGE         Language = "de"
	ENGLISH_UK_LANGUAGE     Language = "en-GB"
	ENGLISH_US_LANGUAGE     Language = "en-US"
	SPANISH_LANGUAGE        Language = "es-ES"
	FRENCH_LANGUAGE         Language = "fr"
	CROATIAN_LANGUAGE       Language = "hr"
	ITALIAN_LANGUAGE        Language = "it"
	LITHUANIAN_LANGUAGE     Language = "lt"
	HUNGARIAN_LANGUAGE      Language = "hu"
	DUTCH_LANGUAGE          Language = "nl"
	NORWEGIAN_LANGUAGE      Language = "no"
	POLISH_LANGUAGE         Language = "pl"
	PORTUGUESE_BR_LANGUAGE  Language = "pt-BR"
	ROMANIAN_LANGUAGE       Language = "ro"
	FINNISH_LANGUAGE        Language = "fi"
	SWEDISH_LANGUAGE        Language = "sv-SE"
	VIETNAMESE_LANGUAGE     Language = "vi"
	TURKISH_LANGUAGE        Language = "tr"
	CHECH_LANGUAGE          Language = "cs"
	GREEK_LANGUAGE          Language = "el"
	BULGARIAN_LANGUAGE      Language = "bg"
	RUSSIAN_LANGUAGE        Language = "ru"
	UKRAINIAN_LANGUAGE      Language = "uk"
	HINDI_LANGUAGE          Language = "hi"
	THAI_LANGUAGE           Language = "th"
	CHINESE_CHINA_LANGUAGE  Language = "zh-CN"
	JAPANESE_LANGUAGE       Language = "ja"
	CHINESE_TAIWAN_LANGUAGE Language = "zh-TW"
	KOREAN_LANGUAGE         Language = "ko"
)

type LayoutComponent added in v1.3.0

type LayoutComponent interface {
	AnyComponent
	// contains filtered or unexported methods
}

LayoutComponent represents message layout containers like Action Rows, Sections, Separators & Containers.

These are used to control the final look of your custom message/modal.

type MFALevel added in v1.3.5

type MFALevel uint8

https://docs.discord.com/developers/resources/guild#guild-object-mfa-level

const (
	NONE_MFA_LEVEL MFALevel = iota
	ELEVATED_MFA_LEVEL
)

type MediaGalleryComponent added in v1.3.0

type MediaGalleryComponent struct {
	Type  ComponentType      `json:"type"` // Always = MEDIA_GALLERY_COMPONENT_TYPE (12)
	ID    uint32             `json:"id,omitempty"`
	Items []MediaGalleryItem `json:"items,omitzero"` // 1 to 10 media gallery items
}

https://docs.discord.com/developers/components/reference#media-gallery-media-gallery-structure

type MediaGalleryItem added in v1.3.0

type MediaGalleryItem struct {
	Media       UnfurledMediaItem `json:"media"`
	Description string            `json:"description,omitempty"` // Alt text for the media, max 1024 characters
	Spoiler     bool              `json:"spoiler"`
}

https://docs.discord.com/developers/components/reference#media-gallery-media-gallery-item-structure

type Member

type Member struct {
	User                       *User             `json:"user,omitempty"`
	Nickname                   string            `json:"nick,omitempty"`
	GuildAvatarHash            string            `json:"avatar,omitempty"` // Hash code used to access member's custom, guild avatar. Call Member.GuildAvatarURL to get direct url.
	GuildBannerHash            string            `json:"banner,omitempty"` // Hash code used to access member's custom, guild banner. Call Member.GuildBannerURL to get direct url.
	RoleIDs                    []Snowflake       `json:"roles"`
	JoinedAt                   *time.Time        `json:"joined_at"`
	PremiumSince               *time.Time        `json:"premium_since,omitempty"`
	Deaf                       bool              `json:"deaf"`
	Mute                       bool              `json:"mute"`
	Flags                      MemberFlags       `json:"flags"`
	Pending                    bool              `json:"pending"`
	PermissionFlags            PermissionFlags   `json:"permissions,string"`
	CommunicationDisabledUntil *time.Time        `json:"communication_disabled_until,omitempty"`
	AvatarDecorationData       *AvatarDecoration `json:"avatar_decoration_data,omitempty"`

	// It's not part of Member API data struct but tempest Client should always attach it for conveniency.
	GuildID Snowflake `json:"-"`
}

https://docs.discord.com/developers/resources/guild#guild-member-object-guild-member-structure

func (*Member) GuildAvatarURL

func (member *Member) GuildAvatarURL() string

Returns a direct url to members's guild specific avatar. It'll return empty string if targeted member don't use custom avatar for that server.

func (*Member) GuildBannerURL added in v1.2.3

func (member *Member) GuildBannerURL() string

Returns a direct url to members's guild specific banner. It'll return empty string if targeted member don't use custom banner for that server.

type MemberFlags added in v1.2.3

type MemberFlags BitSet

https://docs.discord.com/developers/resources/guild#guild-member-object-guild-member-flags

const (
	DID_REJOIN_MEMBER_FLAG MemberFlags = 1 << iota
	COMPLETED_ONBOARDING_MEMBER_FLAG
	BYPASSES_VERIFICATION_MEMBER_FLAG
	STARTED_ONBOARDING_MEMBER_FLAG
	IS_GUEST_MEMBER_FLAG
	STARTED_HOME_ACTIONS_MEMBER_FLAG
	COMPLETED_HOME_ACTIONS_MEMBER_FLAG
	AUTOMOD_QUARANTINED_USERNAME_MEMBER_FLAG

	DM_SETTINGS_UPSELL_ACKNOWLEDGED_MEMBER_FLAG
)

type Message

type Message struct {
	ID                  Snowflake                   `json:"id"`
	ChannelID           Snowflake                   `json:"channel_id"`
	Author              *User                       `json:"author,omitempty"`  // The author of this message.
	Content             string                      `json:"content,omitempty"` // The message's content.
	Timestamp           *time.Time                  `json:"timestamp"`
	EditedTimestamp     *time.Time                  `json:"edited_timestamp,omitempty"`
	TTS                 bool                        `json:"tts"`              // Whether this was a TTS message.
	MentionEveryone     bool                        `json:"mention_everyone"` // Whether this message mentions everyone.
	Mentions            []User                      `json:"mentions"`         // All users specifically mentioned in the message.
	MentionRoles        []Snowflake                 `json:"mention_roles"`
	MentionChannels     []ChannelMention            `json:"mention_channels,omitzero"`
	Attachments         []Attachment                `json:"attachments"`
	Embeds              []Embed                     `json:"embeds"`
	Reactions           []Reaction                  `json:"reactions,omitzero"`
	Pinned              bool                        `json:"pinned"`
	WebhookID           Snowflake                   `json:"webhook_id,omitempty"`
	Type                BitSet                      `json:"type,omitempty"` // https://docs.discord.com/developers/resources/channel#message-object-message-types
	ApplicationID       Snowflake                   `json:"application_id,omitempty"`
	MessageReference    *MessageReference           `json:"message_reference,omitempty"`
	Flags               MessageFlags                `json:"flags,omitempty"`
	ReferencedMessage   *Message                    `json:"referenced_message,omitempty"`
	InteractionMetadata *MessageInteractionMetadata `json:"interaction_metadata,omitempty"`
	Components          []MessageComponent          `json:"components,omitzero"` // All components included in the message.
	StickerItems        []StickerItem               `json:"sticker_items,omitzero"`
}

https://docs.discord.com/developers/resources/message#message-object-message-structure

func (*Message) UnmarshalJSON added in v1.3.0

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

type MessageComponent added in v1.5.0

type MessageComponent interface {
	AnyComponent
	// contains filtered or unexported methods
}

MessageComponent represents components that can be used inside the top level of messages, such as ActionRowComponent and [SectionComponent]s.

A list of all valid types can be found on Discord's website, though this interface intentionally excludes certain components that cannot appear by themselves (such as [SelectComponent]s).

type MessageFlags added in v1.2.3

type MessageFlags BitSet

https://docs.discord.com/developers/resources/message#message-object-message-flags

const (
	CROSSPOSTED_MESSAGE_FLAG MessageFlags = 1 << iota
	IS_CROSSPOST_MESSAGE_FLAG
	SUPPRESS_EMBEDS_MESSAGE_FLAG
	SOURCE_MESSAGE_DELETED_MESSAGE_FLAG
	URGENT_MESSAGE_FLAG
	HAS_THREAD_MESSAGE_FLAG
	EPHEMERAL_MESSAGE_FLAG
	LOADING_MESSAGE_FLAG
	FAILED_TO_MENTION_SOME_ROLES_IN_THREAD_MESSAGE_FLAG

	SUPPRESS_NOTIFICATIONS_MESSAGE_FLAG
	IS_VOICE_MESSAGE_MESSAGE_FLAG
	HAS_SNAPSHOT_MESSAGE_FLAG
	IS_COMPONENTS_V2_MESSAGE_FLAG // When used, regular content, embeds, poll & stickers fields will be ignored.
)

type MessageInteractionMetadata added in v1.4.2

type MessageInteractionMetadata struct {
	ID              Snowflake       `json:"id"`
	Type            InteractionType `json:"type"`
	User            User            `json:"user"`
	TargetUser      *User           `json:"target_user,omitempty"`
	TargetMessageID Snowflake       `json:"target_message_id,omitempty"`
}

https://docs.discord.com/developers/resources/message#message-interaction-metadata-object-application-command-interaction-metadata-structure

type MessageNotificationLevel added in v1.3.5

type MessageNotificationLevel uint8

https://docs.discord.com/developers/resources/guild#guild-object-default-message-notification-level

const (
	ALL_MESSAGES_NOTIFICATION_LEVEL MessageNotificationLevel = iota
	ONLY_MENTIONS_NOTIFICATION_LEVEL
)

type MessageReference

type MessageReference struct {
	Type            MessageReferenceType `json:"type,omitempty"`
	MessageID       Snowflake            `json:"message_id,omitempty"`
	ChannelID       Snowflake            `json:"channel_id,omitempty"`
	GuildID         Snowflake            `json:"guild_id,omitempty"`
	FailIfNotExists bool                 `json:"fail_if_not_exists"`
}

https://docs.discord.com/developers/resources/message#message-reference-structure

type MessageReferenceType added in v1.6.0

type MessageReferenceType uint8

https://docs.discord.com/developers/resources/message#message-reference-types

const (
	DEFAULT_MESSAGE_REFERENCE_TYPE MessageReferenceType = iota // A standard reference used by replies. Coupled with: referenced_message
	FORWARD_MESSAGE_REFERENCE_TYPE                             // Reference used to point to a message at a point in time. Coupled with: message_snapshot
)

type ModalComponent added in v1.5.0

type ModalComponent interface {
	AnyComponent
	// contains filtered or unexported methods
}

ModalComponent represents components that can be used inside the top level of modals, such as [TextDisplayComponent]s and [LabelComponent]s.

A list of all valid types can be found on Discord's website, though this interface intentionally excludes certain components that cannot appear by themselves (such as [SelectComponent]s).

type ModalInteraction

type ModalInteraction struct {
	*Interaction
	Data ModalInteractionData `json:"data"`
}

https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-object

func (*ModalInteraction) Acknowledge

func (itx *ModalInteraction) Acknowledge() error

Sends to discord info that this component was handled successfully without sending anything more.

func (*ModalInteraction) AcknowledgeWithLinearMessage

func (itx *ModalInteraction) AcknowledgeWithLinearMessage(content string, ephemeral bool) error

func (*ModalInteraction) AcknowledgeWithMessage

func (itx *ModalInteraction) AcknowledgeWithMessage(response ResponseMessageData, ephemeral bool) error

func (*ModalInteraction) AcknowledgeWithModal

func (itx *ModalInteraction) AcknowledgeWithModal(modal ResponseModalData) error

func (*ModalInteraction) Defer added in v1.3.2

func (itx *ModalInteraction) Defer(ephemeral bool) error

Used to let user/member know that the bot is processing the modal submission, which will close the modal dialog. Set ephemeral = true to make notification visible only to the submitter.

func (*ModalInteraction) GetInputValue

func (itx *ModalInteraction) GetInputValue(customID string) string

GetInputValue retrieves the contents of the first TextInputComponent inside the modal (at any depth) with the given customID.

If no such component exists, an empty string is returned instead.

func (*ModalInteraction) SendFollowUp added in v1.3.2

func (itx *ModalInteraction) SendFollowUp(content ResponseMessageData, ephemeral bool) (Message, error)

Used after defering a modal submission to send a message to the user/member. Set ephemeral = true to make message visible only to the submitter.

func (*ModalInteraction) SendLinearFollowUp added in v1.3.2

func (itx *ModalInteraction) SendLinearFollowUp(content string, ephemeral bool) (Message, error)

Used after defering a modal submission to send a message to the user/member. Set ephemeral = true to make message visible only to the submitter.

type ModalInteractionData

type ModalInteractionData struct {
	CustomID   string           `json:"custom_id"`
	Components []ModalComponent `json:"components,omitzero"` // The components that were sent inside the modal, having been filled with user input.
}

ModalInteractionData represents the data received from a user submitting a modal.

https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-object-modal-submit-data-structure

func (*ModalInteractionData) UnmarshalJSON added in v1.3.0

func (msd *ModalInteractionData) UnmarshalJSON(data []byte) error

type NitroType

type NitroType uint8

https://docs.discord.com/developers/resources/user#user-object-premium-types

const (
	NO_NITRO_TYPE NitroType = iota
	CLASSIC_NITRO_TYPE
	FULL_NITRO_TYPE
	BASIC_NITRO_TYPE
)

type Opcode added in v1.4.0

type Opcode uint8

https://docs.discord.com/developers/topics/opcodes-and-status-codes#gateway-gateway-opcodes

const (
	DISPATCH_OPCODE Opcode = iota
	HEARTBEAT_OPCODE
	IDENTIFY_OPCODE
	PRESENCE_UPDATE_OPCODE
	VOICE_STATUS_UPDATE_OPCODE

	RESUME_OPCODE
	RECONNECT_OPCODE
	REQUEST_GUILD_MEMBERS_OPCODE
	INVALID_SESSION_OPCODE
	HELLO_OPCODE
	HEARTBEAT_ACK_OPCODE
	REQUEST_SOUNDBOARD_SOUNDS_OPCODE Opcode = 31
)

type OptionType

type OptionType uint8

https://docs.discord.com/developers/interactions/application-commands#application-command-object-application-command-option-type

const (
	SUB_COMMAND_OPTION_TYPE       OptionType = iota + 1
	SUB_COMMAND_GROUP_OPTION_TYPE            // NOT OFFICIALLY SUPPORTED BY LIBRARY
	STRING_OPTION_TYPE
	INTEGER_OPTION_TYPE
	BOOLEAN_OPTION_TYPE
	USER_OPTION_TYPE
	CHANNEL_OPTION_TYPE
	ROLE_OPTION_TYPE
	MENTIONABLE_OPTION_TYPE
	NUMBER_OPTION_TYPE
	ATTACHMENT_OPTION_TYPE
)

type PartialChannel

type PartialChannel struct {
	ID              Snowflake       `json:"id"`
	Name            string          `json:"name"`
	PermissionFlags PermissionFlags `json:"permissions,string"`
	Type            ChannelType     `json:"type"`
}

https://docs.discord.com/developers/resources/channel#channel-object

type PermissionFlags added in v1.2.3

type PermissionFlags BitSet

https://docs.discord.com/developers/topics/permissions#permissions

const (
	CREATE_INSTANT_INVITE_PERMISSION_FLAG PermissionFlags = 1 << iota
	KICK_MEMBERS_PERMISSION_FLAG
	BAN_MEMBERS_PERMISSION_FLAG
	ADMINISTRATOR_PERMISSION_FLAG
	MANAGE_CHANNELS_PERMISSION_FLAG
	MANAGE_GUILD_PERMISSION_FLAG
	ADD_REACTIONS_PERMISSION_FLAG
	VIEW_AUDIT_LOG_PERMISSION_FLAG
	PRIORITY_SPEAKER_PERMISSION_FLAG
	STREAM_PERMISSION_FLAG
	VIEW_CHANNEL_PERMISSION_FLAG
	SEND_MESSAGES_PERMISSION_FLAG
	SEND_TTS_MESSAGES_PERMISSION_FLAG
	MANAGE_MESSAGES_PERMISSION_FLAG
	EMBED_LINKS_PERMISSION_FLAG
	ATTACH_FILES_PERMISSION_FLAG
	READ_MESSAGE_HISTORY_PERMISSION_FLAG
	MENTION_EVERYONE_PERMISSION_FLAG
	USE_EXTERNAL_EMOJIS_PERMISSION_FLAG
	VIEW_GUILD_INSIGHTS_PERMISSION_FLAG
	CONNECT_PERMISSION_FLAG
	SPEAK_PERMISSION_FLAG
	MUTE_MEMBERS_PERMISSION_FLAG
	DEAFEN_MEMBERS_PERMISSION_FLAG
	MOVE_MEMBERS_PERMISSION_FLAG
	USE_VAD_PERMISSION_FLAG
	CHANGE_NICKNAME_PERMISSION_FLAG
	MANAGE_NICKNAMES_PERMISSION_FLAG
	MANAGE_ROLES_PERMISSION_FLAG
	MANAGE_WEBHOOKS_PERMISSION_FLAG
	MANAGE_GUILD_EXPRESSIONS_PERMISSION_FLAG
	USE_APPLICATION_COMMANDS_PERMISSION_FLAG
	REQUEST_TO_SPEAK_PERMISSION_FLAG
	MANAGE_EVENTS_PERMISSION_FLAG
	MANAGE_THREADS_PERMISSION_FLAG
	CREATE_PUBLIC_THREADS_PERMISSION_FLAG
	CREATE_PRIVATE_THREADS_PERMISSION_FLAG
	USE_EXTERNAL_STICKERS_PERMISSION_FLAG
	SEND_MESSAGES_IN_THREADS_PERMISSION_FLAG
	USE_EMBEDDED_ACTIVITIES_PERMISSION_FLAG
	MODERATE_MEMBERS_PERMISSION_FLAG
	VIEW_CREATOR_MONETIZATION_ANALYTICS_PERMISSION_FLAG
	USE_SOUNDBOARD_PERMISSION_FLAG
	CREATE_GUILD_EXPRESSIONS_PERMISSION_FLAG
	CREATE_EVENTS_PERMISSION_FLAG
	USE_EXTERNAL_SOUNDS_PERMISSION_FLAG
	SEND_VOICE_MESSAGES_PERMISSION_FLAG

	SEND_POLLS_PERMISSION_FLAG
	USE_EXTERNAL_APPS_PERMISSION_FLAG

	ALL_TEXT_PERMISSION_FLAGS = VIEW_CHANNEL_PERMISSION_FLAG |
		SEND_MESSAGES_PERMISSION_FLAG |
		SEND_TTS_MESSAGES_PERMISSION_FLAG |
		MANAGE_MESSAGES_PERMISSION_FLAG |
		EMBED_LINKS_PERMISSION_FLAG |
		ATTACH_FILES_PERMISSION_FLAG |
		READ_MESSAGE_HISTORY_PERMISSION_FLAG |
		MENTION_EVERYONE_PERMISSION_FLAG |
		SEND_VOICE_MESSAGES_PERMISSION_FLAG |
		SEND_POLLS_PERMISSION_FLAG |
		USE_EXTERNAL_APPS_PERMISSION_FLAG

	ALL_THREAD_PERMISSION_FLAGS = MANAGE_THREADS_PERMISSION_FLAG |
		CREATE_PUBLIC_THREADS_PERMISSION_FLAG |
		CREATE_PRIVATE_THREADS_PERMISSION_FLAG |
		SEND_MESSAGES_IN_THREADS_PERMISSION_FLAG

	ALL_VOICE_PERMISSION_FLAGS = VIEW_CHANNEL_PERMISSION_FLAG |
		CONNECT_PERMISSION_FLAG |
		SPEAK_PERMISSION_FLAG |
		STREAM_PERMISSION_FLAG |
		MUTE_MEMBERS_PERMISSION_FLAG |
		DEAFEN_MEMBERS_PERMISSION_FLAG |
		MOVE_MEMBERS_PERMISSION_FLAG |
		USE_VAD_PERMISSION_FLAG |
		PRIORITY_SPEAKER_PERMISSION_FLAG |
		USE_SOUNDBOARD_PERMISSION_FLAG |
		USE_EXTERNAL_SOUNDS_PERMISSION_FLAG |
		REQUEST_TO_SPEAK_PERMISSION_FLAG |
		USE_EMBEDDED_ACTIVITIES_PERMISSION_FLAG |
		CREATE_GUILD_EXPRESSIONS_PERMISSION_FLAG |
		CREATE_EVENTS_PERMISSION_FLAG |
		MANAGE_EVENTS_PERMISSION_FLAG

	ALL_CHANNEL_PERMISSION_FLAGS = ALL_TEXT_PERMISSION_FLAGS |
		ALL_THREAD_PERMISSION_FLAGS |
		ALL_VOICE_PERMISSION_FLAGS |
		CREATE_INSTANT_INVITE_PERMISSION_FLAG |
		MANAGE_CHANNELS_PERMISSION_FLAG |
		ADD_REACTIONS_PERMISSION_FLAG |
		USE_EXTERNAL_EMOJIS_PERMISSION_FLAG |
		USE_APPLICATION_COMMANDS_PERMISSION_FLAG |
		USE_EXTERNAL_STICKERS_PERMISSION_FLAG

	ALL_PERMISSION_FLAGS = ALL_CHANNEL_PERMISSION_FLAGS |
		KICK_MEMBERS_PERMISSION_FLAG |
		BAN_MEMBERS_PERMISSION_FLAG |
		MANAGE_GUILD_PERMISSION_FLAG |
		ADMINISTRATOR_PERMISSION_FLAG |
		MANAGE_WEBHOOKS_PERMISSION_FLAG |
		MANAGE_GUILD_EXPRESSIONS_PERMISSION_FLAG |
		VIEW_CREATOR_MONETIZATION_ANALYTICS_PERMISSION_FLAG |
		VIEW_GUILD_INSIGHTS_PERMISSION_FLAG |
		VIEW_AUDIT_LOG_PERMISSION_FLAG |
		MANAGE_ROLES_PERMISSION_FLAG |
		CHANGE_NICKNAME_PERMISSION_FLAG |
		MANAGE_NICKNAMES_PERMISSION_FLAG |
		MODERATE_MEMBERS_PERMISSION_FLAG
)

type Poll added in v1.2.3

type Poll struct {
	Question    PollMedia      `json:"question"`
	Answers     []PollAnswer   `json:"answers,omitzero"`
	Duration    uint16         `json:"duration,omitempty"` // Number of hours the poll should be open for, up to 32 days (defaults to 24)
	Multiselect bool           `json:"allow_multiselect"`
	LayoutType  PoolLayoutType `json:"layout_type"`
}

https://docs.discord.com/developers/resources/poll#poll-create-request-object

type PollAnswer added in v1.2.3

type PollAnswer struct {
	AnswerID  uint32    `json:"answer_id,omitempty"`
	PollMedia PollMedia `json:"poll_media"`
}

https://docs.discord.com/developers/resources/poll#poll-answer-object-poll-answer-object-structure

type PollMedia added in v1.2.3

type PollMedia struct {
	Text  string `json:"text,omitempty"`
	Emoji *Emoji `json:"emoji,omitempty"`
}

https://docs.discord.com/developers/resources/poll#poll-media-object-poll-media-object-structure

type PoolAnswerCounts added in v1.2.3

type PoolAnswerCounts struct {
	ID      uint32 `json:"id"` // The answer_id
	Count   uint32 `json:"count"`
	MeVoted bool   `json:"me_voted"`
}

https://docs.discord.com/developers/resources/poll#poll-results-object-poll-answer-count-object-structure

type PoolLayoutType added in v1.2.3

type PoolLayoutType uint8

https://docs.discord.com/developers/resources/poll#layout-type

const (
	DEFAULT_POOL_LAYOUT_TYPE PoolLayoutType = iota + 1
)

type PoolResult added in v1.2.3

type PoolResult struct {
	Finalized    bool               `json:"is_finalized"`
	AnswerCounts []PoolAnswerCounts `json:"answer_counts"`
}

https://docs.discord.com/developers/resources/poll#poll-results-object-poll-results-object-structure

type PremiumTier added in v1.3.5

type PremiumTier uint8

https://docs.discord.com/developers/resources/guild#guild-object-premium-tier

const (
	NONE_PREMIUM_TIER PremiumTier = iota
	BOOST_1_PREMIUM_TIER
	BOOST_2_PREMIUM_TIER
	BOOST_3_PREMIUM_TIER
)

type RadioGroupComponent added in v1.6.0

type RadioGroupComponent struct {
	Type     ComponentType      `json:"type"`         // Always = RADIO_GROUP_COMPONENT_TYPE (21)
	ID       uint32             `json:"id,omitempty"` // Optional identifier for component
	CustomID string             `json:"custom_id,omitempty"`
	Options  []RadioGroupOption `json:"options,omitzero"` // List of options to show; min 2, max 10
	Required bool               `json:"required"`         // Whether a selection is required to submit the modal (defaults to true)
}

A Radio Group is an interactive component for selecting exactly one option from a defined list. Radio Groups are available in modals and must be placed inside a Label Component(s).

https://docs.discord.com/developers/components/reference#radio-group

type RadioGroupOption added in v1.6.0

type RadioGroupOption struct {
	Value       string `json:"value"`
	Label       string `json:"label"`
	Description string `json:"description,omitempty"`
	Default     bool   `json:"default"` // Whether to render this option as selected by default.
}

https://docs.discord.com/developers/components/reference#radio-group-option-structure

type Reaction

type Reaction struct {
	Count        uint32               `json:"count"`
	CountDetails ReactionCountDetails `json:"count_details"`
	Me           bool                 `json:"me"`
	MeBurst      bool                 `json:"me_burst"`
	Emoji        Emoji                `json:"emoji"`
	BurstColors  []string             `json:"burst_colors"` // HEX colors used for super reaction
}

https://docs.discord.com/developers/resources/message#reaction-object

type ReactionCountDetails added in v1.2.3

type ReactionCountDetails struct {
	Burst  uint32 `json:"burst"`
	Normal uint32 `json:"normal"`
}

https://docs.discord.com/developers/resources/message#reaction-count-details-object

type ReadyEventData added in v1.4.0

type ReadyEventData struct {
	User             User               `json:"user"`
	Version          uint8              `json:"v"` // Version of Discord API version
	SessionID        string             `json:"session_id"`
	ResumeGatewayURL string             `json:"resume_gateway_url"`
	Guilds           []UnavailableGuild `json:"guilds"`
}

https://docs.discord.com/developers/events/gateway-events#ready

type Response added in v1.4.0

type Response struct {
	Type  ResponseType `json:"type"`
	Data  any          `json:"data,omitempty"`
	Files []File       `json:"-"`
}

Unified response type for all interaction replies. Data field holds one of three response data types (message/modal/auto-complete). We're using "any" type because those types are not compatible with each other and will never be used at the same time.

type ResponseAutoCompleteData

type ResponseAutoCompleteData struct {
	Choices []CommandOptionChoice `json:"choices,omitzero"` // The autocomplete choices to show, up to 25 in total.
}

https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-response-object-autocomplete

type ResponseMessageData

type ResponseMessageData struct {
	TTS             bool               `json:"tts"`                        // Whether the message is a TTS message.
	Content         string             `json:"content,omitempty"`          // The message content.
	Embeds          []Embed            `json:"embeds,omitzero"`            // Up to 10 rich content embeds to include.
	AllowedMentions *AllowedMentions   `json:"allowed_mentions,omitempty"` // Data pertaining to the message's allowed mentions.
	Flags           MessageFlags       `json:"flags,omitempty"`            // A bitfield containing message flags. Note that only [SUPPRESS_EMBEDS_MESSAGE_FLAG], [EPHEMERAL_MESSAGE_FLAG], [IS_COMPONENTS_V2_MESSAGE_FLAG], [IS_VOICE_MESSAGE_MESSAGE_FLAG] and [SUPPRESS_NOTIFICATIONS_MESSAGE_FLAG] can be set.
	Components      []MessageComponent `json:"components,omitzero"`        // Any components to send alongside the message.
	Attachments     []Attachment       `json:"attachments,omitzero"`       // Any attachments to send alongside the message.
	Poll            *Poll              `json:"poll,omitempty"`             // An optional poll to include in the message.
}

ResponseMessageData represents the data sent for message responses.

https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-response-object-messages

type ResponseModalData

type ResponseModalData struct {
	CustomID   string           `json:"custom_id"`           // A custom identifier for the modal. Must be non-empty and between 1-100 characters.
	Title      string           `json:"title"`               // The title of the modal. Must be under 45 characters.
	Components []ModalComponent `json:"components,omitzero"` // 1-5 components that will make up the modal's body. Will be returned populated with user-filled data.
}

ResponseModalData represents the data sent for modal responses.

https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-response-object-modal

type ResponseType

type ResponseType uint8

https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-response-object-interaction-callback-type

const (
	PONG_RESPONSE_TYPE ResponseType = iota + 1
	ACKNOWLEDGE_RESPONSE_TYPE
	CHANNEL_MESSAGE_RESPONSE_TYPE
	CHANNEL_MESSAGE_WITH_SOURCE_RESPONSE_TYPE
	DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE_RESPONSE_TYPE
	DEFERRED_UPDATE_MESSAGE_RESPONSE_TYPE // Only valid for component-based interactions.
	UPDATE_MESSAGE_RESPONSE_TYPE          // Only valid for component-based interactions.
	AUTOCOMPLETE_RESPONSE_TYPE
	MODAL_RESPONSE_TYPE // Not available for MODAL_SUBMIT and PING interactions.

	LAUNCH_ACTIVITY_RESPONSE_TYPE // Launch the Activity associated with the app. Only available for apps with Activities enabled.
)

type Rest added in v1.2.3

type Rest struct {
	HTTPClient http.Client
	MaxRetries uint8
	// contains filtered or unexported fields
}

func NewRest added in v1.2.3

func NewRest(token string) *Rest

func (*Rest) Request added in v1.2.3

func (rest *Rest) Request(method, route string, jsonPayload any) ([]byte, error)

func (*Rest) RequestWithFiles added in v1.2.3

func (rest *Rest) RequestWithFiles(method string, route string, jsonPayload any, files []File) ([]byte, error)

type ResumeEvent added in v1.4.0

type ResumeEvent struct {
	Opcode Opcode          `json:"op"`
	Data   ResumeEventData `json:"d"`
}

https://docs.discord.com/developers/events/gateway-events#resume

type ResumeEventData added in v1.4.0

type ResumeEventData struct {
	Token     string `json:"token"`
	SessionID string `json:"session_id"`
	Sequence  uint32 `json:"seq"` // Last sequence number received
}

https://docs.discord.com/developers/events/gateway-events#resume-resume-structure

type Role

type Role struct {
	ID              Snowflake       `json:"id"`
	Name            string          `json:"name"`
	Color           uint32          `json:"color"` // Integer representation of hexadecimal color code. Roles without colors (color == 0) do not count towards the final computed color in the user list.
	Hoist           bool            `json:"hoist"` // Whether this role is pinned in the user listing.
	IconHash        string          `json:"icon,omitempty"`
	UnicodeEmoji    string          `json:"unicode_emoji,omitempty"`
	Position        uint8           `json:"position"`
	PermissionFlags PermissionFlags `json:"permissions,string"`
	Managed         bool            `json:"managed"`     // Whether this role is managed by an integration.
	Mentionable     bool            `json:"mentionable"` // Whether this role is mentionable.
	Tags            RoleTag         `json:"tags"`
	Flags           BitSet          `json:"flags"` // https://docs.discord.com/developers/topics/permissions#role-object-role-flags
}

https://docs.discord.com/developers/topics/permissions#role-object-role-structure

func (*Role) IconURL

func (role *Role) IconURL() string

Returns a direct url to role icon. It'll return empty string if there's no custom icon.

func (*Role) Mention

func (role *Role) Mention() string

type RoleTag

type RoleTag struct {
	BotID                 Snowflake `json:"bot_id,omitempty"`
	IntegrationID         Snowflake `json:"integration_id,omitempty"`          // The id of the integration this role belongs to.
	PremiumSubscriber     bool      `json:"premium_subscriber"`                // Whether this is the guild's Booster role.
	SubscriptionListingID Snowflake `json:"subscription_listing_id,omitempty"` // The id of this role's subscription sku and listing.
	AvailableForPurchase  bool      `json:"available_for_purchase"`
	GuildConnections      bool      `json:"guild_connections"` // Whether this role is a guild's linked role.
}

https://docs.discord.com/developers/topics/permissions#role-object-role-tags-structure

type SectionComponent added in v1.3.0

type SectionComponent struct {
	Type       ComponentType          `json:"type"` // Always = SECTION_COMPONENT_TYPE (9)
	ID         uint32                 `json:"id,omitempty"`
	Components []TextDisplayComponent `json:"components,omitzero"` // 1-3 text display components representing the section's text content.
	Accessory  AccessoryComponent     `json:"accessory,omitempty"` // A component contextually associated to the section's content.
}

A SectionComponent associates text content with a given AccessoryComponent.

They can only be used inside messages.

https://docs.discord.com/developers/components/reference#section-section-structure

func (*SectionComponent) UnmarshalJSON added in v1.3.0

func (c *SectionComponent) UnmarshalJSON(data []byte) error

type SelectComponent added in v1.3.0

type SelectComponent struct {
	Type          ComponentType        `json:"type"` // Either USER_SELECT_COMPONENT_TYPE, ROLE_SELECT_COMPONENT_TYPE, MENTIONABLE_SELECT_COMPONENT_TYPE or CHANNEL_SELECT_COMPONENT_TYPE
	ID            uint32               `json:"id,omitempty"`
	CustomID      string               `json:"custom_id,omitempty"`
	ChannelTypes  []ChannelType        `json:"channel_types,omitzero"`  // List of channel types to include in the channel select component; should be omitted for all other select types
	Placeholder   string               `json:"placeholder,omitempty"`   // Placeholder text if nothing is selected, max: 150 characters
	DefaultValues []DefaultValueOption `json:"default_values,omitzero"` // List of default values for auto-populated select menu components; must have between MinValues and MaxValues entries
	MinValues     uint8                `json:"min_values,omitempty"`    // The minimum number of items that must be chosen; defaults to 1 and must be between 0 and 25
	MaxValues     uint8                `json:"max_values,omitempty"`    // The maximum number of items that can be chosen; defaults to 1 and must be between 0 and 25
	Disabled      bool                 `json:"disabled"`                // Whether the select menu is disabled inside a message; default false. Will result in an error if used inside a modal!
}

A SelectComponent displays a drop-down menu for a user to select either Users, Roles, Mentionables or Channels. It encapsulates the User Select, Role Select, Mentionable Select and Channel Select components from Discord.

They are available in both messages and modals, but must be placed inside an ActionRowComponent or LabelComponent respectively.

type SelectMenuOption

type SelectMenuOption struct {
	Label       string `json:"label"`                 // Text label that appears on the option label, max 80 characters.
	Value       string `json:"value"`                 // Value to return back to app once clicked, max 100 characters.
	Description string `json:"description,omitempty"` // An additional description of the option, max 100 characters.
	Emoji       *Emoji `json:"emoji,omitempty"`       // It may only contain id, name, and animated from regular Emoji struct.
	Default     bool   `json:"default"`               // Whether to render this option as selected by default.
}

A SelectMenuOption represents a single option within a StringSelectComponent.

https://docs.discord.com/developers/components/reference#string-select-select-option-structure

type SeparatorComponent added in v1.3.0

type SeparatorComponent struct {
	Type    ComponentType `json:"type"` // Always = SEPARATOR_COMPONENT_TYPE (14)
	ID      uint32        `json:"id,omitempty"`
	Divider bool          `json:"divider"`           // Whether a visual divider should be displayed in the component (defaults to true).
	Spacing uint8         `json:"spacing,omitempty"` // Size of separator padding—1 for small padding, 2 for large padding (defaults to 1).
}

https://docs.discord.com/developers/components/reference#separator-separator-structure

type SessionStartLimit added in v1.4.0

type SessionStartLimit struct {
	ResetAfter     uint32 `json:"reset_after"`
	Total          uint16 `json:"total"`           // max 1000
	Remaining      uint16 `json:"remaining"`       // max 1000
	MaxConcurrency uint16 `json:"max_concurrency"` // Number of identify requests allowed per 5 seconds.
}

https://docs.discord.com/developers/events/gateway#session-start-limit-object

type Shard added in v1.4.0

type Shard struct {
	ID uint16
	// contains filtered or unexported fields
}

Shard represents a single connection to the Discord Gateway. It handles the full lifecycle of the connection, including identifying, heartbeating, and resuming. It is designed to be managed by a Manager.

func NewShard added in v1.4.0

func NewShard(
	id uint16,
	totalShards uint16,
	token string,
	intents uint32,
	traceLogger *log.Logger,
	eventHandler func(shardID uint16, packet EventPacket),
) *Shard

Creates a new Shard instance - shard by default will handle own session lifecycle (identify, heartbeat, session resume).

All packets shard receives that are not related to connection lifecycle will be pushed to eventHandler function.

Warning: Shards are intended to be used via Manager. If you don't know what you're doing - use manager instead.

func (*Shard) Close added in v1.4.0

func (s *Shard) Close()

func (*Shard) Ping added in v1.4.0

func (s *Shard) Ping() time.Duration

func (*Shard) Send added in v1.4.0

func (s *Shard) Send(jsonPayload any) error

func (*Shard) Start added in v1.4.0

func (s *Shard) Start(ctx context.Context, gatewayURL string)

Start establishes a connection to the Discord Gateway and starts handling events. This is a blocking call that will manage the connection until the context is canceled.

func (*Shard) Status added in v1.4.0

func (s *Shard) Status() ShardState

type ShardManager added in v1.4.0

type ShardManager struct {
	// contains filtered or unexported fields
}

ShardManager is responsible for orchestrating multiple Shard connections to the Discord Gateway. It handles everything that is required for Bot to start receiving packets with event data.

func NewShardManager added in v1.4.0

func NewShardManager(token string, trace bool, eventHandler func(shardID uint16, packet EventPacket), logger *log.Logger) *ShardManager

Creates a new gateway connection manager. Set trace to true to enable detailed logging for the manager & all shards under its control. If tracing is enabled and logger is provided, it'll be used for all internal messages. If none is provided, the default Stdout logger will be used instead.

func (*ShardManager) AllShardDetails added in v1.4.4

func (m *ShardManager) AllShardDetails() ([]ShardState, []time.Duration)

Returns shard status and ping value (calculated based on shard heartbeat) for each started shard.

func (*ShardManager) Broadcast added in v1.4.0

func (m *ShardManager) Broadcast(jsonStruct any)

Sends a payload to all online shards. This is useful for actions that affect the bot's global state, such as presence updates.

func (*ShardManager) Send added in v1.4.0

func (m *ShardManager) Send(shardID uint16, jsonStruct any)

func (*ShardManager) ShardDetails added in v1.4.4

func (m *ShardManager) ShardDetails(shardID uint16) (ShardState, time.Duration, error)

Returns shard status and ping value (calculated based on shard heartbeat).

func (*ShardManager) Start added in v1.4.0

func (m *ShardManager) Start(ctx context.Context, intents uint32, forcedShardCount uint16, readyCallback func()) error

Start connects the manager to Discord. It fetches the gateway configuration, creates the necessary shards, and starts them in parallel. This is a blocking call that waits for all shards to complete their lifecycle.

Note: Normally Manager will ask Discord API for recommended number of shards and use that. You can manually change that by setting forcedShardCount param to value larger than 0. There's also option to provide on ready function callback to detect once all shards are online.

func (*ShardManager) Status added in v1.4.0

func (m *ShardManager) Status() map[uint16]ShardState

func (*ShardManager) Stop added in v1.4.0

func (m *ShardManager) Stop()

Stop gracefully closes all shard connections.

func (*ShardManager) UpdateStatus added in v1.4.0

func (m *ShardManager) UpdateStatus(statusGenerator func(shardID uint16) *UpdatePresenceEvent)

Allows to update status (presence) of the bot. Have generator function return nil to skip updating status for a specific shard.

type ShardState added in v1.4.0

type ShardState uint8
const (
	// Represents any state that cannot be considered ready
	// (offline, dead, zombie connection, just disconnected, etc.).
	OFFLINE_SHARD_STATE ShardState = iota
	CONNECTING_SHARD_STATE
	// State where Shard's socket is connected but still in process of identifying or resuming session.
	AUTHENTICATING_SHARD_STATE
	ONLINE_SHARD_STATE
)

func (ShardState) String added in v1.4.0

func (s ShardState) String() string

type SharedMap added in v1.2.3

type SharedMap[K comparable, V any] struct {
	// contains filtered or unexported fields
}

Map but wrapped with mutex so it's safe to use between goroutines. It also supports few extra, helper methods that are new to std Map.

func NewSharedMap added in v1.2.3

func NewSharedMap[K comparable, V any]() *SharedMap[K, V]

func (*SharedMap[K, V]) Delete added in v1.2.3

func (sm *SharedMap[K, V]) Delete(key K)

func (*SharedMap[K, V]) ExportKeys added in v1.2.3

func (sm *SharedMap[K, V]) ExportKeys() []K

Creates new slice with keys.

func (*SharedMap[K, V]) ExportValues added in v1.2.3

func (sm *SharedMap[K, V]) ExportValues() []V

Creates new slice with values/items.

func (*SharedMap[K, V]) FilterKeys added in v1.3.2

func (sm *SharedMap[K, V]) FilterKeys(fn func(key K, value V) bool, limit int) []K

Same as FilterMap but returns slice of keys that pass the provided test function.

func (*SharedMap[K, V]) FilterMap added in v1.3.2

func (sm *SharedMap[K, V]) FilterMap(fn func(key K, value V) bool, limit int) *SharedMap[K, V]

Creates a copy of a given shared map, filtered down to just the elements from the given array that pass the test implemented by the provided function.

func (*SharedMap[K, V]) FilterValues added in v1.3.2

func (sm *SharedMap[K, V]) FilterValues(fn func(key K, value V) bool, limit int) []V

Same as FilterMap but returns slice of values that pass the provided test function.

func (*SharedMap[K, V]) Get added in v1.2.3

func (sm *SharedMap[K, V]) Get(key K) (V, bool)

func (*SharedMap[K, V]) Has added in v1.2.3

func (sm *SharedMap[K, V]) Has(key K) bool

func (*SharedMap[K, V]) ReadRange added in v1.4.2

func (sm *SharedMap[K, V]) ReadRange(fn func(key K, value V))

Runs provided function on every map entry. Map contents stays locked for entire duration of this function call.

func (*SharedMap[K, V]) Reset added in v1.2.3

func (sm *SharedMap[K, V]) Reset()

func (*SharedMap[K, V]) Set added in v1.2.3

func (sm *SharedMap[K, V]) Set(key K, value V)

func (*SharedMap[K, V]) Size added in v1.2.3

func (sm *SharedMap[K, V]) Size() int

func (*SharedMap[K, V]) Sweep added in v1.2.3

func (sm *SharedMap[K, V]) Sweep(fn func(key K, value V) bool)

Deletes items that satisfy the provided filter function within 1 mutex lock.

type Snowflake

type Snowflake uint64

Represents a Discord's ID snowflake.

func EnvToSnowflake

func EnvToSnowflake(key string) (Snowflake, error)

Shortcut to calling os.Getenv method and casting to Snowflake.

func StringToSnowflake

func StringToSnowflake(s string) (Snowflake, error)

func (Snowflake) CreationTimestamp

func (s Snowflake) CreationTimestamp() time.Time

func (Snowflake) MarshalJSON

func (s Snowflake) MarshalJSON() ([]byte, error)

func (Snowflake) String

func (s Snowflake) String() string

func (*Snowflake) UnmarshalJSON

func (s *Snowflake) UnmarshalJSON(b []byte) error

type StatusType added in v1.4.0

type StatusType string
const (
	ONLINE_STATUS    StatusType = "online"
	DND_STATUS       StatusType = "dnd"
	IDLE_STATUS      StatusType = "idle"
	INVISIBLE_STATUS StatusType = "invisible"
	OFFLINE_STATUS   StatusType = "offline"
)

type StickerFormatType

type StickerFormatType uint8

https://docs.discord.com/developers/resources/sticker#sticker-object-sticker-format-types

const (
	PNG_STICKER_FORMAT_TYPE StickerFormatType = iota + 1
	APNG_STICKER_FORMAT_TYPE
	LOTTIE_STICKER_FORMAT_TYPE
	GIF_STICKER_FORMAT_TYPE
)

type StickerItem

type StickerItem struct {
	ID         Snowflake         `json:"id"`
	Name       string            `json:"name"`
	FormatType StickerFormatType `json:"format_type"`
}

https://docs.discord.com/developers/resources/sticker#sticker-item-object-sticker-item-structure

type StringSelectComponent added in v1.3.0

type StringSelectComponent struct {
	Type        ComponentType      `json:"type"` // Always = STRING_SELECT_COMPONENT_TYPE (3). For responses, only provided for modal interactions
	ID          uint32             `json:"id,omitempty"`
	CustomID    string             `json:"custom_id,omitempty"`
	Options     []SelectMenuOption `json:"options,omitzero"`
	Placeholder string             `json:"placeholder,omitempty"`
	MinValues   uint8              `json:"min_values,omitempty"`
	MaxValues   uint8              `json:"max_values,omitempty"`
	Disabled    bool               `json:"disabled"`
	Required    bool               `json:"required"`

	// Below 2 fields are controlled by API and should be readonly for us, developers.
	// https://docs.discord.com/developers/components/reference#string-select-string-select-interaction-response-structure
	ComponentType ComponentType `json:"component_type,omitempty"` // This field is ignored and provided by the API as part of the response (only provided for message interaction)
	Values        []string      `json:"values,omitzero"`          // This field is ignored and provided by the API as part of the response.
}

A StringSelectComponent displays a dropdown menu for users to select one or more pre-defined options.

They are available in both messages and modals, but must be placed inside an ActionRowComponent or LabelComponent respectively.

https://docs.discord.com/developers/components/reference#string-select

type TestEntitlementPayload added in v1.3.0

type TestEntitlementPayload struct {
	SkuID     Snowflake `json:"sku_id"`
	OwnerID   Snowflake `json:"owner_id"`
	OwnerType uint8     `json:"owner_type"` // 1 for a guild subscription, 2 for a user subscription
}

https://docs.discord.com/developers/resources/entitlement#create-test-entitlement-json-params

type TextDisplayComponent added in v1.3.0

type TextDisplayComponent struct {
	Type    ComponentType `json:"type"` // Always = TEXT_DISPLAY_COMPONENT_TYPE (10)
	ID      uint32        `json:"id,omitempty"`
	Content string        `json:"content"` // The Markdown content to display.
}

A TextDisplayComponent displays Markdown-formatted text content within a message or modal, similar to the 'content' field of a message.

https://docs.discord.com/developers/components/reference#text-display-text-display-structure

type TextInputComponent added in v1.3.0

type TextInputComponent struct {
	Type        ComponentType  `json:"type"` // Always = TEXT_INPUT_COMPONENT_TYPE (4)
	ID          uint32         `json:"id,omitempty"`
	CustomID    string         `json:"custom_id,omitempty"`
	Style       TextInputStyle `json:"style"`
	Label       string         `json:"label,omitempty"`       // Deprecated: use `label` and `description` on a Label component instead
	MinLength   uint16         `json:"min_length,omitempty"`  // min: 0, max: 4000 characters
	MaxLength   uint16         `json:"max_length,omitempty"`  // min: 1, max: 4000 characters
	Required    bool           `json:"required"`              // Whether this component is required to be filled, defaults to true
	Value       string         `json:"value,omitempty"`       // Pre-filled value for this component; max 4000 characters. Once the user submits the modal, this will be populated with their input.
	Placeholder string         `json:"placeholder,omitempty"` // Placeholder text to display when no text is present. Max: 100 characters
}

A TextInputComponent displays a field for the user to input free-form text.

They can only be used inside [LabelComponents] within modals.

https://docs.discord.com/developers/components/reference#text-input

type TextInputStyle

type TextInputStyle uint8

https://docs.discord.com/developers/components/reference#text-input-text-input-styles

const (
	SHORT_TEXT_INPUT_STYLE     TextInputStyle = iota + 1 // 	A single-line input.
	PARAGRAPH_TEXT_INPUT_STYLE                           // A multi-line input.
)

type ThumbnailComponent added in v1.3.0

type ThumbnailComponent struct {
	Type        ComponentType     `json:"type"` // Always = THUMBNAIL_COMPONENT_TYPE (11)
	ID          uint32            `json:"id,omitempty"`
	Media       UnfurledMediaItem `json:"media"`
	Description string            `json:"description,omitempty"` // Alt text for the media, max 1024 characters
	Spoiler     bool              `json:"spoiler"`
}

A ThumbnailComponent displays visual media as a small thumbnail within a message.

They are only available as accessories inside [SectionComponent]s.

https://docs.discord.com/developers/components/reference#thumbnail-thumbnail-structure

type UnavailableGuild added in v1.3.4

type UnavailableGuild struct {
	ID          Snowflake `json:"id"`
	Unavailable bool      `json:"unavailable"`
}

https://docs.discord.com/developers/resources/guild#unavailable-guild-object

type UnfurledMediaItem added in v1.3.0

type UnfurledMediaItem struct {
	URL          string    `json:"url"` // 	Supports arbitrary urls and attachment://<filename> references
	ProxyURL     string    `json:"proxy_url,omitempty"`
	Width        uint32    `json:"width,omitempty"`
	Height       uint32    `json:"height,omitempty"`
	ContentType  string    `json:"content_type,omitempty"`  // This field is ignored and provided by the API as part of the response
	AttachmentID Snowflake `json:"attachment_id,omitempty"` // This field is ignored and provided by the API as part of the response
}

https://docs.discord.com/developers/components/reference#unfurled-media-item-structure

type UpdatePresenceEvent added in v1.4.0

type UpdatePresenceEvent struct {
	Opcode Opcode                  `json:"op"`
	Data   UpdatePresenceEventData `json:"d"`
}

https://docs.discord.com/developers/events/gateway-events#update-presence

type UpdatePresenceEventData added in v1.4.0

type UpdatePresenceEventData struct {
	Since      *int64     `json:"since"` // Unix time (in milliseconds) of when the client went idle, or null if the client is not idle
	Activities []Activity `json:"activities"`
	Emoji      Emoji      `json:"emoji"`
	AFK        bool       `json:"afk"`
}

https://docs.discord.com/developers/events/gateway-events#update-presence-gateway-presence-update-structure

type User

type User struct {
	ID                   Snowflake         `json:"id"`
	Username             string            `json:"username"`
	GlobalName           string            `json:"global_name,omitempty"`  // User's display name. Tempest lib will make it equal to user.Username if it was empty.
	AvatarHash           string            `json:"avatar,omitempty"`       // Hash code used to access user's profile. Call User.AvatarURL to get direct url.
	Bot                  bool              `json:"bot"`                    // Whether it's bot/app account.
	System               bool              `json:"system"`                 // Whether user is Discord System Message account.
	BannerHash           string            `json:"banner,omitempty"`       // Hash code used to access user's baner. Call User.BannerURL to get direct url.
	AccentColor          uint32            `json:"accent_color,omitempty"` // User's banner color, encoded as an integer representation of hexadecimal color code.
	Locale               string            `json:"locale,omitempty"`
	PremiumType          NitroType         `json:"premium_type,omitempty"`
	PublicFlags          UserFlags         `json:"public_flags,omitempty"` // (Same as regular, user flags)
	AvatarDecorationData *AvatarDecoration `json:"avatar_decoration_data,omitempty"`
}

https://docs.discord.com/developers/resources/user#user-object-user-structure

func (*User) AvatarURL

func (user *User) AvatarURL() string

Returns a direct url to user's avatar. It'll return url to default Discord's avatar if targeted user don't use avatar.

func (*User) BannerURL

func (user *User) BannerURL() string

Returns a direct url to user's banner. It'll return empty string if targeted user don't use avatar.

func (*User) Mention

func (user *User) Mention() string

func (*User) UnmarshalJSON added in v1.3.3

func (u *User) UnmarshalJSON(data []byte) error

type UserFlags added in v1.2.3

type UserFlags BitSet

https://docs.discord.com/developers/resources/user#user-object-user-flags

const (
	DISCORD_EMPLOYEE_USER_FLAG       UserFlags = 1 << iota // Discord Employee, Staff
	PARTNERED_SERVER_OWNER_USER_FLAG                       // Partner
	HYPESQUAD_USER_FLAG
	BUG_HUNTER_LEVEL_1_USER_FLAG

	HYPESQUAD_ONLINE_HOUSE_1_USER_FLAG
	HYPESQUAD_ONLINE_HOUSE_2_USER_FLAG
	HYPESQUAD_ONLINE_HOUSE_3_USER_FLAG
	PREMIUM_EARLY_SUPPORTER_USER_FLAG
	TEAM_USER_USER_FLAG // Discord docs mentions "pseudo user" and that user is a team...

	BUG_HUNTER_LEVEL_2_USER_FLAG

	VERIFIED_BOT_USER_FLAG
	VERIFIED_DEVELOPER_USER_FLAG    // Early Verified Bot Developer
	CERTIFIED_MODERATOR_USER_FLAG   // Moderator Programs Alumni
	BOT_HTTP_INTERACTIONS_USER_FLAG // Bot/App uses only HTTP interactions and is shown in the online member list.

	ACTIVE_DEVELOPER_USER_FLAG // User has regular discord developer badge
)

Jump to

Keyboard shortcuts

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