goda

package module
v0.0.0-...-b18cf60 Latest Latest
Warning

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

Go to latest
Published: Dec 19, 2025 License: BSD-3-Clause Imports: 32 Imported by: 0

README

Goda - Golang Optimized Discord API

Goda 5alina men lmar9a kat3ref tsaybe bot b goda?

Overview

Goda is a lightweight and modern Discord API wrapper written in Go, designed for developers building Discord bots or integrations. With a focus on simplicity and performance, Goda provides an intuitive interface to interact with Discord's API, leveraging Go's concurrency features for efficient bot development.

Installation

To use Goda in your Go project, install it via:

go get github.com/ra7eemi/goda

Ensure you have Go 1.22 or later installed, as specified in the project’s go.mod.

Usage

Here’s a basic Ping Pong example to get started with Goda:

package main

import (
    "github.com/ra7eemi/goda"
    "context"
    "fmt"
)

func main() {
    // Initialize a new Goda client
    client := goda.New(
        context.TODO(),
		goda.WithToken("YOUR_BOT_TOKEN"),
		goda.WithIntents(goda.GatewayIntentGuildMessages, goda.GatewayIntentMessageContent),
    )

    // Add message create even handlers
    client.OnMessageCreate(func(event goda.MessageCreateEvent) {
        if event.Message.Content == "!ping" {
            fmt.Println("Pong!")
        }
    })

    // Start the bot
    client.Start()
}

Replace YOUR_BOT_TOKEN with your Discord bot token. Check the documentation for more examples and API details.

Badges

Go Reference Go Report Go Version License Yada Version Issues Last Commit Lines of Code

Documentation

Index

Constants

View Source
const (
	// Indicates if an app uses the Auto Moderation API.
	//
	// See: https://discord.com/developers/docs/resources/auto-moderation
	ApplicationFlagAutoModerationRuleCreateBadge = 1 << (iota + 6)

	// Intent required for bots in 100 or more servers to receive presence_update events
	//
	// See: https://discord.com/developers/docs/events/gateway-events#presence-update
	ApplicationFlagGatewayPresence

	// Intent required for bots in under 100 servers to receive presence_update events,
	// found on the Bot page in your app's settings.
	//
	// See: https://discord.com/developers/docs/events/gateway-events#presence-update
	ApplicationFlagGatewayPresenceLimited

	// Intent required for bots in 100 or more servers to receive member-related
	// events like guild_member_add. See the list of member-related events under goda.GatewayIntentGuildMembers
	ApplicationFlagGatewayGuildMembers

	// Intent required for bots in under 100 servers to receive member-related
	// events like guild_member_add, found on the Bot page in your app's settings.
	// See the list of member-related events under goda.GatewayIntentGuildMembers
	ApplicationFlagGatewayGuildMemberLimited

	// Indicates unusual growth of an app that prevents verification.
	ApplicationFlagVerificationPendingGuildLimit

	// Indicates if an app is embedded within the Discord client (currently unavailable publicly).
	ApplicationFlagEmbedded

	// Intent required for bots in 100 or more servers to receive message content.
	//
	// See: https://support-dev.discord.com/hc/en-us/articles/4404772028055-Message-Content-Privileged-Intent-FAQ
	ApplicationFlagGatewayMessageContent

	// Intent required for bots in under 100 servers to receive message content, found on the Bot page in your app's settings.
	//
	// See: https://support-dev.discord.com/hc/en-us/articles/4404772028055-Message-Content-Privileged-Intent-FAQ
	ApplicationFlagGatewayMessageContentLimited

	// Indicates if an app has registered global application commands.
	//
	// See: https://discord.com/developers/docs/interactions/application-commands
	ApplicationFlagApplicationCommandBadge
)
View Source
const (
	// ComponentTypeActionRow is a container to display a row of interactive components.
	//
	// Style: Layout
	// Usage: Message
	ComponentTypeActionRow = 1 + iota

	// ComponentTypeButton represents a button object.
	//
	// Style: Interactive
	// Usage: Message
	ComponentTypeButton

	// ComponentTypeStringSelect is a select menu for picking from defined text options.
	//
	// Style: Interactive
	// Usage: Message, Modal
	ComponentTypeStringSelect

	// ComponentTypeTextInput is a text input object.
	//
	// Style: Interactive
	// Usage: Modal
	ComponentTypeTextInput

	// ComponentTypeUserSelect is a select menu for users.
	//
	// Style: Interactive
	// Usage: Message
	ComponentTypeUserSelect

	// ComponentTypeRoleSelect is a select menu for roles.
	//
	// Style: Interactive
	// Usage: Message
	ComponentTypeRoleSelect

	// ComponentTypeMentionableSelect is a select menu for mentionables (users and roles).
	//
	// Style: Interactive
	// Usage: Message
	ComponentTypeMentionableSelect

	// ComponentTypeChannelSelect is a select menu for channels.
	//
	// Style: Interactive
	// Usage: Message
	ComponentTypeChannelSelect

	// ComponentTypeSection is a container to display text alongside an accessory component.
	//
	// Style: Layout
	// Usage: Message
	ComponentTypeSection

	// ComponentTypeTextDisplay is a markdown text display component.
	//
	// Style: Content
	// Usage: Message
	ComponentTypeTextDisplay

	// ComponentTypeThumbnail is a small image used as an accessory component.
	//
	// Style: Content
	// Usage: Message
	ComponentTypeThumbnail

	// ComponentTypeMediaGallery displays images and other media.
	//
	// Style: Content
	// Usage: Message
	ComponentTypeMediaGallery

	// ComponentTypeFile displays an attached file.
	//
	// Style: Content
	// Usage: Message
	ComponentTypeFile

	// ComponentTypeSeparator adds vertical padding between other components.
	//
	// Style: Layout
	// Usage: Message
	ComponentTypeSeparator

	// ComponentTypeContainer visually groups a set of components.
	//
	// Style: Layout
	// Usage: Message
	ComponentTypeContainer

	// ComponentTypeLabel associates a label and description with a component.
	//
	// Style: Layout
	// Usage: Modal
	ComponentTypeLabel
)
View Source
const (
	ImageBaseURL = "https://cdn.discordapp.com/"
	MediaBaseURL = "https://media.discordapp.net/"
)

Base URLs for Discord CDN and media assets.

View Source
const (
	LIB_NAME    = "goda"
	LIB_VERSION = "0.14.5"
)

Variables

View Source
var (
	// ErrNoClient is returned when an entity action method is called
	// but the entity has no client reference.
	ErrNoClient = errors.New("goda: entity has no client reference")

	// ErrNotFound is returned when a requested resource does not exist.
	ErrNotFound = errors.New("goda: resource not found")

	// ErrUnauthorized is returned when the bot lacks permission for an action.
	ErrUnauthorized = errors.New("goda: unauthorized")

	// ErrRateLimited is returned when the API rate limit has been exceeded.
	ErrRateLimited = errors.New("goda: rate limited")

	// ErrInvalidToken is returned when the bot token is invalid.
	ErrInvalidToken = errors.New("goda: invalid token")

	// ErrMissingPermissions is returned when the bot lacks required permissions.
	ErrMissingPermissions = errors.New("goda: missing permissions")

	// ErrInvalidSnowflake is returned when a snowflake ID is invalid.
	ErrInvalidSnowflake = errors.New("goda: invalid snowflake")

	// ErrChannelNotText is returned when a text channel operation is attempted
	// on a non-text channel.
	ErrChannelNotText = errors.New("goda: channel is not a text channel")

	// ErrChannelNotVoice is returned when a voice channel operation is attempted
	// on a non-voice channel.
	ErrChannelNotVoice = errors.New("goda: channel is not a voice channel")

	// ErrChannelNotAnnouncement is returned when an announcement channel operation
	// is attempted on a non-announcement channel.
	ErrChannelNotAnnouncement = errors.New("goda: channel is not an announcement channel")

	// ErrChannelNotStage is returned when a stage channel operation is attempted
	// on a non-stage channel.
	ErrChannelNotStage = errors.New("goda: channel is not a stage channel")

	// ErrChannelNotThread is returned when a thread channel operation is attempted
	// on a non-thread channel.
	ErrChannelNotThread = errors.New("goda: channel is not a thread channel")

	// ErrChannelNotForum is returned when a forum channel operation is attempted
	// on a non-forum channel.
	ErrChannelNotForum = errors.New("goda: channel is not a forum channel")

	// ErrChannelNotMedia is returned when a media channel operation is attempted
	// on a non-media channel.
	ErrChannelNotMedia = errors.New("goda: channel is not a media channel")

	// ErrDMNotAllowed is returned when a DM cannot be sent to a user.
	ErrDMNotAllowed = errors.New("goda: cannot send DM to this user")
)

Common errors returned by the goda library.

Functions

func AchievementIconURL

func AchievementIconURL(appID, achID Snowflake, iconHash string, format ImageFormat, size ImageSize) string

func AcquireBytes

func AcquireBytes(sizeHint int) *[]byte

AcquireBytes gets a byte slice from the appropriate pool based on size hint. The returned slice has len=0 and cap >= sizeHint.

func AcquireZlibReader

func AcquireZlibReader() *zlibReaderWrapper

AcquireZlibReader gets a zlib reader wrapper from the pool.

func ApplicationAssetURL

func ApplicationAssetURL(appID, assetID Snowflake, format ImageFormat, size ImageSize) string

func ApplicationCoverURL

func ApplicationCoverURL(appID Snowflake, coverHash string, format ImageFormat, size ImageSize) string

func ApplicationIconURL

func ApplicationIconURL(appID Snowflake, iconHash string, format ImageFormat, size ImageSize) string

func AvatarDecorationURL

func AvatarDecorationURL(asset string, size ImageSize) string

func BitFieldAdd

func BitFieldAdd[T BitField](bitfield T, bitmasks ...T) T

BitFieldAdd returns a new bitfield with the specified bitmasks set. Each bitmask corresponds to a flag value that will be added (ORed) into the bitfield.

Example:

var flags uint8 = 0
flags = BitFieldAdd(flags, 1, 4) // sets bit 0 and 2 → flags = 5

func BitFieldHas

func BitFieldHas[T BitField](bitfield T, bitmasks ...T) bool

BitFieldHas reports whether the given bitfield contains all of the specified bitmasks. It returns true if every bitmask is fully present in the bitfield.

Example:

const (
	A uint8 = 1 << iota // 0001
	B                   // 0010
	C                   // 0100
)

var flags = A | C // 0101

BitFieldHas(flags, A)    // true
BitFieldHas(flags, B)    // false
BitFieldHas(flags, A, C) // true

func BitFieldMissing

func BitFieldMissing[T BitField](bitfield T, bitmasks ...T) T

BitFieldMissing returns a bitfield containing the subset of bitmasks that are not present in the given bitfield. If all specified bitmasks are already set, it returns zero.

Example:

const (
	A uint8 = 1 << iota // 0001
	B                   // 0010
	C                   // 0100
)

var flags = A | C // 0101

BitFieldMissing(flags, A, B, C) // 0010 (B is missing)
BitFieldMissing(flags, A)       // 0000 (A is present)
BitFieldMissing(flags, B, C)    // 0010 (only B is missing)

func BitFieldRemove

func BitFieldRemove[T BitField](bitfield T, bitmasks ...T) T

BitFieldRemove returns a new bitfield with the specified bitmasks cleared. Each bitmask corresponds to a flag value that will be removed (AND NOTed) from the bitfield.

Example:

var flags uint8 = 5 // 0101
flags = BitFieldRemove(flags, 1) // clears bit 0 → flags = 4

func BytesToString

func BytesToString(b []byte) string

BytesToString converts a byte slice to a string without allocation. WARNING: The returned string shares memory with the byte slice. The byte slice MUST NOT be modified after this call, or the string will be corrupted. The byte slice must remain alive for the lifetime of the returned string.

func DecompressOneShot

func DecompressOneShot(data []byte) ([]byte, error)

DecompressOneShot decompresses a single zlib-compressed message. This is a convenience function for one-off decompression. For streaming decompression (Discord gateway), use the pooled wrapper.

func DefaultUserAvatarURL

func DefaultUserAvatarURL(index int) string

func DownloadFile

func DownloadFile(url, baseName, dir string) (string, error)

DownloadFile downloads a file from the given URL and saves it in the specified directory. The filename is derived from baseName and the Content-Type returned by the server. Returns the full path of the saved file.

func EmojiURL

func EmojiURL(emojiID Snowflake, format ImageFormat, size ImageSize) string

func GuildBannerURL

func GuildBannerURL(guildID Snowflake, bannerHash string, format ImageFormat, size ImageSize) string

func GuildDiscoverySplashURL

func GuildDiscoverySplashURL(guildID Snowflake, discoverySplashHash string, format ImageFormat, size ImageSize) string

func GuildIconURL

func GuildIconURL(guildID Snowflake, iconHash string, format ImageFormat, size ImageSize) string

func GuildMemberAvatarURL

func GuildMemberAvatarURL(guildID, userID Snowflake, avatarHash string, format ImageFormat, size ImageSize) string

func GuildMemberBannerURL

func GuildMemberBannerURL(guildID, userID Snowflake, bannerHash string, format ImageFormat, size ImageSize) string

func GuildScheduledEventCoverURL

func GuildScheduledEventCoverURL(eventID Snowflake, coverHash string, format ImageFormat, size ImageSize) string

func GuildSplashURL

func GuildSplashURL(guildID Snowflake, splashHash string, format ImageFormat, size ImageSize) string

func GuildTagBadgeURL

func GuildTagBadgeURL(guildID Snowflake, badgeHash string, format ImageFormat, size ImageSize) string

func HasZlibSuffix

func HasZlibSuffix(data []byte) bool

HasZlibSuffix checks if data ends with the Discord zlib flush suffix.

func IsZlibCompressed

func IsZlibCompressed(data []byte) bool

IsZlibCompressed checks if data appears to be zlib-compressed. Zlib data starts with a specific header based on compression level.

func MonotonicNow

func MonotonicNow() int64

MonotonicNow returns the current monotonic time in nanoseconds. This is a safe wrapper around the linked nanotime function.

func MonotonicSince

func MonotonicSince(start int64) int64

MonotonicSince returns the time elapsed since the given start time in nanoseconds. Both start and the return value are in nanoseconds.

func MonotonicSinceMs

func MonotonicSinceMs(start int64) int64

MonotonicSinceMs returns the time elapsed since the given start time in milliseconds.

func ReleaseBytes

func ReleaseBytes(b *[]byte)

ReleaseBytes returns a byte slice to the appropriate pool. The slice is reset (len=0) but capacity is preserved.

func ReleaseGuild

func ReleaseGuild(g *Guild)

ReleaseGuild returns a Guild to the pool. The Guild is reset before being returned to the pool. Do NOT use the Guild after calling this function.

func ReleaseMember

func ReleaseMember(m *Member)

ReleaseMember returns a Member to the pool. The Member is reset before being returned to the pool. Do NOT use the Member after calling this function.

func ReleaseMessage

func ReleaseMessage(m *Message)

ReleaseMessage returns a Message to the pool. The Message is reset before being returned to the pool. Do NOT use the Message after calling this function.

func ReleaseTextChannel

func ReleaseTextChannel(c *TextChannel)

ReleaseTextChannel returns a TextChannel to the pool.

func ReleaseUser

func ReleaseUser(u *User)

ReleaseUser returns a User to the pool. The User is reset before being returned to the pool. Do NOT use the User after calling this function.

func ReleaseVoiceChannel

func ReleaseVoiceChannel(c *VoiceChannel)

ReleaseVoiceChannel returns a VoiceChannel to the pool.

func ReleaseZlibReader

func ReleaseZlibReader(w *zlibReaderWrapper)

ReleaseZlibReader returns a zlib reader wrapper to the pool.

func RoleIconURL

func RoleIconURL(roleID Snowflake, iconHash string, format ImageFormat, size ImageSize) string

func StickerPackBannerURL

func StickerPackBannerURL(stickerPackBannerAssetID Snowflake, format ImageFormat, size ImageSize) string

func StickerURL

func StickerURL(stickerID Snowflake, format ImageFormat) string

func StorePageAssetURL

func StorePageAssetURL(appID, assetID Snowflake, format ImageFormat, size ImageSize) string

func StringToBytes

func StringToBytes(s string) []byte

StringToBytes converts a string to a byte slice without allocation. WARNING: The returned byte slice shares memory with the string. The byte slice MUST NOT be modified, as strings are immutable in Go. Modifying the returned slice results in undefined behavior.

func TeamIconURL

func TeamIconURL(teamID Snowflake, iconHash string, format ImageFormat, size ImageSize) string

func UserAvatarURL

func UserAvatarURL(userID Snowflake, avatarHash string, format ImageFormat, size ImageSize) string

func UserBannerURL

func UserBannerURL(userID Snowflake, bannerHash string, format ImageFormat, size ImageSize) string

func WithCacheManager

func WithCacheManager(cacheManager CacheManager) clientOption

WithCacheManager sets a custom CacheManager implementation for your client.

Usage:

y := goda.New(goda.WithCacheManager(myCacheManager))

Logs fatal and exits if cacheManager is nil.

func WithIdleTimeout

func WithIdleTimeout(d time.Duration) workerOption

WithIdleTimeout sets idle timeout for workers

func WithIntents

func WithIntents(intents ...GatewayIntent) clientOption

WithIntents sets Gateway intents for the client shards.

Usage:

y := goda.New(goda.WithIntents(GatewayIntentGuilds, GatewayIntentMessageContent))

Also supports bitwise OR usage:

y := goda.New(goda.WithIntents(GatewayIntentGuilds | GatewayIntentMessageContent))

func WithLogger

func WithLogger(logger Logger) clientOption

WithLogger sets a custom Logger implementation for your client.

Usage:

y := goda.New(goda.WithLogger(myLogger))

Logs fatal and exits if logger is nil.

func WithMaxWorkers

func WithMaxWorkers(_max int) workerOption

WithMaxWorkers sets max workers

func WithMinWorkers

func WithMinWorkers(_min int) workerOption

WithMinWorkers sets min workers

func WithQueueCap

func WithQueueCap(_cap int) workerOption

WithQueueCap sets queue capacity

func WithQueueGrowThreshold

func WithQueueGrowThreshold(threshold float64) workerOption

WithQueueGrowThreshold sets the queue usage threshold at which the pool attempts to dynamically spawn a new worker. A value of 0.75 means new workers are added when the queue is 75% full.

func WithShardsIdentifyRateLimiter

func WithShardsIdentifyRateLimiter(rateLimiter ShardsIdentifyRateLimiter) clientOption

WithShardsIdentifyRateLimiter sets a custom ShardsIdentifyRateLimiter implementation for your client.

Usage:

y := goda.New(goda.WithShardsIdentifyRateLimiter(myRateLimiter))

Logs fatal and exits if the provided rateLimiter is nil.

func WithToken

func WithToken(token string) clientOption

WithToken sets the bot token for your client.

Usage:

y := goda.New(goda.WithToken("your_bot_token"))

Notes:

  • Logs fatal and exits if token is empty or obviously invalid (< 50 chars).
  • Removes "Bot " prefix automatically if provided.

Warning: Never share your bot token publicly.

func WithWorkerPool

func WithWorkerPool(workerPool WorkerPool) clientOption

WithWorkerPool sets a custom workerpool implementation for your client.

Usage:

y := goda.New(goda.WithWorkerPool(myWorkerPool))

Logs fatal and exits if workerpool is nil.

Types

type Account

type Account struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

Account represents an integration account.

type ActionRowBuilder

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

ButtonBuilder helps build a ButtonComponent with chainable methods.

func NewActionRowBuilder

func NewActionRowBuilder() *ActionRowBuilder

NewActionRowBuilder creates a new ActionRowBuilder instance.

func (*ActionRowBuilder) AddComponent

func (b *ActionRowBuilder) AddComponent(component InteractiveComponent) *ActionRowBuilder

AddComponent add's a component to the action row components.

func (*ActionRowBuilder) Build

Build returns the final ActionRowComponent.

func (*ActionRowBuilder) SetComponent

func (b *ActionRowBuilder) SetComponent(components ...InteractiveComponent) *ActionRowBuilder

SetComponents sets the action row components.

type ActionRowComponent

type ActionRowComponent struct {
	ComponentFields

	// Components is an array of up to 5 interactive button components or a single select component.
	//
	// Valid components:
	//   - ButtonComponent (up to 5)
	//   - StringSelectMenuComponent (1)
	//   - UserSelectMenuComponent (1)
	//   - RoleSelectMenuComponent (1)
	//   - MentionableSelectMenuComponent (1)
	//   - ChannelSelectMenuComponent (1)
	Components []InteractiveComponent `json:"components"`
}

ActionRowComponent is a top-level layout component that organizes interactive components.

It can contain either up to 5 ButtonComponent instances or a single select component (StringSelectMenuComponent, UserSelectMenuComponent, RoleSelectMenuComponent, MentionableSelectMenuComponent, or ChannelSelectMenuComponent). In modals, ActionRowComponent with TextInputComponent is deprecated; use LabelComponent instead.

Note:

  • Only one type of component (buttons or a single select) can be included at a time.

Reference: https://discord.com/developers/docs/interactions/message-components#action-row

func (*ActionRowComponent) MarshalJSON

func (c *ActionRowComponent) MarshalJSON() ([]byte, error)

func (*ActionRowComponent) UnmarshalJSON

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

type AllowedMentionType

type AllowedMentionType string
const (
	AllowedMentionTypeRoles    AllowedMentionType = "roles"
	AllowedMentionTypeUsers    AllowedMentionType = "users"
	AllowedMentionTypeEveryone AllowedMentionType = "everyone"
)

type AllowedMentions

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

type AnnouncementChannel

type AnnouncementChannel struct {
	EntityBase // Embedded client reference for action methods
	GuildChannelFields
	CategorizedChannelFields
	GuildMessageChannelFields
	NsfwChannelFields
	TopicChannelFields
}

AnnouncementChannel represents an announcement channel.

func (*AnnouncementChannel) BulkDelete

func (c *AnnouncementChannel) BulkDelete(messageIDs []Snowflake, reason string) error

BulkDelete deletes multiple messages from this announcement channel.

func (*AnnouncementChannel) Delete

func (c *AnnouncementChannel) Delete(reason string) error

Delete deletes this announcement channel.

func (*AnnouncementChannel) Edit

Edit modifies this announcement channel's settings.

func (*AnnouncementChannel) FetchMessage

func (c *AnnouncementChannel) FetchMessage(messageID Snowflake) (*Message, error)

FetchMessage retrieves a single message from this announcement channel.

func (*AnnouncementChannel) FetchMessages

func (c *AnnouncementChannel) FetchMessages(opts FetchMessagesOptions) ([]*Message, error)

FetchMessages retrieves messages from this announcement channel.

func (*AnnouncementChannel) Guild

func (c *AnnouncementChannel) Guild() (Guild, bool)

Guild returns the cached guild this announcement channel belongs to.

func (*AnnouncementChannel) MarshalJSON

func (c *AnnouncementChannel) MarshalJSON() ([]byte, error)

func (*AnnouncementChannel) Send

func (c *AnnouncementChannel) Send(content string) (*Message, error)

Send sends a message to this announcement channel.

func (*AnnouncementChannel) SendEmbed

func (c *AnnouncementChannel) SendEmbed(embed Embed) (*Message, error)

SendEmbed sends an embed message to this announcement channel.

func (*AnnouncementChannel) SendWith

func (c *AnnouncementChannel) SendWith(opts MessageCreateOptions) (*Message, error)

SendWith sends a message with full options to this announcement channel.

type Application

type Application struct {
	// ID is the applications's unique Discord snowflake ID.
	ID Snowflake `json:"id"`

	// Name is the applications's name.
	Name string `json:"name"`

	// Icon is the application's icon hash.
	//
	// Optional:
	//  - May be empty string if no icon.
	Icon string `json:"icon"`

	// Description is the description of a application.
	Description string `json:"description"`

	// RPCOrigins is a List of RPC origin URLs, if RPC is enabled.
	RPCOrigins []string `json:"rpc_origins"`

	// BotPublic When false, only the app owner can add the app to guilds.
	BotPublic bool `json:"bot_public"`

	// BotRequireCodeGrant When true, the app's bot will only join upon completion
	// of the full OAuth2 code grant flow.
	BotRequireCodeGrant bool `json:"bot_require_code_grant"`

	// Bot is a partial user object for the bot user associated with the app
	//
	// Optional.
	Bot *User `json:"bot"`

	// TermsOfServiceURL is the URL of the app's Terms of Service.
	TermsOfServiceURL string `json:"terms_of_service_url"`

	// PrivacyPolicyURL is the URL of the app's Privacy Policy.
	PrivacyPolicyURL string `json:"privacy_policy_url"`

	// Owner is a partial user object for the owner of the app.
	//
	// Optional.
	Owner *User `json:"owner,omitempty"`

	// VerifyKey is the Hex encoded key for verification in interactions and the GameSDK's GetTicket.
	VerifyKey string `json:"verify_key"`

	// Team is the team this app belongs to.
	//
	// Optional:
	//   - Will be nil if app do not belong to any team.
	Team *Team `json:"team"`

	// GuildID is the id of the guild associated with the app. For example, a developer support server.
	//
	// Optional:
	//   - Will be equal 0 if no associated guild is set.
	GuildID Snowflake `json:"guild_id"`

	// Guild is a the partial guild associated with the app. For example, a developer support server.
	//
	// Optional:
	//   - Will be equal nil if no associated guild is set.
	Guild *Guild `json:"guild"`

	// PrimarySkuID If this app is a game sold on Discord, this field will
	// be the id of the "Game SKU" that is created, if exists
	//
	// Optional:
	//   - Will be equal 0 if this app is not a game sold on discord.
	PrimarySkuID Snowflake `json:"primary_sku_id"`

	// Slug If this app is a game sold on Discord, this field will be the URL slug that links to the store page.
	//
	// Optional:
	//   - Will be empty string if this app is not a game sold on discord.
	Slug string `json:"slug"`

	// CoverImage is the app's default rich presence invite cover image hash.
	//
	// Optional:
	//   - Will be empty string if no cover image is set.
	CoverImage string `json:"cover_image"`

	// Flags are the app's public flags.
	Flags ApplicationFlags `json:"flags"`

	// ApproximateGuildCount is the approximate count of guilds the app has been added to.
	//
	// Optional.
	ApproximateGuildCount *int `json:"approximate_guild_count"`

	// ApproximateUserInstallCount is the Approximate count of users that have installed
	// the app (authorized with application.commands as a scope).
	//
	// Optional.
	ApproximateUserInstallCount *int `json:"approximate_user_install_count"`

	// ApproximateUserAuthorizationCount is the approximate count of users that have OAuth2 authorizations for the app.
	//
	// Optional.
	ApproximateUserAuthorizationCount *int `json:"approximate_user_authorization_count"`

	// RedirectURIs is an array of redirect URIs for the app.
	RedirectURIs []string `json:"redirect_uris"`

	// RedirectURIs is an array of redirect URIs for the app.
	//
	// See: https://discord.com/developers/docs/interactions/receiving-and-responding#receiving-an-interaction
	//
	// Optional:
	//   - Will be empty string if not set.
	InteractionsEndpointURL string `json:"interactions_endpoint_url"`

	// RoleConnectionsVerificationURL is the role connection verification URL for the app.
	//
	// Optional:
	//   - Will be empty string if not set.
	RoleConnectionsVerificationURL string `json:"role_connections_verification_url"`

	// EventWebhooksURL is the event webhooks URL for the app to receive webhook events
	//
	// See: https://discord.com/developers/docs/events/webhook-events#preparing-for-events
	//
	// Optional:
	//   - Will be empty string if not set.
	EventWebhooksURL string `json:"event_webhooks_url"`

	// EventWebhooksStatus is the app event webhook status.
	EventWebhooksStatus ApplicationEventWebhookStatus `json:"event_webhooks_status"`

	// EventWebhooksTypes is a list of Webhook event types the app subscribes to.
	EventWebhooksTypes []WebhookEventTypes `json:"event_webhooks_types"`

	// Tags is a list of tags describing the content and functionality of the app. Max of 5 tags.
	Tags []string `json:"tags"`

	// InstallParams are the settings for the app's default in-app authorization link, if enabled.
	InstallParams *ApplicationInstallParams `json:"install_params"`

	// IntegrationTypesConfig are the default scopes and permissions for each supported installation context.
	// Value for each key is an integration type configuration object
	IntegrationTypesConfig ApplicationIntegrationTypesConfig `json:"integration_types_config"`

	// CustomInstallURL is the default custom authorization URL for the app, if enabled.
	CustomInstallURL string `json:"custom_install_url"`
}

Application represent a Discord application object.

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

func (*Application) CoverImageURL

func (a *Application) CoverImageURL() string

CoverImageURL returns the URL to the app's cover image.

If the application has a custom cover image set, it returns the URL to that image, otherwise empty string. By default, it uses PNG format.

Example usage:

url := application.CoverImageURL()

func (*Application) CoverImageURLWith

func (a *Application) CoverImageURLWith(format ImageFormat, size ImageSize) string

CoverImageURLWith returns the URL to the app's cover image, allowing explicit specification of image format and size.

If the app has a custom cover image set, it returns the URL to that image (otherwise empty string) using the provided format and size.

Example usage:

url := team.CoverImageURLWith(ImageFormatWebP, ImageSize512)

func (*Application) IconURL

func (a *Application) IconURL() string

IconURL returns the URL to the app's icon image.

If the application has a custom icon set, it returns the URL to that icon, otherwise empty string. By default, it uses PNG format.

Example usage:

url := application.IconURL()

func (*Application) IconURLWith

func (a *Application) IconURLWith(format ImageFormat, size ImageSize) string

IconURLWith returns the URL to the app's icon image, allowing explicit specification of image format and size.

If the app has a custom icon set, it returns the URL to that icon (otherwise empty string) using the provided format and size.

Example usage:

url := team.IconURLWith(ImageFormatWebP, ImageSize512)

type ApplicationCommand

type ApplicationCommand interface {
	GetType() ApplicationCommandType
	GetID() Snowflake
	GetApplicationID() Snowflake
	GetGuildID() Snowflake
	GetName() string
	GetNameLocalizations() map[Locale]string
	GetDefaultMemberPermissions() Permissions
	GetVersion() Snowflake
	CreatedAt() time.Time
	IsNSFW() bool
	GetIntegrationTypes() []ApplicationIntegrationType
	GetContexts() []InteractionContextType
	json.Marshaler
}

ApplicationCommand is the interface representing a Discord application command.

This interface can represent any type of command returned by Discord, including slash commands, user commands, message commands, and primary entry point commands.

Use this interface when you want to handle commands generically without knowing the specific concrete type in advance.

You can convert (assert) it to a specific command type using a type assertion or a type switch, as described in the official Go documentation:

Example usage:

var myCommand ApplicationCommand

switch cmd := myCommand.(type) {
case *ChatInputCommand:
    fmt.Println("Slash command:", cmd.Name)
case *ApplicationUserCommand:
    fmt.Println("User command:", cmd.Name)
case *ApplicationMessageCommand:
    fmt.Println("Message command:", cmd.Name)
default:
    fmt.Println("Other command type:", cmd.GetType())
}

func UnmarshalApplicationCommand

func UnmarshalApplicationCommand(buf []byte) (ApplicationCommand, error)

type ApplicationCommandBase

type ApplicationCommandBase struct {
	// Type is the type of the command.
	Type ApplicationCommandType `json:"type"`

	// ID is the unique ID of the command.
	ID Snowflake `json:"id"`

	// ApplicationID is the ID of the parent application.
	ApplicationID Snowflake `json:"application_id"`

	// GuildID is the guild ID of the command, if not global.
	GuildID Snowflake `json:"guild_id"`

	// Name is the name of the command.
	//
	// Info:
	//  - Must be 1-32 characters.
	//  - For CHAT_INPUT commands, must match the regex ^[-_'\p{L}\p{N}\p{sc=Deva}\p{sc=Thai}]{1,32}$ with unicode flag.
	//  - For USER and MESSAGE commands, may be mixed case and include spaces.
	//  - Must use lowercase variants of letters when available.
	Name string `json:"name"`

	// NameLocalizations is a localization dictionary for the name field.
	//
	// Info:
	//  - Keys are available locales.
	//  - Values follow the same restrictions as Name.
	NameLocalizations map[Locale]string `json:"name_localizations"`

	// DefaultMemberPermissions is the set of permissions required to use the command.
	//
	// Info:
	//  - Represented as a bit set.
	//  - Set to "0" to disable the command for everyone except admins by default.
	DefaultMemberPermissions Permissions `json:"default_member_permissions"`

	// DefaultPermission indicates whether the command is enabled by default when the app is added to a guild.
	//
	// Info:
	//  - Defaults to true.
	//  - Deprecated; use DefaultMemberPermissions or Contexts instead.
	DefaultPermission bool `json:"default_permission"`

	// NSFW indicates whether the command is age-restricted.
	//
	// Info:
	//  - Defaults to false.
	NSFW bool `json:"nsfw"`

	// IntegrationTypes is the list of installation contexts where the command is available.
	//
	// Info:
	//  - Only for globally-scoped commands.
	//  - Defaults to the app's configured contexts.
	IntegrationTypes []ApplicationIntegrationType `json:"integration_types"`

	// Contexts is the list of interaction contexts where the command can be used.
	//
	// Info:
	//  - Only for globally-scoped commands.
	Contexts []InteractionContextType `json:"contexts"`

	// Version is the autoincrementing version identifier updated during substantial record changes.
	Version Snowflake `json:"version"`
}

ApplicationCommandBase contains fields common to all application command types.

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

func (*ApplicationCommandBase) CreatedAt

func (a *ApplicationCommandBase) CreatedAt() time.Time

func (*ApplicationCommandBase) GetApplicationID

func (a *ApplicationCommandBase) GetApplicationID() Snowflake

func (*ApplicationCommandBase) GetContexts

func (*ApplicationCommandBase) GetDefaultMemberPermissions

func (a *ApplicationCommandBase) GetDefaultMemberPermissions() Permissions

func (*ApplicationCommandBase) GetGuildID

func (a *ApplicationCommandBase) GetGuildID() Snowflake

GetGuildID returns the guild ID of the command, if it is guild-specific.

Returns:

  • The Snowflake ID of the guild if the command is associated with a guild.
  • 0 if the command is global (not tied to a specific guild).

func (*ApplicationCommandBase) GetID

func (a *ApplicationCommandBase) GetID() Snowflake

func (*ApplicationCommandBase) GetIntegrationTypes

func (a *ApplicationCommandBase) GetIntegrationTypes() []ApplicationIntegrationType

func (*ApplicationCommandBase) GetName

func (a *ApplicationCommandBase) GetName() string

func (*ApplicationCommandBase) GetNameLocalizations

func (a *ApplicationCommandBase) GetNameLocalizations() map[Locale]string

func (*ApplicationCommandBase) GetType

func (*ApplicationCommandBase) GetVersion

func (a *ApplicationCommandBase) GetVersion() Snowflake

func (*ApplicationCommandBase) IsNSFW

func (a *ApplicationCommandBase) IsNSFW() bool

type ApplicationCommandHandlerType

type ApplicationCommandHandlerType int

ApplicationCommandHandlerType represents the handler type for PRIMARY_ENTRY_POINT commands.

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

const (
	// ApplicationCommandHandlerTypeApp indicates the app handles the interaction using an interaction token.
	ApplicationCommandHandlerTypeApp ApplicationCommandHandlerType = 1 + iota

	// ApplicationCommandHandlerTypeDiscord indicates Discord handles the interaction by launching an Activity and sending a follow-up message.
	ApplicationCommandHandlerTypeDiscord
)

func (ApplicationCommandHandlerType) Is

Is returns true if the command handler's Type matches the provided one.

type ApplicationCommandInteractionDataFields

type ApplicationCommandInteractionDataFields struct {
	// ID is the unique ID of the invoked command.
	ID Snowflake `json:"id"`

	// Type is the type of the invoked command.
	Type ApplicationCommandType `json:"type"`

	// Name is the name of the invoked command.
	Name string `json:"name"`

	// GuildID is the ID of the guild the command is registered to.
	//
	// Optional:
	//   - Will be 0 for global commands.
	GuildID Snowflake `json:"guild_id"`
}

ApplicationCommandInteractionDataFields holds fields common to all application command interaction data.

type ApplicationCommandInteractionFields

type ApplicationCommandInteractionFields struct {
	InteractionFields

	// Guild is the guild the interaction happened in.
	//
	// Optional:
	//   - Will be nil if the interaction occurred in a DM.
	Guild *PartialGuild `json:"guild"`

	// Channel is the channel the interaction happened in.
	Channel ResolvedMessageChannel `json:"channel"`

	// Locale is the selected language of the invoking user.
	Locale Locale `json:"locale"`

	// Member is the guild member data for the invoking user.
	//
	// Optional:
	//   - Present when the interaction is invoked in a guild.
	Member *ResolvedMember `json:"member"`

	// User is the user object for the invoking user, if invoked in a DM.
	//
	// Optional:
	//   - Present only when the interaction is invoked in a DM.
	User *User `json:"user"`

	// AppPermissions is a bitwise set of permissions the app has in the source location of the interaction.
	AppPermissions Permissions `json:"app_permissions"`

	// Entitlements is a list of entitlements for the invoking user.
	Entitlements []Entitlement `json:"entitlement"`

	// AuthorizingIntegrationOwners maps installation contexts that the interaction was authorized for
	// to related user or guild IDs.
	AuthorizingIntegrationOwners map[ApplicationIntegrationType]Snowflake `json:"authorizing_integration_owners"`

	// Context indicates where the interaction was triggered from.
	Context InteractionContextType `json:"context"`

	// AttachmentSizeLimit is the maximum size of attachments in bytes for this interaction.
	AttachmentSizeLimit int `json:"attachment_size_limit"`
}

ApplicationCommandInteractionFields holds fields common to all application command interactions.

Reference: https://discord.com/developers/docs/interactions/receiving-and-responding

type ApplicationCommandOption

type ApplicationCommandOption interface {
	GetType() ApplicationCommandOptionType
	GetName() string
	GetDescription() string
	json.Marshaler
}

ApplicationCommandOption is the interface representing a Discord application command option.

This interface can represent any type of option returned by Discord, including sub-commands, sub-command groups, strings, integers, booleans, users, channels, roles, mentionables, floats, and attachments.

Use this interface when you want to handle options generically without knowing the specific concrete type in advance.

You can convert (assert) it to a specific option type using a type assertion or a type switch, as described in the official Go documentation:

Example usage:

var myOption ApplicationCommandOption

switch opt := myOption.(type) {
case *ApplicationCommandOptionString:
    fmt.Println("String option:", opt.Name)
case *ApplicationCommandOptionInteger:
    fmt.Println("Integer option:", opt.Name)
case *ApplicationCommandOptionSubCommand:
    fmt.Println("Sub-command options:", opt.Options)
default:
    fmt.Println("Other option type:", opt.GetType())
}

func UnmarshalApplicationCommandOption

func UnmarshalApplicationCommandOption(buf []byte) (ApplicationCommandOption, error)

type ApplicationCommandOptionAttachment

type ApplicationCommandOptionAttachment struct {
	OptionBase
	RequiredBase
}

ApplicationCommandOptionAttachment represents an attachment option.

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

func (*ApplicationCommandOptionAttachment) MarshalJSON

func (o *ApplicationCommandOptionAttachment) MarshalJSON() ([]byte, error)

type ApplicationCommandOptionBool

type ApplicationCommandOptionBool struct {
	OptionBase
	RequiredBase
}

ApplicationCommandOptionBool represents a boolean option.

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

func (*ApplicationCommandOptionBool) MarshalJSON

func (o *ApplicationCommandOptionBool) MarshalJSON() ([]byte, error)

type ApplicationCommandOptionChannel

type ApplicationCommandOptionChannel struct {
	OptionBase
	RequiredBase
	ChannelConstraints
}

ApplicationCommandOptionChannel represents a channel option.

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

func (*ApplicationCommandOptionChannel) MarshalJSON

func (o *ApplicationCommandOptionChannel) MarshalJSON() ([]byte, error)

type ApplicationCommandOptionChoice

type ApplicationCommandOptionChoice struct {
	Name              string      `json:"name"`
	NameLocalizations StringMap   `json:"name_localizations,omitempty"`
	Value             interface{} `json:"value"`
}

ApplicationCommandOptionChoice represents a choice for a command option. This is a placeholder type - the full definition is in application_command.go.

type ApplicationCommandOptionChoiceFloat

type ApplicationCommandOptionChoiceFloat struct {
	ChoiceOptionBase
	// Value is the float value of the choice.
	//
	// Info:
	//  - Must be between -2^53 and 2^53.
	Value float64 `json:"value"`
}

ApplicationCommandOptionChoiceFloat represents a choice for float options.

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

type ApplicationCommandOptionChoiceInteger

type ApplicationCommandOptionChoiceInteger struct {
	ChoiceOptionBase
	// Value is the integer value of the choice.
	//
	// Info:
	//  - Must be between -2^53 and 2^53.
	Value int `json:"value"`
}

ApplicationCommandOptionChoiceInteger represents a choice for integer options.

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

type ApplicationCommandOptionChoiceString

type ApplicationCommandOptionChoiceString struct {
	ChoiceOptionBase
	// Value is the string value of the choice.
	Value string `json:"value"`
}

ApplicationCommandOptionChoiceString represents a choice for string options.

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

type ApplicationCommandOptionFloat

type ApplicationCommandOptionFloat struct {
	OptionBase
	RequiredBase
	ChoiceBase
	ChoiceFieldsFloat
	FloatConstraints
}

ApplicationCommandOptionFloat represents a float option.

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

func (*ApplicationCommandOptionFloat) MarshalJSON

func (o *ApplicationCommandOptionFloat) MarshalJSON() ([]byte, error)

type ApplicationCommandOptionInteger

type ApplicationCommandOptionInteger struct {
	OptionBase
	RequiredBase
	ChoiceBase
	ChoiceFieldsInteger
	IntegerConstraints
}

ApplicationCommandOptionInteger represents an integer option.

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

func (*ApplicationCommandOptionInteger) MarshalJSON

func (o *ApplicationCommandOptionInteger) MarshalJSON() ([]byte, error)

type ApplicationCommandOptionMentionable

type ApplicationCommandOptionMentionable struct {
	OptionBase
	RequiredBase
}

ApplicationCommandOptionMentionable represents a mentionable option.

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

func (*ApplicationCommandOptionMentionable) MarshalJSON

func (o *ApplicationCommandOptionMentionable) MarshalJSON() ([]byte, error)

type ApplicationCommandOptionRole

type ApplicationCommandOptionRole struct {
	OptionBase
	RequiredBase
}

ApplicationCommandOptionRole represents a role option.

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

func (*ApplicationCommandOptionRole) MarshalJSON

func (o *ApplicationCommandOptionRole) MarshalJSON() ([]byte, error)

type ApplicationCommandOptionString

type ApplicationCommandOptionString struct {
	OptionBase
	RequiredBase
	ChoiceBase
	ChoiceFieldsString
	StringConstraints
}

ApplicationCommandOptionString represents a string option.

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

func (*ApplicationCommandOptionString) MarshalJSON

func (o *ApplicationCommandOptionString) MarshalJSON() ([]byte, error)

type ApplicationCommandOptionSubCommand

type ApplicationCommandOptionSubCommand struct {
	OptionBase
	// Options is an array of nested options for the sub-command.
	//
	// Info:
	//  - Up to 25 options.
	//  - These are the parameters of the sub-command.
	Options []ApplicationCommandOption `json:"options,omitempty"`
}

ApplicationCommandOptionSubCommand represents a sub-command option.

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

func (*ApplicationCommandOptionSubCommand) MarshalJSON

func (o *ApplicationCommandOptionSubCommand) MarshalJSON() ([]byte, error)

type ApplicationCommandOptionSubCommandGroup

type ApplicationCommandOptionSubCommandGroup struct {
	OptionBase
	// Options is an array of sub-commands for the group.
	//
	// Info:
	//  - Up to 25 sub-commands.
	Options []ApplicationCommandOptionSubCommand `json:"options,omitempty"`
}

ApplicationCommandOptionSubCommandGroup represents a sub-command group option.

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

func (*ApplicationCommandOptionSubCommandGroup) MarshalJSON

func (o *ApplicationCommandOptionSubCommandGroup) MarshalJSON() ([]byte, error)

type ApplicationCommandOptionType

type ApplicationCommandOptionType int

ApplicationCommandOptionType represents the type of an application command option.

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

const (
	// ApplicationCommandOptionTypeSubCommand is a sub-command option, representing a nested command.
	ApplicationCommandOptionTypeSubCommand ApplicationCommandOptionType = iota + 1

	// ApplicationCommandOptionTypeSubCommandGroup is a group of sub-commands.
	ApplicationCommandOptionTypeSubCommandGroup

	// ApplicationCommandOptionTypeString is a string option.
	ApplicationCommandOptionTypeString

	// ApplicationCommandOptionTypeInteger is an integer option, supporting values between -2^53 and 2^53.
	ApplicationCommandOptionTypeInteger

	// ApplicationCommandOptionTypeBool is a boolean option.
	ApplicationCommandOptionTypeBool

	// ApplicationCommandOptionTypeUser is a user option, referencing a Discord user.
	ApplicationCommandOptionTypeUser

	// ApplicationCommandOptionTypeChannel is a channel option, including all channel types and categories.
	ApplicationCommandOptionTypeChannel

	// ApplicationCommandOptionTypeRole is a role option, referencing a Discord role.
	ApplicationCommandOptionTypeRole

	// ApplicationCommandOptionTypeMentionable is a mentionable option, including users and roles.
	ApplicationCommandOptionTypeMentionable

	// ApplicationCommandOptionTypeFloat is a float option, supporting any double between -2^53 and 2^53.
	ApplicationCommandOptionTypeFloat

	// ApplicationCommandOptionTypeAttachment is an attachment option, referencing an uploaded file.
	ApplicationCommandOptionTypeAttachment
)

func (ApplicationCommandOptionType) Is

Is returns true if the option's Type matches the provided one.

type ApplicationCommandOptionUser

type ApplicationCommandOptionUser struct {
	OptionBase
	RequiredBase
}

ApplicationCommandOptionUser represents a user option.

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

func (*ApplicationCommandOptionUser) MarshalJSON

func (o *ApplicationCommandOptionUser) MarshalJSON() ([]byte, error)

type ApplicationCommandType

type ApplicationCommandType int

ApplicationCommandType represents the type of an application command.

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

const (
	// ApplicationCommandTypeChatInput is a text-based slash command that shows up when a user types "/".
	ApplicationCommandTypeChatInput ApplicationCommandType = 1 + iota

	// ApplicationCommandTypeUser is a UI-based command that shows up when you right-click or tap on a user.
	ApplicationCommandTypeUser

	// ApplicationCommandTypeMessage is a UI-based command that shows up when you right-click or tap on a message.
	ApplicationCommandTypeMessage

	// ApplicationCommandTypePrimaryEntryPoint is a UI-based command that represents the primary way to invoke an app's Activity.
	ApplicationCommandTypePrimaryEntryPoint
)

func (ApplicationCommandType) Is

Is returns true if the command's Type matches the provided one.

type ApplicationEntryPointCommand

type ApplicationEntryPointCommand struct {
	ApplicationCommandBase
	DescriptionConstraints
	// Handler determines whether the interaction is handled by the app's interactions handler or by Discord.
	//
	// Info:
	//  - Only applicable for commands with the EMBEDDED flag (i.e., applications with an Activity).
	Handler ApplicationCommandHandlerType `json:"handler"`
}

ApplicationEntryPointCommand represents a UI-based command that is the primary way to invoke an app's Activity.

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

func (*ApplicationEntryPointCommand) MarshalJSON

func (c *ApplicationEntryPointCommand) MarshalJSON() ([]byte, error)

type ApplicationEventWebhookStatus

type ApplicationEventWebhookStatus int

ApplicationEventWebhookStatus represent a Discord application application event webhook status.

Reference: https://discord.com/developers/docs/resources/application#application-object-application-event-webhook-status

const (
	// Webhook events are disabled by developer.
	ApplicationEventWebhookStatusDisabled ApplicationEventWebhookStatus = 1 + iota
	// Webhook events are enabled by developer.
	ApplicationEventWebhookStatusEnabled
	// Webhook events are disabled by Discord, usually due to inactivity.
	ApplicationEventWebhookStatusDisabledByDiscord
)

func (ApplicationEventWebhookStatus) Is

Is returns true if the app webhook event status matches the provided status.

type ApplicationFlags

type ApplicationFlags int

ApplicationFlags represent a Discord application flags.

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

func (ApplicationFlags) Has

func (f ApplicationFlags) Has(flags ...ApplicationFlags) bool

Has returns true if all provided flags are set.

type ApplicationInstallParams

type ApplicationInstallParams struct {
	// Scopes are scopes to add the application to the server with.
	Scopes []OAuth2Scope `json:"scopes"`

	// Permissions are permissions to request for the bot role
	Permissions Permissions `json:"permissions"`
}

ApplicationInstallParams represent a Discord application install params object.

Reference: https://discord.com/developers/docs/resources/application#install-params-object

type ApplicationIntegrationType

type ApplicationIntegrationType int

ApplicationIntegrationType represent where an app can be installed, also called its supported installation contexts.

See: https://discord.com/developers/docs/resources/application#installation-context

Reference: https://discord.com/developers/docs/resources/application#application-object-application-integration-types

const (
	// ApplicationIntegrationTypeGuildInstall if app is installable to servers.
	ApplicationIntegrationTypeGuildInstall ApplicationIntegrationType = iota
	// ApplicationIntegrationTypeUserInstall if app is installable to users.
	ApplicationIntegrationTypeUserInstall
)

type ApplicationIntegrationTypeConfiguration

type ApplicationIntegrationTypeConfiguration struct {
	// OAuth2InstallParams are the install params for each installation context's default in-app authorization link.
	OAuth2InstallParams *ApplicationInstallParams `json:"oauth2_install_params"`
}

ApplicationIntegrationTypeConfiguration object.

Reference: https://discord.com/developers/docs/resources/application#application-object-application-integration-type-configuration-object

type ApplicationMessageCommand

type ApplicationMessageCommand struct {
	ApplicationCommandBase
}

ApplicationMessageCommand represents a UI-based command that appears when right-clicking or tapping on a message.

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

func (*ApplicationMessageCommand) MarshalJSON

func (c *ApplicationMessageCommand) MarshalJSON() ([]byte, error)

type ApplicationUserCommand

type ApplicationUserCommand struct {
	ApplicationCommandBase
}

ApplicationUserCommand represents a UI-based command that appears when right-clicking or tapping on a user.

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

func (*ApplicationUserCommand) MarshalJSON

func (c *ApplicationUserCommand) MarshalJSON() ([]byte, error)

type Attachment

type Attachment struct {
	// ID is the unique Discord snowflake ID of this attachment.
	ID Snowflake `json:"id,omitempty"`

	// Filename is the name of the attached file.
	Filename string `json:"filename"`

	// Title is the optional title of the attachment.
	//
	// Optional
	//  - May be empty string if unset.
	Title string `json:"title,omitempty"`

	// Description is the optional description of the attachment (max 1024 characters).
	//
	// Optional:
	//  - May be empty string if unset.
	Description string `json:"description,omitempty"`

	// ContentType is the media type (MIME type) of the attachment.
	//
	// Optional:
	//  - May be empty string.
	ContentType string `json:"content_type,omitempty"`

	// Size is the size of the file in bytes.
	Size int `json:"size,omitempty"`

	// URL is the source URL of the attachment file.
	URL string `json:"url,omitempty"`

	// ProxyURL is a proxied URL of the attachment file.
	ProxyURL string `json:"proxy_url,omitempty"`

	// Height is the height of the image file, if applicable.
	//  - 0 if the attachment is not an image.
	Height int `json:"height,omitempty"`

	// Width is the width of the image file, if applicable.
	//  - 0 if the attachment is not an image.
	Width int `json:"width,omitempty"`

	// Ephemeral indicates whether this attachment is ephemeral.
	Ephemeral bool `json:"ephemeral,omitempty"`

	// Flags is a bitfield combining attachment flags.
	Flags AttachmentFlags `json:"flags,omitempty"`

	// DurationSec is the duration of the audio file in seconds, if applicable.
	//
	// Optional:
	// 	- Present only for audio or voice message attachments.
	DurationSec *float64 `json:"duration_secs,omitempty"`

	// Waveform is a base64 encoded byte array representing a sampled waveform.
	//
	// Optional:
	//  - present only for voice messages.
	Waveform *string `json:"waveform,omitempty"`
}

Attachment represents a Discord attachment object.

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

func (*Attachment) CreatedAt

func (a *Attachment) CreatedAt() time.Time

CreatedAt returns the time when this attachment is created.

func (*Attachment) Save

func (a *Attachment) Save(fileName, dir string) (string, error)

Save downloads the attachment from its URL and saves it to disk.

If fileName is not provided (empty string), it saves the file in the given directory using Attachment.Filename

Info:

  • The extension is replaced based on the Content-Type of the file.

Example:

err := attachment.Save("myfile", "./downloads")
if err != nil {
    // handle error
}

Returns:

  • string: full path to the downloaded file.
  • error: non-nil if any operation fails.

type AttachmentFlags

type AttachmentFlags int

AttachmentFlags represents bit flags for Discord attachment metadata.

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

const (
	// AttachmentFlagIsRemix means this attachment has been edited using the remix feature on mobile.
	AttachmentFlagIsRemix AttachmentFlags = 1 << 2
)

type AudioChannel

type AudioChannel interface {
	GuildChannel
	GuildMessageChannel
	GetBitrate() int
	GetUserLimit() int
	GetRtcRegion() string
}

AudioChannel represents a Discord channel that supports voice or audio functionality.

This interface is used for guild channels that have voice-related features, such as voice channels and stage voice channels. It provides access to audio-specific properties like bitrate, user limit, and RTC region.

Note:

  • DM channels (ChannelTypeDM) and Group DM channels (ChannelTypeGroupDM) support audio features like calls, streams, and webcams for users. However, for bots, these channels are treated as text channels, as bots cannot interact with their audio features (e.g., bots cannot initiate calls in them).

Use this interface when you want to handle audio channels generically without knowing the specific concrete type in advance.

You can convert (assert) it to a specific channel type using a type assertion or a type switch, as described in the official Go documentation:

Example usage:

var ch AudioChannel

// Using a type switch to handle specific channel types
switch c := ch.(type) {
case *VoiceChannel:
    fmt.Println("Voice channel bitrate:", c.GetBitrate())
    fmt.Println("Voice channel user limit:", c.GetUserLimit())
    fmt.Println("Voice channel RTC region:", c.GetRtcRegion())
case *StageVoiceChannel:
    fmt.Println("Stage voice channel bitrate:", c.GetBitrate())
    fmt.Println("Stage voice channel user limit:", c.GetUserLimit())
    fmt.Println("Stage voice channel RTC region:", c.GetRtcRegion())
}

// Using a type assertion to check a specific type
if voiceCh, ok := ch.(*VoiceChannel); ok {
    fmt.Println("Voice channel bitrate:", voiceCh.GetBitrate())
}

type AudioChannelFields

type AudioChannelFields struct {
	// Bitrate is the bitrate (in bits) of the voice channel.
	Bitrate int `json:"bitrate"`

	// UserLimit is the user limit of the voice channel.
	UserLimit int `json:"user_limit"`

	// RtcRegion is the voice region id for the voice channel. Automatic when set to empty string.
	RtcRegion string `json:"rtc_region"`
}

AudioChannelFields holds voice-related configuration fields.

func (*AudioChannelFields) GetBitrate

func (c *AudioChannelFields) GetBitrate() int

func (*AudioChannelFields) GetRtcRegion

func (c *AudioChannelFields) GetRtcRegion() string

func (*AudioChannelFields) GetUserLimit

func (c *AudioChannelFields) GetUserLimit() int

type AutoArchiveDuration

type AutoArchiveDuration int

AutoArchiveDuration represents the auto archive duration of a thread channel

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

const (
	AutoArchiveDuration1h  AutoArchiveDuration = 60
	AutoArchiveDuration24h AutoArchiveDuration = 1440
	AutoArchiveDuration3d  AutoArchiveDuration = 4320
	AutoArchiveDuration1w  AutoArchiveDuration = 10080
)

func (AutoArchiveDuration) Is

Is returns true if the thread's auto archive duration matches the provided auto archive duration.

type AutoCompleteInteraction

type AutoCompleteInteraction struct {
	InteractionFields
}

type AvatarDecorationData

type AvatarDecorationData struct {
	// Asset is the avatar decoration hash.
	Asset string `json:"asset"`

	// SkuID is the Discord snowflake ID of the avatar decoration SKU.
	SkuID Snowflake `json:"sku_id"`
}

AvatarDecorationData represents avatar decoration info.

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

type Ban

type Ban struct {
	// Reason is the reason for the ban.
	Reason string `json:"reason"`
	// User is the banned user.
	User User `json:"user"`
}

Ban represents a guild ban.

type BanOptions

type BanOptions struct {
	// DeleteMessageSeconds is the number of seconds to delete messages for (0-604800).
	// 0 deletes no messages, 604800 (7 days) is the maximum.
	DeleteMessageSeconds int `json:"delete_message_seconds,omitempty"`
}

BanOptions are options for banning a guild member.

type Base64Image

type Base64Image = string

Base64Image represents a base64-encoded image data URI string.

func NewImageFile

func NewImageFile(path string) (Base64Image, error)

NewImageFile reads an image file and returns its base64 data URI string.

Example output: "data:image/png;base64,<base64-encoded-bytes>"

type BitField

type BitField interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 |
		~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64
}

BitField is a type constraint that matches any integer type. It represents a value that can be used as a bitfield to store multiple boolean flags using bitwise operations.

type BulkBanOptions

type BulkBanOptions struct {
	// UserIDs is a list of user ids to ban (max 200).
	UserIDs []Snowflake `json:"user_ids"`
	// DeleteMessageSeconds is the number of seconds to delete messages for (0-604800).
	DeleteMessageSeconds int `json:"delete_message_seconds,omitempty"`
}

BulkBanOptions are options for bulk banning users.

type BulkBanResponse

type BulkBanResponse struct {
	// BannedUsers is a list of user ids that were banned.
	BannedUsers []Snowflake `json:"banned_users"`
	// FailedUsers is a list of user ids that could not be banned.
	FailedUsers []Snowflake `json:"failed_users"`
}

BulkBanResponse is the response from a bulk ban request.

type ButtonBuilder

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

ButtonBuilder helps build a ButtonComponent with chainable methods.

func NewButtonBuilder

func NewButtonBuilder() *ButtonBuilder

NewButtonBuilder creates a new ButtonBuilder instance.

func (*ButtonBuilder) Build

func (b *ButtonBuilder) Build() *ButtonComponent

Build returns the final ButtonComponent.

func (*ButtonBuilder) Disable

func (b *ButtonBuilder) Disable() *ButtonBuilder

Disable disables the button.

func (*ButtonBuilder) Enable

func (b *ButtonBuilder) Enable() *ButtonBuilder

Enable enables the button.

func (*ButtonBuilder) SetCustomID

func (b *ButtonBuilder) SetCustomID(customID string) *ButtonBuilder

SetCustomID sets the button custom ID.

func (*ButtonBuilder) SetDisabled

func (b *ButtonBuilder) SetDisabled(disabled bool) *ButtonBuilder

SetDisabled sets the button disabled state.

func (*ButtonBuilder) SetLabel

func (b *ButtonBuilder) SetLabel(label string) *ButtonBuilder

SetLabel sets the button label.

func (*ButtonBuilder) SetSkuID

func (b *ButtonBuilder) SetSkuID(skuID Snowflake) *ButtonBuilder

SetSkuID sets the button Sku ID.

func (*ButtonBuilder) SetStyle

func (b *ButtonBuilder) SetStyle(style ButtonStyle) *ButtonBuilder

SetStyle sets the button style.

func (*ButtonBuilder) SetURL

func (b *ButtonBuilder) SetURL(url string) *ButtonBuilder

SetURL sets the button URL.

type ButtonComponent

type ButtonComponent struct {
	InteractiveComponentFields

	// Style is the button style, determining its appearance and behavior.
	Style ButtonStyle `json:"style"`

	// Label is the text that appears on the button.
	//
	// Note:
	//   - Max 80 characters.
	//   - Cannot be set for Premium buttons.
	Label string `json:"label,omitempty"`

	// Emoji is the emoji that appears on the button.
	//
	// Note:
	//   - Cannot be set for Premium buttons.
	Emoji *PartialEmoji `json:"emoji,omitempty"`

	// SkuID is the identifier for a purchasable SKU, used only for Premium buttons.
	//
	// Note:
	//   - Required for Premium buttons.
	//   - Cannot be set for non-Premium buttons.
	SkuID Snowflake `json:"sku_id,omitempty"`

	// URL is the URL for Link buttons.
	//
	// Note:
	//   - Max 512 characters.
	//   - Required for Link buttons.
	//   - Cannot be set for non-Link buttons.
	URL string `json:"url,omitempty"`

	// Disabled is whether the button is disabled.
	//
	// Note:
	//   - Defaults to false.
	Disabled bool `json:"disabled,omitempty"`
}

ButtonComponent is an interactive component used in messages, creating clickable elements that users can interact with.

Buttons must be placed inside an ActionRowComponent or a SectionComponent's accessory field. Non-link and non-premium buttons (Primary, Secondary, Success, Danger) send an interaction to the app when clicked. Link and Premium buttons do not send interactions.

Note:

  • Non-link and non-premium buttons require a custom_id and cannot have a url or sku_id.
  • Link buttons require a url and cannot have a custom_id.
  • Premium buttons require a sku_id and cannot have a custom_id, label, url, or emoji.

Reference: https://discord.com/developers/docs/interactions/message-components#button-object

func (*ButtonComponent) MarshalJSON

func (c *ButtonComponent) MarshalJSON() ([]byte, error)

type ButtonStyle

type ButtonStyle int

ButtonStyle represents different styles for interactive buttons, each with specific actions and required fields.

The style determines the button's appearance and behavior, such as triggering interactions or navigating to a URL. Non-link and non-premium buttons (Primary, Secondary, Success, Danger) require a custom_id and send interactions. Link buttons require a url, cannot have a custom_id, and do not send interactions. Premium buttons require a sku_id, cannot have a custom_id, label, url, or emoji, and do not send interactions.

Reference: https://discord.com/developers/docs/interactions/message-components#button-object-button-styles

const (
	// ButtonStylePrimary is the most important or recommended action in a group of options.
	//
	// Required Field: ButtonComponent.CustomID
	// Note: Sends an interaction when clicked.
	ButtonStylePrimary ButtonStyle = iota + 1

	// ButtonStyleSecondary represents alternative or supporting actions.
	//
	// Required Field: ButtonComponent.CustomID
	// Note: Sends an interaction when clicked.
	ButtonStyleSecondary

	// ButtonStyleSuccess represents positive confirmation or completion actions.
	//
	// Required Field: ButtonComponent.CustomID
	// Note: Sends an interaction when clicked.
	ButtonStyleSuccess

	// ButtonStyleDanger represents an action with irreversible consequences.
	//
	// Required Field: ButtonComponent.CustomID
	// Note: Sends an interaction when clicked.
	ButtonStyleDanger

	// ButtonStyleLink navigates to a URL.
	//
	// Required Field: ButtonComponent.URL
	// Note: Does not send an interaction when clicked.
	ButtonStyleLink

	// ButtonStylePremium represents a purchase action.
	//
	// Required Field: ButtonComponent.SkuID
	// Note: Does not send an interaction when clicked.
	ButtonStylePremium
)

func (ButtonStyle) Is

func (s ButtonStyle) Is(style ButtonStyle) bool

Is returns true if the button style matches the provided one.

type CacheFlags

type CacheFlags int
const (
	CacheFlagUsers CacheFlags = 1 << iota
	CacheFlagGuilds
	CacheFlagMembers
	CacheFlagThreadMembers
	CacheFlagMessages
	CacheFlagChannels
	CacheFlagRoles
	CacheFlagVoiceStates

	CacheFlagsNone CacheFlags = 0

	CacheFlagsAll = CacheFlagUsers | CacheFlagGuilds | CacheFlagMembers | CacheFlagThreadMembers |
		CacheFlagMessages | CacheFlagChannels | CacheFlagRoles | CacheFlagVoiceStates
)

func (CacheFlags) Has

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

type CacheManager

type CacheManager interface {
	Flags() CacheFlags
	SetFlags(flags ...CacheFlags)

	GetUser(userID Snowflake) (User, bool)
	GetGuild(guildID Snowflake) (Guild, bool)
	GetMember(guildID, userID Snowflake) (Member, bool)
	GetChannel(channelID Snowflake) (Channel, bool)
	GetMessage(messageID Snowflake) (Message, bool)
	GetVoiceState(guildID, userID Snowflake) (VoiceState, bool)
	GetGuildChannels(guildID Snowflake) (map[Snowflake]GuildChannel, bool)
	GetGuildMembers(guildID Snowflake) (map[Snowflake]Member, bool)
	GetGuildVoiceStates(guildID Snowflake) (map[Snowflake]VoiceState, bool)
	GetGuildRoles(guildID Snowflake) (map[Snowflake]Role, bool)

	HasUser(userID Snowflake) bool
	HasGuild(guildID Snowflake) bool
	HasMember(guildID, userID Snowflake) bool
	HasChannel(channelID Snowflake) bool
	HasMessage(messageID Snowflake) bool
	HasVoiceState(guildID, userID Snowflake) bool
	HasGuildChannels(guildID Snowflake) bool
	HasGuildMembers(guildID Snowflake) bool
	HasGuildVoiceStates(guildID Snowflake) bool
	HasGuildRoles(guildID Snowflake) bool

	CountUsers() int
	CountGuilds() int
	CountMembers() int
	CountChannels() int
	CountMessages() int
	CountVoiceStates() int
	CountRoles() int
	CountGuildChannels(guildID Snowflake) int
	CountGuildMembers(guildID Snowflake) int
	CountGuildRoles(guildID Snowflake) int

	PutUser(user User)
	PutGuild(guild Guild)
	PutMember(member Member)
	PutChannel(channel Channel)
	PutMessage(message Message)
	PutVoiceState(voiceState VoiceState)
	PutRole(role Role)

	DelUser(userID Snowflake) bool
	DelGuild(guildID Snowflake) bool
	DelMember(guildID, userID Snowflake) bool
	DelChannel(channelID Snowflake) bool
	DelMessage(messageID Snowflake) bool
	DelVoiceState(guildID, userID Snowflake) bool
	DelGuildChannels(guildID Snowflake) bool
	DelGuildMembers(guildID Snowflake) bool
	DelRole(guildID, roleID Snowflake) bool
}

func NewDefaultCache

func NewDefaultCache(flags CacheFlags) CacheManager

type CategorizedChannel

type CategorizedChannel interface {
	NamedChannel
	GetParentID() Snowflake
}

CategorizedChannel represents a Discord channel that can be placed under a parent category channel within a guild.

This interface is used for guild channels that can be organized under a category, such as text channels, voice channels, announcement channels, stage voice channels, forum channels, media channels, and thread channels.

Use this interface when you want to handle channels generically by their parent category without knowing the specific concrete type in advance.

You can convert (assert) it to a specific channel type using a type assertion or a type switch, as described in the official Go documentation:

Example usage:

var ch CategorizedChannel

// Using a type switch to handle specific channel types
switch c := ch.(type) {
case *TextChannel:
    fmt.Println("Text channel parent ID:", c.GetParentID())
case *VoiceChannel:
    fmt.Println("Voice channel parent ID:", c.GetParentID())
case *ThreadChannel:
    fmt.Println("Thread channel parent ID:", c.GetParentID())
default:
    fmt.Println("Other categorized channel type:", c.GetType())
}

// Using a type assertion to check a specific type
if textCh, ok := ch.(*TextChannel); ok {
    fmt.Println("Text channel parent ID:", textCh.GetParentID())
}

type CategorizedChannelFields

type CategorizedChannelFields struct {
	// ParentID is the id of the parent category for this channel.
	//
	// Info:
	//  - Each parent category can contain up to 50 channels.
	//
	// Optional:
	//  - May be equal 0 if the channel is not in a category.
	ParentID Snowflake `json:"parent_id"`
}

CategorizedChannelFields holds the parent category field for categorized guild channels.

func (*CategorizedChannelFields) GetParentID

func (c *CategorizedChannelFields) GetParentID() Snowflake

type CategoryChannel

type CategoryChannel struct {
	GuildChannelFields
}

CategoryChannel represents a guild category channel.

func (*CategoryChannel) MarshalJSON

func (c *CategoryChannel) MarshalJSON() ([]byte, error)

type Channel

type Channel interface {
	json.Marshaler
	GetID() Snowflake
	GetType() ChannelType
	CreatedAt() time.Time
	Mention() string
}

Channel is the interface representing a Discord channel.

This interface can represent any type of channel returned by Discord, including text channels, voice channels, thread channels, forum channels, etc.

Use this interface when you want to handle channels generically without knowing the specific concrete type in advance.

You can convert (assert) it to a specific channel type using a type assertion or a type switch, as described in the official Go documentation:

Example usage:

var myChannel Channel

switch c := ch.(type) {
case *TextChannel:
    fmt.Println("Text channel name:", c.Name)
case *VoiceChannel:
    fmt.Println("Voice channel bitrate:", c.Bitrate)
case *ForumChannel:
    fmt.Println("Forum channel tags:", c.AvailableTags)
default:
    fmt.Println("Other channel type:", c.GetType())
}

You can also use an if-condition to check a specific type:

if textCh, ok := ch.(*TextChannel); ok {
    fmt.Println("Text channel:", textCh.Name)
}

func UnmarshalChannel

func UnmarshalChannel(buf []byte) (Channel, error)

Helper func to Unmarshal any channel type to a Channel interface.

type ChannelConstraints

type ChannelConstraints struct {
	// ChannelTypes is an array of channel types that the option is restricted to.
	//
	// Info:
	//  - If not specified, includes all channel types and categories.
	ChannelTypes []ChannelType `json:"channel_types,omitempty"`
}

ChannelConstraints contains constraints for channel options.

type ChannelCreateOptions

type ChannelCreateOptions struct {
	// Name is the channel's name (1-100 characters).
	//
	// Note:
	//  - This field is required for every channel.
	//
	// Applies to All Channels.
	Name string `json:"name"`

	// Type specifies the type of channel to create.
	//
	// Note:
	//  - Defaults to ChannelTypeGuildText if unset.
	//  - Valid values include ChannelTypeGuildText, ChannelTypeGuildVoice, ChannelTypeGuildForum, etc.
	//
	// Applies to All Channels.
	Type ChannelType `json:"type,omitempty"`

	// Topic is a description of the channel (0-1024 characters).
	//
	// Note:
	//  - This field is optional.
	//
	// Applies to Channels of Type: Text, Announcement, Forum, Media.
	Topic string `json:"topic,omitempty"`

	// Bitrate sets the audio quality for voice or stage channels (in bits, minimum 8000).
	//
	// Note:
	//  - This field is ignored for non-voice channels.
	//
	// Applies to Channels of Type: Voice, Stage.
	Bitrate int `json:"bitrate,omitempty"`

	// UserLimit caps the number of users in a voice or stage channel (0 for unlimited, 1-99 for a limit).
	//
	// Note:
	//  - Set to 0 to allow unlimited users.
	//
	// Applies to Channels of Type: Voice, Stage.
	UserLimit *int `json:"user_limit,omitempty"`

	// RateLimitPerUser sets the seconds a user must wait before sending another message (0-21600).
	//
	// Note:
	//  - Bots and users with manage_messages or manage_channel permissions are unaffected.
	//
	// Applies to Channels of Type: Text, Voice, Stage, Forum, Media.
	RateLimitPerUser *int `json:"rate_limit_per_user,omitempty"`

	// Position determines the channel’s position in the server’s channel list (lower numbers appear higher).
	//
	// Note:
	//  - Channels with the same position are sorted by their internal ID.
	//
	// Applies to All Channels.
	Position int `json:"position,omitempty"`

	// PermissionOverwrites defines custom permissions for specific roles or users.
	//
	// Note:
	//  - This field requires valid overwrite objects.
	//
	// Applies to All Channels.
	PermissionOverwrites []PermissionOverwrite `json:"permission_overwrites,omitempty"`

	// ParentID is the ID of the category to nest the channel under.
	//
	// Note:
	//  - This field is ignored for category channels.
	//
	// Applies to Channels of Type: Text, Voice, Announcement, Stage, Forum, Media.
	ParentID Snowflake `json:"parent_id,omitempty"`

	// Nsfw marks the channel as Not Safe For Work, restricting it to 18+ users.
	//
	// Note:
	//  - Set to true to enable the age restriction.
	//
	// Applies to Channels of Type: Text, Voice, Announcement, Stage, Forum.
	Nsfw *bool `json:"nsfw,omitempty"`

	// VideoQualityMode sets the camera video quality for voice or stage channels.
	//
	// Note:
	//  - Valid options are defined in VideoQualityModes.
	//
	// Applies to Channels of Type: Voice, Stage.
	VideoQualityMode VideoQualityModes `json:"video_quality_mode,omitempty"`

	// DefaultAutoArchiveDuration sets the default time (in minutes) before threads are archived.
	//
	// Note:
	//  - Valid values are 60, 1440, 4320, or 10080.
	//
	// Applies to Channels of Type: Text, Announcement, Forum, Media.
	DefaultAutoArchiveDuration AutoArchiveDuration `json:"default_auto_archive_duration,omitempty"`

	// DefaultReactionEmoji is the default emoji for the add reaction button on threads.
	//
	// Note:
	//  - Set to a valid emoji object or nil if not needed.
	//
	// Applies to Channels of Type: Forum, Media.
	DefaultReactionEmoji *DefaultReactionEmoji `json:"default_reaction_emoji,omitempty"`

	// AvailableTags lists tags that can be applied to threads for organization.
	//
	// Note:
	//  - This field defines tags users can select for threads.
	//
	// Applies to Channels of Type: Forum, Media.
	AvailableTags []ForumTag `json:"available_tags,omitempty"`

	// DefaultSortOrder sets how threads are sorted by default.
	//
	// Note:
	//  - Valid options are defined in ForumPostsSortOrder.
	//
	// Applies to Channels of Type: Forum, Media.
	DefaultSortOrder ForumPostsSortOrder `json:"default_sort_order,omitempty"`

	// DefaultForumLayout sets the default view for forum posts.
	//
	// Note:
	//  - Valid options are defined in ForumLayout.
	//
	// Applies to Channels of Type: Forum.
	DefaultForumLayout ForumLayout `json:"default_forum_layout,omitempty"`

	// DefaultThreadRateLimitPerUser sets the default slow mode for messages in new threads.
	//
	// Note:
	//  - This value is copied to new threads at creation and does not update live.
	//
	// Applies to Channels of Type: Text, Announcement, Forum, Media.
	DefaultThreadRateLimitPerUser int `json:"default_thread_rate_limit_per_user,omitempty"`

	// Reason specifies the audit log reason for creating the channel.
	Reason string `json:"-"`
}

ChannelCreateOptions defines the configuration for creating a new Discord guild channel.

Note:

  • This struct configures properties for a new channel, such as text, voice, or forum.
  • Only set fields applicable to the channel type to avoid errors.

Reference: https://discord.com/developers/docs/resources/guild#create-guild-channel-json-params

type ChannelEditOptions

type ChannelEditOptions struct {
	// Name is the channel name (1-100 characters).
	Name string `json:"name,omitempty"`
	// Type is the type of channel (only conversion between text and announcement is supported).
	Type ChannelType `json:"type,omitempty"`
	// Position is the position of the channel in the left-hand listing.
	Position *int `json:"position,omitempty"`
	// Topic is the channel topic (0-1024 characters for text/announcement, 0-4096 for forum/media).
	Topic string `json:"topic,omitempty"`
	// NSFW indicates whether the channel is nsfw.
	NSFW *bool `json:"nsfw,omitempty"`
	// RateLimitPerUser is the slowmode rate limit in seconds (0-21600).
	RateLimitPerUser *int `json:"rate_limit_per_user,omitempty"`
	// Bitrate is the bitrate for voice channels (8000-96000 or up to 384000 for VIP servers).
	Bitrate *int `json:"bitrate,omitempty"`
	// UserLimit is the user limit for voice channels (0-99, 0 is unlimited).
	UserLimit *int `json:"user_limit,omitempty"`
	// PermissionOverwrites are the channel permission overwrites.
	PermissionOverwrites []PermissionOverwrite `json:"permission_overwrites,omitempty"`
	// ParentID is the id of the parent category for a channel.
	ParentID *Snowflake `json:"parent_id,omitempty"`
	// RTCRegion is the voice region id for the voice channel, automatic when set to nil.
	RTCRegion *string `json:"rtc_region,omitempty"`
	// VideoQualityMode is the camera video quality mode of the voice channel.
	VideoQualityMode *int `json:"video_quality_mode,omitempty"`
	// DefaultAutoArchiveDuration is the default duration (in minutes) for newly created threads.
	DefaultAutoArchiveDuration *int `json:"default_auto_archive_duration,omitempty"`
	// Flags are channel flags combined as a bitfield.
	Flags *ChannelFlags `json:"flags,omitempty"`
	// AvailableTags are tags that can be used in a forum or media channel (max 20).
	AvailableTags []ForumTag `json:"available_tags,omitempty"`
	// DefaultReactionEmoji is the emoji to show in the add reaction button on a thread.
	DefaultReactionEmoji *DefaultReactionEmoji `json:"default_reaction_emoji,omitempty"`
	// DefaultThreadRateLimitPerUser is the default slowmode for threads.
	DefaultThreadRateLimitPerUser *int `json:"default_thread_rate_limit_per_user,omitempty"`
	// DefaultSortOrder is the default sort order type for forum posts.
	DefaultSortOrder *int `json:"default_sort_order,omitempty"`
	// DefaultForumLayout is the default forum layout view for forum channels.
	DefaultForumLayout *int `json:"default_forum_layout,omitempty"`
}

ChannelEditOptions are options for editing a channel.

type ChannelFields

type ChannelFields struct {
	// ID is the unique Discord snowflake ID of the channel.
	ID Snowflake `json:"id"`

	// Type is the type of the channel.
	Type ChannelType `json:"type"`
}

ChannelFields contains only fields present in all channel types.

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

func (*ChannelFields) CreatedAt

func (c *ChannelFields) CreatedAt() time.Time

func (*ChannelFields) GetID

func (c *ChannelFields) GetID() Snowflake

func (*ChannelFields) GetType

func (c *ChannelFields) GetType() ChannelType

func (*ChannelFields) Mention

func (c *ChannelFields) Mention() string

Mention returns a Discord mention string for the channel.

Example output: "<#123456789012345678>"

type ChannelFlags

type ChannelFlags int

ChannelFlags represents Discord channel flags combined as a bitfield.

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

const (
	// ChannelFlagPinned indicates that this thread is pinned to the top of its parent
	// GUILD_FORUM or GUILD_MEDIA channel.
	//
	// Applicable only to threads within forum or media channels.
	ChannelFlagPinned ChannelFlags = 1 << 1

	// ChannelFlagRequireTag indicates whether a tag is required to be specified when
	// creating a thread in a GUILD_FORUM or GUILD_MEDIA channel.
	//
	// Tags are specified in the AppliedTags field.
	ChannelFlagRequireTag ChannelFlags = 1 << 4

	// ChannelFlagHideMediaDownloadOptions, when set, hides the embedded media download options
	// for media channel attachments.
	//
	// Available only for media channels.
	ChannelFlagHideMediaDownloadOptions ChannelFlags = 1 << 15
)

func (ChannelFlags) Has

func (f ChannelFlags) Has(flags ...ChannelFlags) bool

Has returns true if all provided flags are set.

type ChannelSelectMenuComponent

type ChannelSelectMenuComponent struct {
	InteractiveComponentFields

	// ChannelTypes is an array of channel types to include in the select menu.
	//
	// Note:
	//   - Filters the channels shown in the select menu.
	ChannelTypes []ChannelType `json:"channel_types,omitempty"`

	// Placeholder is the custom placeholder text displayed when no channel is selected.
	//
	// Note:
	//   - Maximum of 150 characters.
	Placeholder string `json:"placeholder,omitempty"`

	// DefaultValues is an array of default channels for the select menu.
	//
	// Note:
	//   - Number of default values must be within the range defined by MinValues and MaxValues.
	DefaultValues []SelectDefaultValue `json:"default_values,omitempty"`

	// MinValues is the minimum number of channels that must be selected.
	//
	// Note:
	//   - Defaults to 1.
	//   - Minimum 0, maximum 25.
	MinValues *int `json:"min_values,omitempty"`

	// MaxValues is the maximum number of channels that can be selected.
	//
	// Note:
	//   - Defaults to 1.
	//   - Maximum 25.
	MaxValues int `json:"max_values,omitempty"`

	// Disabled specifies whether the select menu is disabled in a message.
	//
	// Note:
	//   - Defaults to false.
	Disabled bool `json:"disabled,omitempty"`
}

ChannelSelectMenuComponent represents a channel select menu, an interactive component allowing users to select one or more channels in a message. Options are automatically populated based on the server's available channels and can be filtered by channel types.

It supports both single-select and multi-select behavior, sending an interaction to the application when a user makes their selection(s). ChannelSelectMenuComponent must be placed inside an ActionRowComponent and is only available in messages. An ActionRowComponent containing a ChannelSelectMenuComponent cannot include buttons.

Note:

  • Maximum of 25 selections can be allowed (via MaxValues).
  • Options are auto-populated by Discord based on server channels, filterable by ChannelTypes.

Reference: https://discord.com/developers/docs/interactions/message-components#select-menu-object-select-menu-structure

func (*ChannelSelectMenuComponent) MarshalJSON

func (c *ChannelSelectMenuComponent) MarshalJSON() ([]byte, error)

type ChannelType

type ChannelType int

ChannelType represents Discord channel types.

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

const (
	// GuildText is a text channel within a server.
	ChannelTypeGuildText ChannelType = 0

	// DM is a direct message between users.
	ChannelTypeDM ChannelType = 1

	// GuildVoice is a voice channel within a server.
	ChannelTypeGuildVoice ChannelType = 2

	// GroupDM is a direct message between multiple users.
	ChannelTypeGroupDM ChannelType = 3

	// GuildCategory is an organizational category that contains up to 50 channels.
	ChannelTypeGuildCategory ChannelType = 4

	// GuildAnnouncement is a channel that users can follow and crosspost into their own server (formerly news channels).
	ChannelTypeGuildAnnouncement ChannelType = 5

	// AnnouncementThread is a temporary sub-channel within a GuildAnnouncement channel.
	ChannelTypeAnnouncementThread ChannelType = 10

	// PublicThread is a temporary sub-channel within a GuildText or GuildForum channel.
	ChannelTypePublicThread ChannelType = 11

	// PrivateThread is a temporary sub-channel within a GuildText channel that is only viewable by those invited and those with the MANAGE_THREADS permission.
	ChannelTypePrivateThread ChannelType = 12

	// GuildStageVoice is a voice channel for hosting events with an audience.
	ChannelTypeGuildStageVoice ChannelType = 13

	// GuildDirectory is the channel in a hub containing the listed servers.
	ChannelTypeGuildDirectory ChannelType = 14

	// GuildForum is a channel that can only contain threads.
	ChannelTypeGuildForum ChannelType = 15

	// GuildMedia is a channel that can only contain threads, similar to GuildForum channels.
	ChannelTypeGuildMedia ChannelType = 16
)

func (ChannelType) Is

func (t ChannelType) Is(channelType ChannelType) bool

Is returns true if the channel's Type matches the provided one.

type ChatInputCommand

type ChatInputCommand struct {
	ApplicationCommandBase
	DescriptionConstraints
	// Options is an array of parameters for the command.
	//
	// Info:
	//  - Maximum of 25 options.
	Options []ApplicationCommandOption `json:"options"`
}

ChatInputCommand represents a slash command.

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

func (*ChatInputCommand) MarshalJSON

func (c *ChatInputCommand) MarshalJSON() ([]byte, error)

func (*ChatInputCommand) UnmarshalJSON

func (c *ChatInputCommand) UnmarshalJSON(buf []byte) error

type ChatInputCommandInteraction

type ChatInputCommandInteraction struct {
	ApplicationCommandInteractionFields

	// Data contains the payload of the interaction specific to chat input commands.
	Data ChatInputCommandInteractionData `json:"data"`
}

ChatInputCommandInteraction represents an interaction triggered by a chat input (slash) command.

Reference: https://discord.com/developers/docs/interactions/application-commands

type ChatInputCommandInteractionData

type ChatInputCommandInteractionData struct {
	ApplicationCommandInteractionDataFields

	// Resolved contains the resolved objects referenced by this command.
	Resolved ChatInputCommandResolvedInteractionData `json:"resolved"`

	// Options contains the parameters and values provided by the user for this command.
	Options []ChatInputInteractionCommandOption `json:"options"`
}

ChatInputCommandInteractionData represents the data payload for a chat input command interaction.

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

type ChatInputCommandResolvedInteractionData

type ChatInputCommandResolvedInteractionData struct {
	// Users is a map of user IDs to User objects referenced by the command.
	Users map[Snowflake]User `json:"users"`

	// Members is a map of user IDs to partial Member objects for the guild.
	Members map[Snowflake]ResolvedMember `json:"members"`

	// Roles is a map of role IDs to Role objects referenced by the command.
	Roles map[Snowflake]Role `json:"roles"`

	// Channels is a map of channel IDs to partial Channel objects referenced by the command.
	Channels map[Snowflake]ResolvedChannel `json:"channels"`

	// Attachments is a map of attachment IDs to Attachment objects referenced by the command.
	Attachments map[Snowflake]Attachment `json:"attachments"`
}

ChatInputCommandResolvedInteractionData represents the resolved data inside Interaction.Data.Resolved for chat input command interactions. This includes users, members, roles, channels, and attachments referenced by the command.

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

type ChatInputInteractionCommandOption

type ChatInputInteractionCommandOption struct {
	// Name is the name of the option as defined in the command.
	Name string `json:"name"`

	// Type is the type of the option (string, integer, boolean, etc.).
	Type ApplicationCommandOptionType `json:"type"`

	// Value is the raw JSON value provided by the user for this option.
	//
	// Note: It's recommended to use the helper methods provided
	// (String, Int, Float, Bool, Snowflake) to extract the value.
	// These methods will panic if called on a type that doesn't match the
	// expected option type, so you must be sure of the type or check the
	// Type field before calling. For example, if Type is
	// ApplicationCommandOptionTypeString, calling String() is safe.
	Value json.RawMessage `json:"value"`
}

ChatInputInteractionCommandOption represents a single option provided by a user when invoking a chat input command (slash command).

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

func (*ChatInputInteractionCommandOption) Bool

Bool returns the option's value as a boolean.

Panics if the underlying JSON value cannot be unmarshaled into a bool. Make sure the option's Type is ApplicationCommandOptionTypeBoolean before calling.

func (*ChatInputInteractionCommandOption) Float

Float returns the option's value as a float64.

Panics if the underlying JSON value cannot be unmarshaled into a float64. Make sure the option's Type is ApplicationCommandOptionTypeNumber before calling.

func (*ChatInputInteractionCommandOption) Int

Int returns the option's value as an int.

Panics if the underlying JSON value cannot be unmarshaled into an int. Make sure the option's Type is ApplicationCommandOptionTypeInteger before calling.

func (*ChatInputInteractionCommandOption) Snowflake

Snowflake returns the option's value as a Snowflake.

Panics if the underlying JSON value cannot be unmarshaled into a Snowflake. Make sure the option's Type corresponds to an ID-based option before calling.

func (*ChatInputInteractionCommandOption) String

String returns the option's value as a string.

Panics if the underlying JSON value cannot be unmarshaled into a string. Make sure the option's Type is ApplicationCommandOptionTypeString before calling.

type ChoiceBase

type ChoiceBase struct {
	// Autocomplete indicates whether autocomplete interactions are enabled for this option.
	//
	// Info:
	//  - May not be set to true if choices are present.
	//  - Options using autocomplete are not confined to only use choices given by the application.
	Autocomplete bool `json:"autocomplete,omitempty"`
}

ChoiceBase contains the autocomplete field for choice-based options.

type ChoiceFieldsFloat

type ChoiceFieldsFloat struct {
	// Choices is an array of choices for the user to pick from.
	//
	// Info:
	//  - Maximum of 25 choices.
	Choices []ApplicationCommandOptionChoiceFloat `json:"choices,omitempty"`
}

ChoiceFieldsFloat contains fields for float choice options.

type ChoiceFieldsInteger

type ChoiceFieldsInteger struct {
	// Choices is an array of choices for the user to pick from.
	//
	// Info:
	//  - Maximum of 25 choices.
	Choices []ApplicationCommandOptionChoiceInteger `json:"choices,omitempty"`
}

ChoiceFieldsInteger contains fields for integer choice options.

type ChoiceFieldsString

type ChoiceFieldsString struct {
	// Choices is an array of choices for the user to pick from.
	//
	// Info:
	//  - Maximum of 25 choices.
	Choices []ApplicationCommandOptionChoiceString `json:"choices,omitempty"`
}

ChoiceFieldsString contains fields for string choice options.

type ChoiceOptionBase

type ChoiceOptionBase struct {
	// Name is the name of the choice.
	//
	// Info:
	//  - Must be 1-100 characters.
	Name string `json:"name"`

	// NameLocalizations is a localization dictionary for the choice name.
	//
	// Info:
	//  - Keys are available locales.
	//  - Values follow the same restrictions as Name (1-100 characters).
	NameLocalizations map[Locale]string `json:"name_localizations,omitempty"`
}

ChoiceOptionBase contains fields common to all choice option types.

type Client

type Client struct {
	Logger Logger // logger used throughout the client

	CacheManager // CacheManager for caching discord entities
	// contains filtered or unexported fields
}

Client manages your Discord connection at a high level, grouping multiple shards together.

It provides:

  • Central configuration for your bot token, intents, and logger.
  • REST API access via restApi.
  • Event dispatching via dispatcher.
  • Shard management for scalable Gateway connections.

Create a Client using goda.New() with desired options, then call Start().

func New

func New(ctx context.Context, options ...clientOption) *Client

New creates a new Client instance with provided options.

Example:

y := goda.New(
    goda.WithToken("my_bot_token"),
    goda.WithIntents(GatewayIntentGuilds, GatewayIntentMessageContent),
    goda.WithLogger(myLogger),
)

Defaults:

  • Logger: stdout logger at Info level.
  • Intents: GatewayIntentGuilds | GatewayIntentGuildMessages | GatewayIntentGuildMembers

func (Client) AddMemberRole

func (r Client) AddMemberRole(guildID, userID, roleID Snowflake, reason string) error

AddMemberRole adds a role to a guild member. Requires MANAGE_ROLES permission.

Usage example:

err := client.AddMemberRole(guildID, userID, roleID, "Assigning role")

func (Client) BanMember

func (r Client) BanMember(guildID, userID Snowflake, opts BanOptions, reason string) error

BanMember bans a user from a guild, and optionally deletes previous messages sent by them. Requires BAN_MEMBERS permission.

Usage example:

err := client.BanMember(guildID, userID, BanOptions{
    DeleteMessageSeconds: 86400, // Delete 1 day of messages
}, "Rule violation")

func (Client) BulkBanMembers

func (r Client) BulkBanMembers(guildID Snowflake, opts BulkBanOptions, reason string) (BulkBanResponse, error)

BulkBanMembers bans up to 200 users from a guild. Requires BAN_MEMBERS and MANAGE_GUILD permissions.

Usage example:

response, err := client.BulkBanMembers(guildID, BulkBanOptions{
    UserIDs: []Snowflake{userID1, userID2, userID3},
    DeleteMessageSeconds: 86400,
}, "Mass rule violation")

func (Client) BulkDeleteMessages

func (r Client) BulkDeleteMessages(channelID Snowflake, messageIDs []Snowflake, reason string) error

BulkDeleteMessages deletes multiple messages in a single request. This endpoint can only be used on messages that are less than 2 weeks old. Between 2 and 100 messages may be deleted at once.

Usage example:

err := client.BulkDeleteMessages(channelID, messageIDs, "Cleanup")

func (Client) BulkOverwriteGlobalCommands

func (r Client) BulkOverwriteGlobalCommands(applicationID Snowflake, commands []ApplicationCommand) ([]ApplicationCommand, error)

BulkOverwriteGlobalCommands overwrites all global application commands. This will replace all existing global commands.

Usage example:

commands, err := client.BulkOverwriteGlobalCommands(applicationID, []ApplicationCommand{
    {Name: "ping", Description: "Pong!"},
    {Name: "help", Description: "Get help"},
})

func (Client) BulkOverwriteGuildCommands

func (r Client) BulkOverwriteGuildCommands(applicationID, guildID Snowflake, commands []ApplicationCommand) ([]ApplicationCommand, error)

BulkOverwriteGuildCommands overwrites all guild-specific application commands.

Usage example:

commands, err := client.BulkOverwriteGuildCommands(applicationID, guildID, []ApplicationCommand{
    {Name: "admin", Description: "Admin command"},
})

func (Client) CreateChannelInvite

func (r Client) CreateChannelInvite(channelID Snowflake, opts CreateInviteOptions, reason string) (Invite, error)

CreateChannelInvite creates a new invite for a channel. Requires CREATE_INSTANT_INVITE permission.

Usage example:

invite, err := client.CreateChannelInvite(channelID, CreateInviteOptions{
    MaxAge: 3600,
    MaxUses: 10,
}, "Event invite")

func (Client) CreateDM

func (r Client) CreateDM(recipientID Snowflake) (DMChannel, error)

CreateDM creates a DM channel with a user. Returns a DMChannel object.

Usage example:

dm, err := client.CreateDM(userID)
if err == nil {
    client.SendMessage(dm.ID, MessageCreateOptions{Content: "Hello!"})
}

func (Client) CreateFollowupMessage

func (r Client) CreateFollowupMessage(applicationID Snowflake, token string, data InteractionResponseData) (Message, error)

CreateFollowupMessage creates a followup message for an interaction.

Usage example:

message, err := client.CreateFollowupMessage(applicationID, interactionToken, InteractionResponseData{
    Content: "Followup message!",
})

func (Client) CreateGlobalApplicationCommand

func (r Client) CreateGlobalApplicationCommand(applicationID Snowflake, command ApplicationCommand) (ApplicationCommand, error)

CreateGlobalApplicationCommand creates a new global application command.

Usage example:

command, err := client.CreateGlobalApplicationCommand(applicationID, ApplicationCommand{
    Name: "ping",
    Description: "Replies with pong",
})

func (Client) CreateGuildApplicationCommand

func (r Client) CreateGuildApplicationCommand(applicationID, guildID Snowflake, command ApplicationCommand) (ApplicationCommand, error)

CreateGuildApplicationCommand creates a new guild-specific application command.

Usage example:

command, err := client.CreateGuildApplicationCommand(applicationID, guildID, ApplicationCommand{
    Name: "test",
    Description: "A test command",
})

func (Client) CreateGuildChannel

func (r Client) CreateGuildChannel(guildID Snowflake, opts ChannelCreateOptions, reason string) (Channel, error)

CreateGuildChannel creates a new channel in a guild. Returns the created channel. Requires MANAGE_CHANNELS permission.

Usage example:

channel, err := client.CreateGuildChannel(guildID, ChannelCreateOptions{
    Name: "new-channel",
    Type: ChannelTypeGuildText,
}, "Creating new channel")

func (Client) CreateInteractionResponse

func (r Client) CreateInteractionResponse(interactionID Snowflake, token string, response InteractionResponse) error

CreateInteractionResponse responds to an interaction. This must be called within 3 seconds of receiving the interaction.

Usage example:

err := client.CreateInteractionResponse(interactionID, interactionToken, InteractionResponse{
    Type: InteractionResponseTypeChannelMessageWithSource,
    Data: &InteractionResponseData{
        Content: "Hello!",
    },
})

func (Client) CreateReaction

func (r Client) CreateReaction(channelID, messageID Snowflake, emoji string) error

CreateReaction adds a reaction to a message. The emoji must be URL encoded (e.g., %F0%9F%91%8D for thumbs up). For custom emoji, use the format name:id.

Usage example:

err := client.CreateReaction(channelID, messageID, "👍")
err := client.CreateReaction(channelID, messageID, "custom_emoji:123456789")

func (Client) CreateRole

func (r Client) CreateRole(guildID Snowflake, opts RoleCreateOptions, reason string) (Role, error)

CreateRole creates a new role for a guild. Requires MANAGE_ROLES permission.

Usage example:

role, err := client.CreateRole(guildID, RoleCreateOptions{
    Name: "Moderator",
    Color: 0x3498db,
    Hoist: true,
    Mentionable: true,
}, "Creating moderator role")

func (Client) DeleteAllReactions

func (r Client) DeleteAllReactions(channelID, messageID Snowflake) error

DeleteAllReactions removes all reactions from a message. Requires MANAGE_MESSAGES permission.

Usage example:

err := client.DeleteAllReactions(channelID, messageID)

func (Client) DeleteAllReactionsForEmoji

func (r Client) DeleteAllReactionsForEmoji(channelID, messageID Snowflake, emoji string) error

DeleteAllReactionsForEmoji removes all reactions for a specific emoji. Requires MANAGE_MESSAGES permission.

Usage example:

err := client.DeleteAllReactionsForEmoji(channelID, messageID, "👍")

func (Client) DeleteChannel

func (r Client) DeleteChannel(channelID Snowflake, reason string) error

DeleteChannel deletes a channel or closes a DM. Requires MANAGE_CHANNELS permission for guild channels. Deleting a category does not delete its child channels.

Usage example:

err := client.DeleteChannel(channelID, "No longer needed")

func (Client) DeleteChannelPermission

func (r Client) DeleteChannelPermission(channelID, overwriteID Snowflake, reason string) error

DeleteChannelPermission deletes a channel permission overwrite for a user or role. Requires MANAGE_ROLES permission.

Usage example:

err := client.DeleteChannelPermission(channelID, roleID, "Removing permission override")

func (Client) DeleteFollowupMessage

func (r Client) DeleteFollowupMessage(applicationID Snowflake, token string, messageID Snowflake) error

DeleteFollowupMessage deletes a followup message for an interaction.

Usage example:

err := client.DeleteFollowupMessage(applicationID, interactionToken, messageID)

func (Client) DeleteGlobalApplicationCommand

func (r Client) DeleteGlobalApplicationCommand(applicationID, commandID Snowflake) error

DeleteGlobalApplicationCommand deletes a global application command.

Usage example:

err := client.DeleteGlobalApplicationCommand(applicationID, commandID)

func (Client) DeleteGuildApplicationCommand

func (r Client) DeleteGuildApplicationCommand(applicationID, guildID, commandID Snowflake) error

DeleteGuildApplicationCommand deletes a guild-specific application command.

Usage example:

err := client.DeleteGuildApplicationCommand(applicationID, guildID, commandID)

func (Client) DeleteMessage

func (r Client) DeleteMessage(channelID, messageID Snowflake, reason string) error

DeleteMessage deletes a message from a channel.

Usage example:

err := client.DeleteMessage(channelID, messageID, "Spam")

func (Client) DeleteOriginalInteractionResponse

func (r Client) DeleteOriginalInteractionResponse(applicationID Snowflake, token string) error

DeleteOriginalInteractionResponse deletes the initial response to an interaction.

Usage example:

err := client.DeleteOriginalInteractionResponse(applicationID, interactionToken)

func (Client) DeleteOwnReaction

func (r Client) DeleteOwnReaction(channelID, messageID Snowflake, emoji string) error

DeleteOwnReaction removes the bot's own reaction from a message.

Usage example:

err := client.DeleteOwnReaction(channelID, messageID, "👍")

func (Client) DeleteRole

func (r Client) DeleteRole(guildID, roleID Snowflake, reason string) error

DeleteRole deletes a guild role. Requires MANAGE_ROLES permission.

Usage example:

err := client.DeleteRole(guildID, roleID, "Role no longer needed")

func (Client) DeleteUserReaction

func (r Client) DeleteUserReaction(channelID, messageID, userID Snowflake, emoji string) error

DeleteUserReaction removes another user's reaction from a message. Requires MANAGE_MESSAGES permission.

Usage example:

err := client.DeleteUserReaction(channelID, messageID, userID, "👍")

func (Client) EditChannel

func (r Client) EditChannel(channelID Snowflake, opts ChannelEditOptions, reason string) (Channel, error)

EditChannel modifies a channel's settings. Returns the updated channel. Requires MANAGE_CHANNELS permission.

Usage example:

channel, err := client.EditChannel(channelID, ChannelEditOptions{
    Name: "new-channel-name",
    Topic: "Updated topic",
}, "Channel update")

func (Client) EditChannelPermissions

func (r Client) EditChannelPermissions(channelID Snowflake, overwrite PermissionOverwrite, reason string) error

EditChannelPermissions edits permissions for a role or user in a channel. Requires MANAGE_ROLES permission.

Usage example:

err := client.EditChannelPermissions(channelID, roleID, PermissionOverwrite{
    ID: roleID,
    Type: PermissionOverwriteTypeRole,
    Allow: PermissionSendMessages,
    Deny: 0,
}, "Allow sending messages")

func (Client) EditFollowupMessage

func (r Client) EditFollowupMessage(applicationID Snowflake, token string, messageID Snowflake, data InteractionResponseData) (Message, error)

EditFollowupMessage edits a followup message for an interaction.

Usage example:

message, err := client.EditFollowupMessage(applicationID, interactionToken, messageID, InteractionResponseData{
    Content: "Edited followup!",
})

func (Client) EditGuild

func (r Client) EditGuild(guildID Snowflake, opts GuildEditOptions, reason string) (Guild, error)

EditGuild modifies a guild's settings. Returns the updated guild object. Requires MANAGE_GUILD permission.

Usage example:

guild, err := client.EditGuild(guildID, GuildEditOptions{
    Name: "New Server Name",
}, "Renaming server")

func (Client) EditMember

func (r Client) EditMember(guildID, userID Snowflake, opts MemberEditOptions, reason string) (Member, error)

EditMember modifies attributes of a guild member. Returns the updated member object.

Usage example:

nick := "New Nickname"
member, err := client.EditMember(guildID, userID, MemberEditOptions{
    Nick: &nick,
}, "Nickname change")

func (Client) EditMessage

func (r Client) EditMessage(channelID, messageID Snowflake, opts MessageEditOptions) (Message, error)

EditMessage edits a previously sent message.

Usage example:

message, err := client.EditMessage(channelID, messageID, MessageEditOptions{
    Content: "Updated content",
})

func (Client) EditOriginalInteractionResponse

func (r Client) EditOriginalInteractionResponse(applicationID Snowflake, token string, data InteractionResponseData) (Message, error)

EditOriginalInteractionResponse edits the initial response to an interaction.

Usage example:

message, err := client.EditOriginalInteractionResponse(applicationID, interactionToken, InteractionResponseData{
    Content: "Updated content!",
})

func (Client) EditRole

func (r Client) EditRole(guildID, roleID Snowflake, opts RoleEditOptions, reason string) (Role, error)

EditRole modifies a guild role. Requires MANAGE_ROLES permission.

Usage example:

role, err := client.EditRole(guildID, roleID, RoleEditOptions{
    Name: "Senior Moderator",
}, "Promoting role")

func (Client) FetchChannel

func (r Client) FetchChannel(channelID Snowflake) (Channel, error)

FetchChannel retrieves a channel by its Snowflake ID and decodes it into its concrete type (e.g. TextChannel, VoiceChannel, CategoryChannel).

Usage example:

channel, err := api.FetchChannel(123456789012345678)
if err != nil {
    // handle error
}
fmt.Println("Channel ID:", channel.GetID())

Returns:

  • Channel: the decoded channel object.
  • error: if the request failed or the type is unknown or decoding failed.

func (Client) FetchGatewayBot

func (r Client) FetchGatewayBot() (GatewayBot, error)

FetchGatewayBot retrieves bot gateway information including recommended shard count and session limits.

Usage example:

gateway, err := api.FetchGatewayBot()
if err != nil {
    // handle error
}
fmt.Println("Recommended shards:", gateway.Shards)

Returns:

  • GatewayBot: the bot gateway information.
  • error: if the request failed or decoding failed.

func (Client) FetchGuild

func (r Client) FetchGuild(guildID Snowflake) (Guild, error)

FetchGuild retrieves a guild by its ID.

Usage example:

guild, err := client.FetchGuild(guildID)

func (Client) FetchMember

func (r Client) FetchMember(guildID, userID Snowflake) (Member, error)

FetchMember retrieves a guild member by their user ID.

Usage example:

member, err := client.FetchMember(guildID, userID)

func (Client) FetchMessage

func (r Client) FetchMessage(channelID, messageID Snowflake) (Message, error)

FetchMessage retrieves a single message by ID from a channel.

Usage example:

message, err := client.FetchMessage(channelID, messageID)

func (Client) FetchMessages

func (r Client) FetchMessages(channelID Snowflake, opts FetchMessagesOptions) ([]Message, error)

FetchMessages retrieves messages from a channel.

Usage example:

messages, err := client.FetchMessages(channelID, FetchMessagesOptions{
    Limit: 10,
})

func (Client) FetchRoles

func (r Client) FetchRoles(guildID Snowflake) ([]Role, error)

FetchRoles retrieves all roles for a guild.

Usage example:

roles, err := client.FetchRoles(guildID)

func (Client) FetchSelfUser

func (r Client) FetchSelfUser() (User, error)

FetchSelfUser retrieves the current bot user's data including username, ID, avatar, and flags.

Usage example:

user, err := api.FetchSelfUser()
if err != nil {
    // handle error
}
fmt.Println("Bot username:", user.Username)

Returns:

  • User: the current user data.
  • error: if the request failed or decoding failed.

func (Client) FetchUser

func (r Client) FetchUser(userID Snowflake) (User, error)

FetchUser retrieves a user by their Snowflake ID including username, avatar, and flags.

Usage example:

user, err := api.FetchUser(123456789012345678)
if err != nil {
    // handle error
}
fmt.Println("Username:", user.Username)

Returns:

  • User: the user data.
  • error: if the request failed or decoding failed.

func (Client) GetBan

func (r Client) GetBan(guildID, userID Snowflake) (Ban, error)

GetBan retrieves the ban for a specific user. Requires BAN_MEMBERS permission.

Usage example:

ban, err := client.GetBan(guildID, userID)

func (Client) GetChannelInvites

func (r Client) GetChannelInvites(channelID Snowflake) ([]Invite, error)

GetChannelInvites retrieves a list of invites for a channel. Requires MANAGE_CHANNELS permission.

Usage example:

invites, err := client.GetChannelInvites(channelID)

func (Client) GetCurrentUserGuildMember

func (r Client) GetCurrentUserGuildMember(guildID Snowflake) (Member, error)

GetCurrentUserGuildMember retrieves the current user's member object for a guild.

Usage example:

member, err := client.GetCurrentUserGuildMember(guildID)

func (Client) GetCurrentUserGuilds

func (r Client) GetCurrentUserGuilds(opts GetCurrentUserGuildsOptions) ([]PartialGuild, error)

GetCurrentUserGuilds retrieves a list of partial guild objects the current user is a member of. Requires the guilds OAuth2 scope.

Usage example:

guilds, err := client.GetCurrentUserGuilds(GetCurrentUserGuildsOptions{Limit: 100})

func (Client) GetFollowupMessage

func (r Client) GetFollowupMessage(applicationID Snowflake, token string, messageID Snowflake) (Message, error)

GetFollowupMessage retrieves a followup message for an interaction.

Usage example:

message, err := client.GetFollowupMessage(applicationID, interactionToken, messageID)

func (Client) GetGlobalApplicationCommands

func (r Client) GetGlobalApplicationCommands(applicationID Snowflake) ([]ApplicationCommand, error)

GetGlobalApplicationCommands retrieves all global application commands.

Usage example:

commands, err := client.GetGlobalApplicationCommands(applicationID)

func (Client) GetGuildApplicationCommands

func (r Client) GetGuildApplicationCommands(applicationID, guildID Snowflake) ([]ApplicationCommand, error)

GetGuildApplicationCommands retrieves all guild-specific application commands.

Usage example:

commands, err := client.GetGuildApplicationCommands(applicationID, guildID)

func (Client) GetGuildChannels

func (r Client) GetGuildChannels(guildID Snowflake) ([]Channel, error)

GetGuildChannels retrieves all channels in a guild.

Usage example:

channels, err := client.GetGuildChannels(guildID)

func (Client) GetGuildPreview

func (r Client) GetGuildPreview(guildID Snowflake) (GuildPreview, error)

GetGuildPreview retrieves a guild preview by its ID. This is available for all guilds that the bot has MANAGE_GUILD in or guilds that are discoverable.

Usage example:

preview, err := client.GetGuildPreview(guildID)

func (Client) GetOriginalInteractionResponse

func (r Client) GetOriginalInteractionResponse(applicationID Snowflake, token string) (Message, error)

GetOriginalInteractionResponse retrieves the initial response to an interaction.

Usage example:

message, err := client.GetOriginalInteractionResponse(applicationID, interactionToken)

func (Client) GetPinnedMessages

func (r Client) GetPinnedMessages(channelID Snowflake) ([]Message, error)

GetPinnedMessages retrieves all pinned messages in a channel.

Usage example:

messages, err := client.GetPinnedMessages(channelID)

func (Client) GetReactions

func (r Client) GetReactions(channelID, messageID Snowflake, emoji string, opts GetReactionsOptions) ([]User, error)

GetReactions gets a list of users that reacted with a specific emoji.

Usage example:

users, err := client.GetReactions(channelID, messageID, "👍", GetReactionsOptions{Limit: 10})

func (Client) GetUserConnections

func (r Client) GetUserConnections() ([]Connection, error)

GetUserConnections retrieves the current user's connections. Requires the connections OAuth2 scope.

Usage example:

connections, err := client.GetUserConnections()

func (Client) KickMember

func (r Client) KickMember(guildID, userID Snowflake, reason string) error

KickMember removes a member from a guild. Requires KICK_MEMBERS permission.

Usage example:

err := client.KickMember(guildID, userID, "Rule violation")

func (Client) LeaveGuild

func (r Client) LeaveGuild(guildID Snowflake) error

LeaveGuild makes the bot leave a guild.

Usage example:

err := client.LeaveGuild(guildID)

func (Client) ListBans

func (r Client) ListBans(guildID Snowflake, opts ListBansOptions) ([]Ban, error)

ListBans retrieves a list of banned users for a guild. Requires BAN_MEMBERS permission.

Usage example:

bans, err := client.ListBans(guildID, ListBansOptions{Limit: 100})

func (Client) ListMembers

func (r Client) ListMembers(guildID Snowflake, opts ListMembersOptions) ([]Member, error)

ListMembers retrieves a list of guild members. Requires GUILD_MEMBERS privileged intent.

Usage example:

members, err := client.ListMembers(guildID, ListMembersOptions{Limit: 100})

func (Client) ModifyCurrentMember

func (r Client) ModifyCurrentMember(guildID Snowflake, opts ModifyCurrentMemberOptions, reason string) (Member, error)

ModifyCurrentMember modifies the bot's own nickname in a guild. Requires CHANGE_NICKNAME permission.

Usage example:

nick := "Bot Nickname"
member, err := client.ModifyCurrentMember(guildID, ModifyCurrentMemberOptions{
    Nick: &nick,
}, "Changing bot nickname")

func (Client) ModifyGuildChannelPositions

func (r Client) ModifyGuildChannelPositions(guildID Snowflake, positions []ModifyChannelPositionsEntry) error

ModifyGuildChannelPositions modifies the positions of guild channels. Requires MANAGE_CHANNELS permission.

Usage example:

err := client.ModifyGuildChannelPositions(guildID, []ModifyChannelPositionsEntry{
    {ID: channelID1, Position: intPtr(0)},
    {ID: channelID2, Position: intPtr(1)},
})

func (Client) ModifyRolePositions

func (r Client) ModifyRolePositions(guildID Snowflake, positions []ModifyRolePositionsEntry, reason string) ([]Role, error)

ModifyRolePositions modifies the positions of roles in a guild. Requires MANAGE_ROLES permission.

Usage example:

roles, err := client.ModifyRolePositions(guildID, []ModifyRolePositionsEntry{
    {ID: roleID1, Position: intPtr(1)},
    {ID: roleID2, Position: intPtr(2)},
}, "Reordering roles")

func (Client) OnInteractionCreate

func (d Client) OnInteractionCreate(h func(InteractionCreateEvent))

OnInteractionCreate registers a handler function for 'INTERACTION_CREATE' events.

Note:

  • This method is thread-safe via internal locking.
  • However, it is strongly recommended to register all event handlers sequentially during startup, before starting event dispatching, to avoid runtime mutations and ensure stable configuration.
  • Handlers are called sequentially when dispatching in the order they were added.

func (Client) OnMessageCreate

func (d Client) OnMessageCreate(h func(MessageCreateEvent))

OnMessageCreate registers a handler function for 'MESSAGE_CREATE' events.

Note:

  • This method is thread-safe via internal locking.
  • However, it is strongly recommended to register all event handlers sequentially during startup, before starting event dispatching, to avoid runtime mutations and ensure stable configuration.
  • Handlers are called sequentially when dispatching in the order they were added.

func (Client) OnMessageDelete

func (d Client) OnMessageDelete(h func(MessageDeleteEvent))

OnMessageDelete registers a handler function for 'MESSAGE_DELETE' events.

Note:

  • This method is thread-safe via internal locking.
  • However, it is strongly recommended to register all event handlers sequentially during startup, before starting event dispatching, to avoid runtime mutations and ensure stable configuration.
  • Handlers are called sequentially when dispatching in the order they were added.

func (Client) OnMessageUpdate

func (d Client) OnMessageUpdate(h func(MessageDeleteEvent))

OnMessageUpdate registers a handler function for 'MESSAGE_UPDATE' events.

Note:

  • This method is thread-safe via internal locking.
  • However, it is strongly recommended to register all event handlers sequentially during startup, before starting event dispatching, to avoid runtime mutations and ensure stable configuration.
  • Handlers are called sequentially when dispatching in the order they were added.

func (Client) OnVoiceStateUpdate

func (d Client) OnVoiceStateUpdate(h func(VoiceStateUpdateEvent))

OnVoiceStateUpdate registers a handler function for 'VOICE_STATE_UPDATE' events.

Note:

  • This method is thread-safe via internal locking.
  • However, it is strongly recommended to register all event handlers sequentially during startup, before starting event dispatching, to avoid runtime mutations and ensure stable configuration.
  • Handlers are called sequentially when dispatching in the order they were added.

func (Client) PinMessage

func (r Client) PinMessage(channelID, messageID Snowflake, reason string) error

PinMessage pins a message in a channel. Requires MANAGE_MESSAGES permission. Maximum of 50 pinned messages per channel.

Usage example:

err := client.PinMessage(channelID, messageID, "Important message")

func (Client) RemoveMemberRole

func (r Client) RemoveMemberRole(guildID, userID, roleID Snowflake, reason string) error

RemoveMemberRole removes a role from a guild member. Requires MANAGE_ROLES permission.

Usage example:

err := client.RemoveMemberRole(guildID, userID, roleID, "Removing role")

func (Client) RemoveTimeout

func (r Client) RemoveTimeout(guildID, userID Snowflake, reason string) error

RemoveTimeout removes a timeout from a member. This is a convenience method that wraps EditMember. Requires MODERATE_MEMBERS permission.

Usage example:

err := client.RemoveTimeout(guildID, userID, "Timeout lifted")

func (Client) SearchMembers

func (r Client) SearchMembers(guildID Snowflake, query string, limit int) ([]Member, error)

SearchMembers searches for guild members whose username or nickname starts with the query. Returns a max of 1000 members.

Usage example:

members, err := client.SearchMembers(guildID, "john", 10)

func (Client) SendMessage

func (r Client) SendMessage(channelID Snowflake, opts MessageCreateOptions) (Message, error)

SendMessage send's a to the spesified channel.

Usage example:

message, err := .SendMessage(123456789012345678, MessageCreateOptions{
       Content: "Hello, World!",
})
if err != nil {
    // handle error
}
fmt.Println("Message ID:", message.ID)

Returns:

  • Message: the message object.
  • error: if the request or decoding failed.

func (*Client) Shutdown

func (c *Client) Shutdown()

Shutdown cleanly shuts down the Client.

It:

  • Logs shutdown message.
  • Shuts down the REST API client (closes idle connections).
  • Shuts down all managed shards.

func (*Client) Start

func (c *Client) Start() error

Start initializes and connects all shards for the client.

It performs the following steps:

  1. Retrieves Gateway information from Discord.
  2. Creates and connects shards with appropriate rate limiting.
  3. Starts listening to Gateway events.

The lifetime of the client is controlled by the provided context `ctx`:

  • If `ctx` is `nil` or `context.Background()`, Start will block forever, running the client until the program exits or Shutdown is called externally.
  • If `ctx` is cancellable (e.g., created via context.WithCancel or context.WithTimeout), the client will run until the context is cancelled or times out. When the context is done, the client will shutdown gracefully and Start will return.

This design gives you full control over the client's lifecycle. For typical usage where you want the bot to run continuously, simply pass `nil` as the context (recommended for beginners).

Example usage:

// Run the client indefinitely (blocks forever)
err := client.Start(nil)

// Run the client with manual cancellation control
ctx, cancel := context.WithCancel(context.Background())
go func() {
    time.Sleep(time.Hour)
    cancel() // stops the client after 1 hour
}()
err := client.Start(ctx)

Returns an error if Gateway information retrieval or shard connection fails.

func (Client) TimeoutMember

func (r Client) TimeoutMember(guildID, userID Snowflake, duration time.Duration, reason string) error

TimeoutMember times out (mutes) a member for a specified duration. This is a convenience method that wraps EditMember. Requires MODERATE_MEMBERS permission.

Usage example:

err := client.TimeoutMember(guildID, userID, 10*time.Minute, "Spam")

func (Client) TriggerTypingIndicator

func (r Client) TriggerTypingIndicator(channelID Snowflake) error

TriggerTypingIndicator triggers the typing indicator in a channel. Generally bots should not use this, but it's available if needed.

Usage example:

err := client.TriggerTypingIndicator(channelID)

func (Client) UnbanMember

func (r Client) UnbanMember(guildID, userID Snowflake, reason string) error

UnbanMember removes the ban for a user. Requires BAN_MEMBERS permission.

Usage example:

err := client.UnbanMember(guildID, userID, "Appeal accepted")

func (Client) UnpinMessage

func (r Client) UnpinMessage(channelID, messageID Snowflake, reason string) error

UnpinMessage unpins a message from a channel. Requires MANAGE_MESSAGES permission.

Usage example:

err := client.UnpinMessage(channelID, messageID, "No longer important")

func (Client) UpdateSelfUser

func (r Client) UpdateSelfUser(opts UpdateSelfUserOptions) error

UpdateSelfUser updates the current bot user's username, avatar, or banner.

Usage example:

newAvatar, _ := goda.NewImageFile("path/to/avatar.png")
err := api.UpdateSelfUser(UpdateSelfUserOptions{
    Username: "new_username",
    Avatar:   newAvatar,
})
if err != nil {
    // handle error
}
fmt.Println("User updated successfully")

Returns:

  • error: if the request failed.

type Collectibles

type Collectibles struct {
	// Nameplate is the user's nameplate collectible data.
	//
	// Optional:
	//  - May be nil if the user has no nameplate collectible.
	Nameplate *Nameplate `json:"nameplate,omitempty"`
}

Collectibles represents collectibles the user owns, excluding avatar decorations and profile effects.

Reference: https://discord.com/developers/docs/resources/user#collectibles

type Collection

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

Collection is a generic, thread-safe collection of Discord entities. It provides discord.js-style collection methods for filtering, finding, and iterating over entities.

func NewCollection

func NewCollection[K comparable, V any]() *Collection[K, V]

NewCollection creates a new empty collection.

func (*Collection[K, V]) Clear

func (c *Collection[K, V]) Clear()

Clear removes all items from the collection.

func (*Collection[K, V]) Clone

func (c *Collection[K, V]) Clone() *Collection[K, V]

Clone creates a shallow copy of the collection.

func (*Collection[K, V]) Delete

func (c *Collection[K, V]) Delete(key K) bool

Delete removes an item from the collection by key. Returns true if the item was found and deleted, false otherwise.

func (*Collection[K, V]) Every

func (c *Collection[K, V]) Every(fn func(V) bool) bool

Every returns true if all items match the predicate. Returns true for an empty collection.

func (*Collection[K, V]) Filter

func (c *Collection[K, V]) Filter(fn func(V) bool) []V

Filter returns all items matching the predicate function.

func (*Collection[K, V]) FilterToCollection

func (c *Collection[K, V]) FilterToCollection(fn func(K, V) bool) *Collection[K, V]

FilterToCollection returns a new Collection containing only items matching the predicate.

func (*Collection[K, V]) Find

func (c *Collection[K, V]) Find(fn func(V) bool) (V, bool)

Find returns the first item matching the predicate function. Returns the item and true if found, or zero value and false if not found.

func (*Collection[K, V]) First

func (c *Collection[K, V]) First() (V, bool)

First returns an arbitrary item from the collection. Returns the item and true if the collection is not empty, or zero value and false if the collection is empty.

func (*Collection[K, V]) ForEach

func (c *Collection[K, V]) ForEach(fn func(K, V))

ForEach iterates over all items in the collection. The iteration order is not guaranteed.

func (*Collection[K, V]) Get

func (c *Collection[K, V]) Get(key K) (V, bool)

Get retrieves an item by key. Returns the item and true if found, or zero value and false if not found.

func (*Collection[K, V]) Has

func (c *Collection[K, V]) Has(key K) bool

Has checks if a key exists in the collection.

func (*Collection[K, V]) Keys

func (c *Collection[K, V]) Keys() []K

Keys returns all keys in the collection as a slice. The order is not guaranteed.

func (*Collection[K, V]) Map

func (c *Collection[K, V]) Map(fn func(V) V) []V

Map transforms all values using the provided function. Returns a new slice containing the transformed values.

func (*Collection[K, V]) Merge

func (c *Collection[K, V]) Merge(other *Collection[K, V])

Merge adds all items from another collection to this collection. Existing keys will be overwritten.

func (*Collection[K, V]) Reduce

func (c *Collection[K, V]) Reduce(fn func(acc V, item V) V, initial V) V

Reduce reduces the collection to a single value using the accumulator function.

func (*Collection[K, V]) Set

func (c *Collection[K, V]) Set(key K, value V)

Set adds or updates an item in the collection.

func (*Collection[K, V]) Size

func (c *Collection[K, V]) Size() int

Size returns the number of items in the collection.

func (*Collection[K, V]) Some

func (c *Collection[K, V]) Some(fn func(V) bool) bool

Some returns true if at least one item matches the predicate.

func (*Collection[K, V]) Values

func (c *Collection[K, V]) Values() []V

Values returns all values in the collection as a slice. The order is not guaranteed.

type Color

type Color int64

Color represents an RGB color encoded as an integer (e.g. 0xRRGGBB).

It is typically used to represent Discord embed colors or other hex color values.

const (
	ColorWhite                  Color = 0xFFFFFF
	ColorDiscordWhite           Color = 0xFFFFFE
	ColorLightGray              Color = 0xC0C0C0
	ColorGray                   Color = 0x808080
	ColorDarkGray               Color = 0x404040
	ColorBlack                  Color = 0x000000
	ColorDiscordBlack           Color = 0x000001
	ColorRed                    Color = 0xFF0000
	ColorPink                   Color = 0xFFAFAF
	ColorOrange                 Color = 0xFFC800
	ColorYellow                 Color = 0xFFFF00
	ColorGreen                  Color = 0x00FF00
	ColorMagenta                Color = 0xFF00FF
	ColorCyan                   Color = 0x00FFFF
	ColorBlue                   Color = 0x0000FF
	ColorLightSeaGreen          Color = 0x1ABC9C
	ColorMediumSeaGreen         Color = 0x2ECC71
	ColorSummerSky              Color = 0x3498DB
	ColorDeepLilac              Color = 0x9B59B6
	ColorRuby                   Color = 0xE91E63
	ColorMoonYellow             Color = 0xF1C40F
	ColorTahitiGold             Color = 0xE67E22
	ColorCinnabar               Color = 0xE74C3C
	ColorSubmarine              Color = 0x95A5A6
	ColorBlueAquamarine         Color = 0x607D8B
	ColorDeepSea                Color = 0x11806A
	ColorSeaGreen               Color = 0x1F8B4C
	ColorEndeavour              Color = 0x206694
	ColorVividViolet            Color = 0x71368A
	ColorJazzberryJam           Color = 0xAD1457
	ColorDarkGoldenrod          Color = 0xC27C0E
	ColorRust                   Color = 0xA84300
	ColorBrown                  Color = 0x992D22
	ColorGrayChateau            Color = 0x979C9F
	ColorBismark                Color = 0x546E7A
	ColorStiBlue                Color = 0x0E4BEF
	ColorWrxBlue                Color = 0x00247D
	ColorRallyartCrimson        Color = 0xE60012
	ColorLime                   Color = 0x00FF00
	ColorForestGreen            Color = 0x228B22
	ColorCadmiumGreen           Color = 0x097969
	ColorAquamarine             Color = 0x7FFFD4
	ColorBlueGreen              Color = 0x088F8F
	ColorRaspberry              Color = 0xE30B5C
	ColorScarletRed             Color = 0xFF2400
	ColorNight                  Color = 0x0C090A
	ColorCharcoal               Color = 0x34282C
	ColorOil                    Color = 0x3B3131
	ColorLightBlack             Color = 0x454545
	ColorBlackCat               Color = 0x413839
	ColorIridium                Color = 0x3D3C3A
	ColorBlackEel               Color = 0x463E3F
	ColorBlackCow               Color = 0x4C4646
	ColorGrayWolf               Color = 0x504A4B
	ColorGreyWolf               Color = 0x504A4B
	ColorVampireGray            Color = 0x565051
	ColorVampireGrey            Color = 0x565051
	ColorIronGray               Color = 0x52595D
	ColorIronGrey               Color = 0x52595D
	ColorGrayDolphin            Color = 0x5C5858
	ColorGreyDolphin            Color = 0x5C5858
	ColorCarbonGray             Color = 0x625D5D
	ColorCarbonGrey             Color = 0x625D5D
	ColorAshGray                Color = 0x666362
	ColorAshGrey                Color = 0x666362
	ColorDimGray                Color = 0x696969
	ColorDimGrey                Color = 0x696969
	ColorNardoGray              Color = 0x686A6C
	ColorNardoGrey              Color = 0x686A6C
	ColorCloudyGray             Color = 0x6D6968
	ColorCloudyGrey             Color = 0x6D6968
	ColorSmokeyGray             Color = 0x726E6D
	ColorSmokeyGrey             Color = 0x726E6D
	ColorAlienGray              Color = 0x736F6E
	ColorAlienGrey              Color = 0x736F6E
	ColorSonicSilver            Color = 0x757575
	ColorPlatinumGray           Color = 0x797979
	ColorPlatinumGrey           Color = 0x797979
	ColorGranite                Color = 0x837E7C
	ColorBattleshipGray         Color = 0x848482
	ColorBattleshipGrey         Color = 0x848482
	ColorGunmetalGray           Color = 0x8D918D
	ColorGunmetalGrey           Color = 0x8D918D
	ColorGrayCloud              Color = 0xB6B6B4
	ColorGreyCloud              Color = 0xB6B6B4
	ColorSilver                 Color = 0xC0C0C0
	ColorPaleSilver             Color = 0xC9C0BB
	ColorGrayGoose              Color = 0xD1D0CE
	ColorGreyGoose              Color = 0xD1D0CE
	ColorPlatinumSilver         Color = 0xCECECE
	ColorSilverWhite            Color = 0xDADBDD
	ColorGainsboro              Color = 0xDCDCDC
	ColorPlatinum               Color = 0xE5E4E2
	ColorMetallicSilver         Color = 0xBCC6CC
	ColorBlueGray               Color = 0x98AFC7
	ColorBlueGrey               Color = 0x98AFC7
	ColorRomanSilver            Color = 0x838996
	ColorLightSlateGray         Color = 0x778899
	ColorLightSlateGrey         Color = 0x778899
	ColorSlateGray              Color = 0x708090
	ColorSlateGrey              Color = 0x708090
	ColorRatGray                Color = 0x6D7B8D
	ColorSlateGraniteGray       Color = 0x657383
	ColorSlateGraniteGrey       Color = 0x657383
	ColorJetGray                Color = 0x616D7E
	ColorJetGrey                Color = 0x616D7E
	ColorMistBlue               Color = 0x646D7E
	ColorMarbleBlue             Color = 0x566D7E
	ColorSlateBlueGrey          Color = 0x737CA1
	ColorSlateBlueGray          Color = 0x737CA1
	ColorLightPurpleBlue        Color = 0x728FCE
	ColorAzureBlue              Color = 0x4863A0
	ColorBlueJay                Color = 0x2B547E
	ColorCharcoalBlue           Color = 0x36454F
	ColorDarkBlueGrey           Color = 0x29465B
	ColorDarkSlate              Color = 0x2B3856
	ColorDeepSeaBlue            Color = 0x123456
	ColorNightBlue              Color = 0x151B54
	ColorMidnightBlue           Color = 0x191970
	ColorNavy                   Color = 0x000080
	ColorDenimDarkBlue          Color = 0x151B8D
	ColorDarkBlue               Color = 0x00008B
	ColorLapisBlue              Color = 0x15317E
	ColorNewMidnightBlue        Color = 0x0000A0
	ColorEarthBlue              Color = 0x0000A5
	ColorCobaltBlue             Color = 0x0020C2
	ColorMediumBlue             Color = 0x0000CD
	ColorBlueberryBlue          Color = 0x0041C2
	ColorCanaryBlue             Color = 0x2916F5
	ColorSamcoBlue              Color = 0x0002FF
	ColorBrightBlue             Color = 0x0909FF
	ColorBlueOrchid             Color = 0x1F45FC
	ColorSapphireBlue           Color = 0x2554C7
	ColorBlueEyes               Color = 0x1569C7
	ColorBrightNavyBlue         Color = 0x1974D2
	ColorBalloonBlue            Color = 0x2B60DE
	ColorRoyalBlue              Color = 0x4169E1
	ColorOceanBlue              Color = 0x2B65EC
	ColorBlueRibbon             Color = 0x306EFF
	ColorBlueDress              Color = 0x157DEC
	ColorNeonBlue               Color = 0x1589FF
	ColorDodgerBlue             Color = 0x1E90FF
	ColorGlacialBlueIce         Color = 0x368BC1
	ColorSteelBlue              Color = 0x4682B4
	ColorSilkBlue               Color = 0x488AC7
	ColorWindowsBlue            Color = 0x357EC7
	ColorBlueIvy                Color = 0x3090C7
	ColorBlueKoi                Color = 0x659EC7
	ColorColumbiaBlue           Color = 0x87AFC7
	ColorBabyBlue               Color = 0x95B9C7
	ColorCornflowerBlue         Color = 0x6495ED
	ColorSkyBlueDress           Color = 0x6698FF
	ColorIceberg                Color = 0x56A5EC
	ColorButterflyBlue          Color = 0x38ACEC
	ColorDeepSkyBlue            Color = 0x00BFFF
	ColorMiddayBlue             Color = 0x3BB9FF
	ColorCrystalBlue            Color = 0x5CB3FF
	ColorDenimBlue              Color = 0x79BAEC
	ColorDaySkyBlue             Color = 0x82CAFF
	ColorLightSkyBlue           Color = 0x87CEFA
	ColorSkyBlue                Color = 0x87CEEB
	ColorJeansBlue              Color = 0xA0CFEC
	ColorBlueAngel              Color = 0xB7CEEC
	ColorPastelBlue             Color = 0xB4CFEC
	ColorLightDayBlue           Color = 0xADDFFF
	ColorSeaBlue                Color = 0xC2DFFF
	ColorHeavenlyBlue           Color = 0xC6DEFF
	ColorRobinEggBlue           Color = 0xBDEDFF
	ColorPowderBlue             Color = 0xB0E0E6
	ColorCoralBlue              Color = 0xAFDCEC
	ColorLightBlue              Color = 0xADD8E6
	ColorLightSteelBlue         Color = 0xB0CFDE
	ColorGulfBlue               Color = 0xC9DFEC
	ColorPastelLightBlue        Color = 0xD5D6EA
	ColorLavenderBlue           Color = 0xE3E4FA
	ColorWhiteBlue              Color = 0xDBE9FA
	ColorLavender               Color = 0xE6E6FA
	ColorWater                  Color = 0xEBF4FA
	ColorAliceBlue              Color = 0xF0F8FF
	ColorGhostWhite             Color = 0xF8F8FF
	ColorAzure                  Color = 0xF0FFFF
	ColorLightCyan              Color = 0xE0FFFF
	ColorLightSlate             Color = 0xCCFFFF
	ColorElectricBlue           Color = 0x9AFEFF
	ColorTronBlue               Color = 0x7DFDFE
	ColorBlueZircon             Color = 0x57FEFF
	ColorAqua                   Color = 0x00FFFF
	ColorBrightCyan             Color = 0x0AFFFF
	ColorCeleste                Color = 0x50EBEC
	ColorBlueDiamond            Color = 0x4EE2EC
	ColorBrightTurquoise        Color = 0x16E2F5
	ColorBlueLagoon             Color = 0x8EEBEC
	ColorPaleTurquoise          Color = 0xAFEEEE
	ColorPaleBlueLily           Color = 0xCFECEC
	ColorLightTeal              Color = 0xB3D9D9
	ColorTiffanyBlue            Color = 0x81D8D0
	ColorBlueHosta              Color = 0x77BFC7
	ColorCyanOpaque             Color = 0x92C7C7
	ColorNorthernLightsBlue     Color = 0x78C7C7
	ColorMediumAquamarine       Color = 0x66CDAA
	ColorMagicMint              Color = 0xAAF0D1
	ColorLightAquamarine        Color = 0x93FFE8
	ColorBrightTeal             Color = 0x01F9C6
	ColorTurquoise              Color = 0x40E0D0
	ColorMediumTurquoise        Color = 0x48D1CC
	ColorDeepTurquoise          Color = 0x48CCCD
	ColorJellyfish              Color = 0x46C7C7
	ColorBlueTurquoise          Color = 0x43C6DB
	ColorDarkTurquoise          Color = 0x00CED1
	ColorMacawBlueGreen         Color = 0x43BFC7
	ColorSeafoamGreen           Color = 0x3EA99F
	ColorCadetBlue              Color = 0x5F9EA0
	ColorBlueChill              Color = 0x3B9C9C
	ColorDarkCyan               Color = 0x008B8B
	ColorTealGreen              Color = 0x00827F
	ColorTeal                   Color = 0x008080
	ColorTealBlue               Color = 0x007C80
	ColorMediumTeal             Color = 0x045F5F
	ColorDarkTeal               Color = 0x045D5D
	ColorDeepTeal               Color = 0x033E3E
	ColorDarkSlateGray          Color = 0x25383C
	ColorDarkSlateGrey          Color = 0x25383C
	ColorGunmetal               Color = 0x2C3539
	ColorBlueMossGreen          Color = 0x3C565B
	ColorBeetleGreen            Color = 0x4C787E
	ColorGrayishTurquoise       Color = 0x5E7D7E
	ColorGreenishBlue           Color = 0x307D7E
	ColorAquamarineStone        Color = 0x348781
	ColorSeaTurtleGreen         Color = 0x438D80
	ColorDullSeaGreen           Color = 0x4E8975
	ColorDarkGreenBlue          Color = 0x1F6357
	ColorDeepSeaGreen           Color = 0x306754
	ColorBottleGreen            Color = 0x006A4E
	ColorElfGreen               Color = 0x1B8A6B
	ColorDarkMint               Color = 0x31906E
	ColorJade                   Color = 0x00A36C
	ColorEarthGreen             Color = 0x34A56F
	ColorChromeGreen            Color = 0x1AA260
	ColorEmerald                Color = 0x50C878
	ColorMint                   Color = 0x3EB489
	ColorMetallicGreen          Color = 0x7C9D8E
	ColorCamouflageGreen        Color = 0x78866B
	ColorSageGreen              Color = 0x848B79
	ColorHazelGreen             Color = 0x617C58
	ColorVenomGreen             Color = 0x728C00
	ColorOliveDrab              Color = 0x6B8E23
	ColorOlive                  Color = 0x808000
	ColorDarkOliveGreen         Color = 0x556B2F
	ColorMilitaryGreen          Color = 0x4E5B31
	ColorGreenLeaves            Color = 0x3A5F0B
	ColorArmyGreen              Color = 0x4B5320
	ColorFernGreen              Color = 0x667C26
	ColorFallForestGreen        Color = 0x4E9258
	ColorIrishGreen             Color = 0x08A04B
	ColorPineGreen              Color = 0x387C44
	ColorMediumForestGreen      Color = 0x347235
	ColorJungleGreen            Color = 0x347C2C
	ColorCactusGreen            Color = 0x227442
	ColorDarkGreen              Color = 0x006400
	ColorDeepGreen              Color = 0x056608
	ColorDeepEmeraldGreen       Color = 0x046307
	ColorHunterGreen            Color = 0x355E3B
	ColorDarkForestGreen        Color = 0x254117
	ColorLotusGreen             Color = 0x004225
	ColorSeaweedGreen           Color = 0x437C17
	ColorShamrockGreen          Color = 0x347C17
	ColorGreenOnion             Color = 0x6AA121
	ColorMossGreen              Color = 0x8A9A5B
	ColorGrassGreen             Color = 0x3F9B0B
	ColorGreenPepper            Color = 0x4AA02C
	ColorDarkLimeGreen          Color = 0x41A317
	ColorParrotGreen            Color = 0x12AD2B
	ColorCloverGreen            Color = 0x3EA055
	ColorDinosaurGreen          Color = 0x73A16C
	ColorGreenSnake             Color = 0x6CBB3C
	ColorAlienGreen             Color = 0x6CC417
	ColorGreenApple             Color = 0x4CC417
	ColorLimeGreen              Color = 0x32CD32
	ColorPeaGreen               Color = 0x52D017
	ColorKellyGreen             Color = 0x4CC552
	ColorZombieGreen            Color = 0x54C571
	ColorGreenPeas              Color = 0x89C35C
	ColorDollarBillGreen        Color = 0x85BB65
	ColorFrogGreen              Color = 0x99C68E
	ColorTurquoiseGreen         Color = 0xA0D6B4
	ColorDarkSeaGreen           Color = 0x8FBC8F
	ColorBasilGreen             Color = 0x829F82
	ColorGrayGreen              Color = 0xA2AD9C
	ColorIguanaGreen            Color = 0x9CB071
	ColorCitronGreen            Color = 0x8FB31D
	ColorAcidGreen              Color = 0xB0BF1A
	ColorAvocadoGreen           Color = 0xB2C248
	ColorPistachioGreen         Color = 0x9DC209
	ColorSaladGreen             Color = 0xA1C935
	ColorYellowGreen            Color = 0x9ACD32
	ColorPastelGreen            Color = 0x77DD77
	ColorHummingbirdGreen       Color = 0x7FE817
	ColorNebulaGreen            Color = 0x59E817
	ColorStoplightGoGreen       Color = 0x57E964
	ColorNeonGreen              Color = 0x16F529
	ColorJadeGreen              Color = 0x5EFB6E
	ColorLimeMintGreen          Color = 0x36F57F
	ColorSpringGreen            Color = 0x00FF7F
	ColorMediumSpringGreen      Color = 0x00FA9A
	ColorEmeraldGreen           Color = 0x5FFB17
	ColorLawnGreen              Color = 0x7CFC00
	ColorBrightGreen            Color = 0x66FF00
	ColorChartreuse             Color = 0x7FFF00
	ColorYellowLawnGreen        Color = 0x87F717
	ColorAloeVeraGreen          Color = 0x98F516
	ColorDullGreenYellow        Color = 0xB1FB17
	ColorLemonGreen             Color = 0xADF802
	ColorGreenYellow            Color = 0xADFF2F
	ColorChameleonGreen         Color = 0xBDF516
	ColorNeonYellowGreen        Color = 0xDAEE01
	ColorYellowGreenGrosbeak    Color = 0xE2F516
	ColorTeaGreen               Color = 0xCCFB5D
	ColorSlimeGreen             Color = 0xBCE954
	ColorAlgaeGreen             Color = 0x64E986
	ColorLightGreen             Color = 0x90EE90
	ColorDragonGreen            Color = 0x6AFB92
	ColorPaleGreen              Color = 0x98FB98
	ColorMintGreen              Color = 0x98FF98
	ColorGreenThumb             Color = 0xB5EAAA
	ColorOrganicBrown           Color = 0xE3F9A6
	ColorLightJade              Color = 0xC3FDB8
	ColorLightMintGreen         Color = 0xC2E5D3
	ColorLightRoseGreen         Color = 0xDBF9DB
	ColorChromeWhite            Color = 0xE8F1D4
	ColorHoneydew               Color = 0xF0FFF0
	ColorMintCream              Color = 0xF5FFFA
	ColorLemonChiffon           Color = 0xFFFACD
	ColorParchment              Color = 0xFFFFC2
	ColorCream                  Color = 0xFFFFCC
	ColorCreamWhite             Color = 0xFFFDD0
	ColorLightGoldenrodYellow   Color = 0xFAFAD2
	ColorLightYellow            Color = 0xFFFFE0
	ColorBeige                  Color = 0xF5F5DC
	ColorCornsilk               Color = 0xFFF8DC
	ColorBlonde                 Color = 0xFBF6D9
	ColorChampagne              Color = 0xF7E7CE
	ColorAntiqueWhite           Color = 0xFAEBD7
	ColorPapayaWhip             Color = 0xFFEFD5
	ColorBlanchedAlmond         Color = 0xFFEBCD
	ColorBisque                 Color = 0xFFE4C4
	ColorWheat                  Color = 0xF5DEB3
	ColorMoccasin               Color = 0xFFE4B5
	ColorPeach                  Color = 0xFFE5B4
	ColorLightOrange            Color = 0xFED8B1
	ColorPeachPuff              Color = 0xFFDAB9
	ColorCoralPeach             Color = 0xFBD5AB
	ColorNavajoWhite            Color = 0xFFDEAD
	ColorGoldenBlonde           Color = 0xFBE7A1
	ColorGoldenSilk             Color = 0xF3E3C3
	ColorDarkBlonde             Color = 0xF0E2B6
	ColorLightGold              Color = 0xF1E5AC
	ColorVanilla                Color = 0xF3E5AB
	ColorTanBrown               Color = 0xECE5B6
	ColorDirtyWhite             Color = 0xE8E4C9
	ColorPaleGoldenrod          Color = 0xEEE8AA
	ColorKhaki                  Color = 0xF0E68C
	ColorCardboardBrown         Color = 0xEDDA74
	ColorHarvestGold            Color = 0xEDE275
	ColorSunYellow              Color = 0xFFE87C
	ColorCornYellow             Color = 0xFFF380
	ColorPastelYellow           Color = 0xFAF884
	ColorNeonYellow             Color = 0xFFFF33
	ColorCanaryYellow           Color = 0xFFEF00
	ColorBananaYellow           Color = 0xF5E216
	ColorMustardYellow          Color = 0xFFDB58
	ColorGoldenYellow           Color = 0xFFDF00
	ColorBoldYellow             Color = 0xF9DB24
	ColorRubberDuckyYellow      Color = 0xFFD801
	ColorGold                   Color = 0xFFD700
	ColorBrightGold             Color = 0xFDD017
	ColorChromeGold             Color = 0xFFCE44
	ColorGoldenBrown            Color = 0xEAC117
	ColorDeepYellow             Color = 0xF6BE00
	ColorMacaroniAndCheese      Color = 0xF2BB66
	ColorSaffron                Color = 0xFBB917
	ColorNeonGold               Color = 0xFDBD01
	ColorBeer                   Color = 0xFBB117
	ColorYellowOrange           Color = 0xFFAE42
	ColorOrangeYellow           Color = 0xFFAE42
	ColorCantaloupe             Color = 0xFFA62F
	ColorCheeseOrange           Color = 0xFFA600
	ColorBrownSand              Color = 0xEE9A4D
	ColorSandyBrown             Color = 0xF4A460
	ColorBrownSugar             Color = 0xE2A76F
	ColorCamelBrown             Color = 0xC19A6B
	ColorDeerBrown              Color = 0xE6BF83
	ColorBurlyWood              Color = 0xDEB887
	ColorTan                    Color = 0xD2B48C
	ColorLightFrenchBeige       Color = 0xC8AD7F
	ColorSand                   Color = 0xC2B280
	ColorSage                   Color = 0xBCB88A
	ColorFallLeafBrown          Color = 0xC8B560
	ColorGingerBrown            Color = 0xC9BE62
	ColorBronzeGold             Color = 0xC9AE5D
	ColorDarkKhaki              Color = 0xBDB76B
	ColorOliveGreen             Color = 0xBAB86C
	ColorBrass                  Color = 0xB5A642
	ColorCookieBrown            Color = 0xC7A317
	ColorMetallicGold           Color = 0xD4AF37
	ColorBeeYellow              Color = 0xE9AB17
	ColorSchoolBusYellow        Color = 0xE8A317
	ColorGoldenrod              Color = 0xDAA520
	ColorOrangeGold             Color = 0xD4A017
	ColorCaramel                Color = 0xC68E17
	ColorCinnamon               Color = 0xC58917
	ColorPeru                   Color = 0xCD853F
	ColorBronze                 Color = 0xCD7F32
	ColorTigerOrange            Color = 0xC88141
	ColorCopper                 Color = 0xB87333
	ColorDarkGold               Color = 0xAA6C39
	ColorMetallicBronze         Color = 0xA97142
	ColorDarkAlmond             Color = 0xAB784E
	ColorWood                   Color = 0x966F33
	ColorOakBrown               Color = 0x806517
	ColorAntiqueBronze          Color = 0x665D1E
	ColorHazel                  Color = 0x8E7618
	ColorDarkYellow             Color = 0x8B8000
	ColorDarkMoccasin           Color = 0x827839
	ColorKhakiGreen             Color = 0x8A865D
	ColorMillenniumJade         Color = 0x93917C
	ColorDarkBeige              Color = 0x9F8C76
	ColorBulletShell            Color = 0xAF9B60
	ColorArmyBrown              Color = 0x827B60
	ColorSandstone              Color = 0x786D5F
	ColorTaupe                  Color = 0x483C32
	ColorMocha                  Color = 0x493D26
	ColorMilkChocolate          Color = 0x513B1C
	ColorGrayBrown              Color = 0x3D3635
	ColorDarkCoffee             Color = 0x3B2F2F
	ColorOldBurgundy            Color = 0x43302E
	ColorWesternCharcoal        Color = 0x49413F
	ColorBakersBrown            Color = 0x5C3317
	ColorDarkBrown              Color = 0x654321
	ColorSepiaBrown             Color = 0x704214
	ColorDarkBronze             Color = 0x804A00
	ColorCoffee                 Color = 0x6F4E37
	ColorBrownBear              Color = 0x835C3B
	ColorRedDirt                Color = 0x7F5217
	ColorSepia                  Color = 0x7F462C
	ColorSienna                 Color = 0xA0522D
	ColorSaddleBrown            Color = 0x8B4513
	ColorDarkSienna             Color = 0x8A4117
	ColorSangria                Color = 0x7E3817
	ColorBloodRed               Color = 0x7E3517
	ColorChestnut               Color = 0x954535
	ColorCoralBrown             Color = 0x9E4638
	ColorChestnutRed            Color = 0xC34A2C
	ColorMahogany               Color = 0xC04000
	ColorRedGold                Color = 0xEB5406
	ColorRedFox                 Color = 0xC35817
	ColorDarkBisque             Color = 0xB86500
	ColorLightBrown             Color = 0xB5651D
	ColorPetraGold              Color = 0xB76734
	ColorCopperRed              Color = 0xCB6D51
	ColorOrangeSalmon           Color = 0xC47451
	ColorChocolate              Color = 0xD2691E
	ColorSedona                 Color = 0xCC6600
	ColorPapayaOrange           Color = 0xE56717
	ColorHalloweenOrange        Color = 0xE66C2C
	ColorNeonOrange             Color = 0xFF6700
	ColorBrightOrange           Color = 0xFF5F1F
	ColorPumpkinOrange          Color = 0xF87217
	ColorCarrotOrange           Color = 0xF88017
	ColorDarkOrange             Color = 0xFF8C00
	ColorConstructionConeOrange Color = 0xF87431
	ColorIndianSaffron          Color = 0xFF7722
	ColorSunriseOrange          Color = 0xE67451
	ColorMangoOrange            Color = 0xFF8040
	ColorCoral                  Color = 0xFF7F50
	ColorBasketBallOrange       Color = 0xF88158
	ColorLightSalmonRose        Color = 0xF9966B
	ColorLightSalmon            Color = 0xFFA07A
	ColorDarkSalmon             Color = 0xE9967A
	ColorTangerine              Color = 0xE78A61
	ColorLightCopper            Color = 0xDA8A67
	ColorSalmonPink             Color = 0xFF8674
	ColorSalmon                 Color = 0xFA8072
	ColorPeachPink              Color = 0xF98B88
	ColorLightCoral             Color = 0xF08080
	ColorPastelRed              Color = 0xF67280
	ColorPinkCoral              Color = 0xE77471
	ColorBeanRed                Color = 0xF75D59
	ColorValentineRed           Color = 0xE55451
	ColorIndianRed              Color = 0xCD5C5C
	ColorTomato                 Color = 0xFF6347
	ColorShockingOrange         Color = 0xE55B3C
	ColorOrangeRed              Color = 0xFF4500
	ColorNeonRed                Color = 0xFD1C03
	ColorRubyRed                Color = 0xF62217
	ColorFerrariRed             Color = 0xF70D1A
	ColorFireEngineRed          Color = 0xF62817
	ColorLavaRed                Color = 0xE42217
	ColorLoveRed                Color = 0xE41B17
	ColorGrapefruit             Color = 0xDC381F
	ColorCherryRed              Color = 0xC24641
	ColorChilliPepper           Color = 0xC11B17
	ColorFireBrick              Color = 0xB22222
	ColorTomatoSauceRed         Color = 0xB21807
	ColorCarbonRed              Color = 0xA70D2A
	ColorCranberry              Color = 0x9F000F
	ColorSaffronRed             Color = 0x931314
	ColorCrimsonRed             Color = 0x990000
	ColorRedWine                Color = 0x990012
	ColorWineRed                Color = 0x990012
	ColorDarkRed                Color = 0x8B0000
	ColorMaroon                 Color = 0x800000
	ColorBurgundy               Color = 0x8C001A
	ColorVermilion              Color = 0x7E191B
	ColorDeepRed                Color = 0x800517
	ColorRedBlood               Color = 0x660000
	ColorBloodNight             Color = 0x551606
	ColorDarkScarlet            Color = 0x560319
	ColorBlackBean              Color = 0x3D0C02
	ColorChocolateBrown         Color = 0x3F000F
	ColorMidnight               Color = 0x2B1B17
	ColorPurpleLily             Color = 0x550A35
	ColorPurpleMaroon           Color = 0x810541
	ColorPlumPie                Color = 0x7D0541
	ColorPlumVelvet             Color = 0x7D0552
	ColorDarkRaspberry          Color = 0x872657
	ColorVelvetMaroon           Color = 0x7E354D
	ColorRosyFinch              Color = 0x7F4E52
	ColorDullPurple             Color = 0x7F525D
	ColorPuce                   Color = 0x7F5A58
	ColorRoseDust               Color = 0x997070
	ColorPastelBrown            Color = 0xB1907F
	ColorRosyPink               Color = 0xB38481
	ColorRosyBrown              Color = 0xBC8F8F
	ColorKhakiRose              Color = 0xC5908E
	ColorLipstickPink           Color = 0xC48793
	ColorPinkBrown              Color = 0xC48189
	ColorOldRose                Color = 0xC08081
	ColorDustyPink              Color = 0xD58A94
	ColorPinkDaisy              Color = 0xE799A3
	ColorRose                   Color = 0xE8ADAA
	ColorDustyRose              Color = 0xC9A9A6
	ColorSilverPink             Color = 0xC4AEAD
	ColorGoldPink               Color = 0xE6C7C2
	ColorRoseGold               Color = 0xECC5C0
	ColorDeepPeach              Color = 0xFFCBA4
	ColorPastelOrange           Color = 0xF8B88B
	ColorDesertSand             Color = 0xEDC9AF
	ColorUnbleachedSilk         Color = 0xFFDDCA
	ColorPigPink                Color = 0xFDD7E4
	ColorPalePink               Color = 0xF2D4D7
	ColorBlush                  Color = 0xFFE6E8
	ColorMistyRose              Color = 0xFFE4E1
	ColorPinkBubbleGum          Color = 0xFFDFDD
	ColorLightRose              Color = 0xFBCFCD
	ColorLightRed               Color = 0xFFCCCB
	ColorWarmPink               Color = 0xF6C6BD
	ColorDeepRose               Color = 0xFBBBB9
	ColorLightPink              Color = 0xFFB6C1
	ColorSoftPink               Color = 0xFFB8BF
	ColorDonutPink              Color = 0xFAAFBE
	ColorBabyPink               Color = 0xFAAFBA
	ColorFlamingoPink           Color = 0xF9A7B0
	ColorPastelPink             Color = 0xFEA3AA
	ColorRosePink               Color = 0xE7A1B0
	ColorPinkRose               Color = 0xE7A1B0
	ColorCadillacPink           Color = 0xE38AAE
	ColorCarnationPink          Color = 0xF778A1
	ColorPastelRose             Color = 0xE5788F
	ColorBlushRed               Color = 0xE56E94
	ColorPaleVioletRed          Color = 0xDB7093
	ColorPurplePink             Color = 0xD16587
	ColorTulipPink              Color = 0xC25A7C
	ColorBashfulPink            Color = 0xC25283
	ColorDarkPink               Color = 0xE75480
	ColorDarkHotPink            Color = 0xF660AB
	ColorHotPink                Color = 0xFF69B4
	ColorWatermelonPink         Color = 0xFC6C85
	ColorVioletRed              Color = 0xF6358A
	ColorHotDeepPink            Color = 0xF52887
	ColorBrightPink             Color = 0xFF007F
	ColorDeepPink               Color = 0xFF1493
	ColorNeonPink               Color = 0xF535AA
	ColorChromePink             Color = 0xFF33AA
	ColorNeonHotPink            Color = 0xFD349C
	ColorPinkCupcake            Color = 0xE45E9D
	ColorRoyalPink              Color = 0xE759AC
	ColorDimorphothecaMagenta   Color = 0xE3319D
	ColorPinkLemonade           Color = 0xE4287C
	ColorRedPink                Color = 0xFA2A55
	ColorCrimson                Color = 0xDC143C
	ColorBrightMaroon           Color = 0xC32148
	ColorRoseRed                Color = 0xC21E56
	ColorRoguePink              Color = 0xC12869
	ColorBurntPink              Color = 0xC12267
	ColorPinkViolet             Color = 0xCA226B
	ColorMagentaPink            Color = 0xCC338B
	ColorMediumVioletRed        Color = 0xC71585
	ColorDarkCarnationPink      Color = 0xC12283
	ColorRaspberryPurple        Color = 0xB3446C
	ColorPinkPlum               Color = 0xB93B8F
	ColorOrchid                 Color = 0xDA70D6
	ColorDeepMauve              Color = 0xDF73D4
	ColorViolet                 Color = 0xEE82EE
	ColorFuchsiaPink            Color = 0xFF77FF
	ColorBrightNeonPink         Color = 0xF433FF
	ColorFuchsia                Color = 0xFF00FF
	ColorCrimsonPurple          Color = 0xE238EC
	ColorHeliotropePurple       Color = 0xD462FF
	ColorTyrianPurple           Color = 0xC45AEC
	ColorMediumOrchid           Color = 0xBA55D3
	ColorPurpleFlower           Color = 0xA74AC7
	ColorOrchidPurple           Color = 0xB048B5
	ColorRichLilac              Color = 0xB666D2
	ColorPastelViolet           Color = 0xD291BC
	ColorMauveTaupe             Color = 0x915F6D
	ColorViolaPurple            Color = 0x7E587E
	ColorEggplant               Color = 0x614051
	ColorPlumPurple             Color = 0x583759
	ColorGrape                  Color = 0x5E5A80
	ColorPurpleNavy             Color = 0x4E5180
	ColorSlateBlue              Color = 0x6A5ACD
	ColorBlueLotus              Color = 0x6960EC
	ColorBlurple                Color = 0x5865F2
	ColorLightSlateBlue         Color = 0x736AFF
	ColorMediumSlateBlue        Color = 0x7B68EE
	ColorPeriwinklePurple       Color = 0x7575CF
	ColorVeryPeri               Color = 0x6667AB
	ColorBrightGrape            Color = 0x6F2DA8
	ColorPurpleAmethyst         Color = 0x6C2DC7
	ColorBrightPurple           Color = 0x6A0DAD
	ColorDeepPeriwinkle         Color = 0x5453A6
	ColorDarkSlateBlue          Color = 0x483D8B
	ColorPurpleHaze             Color = 0x4E387E
	ColorPurpleIris             Color = 0x571B7E
	ColorDarkPurple             Color = 0x4B0150
	ColorDeepPurple             Color = 0x36013F
	ColorMidnightPurple         Color = 0x2E1A47
	ColorPurpleMonster          Color = 0x461B7E
	ColorIndigo                 Color = 0x4B0082
	ColorBlueWhale              Color = 0x342D7E
	ColorRebeccaPurple          Color = 0x663399
	ColorPurpleJam              Color = 0x6A287E
	ColorDarkMagenta            Color = 0x8B008B
	ColorPurple                 Color = 0x800080
	ColorFrenchLilac            Color = 0x86608E
	ColorDarkOrchid             Color = 0x9932CC
	ColorDarkViolet             Color = 0x9400D3
	ColorPurpleViolet           Color = 0x8D38C9
	ColorJasminePurple          Color = 0xA23BEC
	ColorPurpleDaffodil         Color = 0xB041FF
	ColorClematisViolet         Color = 0x842DCE
	ColorBlueViolet             Color = 0x8A2BE2
	ColorPurpleSageBush         Color = 0x7A5DC7
	ColorLovelyPurple           Color = 0x7F38EC
	ColorNeonPurple             Color = 0x9D00FF
	ColorPurplePlum             Color = 0x8E35EF
	ColorAztechPurple           Color = 0x893BFF
	ColorMediumPurple           Color = 0x9370DB
	ColorLightPurple            Color = 0x8467D7
	ColorCrocusPurple           Color = 0x9172EC
	ColorPurpleMimosa           Color = 0x9E7BFF
	ColorPeriwinkle             Color = 0xCCCCFF
	ColorPaleLilac              Color = 0xDCD0FF
	ColorLavenderPurple         Color = 0x967BB6
	ColorRosePurple             Color = 0xB09FCA
	ColorLilac                  Color = 0xC8A2C8
	ColorMauve                  Color = 0xE0B0FF
	ColorBrightLilac            Color = 0xD891EF
	ColorPurpleDragon           Color = 0xC38EC7
	ColorPlum                   Color = 0xDDA0DD
	ColorBlushPink              Color = 0xE6A9EC
	ColorPastelPurple           Color = 0xF2A2E8
	ColorBlossomPink            Color = 0xF9B7FF
	ColorWisteriaPurple         Color = 0xC6AEC7
	ColorPurpleThistle          Color = 0xD2B9D3
	ColorThistle                Color = 0xD8BFD8
	ColorPurpleWhite            Color = 0xDFD3E3
	ColorPeriwinklePink         Color = 0xE9CFEC
	ColorCottonCandy            Color = 0xFCDFFF
	ColorLavenderPinocchio      Color = 0xEBDDE2
	ColorDarkWhite              Color = 0xE1D9D1
	ColorAshWhite               Color = 0xE9E4D4
	ColorWhiteChocolate         Color = 0xEDE6D6
	ColorSoftIvory              Color = 0xFAF0DD
	ColorOffWhite               Color = 0xF8F0E3
	ColorPearlWhite             Color = 0xF8F6F0
	ColorRedWhite               Color = 0xF3E8EA
	ColorLavenderBlush          Color = 0xFFF0F5
	ColorPearl                  Color = 0xFDEEF4
	ColorEggShell               Color = 0xFFF9E3
	ColorOldLace                Color = 0xFEF0E3
	ColorLinen                  Color = 0xFAF0E6
	ColorSeaShell               Color = 0xFFF5EE
	ColorBoneWhite              Color = 0xF9F6EE
	ColorRice                   Color = 0xFAF5EF
	ColorFloralWhite            Color = 0xFFFAF0
	ColorIvory                  Color = 0xFFFFF0
	ColorWhiteGold              Color = 0xFFFFF4
	ColorLightWhite             Color = 0xFFFFF7
	ColorWhiteSmoke             Color = 0xF5F5F5
	ColorCotton                 Color = 0xFBFBF9
	ColorSnow                   Color = 0xFFFAFA
	ColorMilkWhite              Color = 0xFEFCFF
	ColorHalfWhite              Color = 0xFFFEFA
)

NOTE:: These color constants are copied from the DPP library (Discord++), a popular C++ Discord library.

Check it out here: https://github.com/brainboxdotcc/DPP

func ParseColor

func ParseColor(s string) (Color, error)

ParseColor parses a hex color string "#RRGGBB" (or without "#") and returns it as Color.

Usage example:

color, err := ParseColor("#1ABC9C")
if err != nil {
    // handle error
}
fmt.Println(color) // prints: 1756092

Returns:

  • Color: parsed color value.
  • error: if parsing fails or input is invalid.

func (Color) String

func (c Color) String() string

String returns the Color formatted as a standard hex color string "#RRGGBB".

Usage example:

c := Color(0x1ABC9C)
fmt.Println(c.String()) // prints: "#1ABC9C"

type Component

type Component interface {
	GetID() int
	GetType() ComponentType
	json.Marshaler
}

Component is an interface for all kind of components.

ActionRowComponent, ButtonComponent StringSelectMenuComponent, TextInputComponent UserSelectMenuComponent, RoleSelectMenuComponent MentionableSelectMenuComponent, ChannelSelectMenuComponent SectionComponent, TextDisplayComponent ThumbnailComponent, MediaGalleryComponent FileComponent, SeparatorComponent ContainerComponent, UnknownComponent

func UnmarshalComponent

func UnmarshalComponent(buf []byte) (Component, error)

type ComponentFields

type ComponentFields struct {
	// ID is an optional 32-bit integer identifier for the component, unique within the message.
	//
	// Note:
	//   - If not specified or set to 0, the API generates a sequential ID.
	//   - Generated IDs do not conflict with other defined IDs in the message.
	ID int `json:"id,omitempty"`

	// Type is the type of the component.
	Type ComponentType `json:"type"`
}

ComponentFields holds common fields for all components.

All components include a type field indicating the component type and an optional id field for identification in interaction responses. The id is a 32-bit integer, unique within the message, and is generated sequentially by the API if not specified. If set to 0, it is treated as empty and replaced by the API. The API ensures generated IDs do not conflict with other defined IDs in the message.

Reference: https://discord.com/developers/docs/interactions/message-components#component-object

func (*ComponentFields) GetID

func (c *ComponentFields) GetID() int

func (*ComponentFields) GetType

func (c *ComponentFields) GetType() ComponentType

type ComponentInteraction

type ComponentInteraction struct {
	InteractionFields
}

TODO: continue the three interactions under this comment.

type ComponentType

type ComponentType int

ComponentType represents the type of a Discord component.

Reference: https://discord.com/developers/docs/interactions/message-components#component-object-component-types

func (ComponentType) Is

func (t ComponentType) Is(componentType ComponentType) bool

Is returns true if the component's Type matches the provided one.

type Connection

type Connection struct {
	// ID is the id of the connection account.
	ID string `json:"id"`
	// Name is the username of the connection account.
	Name string `json:"name"`
	// Type is the service of the connection (twitch, youtube, etc.).
	Type string `json:"type"`
	// Revoked indicates whether the connection is revoked.
	Revoked bool `json:"revoked"`
	// Integrations is an array of partial server integrations.
	Integrations []Integration `json:"integrations"`
	// Verified indicates whether the connection is verified.
	Verified bool `json:"verified"`
	// FriendSync indicates whether friend sync is enabled.
	FriendSync bool `json:"friend_sync"`
	// ShowActivity indicates whether activities related to this connection are shown.
	ShowActivity bool `json:"show_activity"`
	// TwoWayLink indicates whether this connection has a corresponding third party OAuth2 token.
	TwoWayLink bool `json:"two_way_link"`
	// Visibility is the visibility of this connection.
	Visibility int `json:"visibility"`
}

Connection represents a user's connected account.

type ContainerComponent

type ContainerComponent struct {
	ComponentFields

	// Components is an array of child components encapsulated within the container.
	//
	// Valid components:
	//   - ActionRowComponent
	//   - TextDisplayComponent
	//   - SectionComponent
	//   - MediaGalleryComponent
	//   - SeparatorComponent
	//   - FileComponent
	Components []ContainerSubComponent `json:"components"`

	// AccentColor is an optional RGB color for the accent bar on the container.
	//
	// Note:
	//   - Represented as an integer (0x000000 to 0xFFFFFF).
	AccentColor Color `json:"accent_color,omitempty"`

	// Spoiler indicates whether the container content should be blurred out as a spoiler.
	//
	// Note:
	//   - Defaults to false.
	Spoiler bool `json:"spoiler,omitempty"`
}

ContainerComponent is a top-level layout component that visually encapsulates a collection of child components with an optional customizable accent color bar.

It is used to group components in messages, providing a visual container with an optional colored accent. Containers require the IS_COMPONENTS_V2 message flag (1 << 15) to be set when sending the message.

Note:

  • Only available in messages.
  • Requires the IS_COMPONENTS_V2 message flag (1 << 15).
  • The accent_color is an optional RGB color value (0x000000 to 0xFFFFFF).
  • The spoiler field defaults to false, indicating whether the container content is blurred out.

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

func (*ContainerComponent) MarshalJSON

func (c *ContainerComponent) MarshalJSON() ([]byte, error)

func (*ContainerComponent) UnmarshalJSON

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

type ContainerSubComponent

type ContainerSubComponent interface {
	Component
}

ContainerSubComponent is an interface for all components that can be present in a ContainerComponent.

ActionRowComponent, TextDisplayComponent, MediaGalleryComponent, SeparatorComponent, FileComponent

type CreateInviteOptions

type CreateInviteOptions struct {
	// MaxAge is the duration of invite in seconds, 0 for never. Default 86400 (24 hours).
	MaxAge int `json:"max_age,omitempty"`
	// MaxUses is the max number of uses, 0 for unlimited. Default 0.
	MaxUses int `json:"max_uses,omitempty"`
	// Temporary indicates whether this invite grants temporary membership.
	Temporary bool `json:"temporary,omitempty"`
	// Unique indicates whether to try to reuse a similar invite (when false).
	Unique bool `json:"unique,omitempty"`
	// TargetType is the type of target for this voice channel invite.
	TargetType int `json:"target_type,omitempty"`
	// TargetUserID is the id of the user whose stream to display.
	TargetUserID Snowflake `json:"target_user_id,omitempty"`
	// TargetApplicationID is the id of the embedded application to open.
	TargetApplicationID Snowflake `json:"target_application_id,omitempty"`
}

CreateInviteOptions are options for creating an invite.

type DMChannel

type DMChannel struct {
	EntityBase // Embedded client reference for action methods
	DMChannelFields
	// Recipients is the list of users participating in the group DM channel.
	//
	// Info:
	//   - Contains the users involved in the group DM, excluding the current user or bot.
	Recipients []User `json:"recipients"`
}

DMChannel represents a DM channel between the current user and another user.

func (*DMChannel) FetchMessage

func (c *DMChannel) FetchMessage(messageID Snowflake) (*Message, error)

FetchMessage retrieves a single message from this DM channel.

func (*DMChannel) FetchMessages

func (c *DMChannel) FetchMessages(opts FetchMessagesOptions) ([]*Message, error)

FetchMessages retrieves messages from this DM channel.

func (*DMChannel) MarshalJSON

func (c *DMChannel) MarshalJSON() ([]byte, error)

func (*DMChannel) Send

func (c *DMChannel) Send(content string) (*Message, error)

Send sends a message to this DM channel.

func (*DMChannel) SendEmbed

func (c *DMChannel) SendEmbed(embed Embed) (*Message, error)

SendEmbed sends an embed message to this DM channel.

func (*DMChannel) SendWith

func (c *DMChannel) SendWith(opts MessageCreateOptions) (*Message, error)

SendWith sends a message with full options to this DM channel.

type DMChannelFields

type DMChannelFields struct {
	ChannelFields
	MessageChannelFields
}

DMChannelFields contains fields common to DM and Group DM channels.

type DefaultCache

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

DefaultCache is a high-performance cache implementation using 256-way sharding. Lock contention is reduced by ~99.6% compared to single-mutex implementations, making it suitable for bots with 10,000+ guilds.

func (*DefaultCache) CountChannels

func (c *DefaultCache) CountChannels() int

func (*DefaultCache) CountGuildChannels

func (c *DefaultCache) CountGuildChannels(guildID Snowflake) int

func (*DefaultCache) CountGuildMembers

func (c *DefaultCache) CountGuildMembers(guildID Snowflake) int

func (*DefaultCache) CountGuildRoles

func (c *DefaultCache) CountGuildRoles(guildID Snowflake) int

func (*DefaultCache) CountGuilds

func (c *DefaultCache) CountGuilds() int

func (*DefaultCache) CountMembers

func (c *DefaultCache) CountMembers() int

func (*DefaultCache) CountMessages

func (c *DefaultCache) CountMessages() int

func (*DefaultCache) CountRoles

func (c *DefaultCache) CountRoles() int

func (*DefaultCache) CountUsers

func (c *DefaultCache) CountUsers() int

func (*DefaultCache) CountVoiceStates

func (c *DefaultCache) CountVoiceStates() int

func (*DefaultCache) DelChannel

func (c *DefaultCache) DelChannel(channelID Snowflake) bool

func (*DefaultCache) DelGuild

func (c *DefaultCache) DelGuild(guildID Snowflake) bool

func (*DefaultCache) DelGuildChannels

func (c *DefaultCache) DelGuildChannels(guildID Snowflake) bool

func (*DefaultCache) DelGuildMembers

func (c *DefaultCache) DelGuildMembers(guildID Snowflake) bool

func (*DefaultCache) DelMember

func (c *DefaultCache) DelMember(guildID, userID Snowflake) bool

func (*DefaultCache) DelMessage

func (c *DefaultCache) DelMessage(messageID Snowflake) bool

func (*DefaultCache) DelRole

func (c *DefaultCache) DelRole(guildID, roleID Snowflake) bool

func (*DefaultCache) DelUser

func (c *DefaultCache) DelUser(userID Snowflake) bool

func (*DefaultCache) DelVoiceState

func (c *DefaultCache) DelVoiceState(guildID, userID Snowflake) bool

func (*DefaultCache) Flags

func (c *DefaultCache) Flags() CacheFlags

func (*DefaultCache) GetChannel

func (c *DefaultCache) GetChannel(channelID Snowflake) (Channel, bool)

func (*DefaultCache) GetGuild

func (c *DefaultCache) GetGuild(guildID Snowflake) (Guild, bool)

func (*DefaultCache) GetGuildChannels

func (c *DefaultCache) GetGuildChannels(guildID Snowflake) (map[Snowflake]GuildChannel, bool)

func (*DefaultCache) GetGuildMembers

func (c *DefaultCache) GetGuildMembers(guildID Snowflake) (map[Snowflake]Member, bool)

func (*DefaultCache) GetGuildRoles

func (c *DefaultCache) GetGuildRoles(guildID Snowflake) (map[Snowflake]Role, bool)

func (*DefaultCache) GetGuildVoiceStates

func (c *DefaultCache) GetGuildVoiceStates(guildID Snowflake) (map[Snowflake]VoiceState, bool)

func (*DefaultCache) GetMember

func (c *DefaultCache) GetMember(guildID, userID Snowflake) (Member, bool)

func (*DefaultCache) GetMessage

func (c *DefaultCache) GetMessage(messageID Snowflake) (Message, bool)

func (*DefaultCache) GetUser

func (c *DefaultCache) GetUser(userID Snowflake) (User, bool)

func (*DefaultCache) GetVoiceState

func (c *DefaultCache) GetVoiceState(guildID, userID Snowflake) (VoiceState, bool)

func (*DefaultCache) HasChannel

func (c *DefaultCache) HasChannel(channelID Snowflake) bool

func (*DefaultCache) HasGuild

func (c *DefaultCache) HasGuild(guildID Snowflake) bool

func (*DefaultCache) HasGuildChannels

func (c *DefaultCache) HasGuildChannels(guildID Snowflake) bool

func (*DefaultCache) HasGuildMembers

func (c *DefaultCache) HasGuildMembers(guildID Snowflake) bool

func (*DefaultCache) HasGuildRoles

func (c *DefaultCache) HasGuildRoles(guildID Snowflake) bool

func (*DefaultCache) HasGuildVoiceStates

func (c *DefaultCache) HasGuildVoiceStates(guildID Snowflake) bool

func (*DefaultCache) HasMember

func (c *DefaultCache) HasMember(guildID, userID Snowflake) bool

func (*DefaultCache) HasMessage

func (c *DefaultCache) HasMessage(messageID Snowflake) bool

func (*DefaultCache) HasUser

func (c *DefaultCache) HasUser(userID Snowflake) bool

func (*DefaultCache) HasVoiceState

func (c *DefaultCache) HasVoiceState(guildID, userID Snowflake) bool

func (*DefaultCache) PutChannel

func (c *DefaultCache) PutChannel(channel Channel)

func (*DefaultCache) PutGuild

func (c *DefaultCache) PutGuild(guild Guild)

func (*DefaultCache) PutMember

func (c *DefaultCache) PutMember(member Member)

func (*DefaultCache) PutMessage

func (c *DefaultCache) PutMessage(message Message)

func (*DefaultCache) PutRole

func (c *DefaultCache) PutRole(role Role)

func (*DefaultCache) PutUser

func (c *DefaultCache) PutUser(user User)

func (*DefaultCache) PutVoiceState

func (c *DefaultCache) PutVoiceState(voiceState VoiceState)

func (*DefaultCache) SetFlags

func (c *DefaultCache) SetFlags(flags ...CacheFlags)

type DefaultLogger

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

func NewDefaultLogger

func NewDefaultLogger(out io.Writer, level LogLevel) *DefaultLogger

func (*DefaultLogger) Debug

func (l *DefaultLogger) Debug(msg string)

func (*DefaultLogger) Error

func (l *DefaultLogger) Error(msg string)

func (*DefaultLogger) Fatal

func (l *DefaultLogger) Fatal(msg string)

func (*DefaultLogger) Info

func (l *DefaultLogger) Info(msg string)

func (*DefaultLogger) Warn

func (l *DefaultLogger) Warn(msg string)

func (*DefaultLogger) WithField

func (l *DefaultLogger) WithField(key string, value any) Logger

func (*DefaultLogger) WithFields

func (l *DefaultLogger) WithFields(fields map[string]any) Logger

type DefaultReactionEmoji

type DefaultReactionEmoji struct {
	// EmojiID is the ID of a guild's custom emoji.
	//
	// Optional:
	//  - May be equal to 0.
	//
	// Info:
	//  - If 0, EmojiName will be set instead.
	EmojiID Snowflake `json:"emoji_id"`

	// EmojiName is the Unicode character of the emoji.
	//
	// Optional:
	//  - May be empty string.
	//
	// Info:
	//  - If empty, EmojiID will be set instead.
	EmojiName string `json:"emoji_name"`
}

DefaultReactionEmoji represents a default reaction emoji for forum channels.

type DefaultShardsRateLimiter

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

DefaultShardsRateLimiter implements a simple token bucket rate limiter using a buffered channel of tokens.

The capacity and refill interval control the max burst and rate.

func NewDefaultShardsRateLimiter

func NewDefaultShardsRateLimiter(r int, interval time.Duration) *DefaultShardsRateLimiter

NewDefaultShardsRateLimiter creates a new token bucket rate limiter.

r specifies the maximum burst tokens allowed. interval specifies how frequently tokens are refilled.

func (*DefaultShardsRateLimiter) Wait

func (rl *DefaultShardsRateLimiter) Wait()

Wait blocks until a token is available for sending Identify.

type DefaultWorkerPool

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

func (*DefaultWorkerPool) Shutdown

func (p *DefaultWorkerPool) Shutdown()

Shutdown stops the pool immediately; no waiting for workers.

func (*DefaultWorkerPool) Submit

func (p *DefaultWorkerPool) Submit(task WorkerTask) bool

Submit submits a task to the pool. Returns false if the queue is full and task dropped.

type DescriptionConstraints

type DescriptionConstraints struct {
	// Description is the description of the command.
	//
	// Info:
	//  - Must be 1-100 characters.
	Description string `json:"description"`

	// DescriptionLocalizations is a localization dictionary for the description field.
	//
	// Info:
	//  - Keys are available locales.
	//  - Values follow the same restrictions as Description (1-100 characters).
	DescriptionLocalizations map[Locale]string `json:"description_localizations"`
}

DescriptionConstraints contains description fields for application commands.

type DiscordAPIError

type DiscordAPIError struct {
	// Code is the Discord error code.
	Code int `json:"code"`

	// Message is the error message from Discord.
	Message string `json:"message"`

	// HTTPStatus is the HTTP status code.
	HTTPStatus int `json:"-"`

	// Errors contains nested validation errors.
	Errors map[string]interface{} `json:"errors,omitempty"`
}

DiscordAPIError represents an error returned by the Discord API.

func (*DiscordAPIError) Error

func (e *DiscordAPIError) Error() string

Error implements the error interface.

func (*DiscordAPIError) IsForbidden

func (e *DiscordAPIError) IsForbidden() bool

IsForbidden returns true if this is a 403 Forbidden error.

func (*DiscordAPIError) IsNotFound

func (e *DiscordAPIError) IsNotFound() bool

IsNotFound returns true if this is a 404 Not Found error.

func (*DiscordAPIError) IsRateLimited

func (e *DiscordAPIError) IsRateLimited() bool

IsRateLimited returns true if this is a 429 Rate Limited error.

func (*DiscordAPIError) IsUnauthorized

func (e *DiscordAPIError) IsUnauthorized() bool

IsUnauthorized returns true if this is a 401 Unauthorized error.

type Embed

type Embed struct {
	// Title is the title of the embed.
	//
	// Optional, max 256 characters, empty string if not set.
	Title string `json:"title,omitempty"`

	// Type is the type of the embed.
	//
	// Optional, always "rich" for webhook embeds.
	Type EmbedType `json:"type,omitempty"`

	// Description is the description text of the embed.
	//
	// Optional, max 4096 characters, empty string if not set.
	Description string `json:"description,omitempty"`

	// URL is the URL of the embed.
	//
	// Optional, empty string if not set.
	URL string `json:"url,omitempty"`

	// Timestamp is the timestamp of the embed content in ISO8601 format.
	//
	// Optional, zero value if not set.
	Timestamp *time.Time `json:"timestamp"`

	// Color is the color code of the embed (decimal integer).
	//
	// Optional, 0 if not set.
	Color Color `json:"color,omitempty"`

	// Footer contains footer information.
	//
	// Optional, may be nil if not set.
	Footer *EmbedFooter `json:"footer,omitempty"`

	// Image contains image information.
	//
	// Optional, may be nil if not set.
	Image *EmbedImage `json:"image,omitempty"`

	// Thumbnail contains thumbnail information.
	//
	// Optional, may be nil if not set.
	Thumbnail *EmbedThumbnail `json:"thumbnail,omitempty"`

	// Video contains video information.
	//
	// Optional, may be nil if not set.
	Video *EmbedVideo `json:"video,omitempty"`

	// Provider contains provider information.
	//
	// Optional, may be nil if not set.
	Provider *EmbedProvider `json:"provider,omitempty"`

	// Author contains author information.
	//
	// Optional, may be nil if not set.
	// author.name max 256 characters
	Author *EmbedAuthor `json:"author,omitempty"`

	// Fields contains an array of embed fields.
	//
	// Optional, max 25 fields.
	// field.name max 256 characters, field.value max 1024 characters
	Fields []EmbedField `json:"fields,omitempty"`
}

Embed represents a Discord embed object.

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

Limits:

  • The combined sum of characters in all title, description, field.name, field.value, footer.text, and author.name fields across all embeds in a message must not exceed 6000.

func (*Embed) Builder

func (e *Embed) Builder() EmbedBuilder

Builder returns a new EmbedBuilder initialized with a copy of the current embed.

type EmbedAuthor

type EmbedAuthor struct {
	// Name is the name of the author.
	//
	// Always present, max 256 characters.
	Name string `json:"name"`

	// URL is the URL of the author.
	//
	// Optional, may be empty string if not set.
	URL string `json:"url,omitempty"`

	// IconURL is the URL of the author icon.
	//
	// Optional, may be empty string if not set.
	IconURL string `json:"icon_url,omitempty"`

	// ProxyIconURL is a proxied URL of the author icon.
	//
	// Optional, may be empty string if not set.
	ProxyIconURL string `json:"proxy_icon_url,omitempty"`
}

EmbedAuthor represents the author object of an embed.

Limits: - name max 256 characters

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

type EmbedBuilder

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

EmbedBuilder helps build an Embed with chainable methods.

func NewEmbedBuilder

func NewEmbedBuilder() *EmbedBuilder

NewEmbedBuilder creates a new EmbedBuilder instance.

func (*EmbedBuilder) AddField

func (b *EmbedBuilder) AddField(name, value string, inline bool) *EmbedBuilder

AddField appends a field to the embed fields slice.

func (*EmbedBuilder) Build

func (b *EmbedBuilder) Build() Embed

Build returns the final Embed object ready to send.

func (*EmbedBuilder) RemoveField

func (b *EmbedBuilder) RemoveField(i int) *EmbedBuilder

RemoveField removes a field from the EmbedBuilder

func (*EmbedBuilder) SetAuthor

func (b *EmbedBuilder) SetAuthor(name, url, iconURL string) *EmbedBuilder

SetAuthor sets the embed author name and optional URL/icon.

func (*EmbedBuilder) SetColor

func (b *EmbedBuilder) SetColor(color Color) *EmbedBuilder

SetColor sets the embed color.

func (*EmbedBuilder) SetDescription

func (b *EmbedBuilder) SetDescription(desc string) *EmbedBuilder

SetDescription sets the embed description (max 4096 chars).

func (*EmbedBuilder) SetFields

func (e *EmbedBuilder) SetFields(fields ...EmbedField)

SetFields sets all embed fields at once.

Note: This method does not enforce field limits or length constraints. It's recommended to use EmbedBuilder.AddField for validation.

func (*EmbedBuilder) SetFooter

func (b *EmbedBuilder) SetFooter(text, iconURL string) *EmbedBuilder

SetFooter sets the embed footer text and optional icon URL.

func (*EmbedBuilder) SetImage

func (b *EmbedBuilder) SetImage(url string) *EmbedBuilder

SetImage sets the embed image URL.

func (*EmbedBuilder) SetThumbnail

func (b *EmbedBuilder) SetThumbnail(url string) *EmbedBuilder

SetThumbnail sets the embed thumbnail URL.

func (*EmbedBuilder) SetTimestamp

func (b *EmbedBuilder) SetTimestamp(t time.Time) *EmbedBuilder

SetTimestamp sets the embed timestamp.

func (*EmbedBuilder) SetTitle

func (b *EmbedBuilder) SetTitle(title string) *EmbedBuilder

SetTitle sets the embed title (max 256 chars).

func (*EmbedBuilder) SetURL

func (b *EmbedBuilder) SetURL(url string) *EmbedBuilder

SetURL sets the embed SetURL.

type EmbedField

type EmbedField struct {
	// Name is the name of the field.
	//
	// Always present, max 256 characters.
	Name string `json:"name"`

	// Value is the value of the field.
	//
	// Always present, max 1024 characters.
	Value string `json:"value"`

	// Inline indicates whether this field should display inline.
	//
	// Optional, false if not set.
	Inline bool `json:"inline,omitempty"`
}

EmbedField represents a field object in an embed.

Limits: - name max 256 characters - value max 1024 characters

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

type EmbedFooter

type EmbedFooter struct {
	// Text is the footer text.
	//
	// Always present, max 2048 characters.
	Text string `json:"text"`

	// IconURL is the URL of the footer icon.
	//
	// Optional, may be empty string if not set.
	IconURL string `json:"icon_url,omitempty"`

	// ProxyIconURL is a proxied URL of the footer icon.
	//
	// Optional, may be empty string if not set.
	ProxyIconURL string `json:"proxy_icon_url,omitempty"`
}

EmbedFooter represents the footer object of an embed.

Limits: - text max 2048 characters

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

type EmbedImage

type EmbedImage struct {
	// URL is the source URL of the image.
	//
	// Always present. Supports only http(s) and attachments.
	URL string `json:"url"`

	// ProxyURL is a proxied URL of the image.
	//
	// Optional, may be empty string if not set.
	ProxyURL string `json:"proxy_url,omitempty"`

	// Height is the height of the image.
	//
	// Optional, 0 if not set.
	Height int `json:"height,omitempty"`

	// Width is the width of the image.
	//
	// Optional, 0 if not set.
	Width int `json:"width,omitempty"`
}

EmbedImage represents the image object of an embed.

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

type EmbedProvider

type EmbedProvider struct {
	// Name is the name of the provider.
	//
	// Optional, may be empty string if not set.
	Name string `json:"name,omitempty"`

	// URL is the URL of the provider.
	//
	// Optional, may be empty string if not set.
	URL string `json:"url,omitempty"`
}

EmbedProvider represents the provider object of an embed.

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

type EmbedThumbnail

type EmbedThumbnail struct {
	// URL is the source URL of the thumbnail.
	//
	// Always present. Supports only http(s) and attachments.
	URL string `json:"url"`

	// ProxyURL is a proxied URL of the thumbnail.
	//
	// Optional, may be empty string if not set.
	ProxyURL string `json:"proxy_url,omitempty"`

	// Height is the height of the thumbnail.
	//
	// Optional, 0 if not set.
	Height int `json:"height,omitempty"`

	// Width is the width of the thumbnail.
	//
	// Optional, 0 if not set.
	Width int `json:"width,omitempty"`
}

EmbedThumbnail represents the thumbnail object of an embed.

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

type EmbedType

type EmbedType string

EmbedType represents the type of an embed.

const (
	EmbedTypeRich       EmbedType = "rich"
	EmbedTypeImage      EmbedType = "image"
	EmbedTypeVideo      EmbedType = "video"
	EmbedTypeGifv       EmbedType = "gifv"
	EmbedTypeArticle    EmbedType = "article"
	EmbedTypeLink       EmbedType = "link"
	EmbedTypePollResult EmbedType = "poll_result"
)

type EmbedVideo

type EmbedVideo struct {
	// URL is the source URL of the video.
	//
	// Optional, may be empty string if not set.
	URL string `json:"url,omitempty"`

	// ProxyURL is a proxied URL of the video.
	//
	// Optional, may be empty string if not set.
	ProxyURL string `json:"proxy_url,omitempty"`

	// Height is the height of the video.
	//
	// Optional, 0 if not set.
	Height int `json:"height,omitempty"`

	// Width is the width of the video.
	//
	// Optional, 0 if not set.
	Width int `json:"width,omitempty"`
}

EmbedVideo represents the video object of an embed.

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

type Emoji

type Emoji struct {
	// ID is the unique Discord snowflake ID of the emoji.
	//
	// Optional:
	//   - May be nil (zero value) for unicode emojis
	ID Snowflake `json:"id,omitempty"`

	// Name is the emoji's name.
	//
	// Optional:
	//   - May be empty in deleted emojis.
	Name string `json:"name,omitempty"`

	// Roles is a list of role IDs allowed to use this emoji.
	Roles []Snowflake `json:"roles,omitempty"`

	// RequireColons indicates whether the emoji must be wrapped in colons to be used.
	RequireColons bool `json:"require_colons,omitempty"`

	// Managed indicates whether the emoji is managed by an integration.
	Managed bool `json:"managed,omitempty"`

	// Animated indicates whether the emoji is an animated emoji (.gif).
	Animated bool `json:"animated,omitempty"`

	// Available indicates whether the emoji can currently be used.
	Available bool `json:"available,omitempty"`
}

Emoji represents a custom emoji object used within a Discord guild.

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

func (*Emoji) CreatedAt

func (e *Emoji) CreatedAt() time.Time

CreatedAt returns the time when this emojis is created at.

func (*Emoji) Mention

func (e *Emoji) Mention() string

Mention returns a Discord mention string for the emoji.

Example output: "<:sliming:123456789012345678>"

func (*Emoji) URL

func (e *Emoji) URL() string

URL returns the URL to the emoji's image.

func (*Emoji) URLWith

func (e *Emoji) URLWith(format ImageFormat, size ImageSize) string

URLWith returns the URL to the emoji's image. allowing explicit specification of image format and size.

type Entitlement

type Entitlement struct {
	// ID is the unique identifier of the entitlement.
	ID Snowflake `json:"id"`

	// SkuID is the ID of the SKU associated with this entitlement.
	SkuID Snowflake `json:"sku_id"`

	// ApplicationID is the ID of the application this entitlement belongs to.
	ApplicationID Snowflake `json:"application_id"`

	// UserID is the id of the user that is granted access to the entitlement's SKU.
	//
	// Optional:
	//   - Will be 0 if the entitlement is not associated with a specific user.
	UserID Snowflake `json:"user_id"`

	// Type is the type of entitlement.
	Type EntitlementType `json:"type"`

	// Deleted indicates whether the entitlement has been deleted.
	Deleted bool `json:"deleted"`

	// StartsAt is the start date at which the entitlement is valid.
	//
	// Optional.
	StartsAt *time.Time `json:"starts_at"`

	// EndsAt is the optional date at which the entitlement is no longer valid.
	//
	// Optional.
	EndsAt *time.Time `json:"ends_at"`

	// GuildID is the id of the guild that is granted access to the entitlement's SKU.
	//
	// Optional:
	//   - Will be 0 if the entitlement is not associated with a guild.
	GuildID Snowflake `json:"guild_id"`

	// Consumed indicates whether the entitlement for a consumable item has been consumed.
	//
	// Optional:
	//   - Will be null for non-consumable entitlements.
	Consumed *bool `json:"consumed"`
}

Entitlement represents a Discord Entitlement.

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

type EntitlementType

type EntitlementType int

EntitlementType represents the type of an entitlement in Discord.

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

const (
	// EntitlementTypePurchase indicates the entitlement was purchased by the user.
	EntitlementTypePurchase EntitlementType = 1 + iota

	// EntitlementTypePremiumSubscription indicates the entitlement is for a Discord Nitro subscription.
	EntitlementTypePremiumSubscription

	// EntitlementTypeDeveloperGift indicates the entitlement was gifted by a developer.
	EntitlementTypeDeveloperGift

	// EntitlementTypeTestModePurchase indicates the entitlement was purchased by a developer in application test mode.
	EntitlementTypeTestModePurchase

	// EntitlementTypeFreePurchase indicates the entitlement was granted when the SKU was free.
	EntitlementTypeFreePurchase

	// EntitlementTypeUserGift indicates the entitlement was gifted by another user.
	EntitlementTypeUserGift

	// EntitlementTypePremiumPurchase indicates the entitlement was claimed for free by a Nitro subscriber.
	EntitlementTypePremiumPurchase

	// EntitlementTypeApplicationSubscription indicates the entitlement was purchased as an app subscription.
	EntitlementTypeApplicationSubscription
)

func (EntitlementType) Is

func (t EntitlementType) Is(entitlementType EntitlementType) bool

Is returns true if the entitlement's Type matches the provided one.

type EntityBase

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

EntityBase provides common functionality for all Discord entities that need to interact with the Discord API.

Entities embedding EntityBase can call action methods like Reply(), Delete(), etc. The client reference is set automatically when entities are received from events or fetched from the API.

func (*EntityBase) Client

func (e *EntityBase) Client() *Client

Client returns the client reference for this entity. Returns nil if the entity was not received from a client context.

func (*EntityBase) HasClient

func (e *EntityBase) HasClient() bool

HasClient returns true if this entity has a client reference.

func (*EntityBase) SetClient

func (e *EntityBase) SetClient(c *Client)

SetClient sets the client reference for this entity. This is called internally when entities are received from events or API responses.

type ExplicitContentFilterLevel

type ExplicitContentFilterLevel int

ExplicitContentFilterLevel represents the explicit content filter level on a Discord guild.

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

const (
	// Media content will not be scanned.
	ExplicitContentFilterLevelDisabled ExplicitContentFilterLevel = iota
	// Media content sent by members without roles will be scanned.
	ExplicitContentFilterLevelMembersWithoutRoles
	// Media content sent by all members will be scanned
	ExplicitContentFilterLevelAllMembers
)

func (ExplicitContentFilterLevel) Is

Is returns true if the explicit content level matches the provided one.

type FetchMessagesOptions

type FetchMessagesOptions struct {
	// Around gets messages around this message ID.
	Around Snowflake
	// Before gets messages before this message ID.
	Before Snowflake
	// After gets messages after this message ID.
	After Snowflake
	// Limit is the maximum number of messages to return (1-100). Default is 50.
	Limit int
}

FetchMessagesOptions are options for fetching messages from a channel.

type FileComponent

type FileComponent struct {
	ComponentFields

	// File is an unfurled media item that only supports attachment references using the attachment://filename syntax.
	File UnfurledMediaItem `json:"file"`

	// Spoiler is whether the media should be a spoiler (or blurred out). Defaults to false.
	Spoiler bool `json:"spoiler,omitempty"`

	// Name is the name of the file. This field is ignored and provided by the API as part of the response.
	Name string `json:"name,omitempty"`

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

FileComponent is a top-level content component that displays an uploaded file as an attachment to the message.

Each file component can only display one attached file, but multiple files can be uploaded and added to different file components within a payload. The file must use the attachment://filename syntax in the unfurled media item. File components require the IS_COMPONENTS_V2 message flag (1 << 15) to be set when sending the message.

Note:

  • Only available in messages.
  • Requires the IS_COMPONENTS_V2 message flag (1 << 15).
  • Only supports attachment references using the attachment://filename syntax.

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

func (*FileComponent) MarshalJSON

func (c *FileComponent) MarshalJSON() ([]byte, error)

type FloatConstraints

type FloatConstraints struct {
	// MinValue is the minimum value permitted for the float.
	//
	// Info:
	//  - Must be between -2^53 and 2^53.
	//
	// Optional:
	//  - May be nil if no minimum value is specified.
	MinValue *float64 `json:"min_value,omitempty"`

	// MaxValue is the maximum value permitted for the float.
	//
	// Info:
	//  - Must be between -2^53 and 2^53.
	//
	// Optional:
	//  - May be nil if no maximum value is specified.
	MaxValue *float64 `json:"max_value,omitempty"`
}

FloatConstraints contains constraints for float options.

type ForumChannel

ForumChannel represents a guild forum channel.

func (*ForumChannel) Delete

func (c *ForumChannel) Delete(reason string) error

Delete deletes this forum channel.

func (*ForumChannel) Edit

func (c *ForumChannel) Edit(opts ChannelEditOptions, reason string) (*ForumChannel, error)

Edit modifies this forum channel's settings.

func (*ForumChannel) Guild

func (c *ForumChannel) Guild() (Guild, bool)

Guild returns the cached guild this forum channel belongs to.

func (*ForumChannel) MarshalJSON

func (c *ForumChannel) MarshalJSON() ([]byte, error)

type ForumChannelFields

type ForumChannelFields struct {
	// AvailableTags is the set of tags that can be used in this channel.
	AvailableTags []ForumTag `json:"available_tags"`

	// DefaultReactionEmoji specifies the emoji used as the default way to react to a forum post.
	DefaultReactionEmoji DefaultReactionEmoji `json:"default_reaction_emoji"`

	// DefaultSortOrder is the default sort order type used to order posts
	// in GuildForum and GuildMedia channels. Defaults to PostsSortOrderLatestActivity.
	DefaultSortOrder ForumPostsSortOrder `json:"default_sort_order"`

	// DefaultForumLayout is the default forum layout view used to display posts
	// in GuildForum channels. Defaults to ForumLayoutNotSet.
	DefaultForumLayout ForumLayout `json:"default_forum_layout"`
}

ForumChannelFields holds forum and media channel specific fields.

type ForumLayout

type ForumLayout int

ForumLayout defines the layout type used to place posts in forum/media channels.

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

const (
	// ForumLayoutNotSet indicates no default has been set for forum channel.
	ForumLayoutNotSet ForumLayout = 0

	// ForumLayoutListView displays posts as a list.
	ForumLayoutListView ForumLayout = 1

	// ForumLayoutGalleryView displays posts as a collection of tiles.
	ForumLayoutGalleryView ForumLayout = 2
)

func (ForumLayout) Is

func (t ForumLayout) Is(layoutType ForumLayout) bool

Is returns true if the channel's PostsLayout type matches the provided one.

type ForumPostsSortOrder

type ForumPostsSortOrder int

ForumPostsSortOrder defines the sort order type used to order posts in forum/media channels.

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

const (
	// ForumPostsSortOrderLatestActivity sorts posts by latest activity (default).
	ForumPostsSortOrderLatestActivity ForumPostsSortOrder = 0

	// ForumPostsSortOrderCreationDate sorts posts by creation time (most recent to oldest).
	ForumPostsSortOrderCreationDate ForumPostsSortOrder = 1
)

func (ForumPostsSortOrder) Is

func (t ForumPostsSortOrder) Is(sortOrderType ForumPostsSortOrder) bool

Is returns true if the channel's SortOrder type matches the provided one.

type ForumTag

type ForumTag struct {
	// ID is the id of the tag.
	ID Snowflake `json:"id"`

	// Name is the name of the tag (0-20 characters).
	Name string `json:"name"`

	// Moderated indicates whether this tag can only be added to or removed from
	// threads by a member with the ManageThreads permission.
	Moderated bool `json:"moderated"`

	// EmojiID is the ID of a guild's custom emoji.
	//
	// Optional:
	//  - May be equal 0.
	//
	// Note:
	//  - If EmojiName is empty (not set), then EmojiID must be set (non-zero).
	EmojiID Snowflake `json:"emoji_id,omitempty"`

	// EmojiName is the Unicode character of the emoji.
	//
	// Optional:
	//  - May be empty string.
	//
	// Note:
	//  - If EmojiName is empty (not set), then EmojiID must be set (non-zero).
	EmojiName string `json:"emoji_name,omitempty"`
}

ForumTag represents a tag that can be applied to a thread in a GuildForum or GuildMedia channel.

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

type GatewayBot

type GatewayBot struct {
	// WSS URL that can be used for connecting to the Gateway
	URL string `json:"url"`
	// Recommended number of shards to use when connecting
	Shards int `json:"shards"`
	// Information on the current session start limit
	SessionStartLimit struct {
		Total          int `json:"total"`
		Remaining      int `json:"remaining"`
		ResetAfter     int `json:"reset_after"`
		MaxConcurrency int `json:"max_concurrency"`
	} `json:"session_start_limit"`
}

GatewayBot is Discord Gateway Bot.

type GatewayCloseEventCode

type GatewayCloseEventCode int

GatewayCloseEventCode represents Discord Gateway close event codes.

const (
	// UnknownError
	//
	//  - Explanation: We're not sure what went wrong. Try reconnecting?
	//  - Reconnect: true.
	GatewayCloseEventCodeUnknownError GatewayCloseEventCode = 4000

	// UnknownOpcode
	//
	//  - Explanation: You sent an invalid Gateway opcode or an invalid payload for an opcode. Don't do that!
	//  - Reconnect: true.
	GatewayCloseEventCodeUnknownOpcode GatewayCloseEventCode = 4001

	// DecodeError
	//
	//  - Explanation: You sent an invalid payload to Discord. Don't do that!
	//  - Reconnect: true.
	GatewayCloseEventCodeDecodeError GatewayCloseEventCode = 4002

	// NotAuthenticated
	//
	//  - Explanation: You sent a payload prior to identifying, or this session has been invalidated.
	//  - Reconnect: true.
	GatewayCloseEventCodeNotAuthenticated GatewayCloseEventCode = 4003

	// AuthenticationFailed
	//
	//  - Explanation: The account token sent with your identify payload is incorrect.
	//  - Reconnect: false.
	GatewayCloseEventCodeAuthenticationFailed GatewayCloseEventCode = 4004

	// AlreadyAuthenticated
	//
	//  - Explanation: You sent more than one identify payload. Don't do that!
	//  - Reconnect: true.
	GatewayCloseEventCodeAlreadyAuthenticated GatewayCloseEventCode = 4005

	// InvalidSeq
	//
	//  - Explanation: The sequence sent when resuming the session was invalid. Reconnect and start a new session.
	//  - Reconnect: true.
	GatewayCloseEventCodeInvalidSeq GatewayCloseEventCode = 4007

	// RateLimited
	//
	//  - Explanation: You're sending payloads too quickly. Slow down! You will be disconnected on receiving this.
	//  - Reconnect: true.
	GatewayCloseEventCodeRateLimited GatewayCloseEventCode = 4008

	// SessionTimedOut
	//
	//  - Explanation: Your session timed out. Reconnect and start a new one.
	//  - Reconnect: true.
	GatewayCloseEventCodeSessionTimedOut GatewayCloseEventCode = 4009

	// InvalidShard
	//
	//  - Explanation: You sent an invalid shard when identifying.
	//  - Reconnect: false.
	GatewayCloseEventCodeInvalidShard GatewayCloseEventCode = 4010

	// ShardingRequired
	//
	//  - Explanation: The session would have handled too many guilds - sharding is required.
	//  - Reconnect: false.
	GatewayCloseEventCodeShardingRequired GatewayCloseEventCode = 4011

	// InvalidAPIVersion
	//
	//  - Explanation: You sent an invalid version for the gateway.
	//  - Reconnect: false.
	GatewayCloseEventCodeInvalidAPIVersion GatewayCloseEventCode = 4012

	// InvalidIntents
	//
	//  - Explanation: You sent an invalid intent for a Gateway Intent. You may have incorrectly calculated the bitwise value.
	//  - Reconnect: false.
	GatewayCloseEventCodeInvalidIntents GatewayCloseEventCode = 4013

	// DisallowedIntents
	//
	//  - Explanation: You sent a disallowed intent for a Gateway Intent. You may have tried to specify an intent you are not approved for.
	//  - Reconnect: false.
	GatewayCloseEventCodeDisallowedIntents GatewayCloseEventCode = 4014
)

type GatewayGuild

type GatewayGuild struct {
	RestGuild

	// Large if true this is considered a large guild.
	Large bool `json:"large"`

	// MemberCount is the total number of members in this guild.
	MemberCount int `json:"member_count"`

	// VoiceStates is the states of members currently in voice channels; lacks the GuildID key.
	VoiceStates []VoiceState `json:"voice_states"`

	// Members is a slice of the Users in the guild.
	Members []Member `json:"members"`

	// Channels is a slice of the Channels in the guild.
	Channels []GuildChannel `json:"channels"`

	// Threads are all active threads in the guild that current user has permission to view.
	Threads []ThreadChannel `json:"threads"`

	// StageInstances is a slice of the Stage instances in the guild.
	StageInstances []StageInstance `json:"stage_instances"`

	// SoundboardSounds is a slice of the Soundboard sounds in the guild.
	SoundboardSounds []SoundBoardSound `json:"soundboard_sounds"`
}

RestGuild represents a guild object returned by the Discord gateway. It embeds RestGuild and adds additional fields provided in the gateway.

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

func (*GatewayGuild) UnmarshalJSON

func (g *GatewayGuild) UnmarshalJSON(buf []byte) error

UnmarshalJSON implements json.Unmarshaler for GatewayGuild.

type GatewayIntent

type GatewayIntent uint32

GatewayIntent represents Discord Gateway Intents.

Intents are bit flags that specify which events your bot receives over the WebSocket connection. Combine multiple intents using bitwise OR (|).

Example:

intents := GatewayIntent_Guilds | GatewayIntent_GuildMessages
const (
	// Guilds includes:
	//   GuildCreate, GuildUpdate, GuildDelete
	//   GuildRoleCreate, GuildRoleUpdate, GuildRoleDelete
	//   ChannelCreate, ChannelUpdate, ChannelDelete, ChannelPinsUpdate
	//   ThreadCreate, ThreadUpdate, ThreadDelete, ThreadListSync
	//   ThreadMemberUpdate, ThreadMembersUpdate
	//   StageInstanceCreate, StageInstanceUpdate, StageInstanceDelete
	GatewayIntentGuilds GatewayIntent = 1 << 0

	// GuildMembers includes:
	//   GuildMemberAdd, GuildMemberUpdate, GuildMemberRemove
	//   ThreadMembersUpdate
	GatewayIntentGuildMembers GatewayIntent = 1 << 1

	// GuildModeration includes:
	//   GuildAuditLogEntryCreate, GuildBanAdd, GuildBanRemove
	GatewayIntentGuildModeration GatewayIntent = 1 << 2

	// GuildExpressions includes:
	//   GuildEmojisUpdate, GuildStickersUpdate
	//   GuildSoundboardSoundCreate, GuildSoundboardSoundUpdate, GuildSoundboardSoundDelete
	//   GuildSoundboardSoundsUpdate
	GatewayIntentGuildExpressions GatewayIntent = 1 << 3

	// GuildIntegrations includes:
	//   GuildIntegrationsUpdate, IntegrationCreate, IntegrationUpdate, IntegrationDelete
	GatewayIntentGuildIntegrations GatewayIntent = 1 << 4

	// GuildWebhooks includes:
	//   WebhooksUpdate
	GatewayIntentGuildWebhooks GatewayIntent = 1 << 5

	// GuildInvites includes:
	//   InviteCreate, InviteDelete
	GatewayIntentGuildInvites GatewayIntent = 1 << 6

	// GuildVoiceStates includes:
	//   VoiceChannelEffectSend, VoiceStateUpdate
	GatewayIntentGuildVoiceStates GatewayIntent = 1 << 7

	// GuildPresences includes:
	//   PresenceUpdate
	GatewayIntentGuildPresences GatewayIntent = 1 << 8

	// GuildMessages includes:
	//   MessageCreate, MessageUpdate, MessageDelete, MessageDeleteBulk
	GatewayIntentGuildMessages GatewayIntent = 1 << 9

	// GuildMessageReactions includes:
	//   MessageReactionAdd, MessageReactionRemove, MessageReactionRemoveAll, MessageReactionRemoveEmoji
	GatewayIntentGuildMessageReactions GatewayIntent = 1 << 10

	// GuildMessageTyping includes:
	//   TypingStart
	GatewayIntentGuildMessageTyping GatewayIntent = 1 << 11

	// DirectMessages includes:
	//   MessageCreate, MessageUpdate, MessageDelete, ChannelPinsUpdate
	GatewayIntentDirectMessages GatewayIntent = 1 << 12

	// DirectMessageReactions includes:
	//   MessageReactionAdd, MessageReactionRemove, MessageReactionRemoveAll, MessageReactionRemoveEmoji
	GatewayIntentDirectMessageReactions GatewayIntent = 1 << 13

	// DirectMessageTyping includes:
	//   TypingStart
	GatewayIntentDirectMessageTyping GatewayIntent = 1 << 14

	// MessageContent enables access to message content in events.
	GatewayIntentMessageContent GatewayIntent = 1 << 15

	// GuildScheduledEvents includes:
	//   GuildScheduledEventCreate, GuildScheduledEventUpdate, GuildScheduledEventDelete
	//   GuildScheduledEventUserAdd, GuildScheduledEventUserRemove
	GatewayIntentGuildScheduledEvents GatewayIntent = 1 << 16

	// AutoModerationConfiguration includes:
	//   AutoModerationRuleCreate, AutoModerationRuleUpdate, AutoModerationRuleDelete
	GatewayIntentAutoModerationConfiguration GatewayIntent = 1 << 20

	// AutoModerationExecution includes:
	//   AutoModerationActionExecution
	GatewayIntentAutoModerationExecution GatewayIntent = 1 << 21

	// GuildMessagePolls includes:
	//   MessagePollVoteAdd, MessagePollVoteRemove
	GatewayIntentGuildMessagePolls GatewayIntent = 1 << 24

	// DirectMessagePolls includes:
	//   MessagePollVoteAdd, MessagePollVoteRemove
	GatewayIntentDirectMessagePolls GatewayIntent = 1 << 25
)

type GetCurrentUserGuildsOptions

type GetCurrentUserGuildsOptions struct {
	// Before gets guilds before this guild ID.
	Before Snowflake
	// After gets guilds after this guild ID.
	After Snowflake
	// Limit is the max number of guilds to return (1-200). Default is 200.
	Limit int
	// WithCounts includes approximate member and presence counts.
	WithCounts bool
}

GetCurrentUserGuildsOptions are options for getting current user guilds.

type GetReactionsOptions

type GetReactionsOptions struct {
	// After gets users after this user ID.
	After Snowflake
	// Limit is the maximum number of users to return (1-100). Default is 25.
	Limit int
}

GetReactionsOptions are options for getting reactions on a message.

type GroupDMChannel

type GroupDMChannel struct {
	EntityBase // Embedded client reference for action methods
	DMChannelFields
	// Icon is the custom icon for the group DM channel.
	//
	// Optional:
	//   - Will be empty string if no icon.
	Icon string `json:"icon"`
}

GroupDMChannel represents a group DM channel between multiple users.

func (*GroupDMChannel) FetchMessage

func (c *GroupDMChannel) FetchMessage(messageID Snowflake) (*Message, error)

FetchMessage retrieves a single message from this group DM channel.

func (*GroupDMChannel) FetchMessages

func (c *GroupDMChannel) FetchMessages(opts FetchMessagesOptions) ([]*Message, error)

FetchMessages retrieves messages from this group DM channel.

func (*GroupDMChannel) MarshalJSON

func (c *GroupDMChannel) MarshalJSON() ([]byte, error)

func (*GroupDMChannel) Send

func (c *GroupDMChannel) Send(content string) (*Message, error)

Send sends a message to this group DM channel.

func (*GroupDMChannel) SendEmbed

func (c *GroupDMChannel) SendEmbed(embed Embed) (*Message, error)

SendEmbed sends an embed message to this group DM channel.

func (*GroupDMChannel) SendWith

func (c *GroupDMChannel) SendWith(opts MessageCreateOptions) (*Message, error)

SendWith sends a message with full options to this group DM channel.

type Guild

type Guild struct {
	EntityBase // Embedded client reference for action methods

	// ID is the guild's unique Discord snowflake ID.
	ID Snowflake `json:"id"`

	// Unavailable is whether this guild is available or not.
	Unavailable bool `json:"unavailable"`

	// Name is the guild's name.
	Name string `json:"name"`

	// Description is the description of a guild.
	//
	// Optional:
	//  - May be empty string if no description is set.
	Description string `json:"description"`

	// Icon is the guild's icon hash.
	//
	// Optional:
	//  - May be empty string if no icon.
	Icon string `json:"icon"`

	// Splash is the guild's splash hash.
	//
	// Optional:
	//  - May be empty string if no splash.
	Splash string `json:"splash"`

	// DiscoverySplash is the guild's discovery splash hash.
	//
	// Optional:
	//  - May be empty string if no discovery splash.
	DiscoverySplash string `json:"discovery_splash"`

	// OwnerID is the guild's owner id.
	OwnerID Snowflake `json:"owner_id"`

	// AfkChannelID is the guild's afk channel id.
	//
	// Optional:
	//  - May be equal to 0 if no Afk channel is set.
	AfkChannelID Snowflake `json:"afk_channel_id"`

	// AfkTimeout is the afk timeout in seconds.
	AfkTimeout int `json:"afk_timeout"`

	// WidgetEnabled is whether the server widget is enabled.
	WidgetEnabled bool `json:"widget_enabled"`

	// WidgetChannelID is the channel id that the widget will generate an invite to, or 0 if set to no invite.
	//
	// Optional:
	//  - May be equal to 0 if no widget channel is set.
	WidgetChannelID Snowflake `json:"widget_channel_id"`

	// VerificationLevel is the verification level required for the guild.
	VerificationLevel VerificationLevel `json:"verification_level"`

	// DefaultMessageNotifications is the default message notifications level.
	DefaultMessageNotifications MessageNotificationsLevel `json:"default_message_notifications"`

	// ExplicitContentFilter is the explicit content filter level.
	ExplicitContentFilter ExplicitContentFilterLevel `json:"explicit_content_filter"`

	// Features is the enabled guild features.
	Features []GuildFeature `json:"features"`

	// MFALevel is the required MFA level for the guild
	MFALevel MFALevel `json:"mfa_level"`

	// SystemChannelID is the guild's system channel id.
	//
	// Optional:
	//  - May be equal to 0 if no system channel is set.
	SystemChannelID Snowflake `json:"system_channel_id"`

	// SystemChannelFlags is the system channel flags on this guild.
	SystemChannelFlags SystemChannelFlags `json:"system_channel_flags"`

	// RulesChannelID is the guild's rules channel id.
	//
	// Optional:
	//  - May be equal to 0 if no rules channel is set.
	RulesChannelID Snowflake `json:"rules_channel_id"`

	// MaxPresences is the maximum number of presences for the guild.
	//
	// Optional:
	//  - ALways nil, apart from the largest of guilds.
	MaxPresences *int `json:"max_presences"`

	// MaxMembers is the maximum number of members for the guild.
	MaxMembers int `json:"max_members"`

	// VanityURLCode is the vanity url code for the guild
	//
	// Optional:
	//  - May be empty string if no vanity url code is set.
	VanityURLCode string `json:"vanity_url_code"`

	// Banner is the guild's banner hash.
	//
	// Optional:
	//  - May be empty string if no banner is set.
	Banner string `json:"banner"`

	// PremiumTier is premium tier of this guild (Server Boost level).
	PremiumTier PremiumTier `json:"premium_tier"`

	// PremiumSubscriptionCount is the number of boosts this guild currently has.
	PremiumSubscriptionCount int `json:"premium_subscription_count"`

	// PreferredLocale is the preferred locale of a Community guild;
	// used in server discovery and notices from Discord, and sent in interactions; defaults to "en-US"
	PreferredLocale Locale `json:"preferred_locale"`

	// PublicUpdatesChannelID is the id of the channel where admins and moderators
	// of Community guilds receive notices from Discord
	//
	// Optional:
	//  - May be equal to 0 if no public updates channel is set.
	PublicUpdatesChannelID Snowflake `json:"public_updates_channel_id"`

	// MaxVideoChannelUsers is the maximum amount of users in a video channel.
	MaxVideoChannelUsers int `json:"max_video_channel_users"`

	// MaxStageVideoChannelUsers is the maximum amount of users in a stage video channel.
	MaxStageVideoChannelUsers int `json:"max_stage_video_channel_users"`

	// WelcomeScreen is the welcome screen of a Community guild, shown to new members.
	WelcomeScreen GuildWelcomeScreen `json:"welcome_screen"`

	// NSFWLevel is the guild NSFW level.
	NSFWLevel NSFWLevel `json:"nsfw_level"`

	// PremiumProgressBarEnabled is whether the guild has the boost progress bar enabled.
	PremiumProgressBarEnabled bool `json:"premium_progress_bar_enabled"`

	// SafetyAlertsChannelID is the id of the channel where admins and moderators
	// of Community guilds receive safety alerts from Discord.
	//
	// Optional:
	//  - May be equal to 0 if no safety alerts channel is set.
	SafetyAlertsChannelID Snowflake `json:"safety_alerts_channel_id"`

	// IncidentsData is the incidents data for this guild.
	//
	// Optional:
	//  - May be nil if guild has no incidents data.
	IncidentsData *GuildIncidentsData `json:"incidents_data"`

	// Channels is the guild's channel manager.
	// Provides access to cached channels and channel operations.
	//
	// Note:
	//  - This field is not serialized and is populated by the library.
	Channels *GuildChannelManager `json:"-"`

	// Members is the guild's member manager.
	// Provides access to cached members and member operations.
	//
	// Note:
	//  - This field is not serialized and is populated by the library.
	Members *GuildMemberManager `json:"-"`

	// Roles is the guild's role manager.
	// Provides access to cached roles and role operations.
	//
	// Note:
	//  - This field is not serialized and is populated by the library.
	RolesManager *GuildRoleManager `json:"-"`
}

Guild represent a Discord guild.

Reference: https://discord.com/developers/docs/resources/guild

func AcquireGuild

func AcquireGuild() *Guild

AcquireGuild gets a Guild from the pool. The returned Guild must be released back to the pool after use.

func (*Guild) BannerURL

func (g *Guild) BannerURL() string

BannerURL returns the URL to the guild's banner image.

If the guild has a custom banner set, it returns the URL to that banner, otherwise empty string. By default, it uses GIF format if the banner is animated, otherwise PNG.

Example usage:

url := guild.BannerURL()

func (*Guild) BannerURLWith

func (g *Guild) BannerURLWith(format ImageFormat, size ImageSize) string

BannerURLWith returns the URL to the guild's banner image, allowing explicit specification of image format and size.

If the guild has a custom banner set, it returns the URL to that banner (otherwise empty string) using the provided format and size.

Example usage:

url := guild.BannerURLWith(ImageFormatWebP, ImageSize512)

func (*Guild) CreatedAt

func (g *Guild) CreatedAt() time.Time

CreatedAt returns the time when this guild is created.

func (*Guild) DiscoverySplashURL

func (g *Guild) DiscoverySplashURL() string

DiscoverySplashURL returns the URL to the guild's discovery splash image.

If the guild has a discovery splash image set, it returns the URL to that image, Otherwise empty string, By default it uses PNG.

Example usage:

url := guild.DiscoverySplashURL()

func (*Guild) DiscoverySplashURLWith

func (g *Guild) DiscoverySplashURLWith(format ImageFormat, size ImageSize) string

DiscoverySplashURLWith returns the URL to the guild's discovery splash image, allowing explicit specification of image format and size.

If the guild has a discovery splash image set, it returns the URL to that image (otherwise empty string). using the provided format and size.

Example usage:

url := guild.DiscoverySplashURLWith(ImageFormatWebP, ImageSize512)

func (*Guild) IconURL

func (g *Guild) IconURL() string

IconURL returns the URL to the guild's icon image.

If the guild has a custom icon set, it returns the URL to that icon, otherwise empty string. By default, it uses GIF format if the icon is animated, otherwise PNG.

Example usage:

url := guild.IconURL()

func (*Guild) IconURLWith

func (g *Guild) IconURLWith(format ImageFormat, size ImageSize) string

IconURLWith returns the URL to the guild's icon image, allowing explicit specification of image format and size.

If the guild has a custom icon set, it returns the URL to that icon (otherwise empty string) using the provided format and size.

Example usage:

url := guild.IconURLWith(ImageFormatWebP, ImageSize512)

func (*Guild) SplashURL

func (g *Guild) SplashURL() string

SplashURL returns the URL to the guild's splash image.

If the guild has a splash image set, it returns the URL to that image, Otherwise empty string, By default it uses PNG.

Example usage:

url := guild.SplashURL()

func (*Guild) SplashURLWith

func (g *Guild) SplashURLWith(format ImageFormat, size ImageSize) string

SplashURLWith returns the URL to the guild's splash image, allowing explicit specification of image format and size.

If the guild has a splash image set, it returns the URL to that image (otherwise empty string). using the provided format and size.

Example usage:

url := guild.SplashURLWith(ImageFormatWebP, ImageSize512)

type GuildChannel

type GuildChannel interface {
	Channel
	NamedChannel
	GetGuildID() Snowflake
	GetPermissionOverwrites() []PermissionOverwrite
	GetFlags() ChannelFlags
	JumpURL() string
}

GuildChannel represents a guild-specific Discord channel.

This interface extends the Channel interface and adds guild-specific fields, such as the guild ID, channel name, permission overwrites, flags, and jump URL.

Use this interface when you want to handle guild channels generically without knowing the specific concrete type (TextChannel, VoiceChannel, ForumChannel, etc.).

You can convert (assert) it to a specific guild channel type using a type assertion or a type switch, as described in the official Go documentation:

Example usage:

var myGuildChannel GuildChannel

switch c := ch.(type) {
case *TextChannel:
    fmt.Println("Text channel name:", c.Name)
case *VoiceChannel:
    fmt.Println("Voice channel bitrate:", c.Bitrate)
case *ForumChannel:
    fmt.Println("Forum channel tags:", c.AvailableTags)
default:
    fmt.Println("Other guild channel type:", c.GetType())
}

You can also use an if-condition to check a specific type:

if textCh, ok := ch.(*TextChannel); ok {
    fmt.Println("Text channel:", textCh.Name)
}

type GuildChannelFields

type GuildChannelFields struct {
	ChannelFields

	// GuildID is the id of the guild.
	GuildID Snowflake `json:"guild_id"`

	// Name is the name of the channel.
	//
	// Info:
	//  - can be 1 to 100 characters.
	Name string `json:"name,omitempty"`

	// Position is the sorting position of the channel.
	Position int `json:"position,omitempty"`

	// PermissionOverwrites are explicit permission overwrites for members and roles.
	PermissionOverwrites []PermissionOverwrite `json:"permission_overwrites,omitempty"`

	// Flags are combined channel flags.
	Flags ChannelFlags `json:"flags,omitempty"`
}

GuildChannelFields embeds BaseChannel and adds fields common to guild channels except threads.

Used by guild-specific channel types like TextChannel, VoiceChannel, ForumChannel, etc.

func (*GuildChannelFields) GetFlags

func (c *GuildChannelFields) GetFlags() ChannelFlags

func (*GuildChannelFields) GetGuildID

func (c *GuildChannelFields) GetGuildID() Snowflake

func (*GuildChannelFields) GetName

func (c *GuildChannelFields) GetName() string

func (*GuildChannelFields) GetPermissionOverwrites

func (c *GuildChannelFields) GetPermissionOverwrites() []PermissionOverwrite

func (*GuildChannelFields) GetPosition

func (c *GuildChannelFields) GetPosition() int

func (*GuildChannelFields) JumpURL

func (c *GuildChannelFields) JumpURL() string

type GuildChannelManager

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

GuildChannelManager manages channels within a guild. It provides methods to get, fetch, create, and filter channels.

func NewGuildChannelManager

func NewGuildChannelManager(client *Client, guildID Snowflake) *GuildChannelManager

NewGuildChannelManager creates a new GuildChannelManager.

func (*GuildChannelManager) All

func (m *GuildChannelManager) All() []GuildChannel

All returns all cached channels.

func (*GuildChannelManager) ByName

func (m *GuildChannelManager) ByName(name string) (GuildChannel, bool)

ByName finds a channel by name.

func (*GuildChannelManager) ByType

ByType returns all channels of a specific type.

func (*GuildChannelManager) Categories

func (m *GuildChannelManager) Categories() []*CategoryChannel

Categories returns all category channels.

func (*GuildChannelManager) Create

Create creates a new channel in the guild. Returns the created channel.

func (*GuildChannelManager) Fetch

func (m *GuildChannelManager) Fetch(channelID Snowflake) (GuildChannel, error)

Fetch fetches a channel from the API and updates the cache. Returns the channel.

func (*GuildChannelManager) Filter

func (m *GuildChannelManager) Filter(fn func(GuildChannel) bool) []GuildChannel

Filter returns channels matching the predicate.

func (*GuildChannelManager) Find

func (m *GuildChannelManager) Find(fn func(GuildChannel) bool) (GuildChannel, bool)

Find returns the first channel matching the predicate.

func (*GuildChannelManager) Get

func (m *GuildChannelManager) Get(channelID Snowflake) (GuildChannel, bool)

Get retrieves a channel from the cache. Returns the channel and true if found, or nil and false if not found.

func (*GuildChannelManager) Size

func (m *GuildChannelManager) Size() int

Size returns the number of cached channels.

func (*GuildChannelManager) TextChannels

func (m *GuildChannelManager) TextChannels() []*TextChannel

TextChannels returns all text channels.

func (*GuildChannelManager) VoiceChannels

func (m *GuildChannelManager) VoiceChannels() []*VoiceChannel

VoiceChannels returns all voice channels.

type GuildCreateEvent

type GuildCreateEvent struct {
	ShardsID int // shard that dispatched this event
	Guild    GatewayGuild
}

GuildCreateEvent Guild was created

type GuildEditOptions

type GuildEditOptions struct {
	// Name is the guild name.
	Name string `json:"name,omitempty"`
	// VerificationLevel is the verification level required for the guild.
	VerificationLevel *VerificationLevel `json:"verification_level,omitempty"`
	// DefaultMessageNotifications is the default message notification level.
	DefaultMessageNotifications *MessageNotificationsLevel `json:"default_message_notifications,omitempty"`
	// ExplicitContentFilter is the explicit content filter level.
	ExplicitContentFilter *ExplicitContentFilterLevel `json:"explicit_content_filter,omitempty"`
	// AFKChannelID is the id of afk channel.
	AFKChannelID *Snowflake `json:"afk_channel_id,omitempty"`
	// AFKTimeout is the afk timeout in seconds.
	AFKTimeout *int `json:"afk_timeout,omitempty"`
	// Icon is the base64 1024x1024 png/jpeg/gif image for the guild icon.
	Icon *ImageFile `json:"icon,omitempty"`
	// OwnerID is the user id to transfer guild ownership to (must be owner).
	OwnerID *Snowflake `json:"owner_id,omitempty"`
	// Splash is the base64 16:9 png/jpeg image for the guild splash.
	Splash *ImageFile `json:"splash,omitempty"`
	// DiscoverySplash is the base64 16:9 png/jpeg image for the discovery splash.
	DiscoverySplash *ImageFile `json:"discovery_splash,omitempty"`
	// Banner is the base64 16:9 png/jpeg image for the guild banner.
	Banner *ImageFile `json:"banner,omitempty"`
	// SystemChannelID is the id of the channel where system messages are sent.
	SystemChannelID *Snowflake `json:"system_channel_id,omitempty"`
	// SystemChannelFlags are system channel flags.
	SystemChannelFlags *int `json:"system_channel_flags,omitempty"`
	// RulesChannelID is the id of the channel where Community guilds display rules.
	RulesChannelID *Snowflake `json:"rules_channel_id,omitempty"`
	// PublicUpdatesChannelID is the id of the channel where public updates are sent.
	PublicUpdatesChannelID *Snowflake `json:"public_updates_channel_id,omitempty"`
	// PreferredLocale is the preferred locale of a Community guild.
	PreferredLocale string `json:"preferred_locale,omitempty"`
	// Features are the enabled guild features.
	Features []string `json:"features,omitempty"`
	// Description is the description for the guild (Community only).
	Description *string `json:"description,omitempty"`
	// PremiumProgressBarEnabled indicates whether the boost progress bar is enabled.
	PremiumProgressBarEnabled *bool `json:"premium_progress_bar_enabled,omitempty"`
	// SafetyAlertsChannelID is the id of the channel where safety alerts are sent.
	SafetyAlertsChannelID *Snowflake `json:"safety_alerts_channel_id,omitempty"`
}

GuildEditOptions are options for editing a guild.

type GuildFeature

type GuildFeature string

GuildFeature represents the features of a Discord guild.

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

const (
	// Guild has access to set an animated guild banner image.
	GuildFeatureAnimatedBanner GuildFeature = "ANIMATED_BANNER"
	// Guild has access to set an animated guild icon.
	GuildFeatureAnimatedIcon GuildFeature = "ANIMATED_ICON"
	// Guild is using the old permissions configuration behavior.
	//
	// Reference: https://discord.com/developers/docs/change-log#upcoming-application-command-permission-changes
	GuildFeatureAPPLICATION_COMMAND_PERMISSIONS_V2 GuildFeature = "APPLICATION_COMMAND_PERMISSIONS_V2"
	// guild has set up auto moderation rules
	GuildFeatureAutoModeration GuildFeature = "AUTO_MODERATION"
	// Guild has access to set a guild banner image.
	GuildFeatureBanner GuildFeature = "BANNER"
	// Guild can enable welcome screen, Membership Screening, stage channels and discovery, and receives community updates.
	GuildFeatureCommunity GuildFeature = "COMMUNITY"
	// Guild has enabled monetization
	GuildFeatureCreatorMonetizableProvisional GuildFeature = "CREATOR_MONETIZABLE_PROVISIONAL"
	// Guild has enabled the role subscription promo page.
	GuildFeatureCreatorStorePage GuildFeature = "CREATOR_STORE_PAGE"
	// Guild has been set as a support server on the App Directory.
	GuildFeatureDeveloperSupportServer GuildFeature = "DEVELOPER_SUPPORT_SERVER"
	// Guild is able to be discovered in the directory.
	GuildFeatureDiscoverable GuildFeature = "DISCOVERABLE"
	// Guild is able to be featured in the directory.
	GuildFeatureFeaturable GuildFeature = "FEATURABLE"
	// Guild has paused invites, preventing new users from joining.
	GuildFeatureInvitesDisabled GuildFeature = "INVITES_DISABLED"
	// Guild has access to set an invite splash background.
	GuildFeatureInviteSplash GuildFeature = "INVITE_SPLASH"
	// Guild has enabled Membership Screening.
	//
	// Reference: https://discord.com/developers/docs/resources/guild#membership-screening-object
	GuildFeatureMemberVerificationGateEnabled GuildFeature = "MEMBER_VERIFICATION_GATE_ENABLED"
	// Guild has increased custom soundboard sound slots.
	GuildFeatureMoreSoundboard GuildFeature = "MORE_SOUNDBOARD"
	// Guild has increased custom sticker slots.
	GuildFeatureMoreStickers GuildFeature = "MORE_STICKERS"
	// Guild has access to create announcement channels.
	GuildFeatureNews GuildFeature = "NEWS"
	// Guild is partnered.
	GuildFeaturePartnered GuildFeature = "PARTNERED"
	// Guild can be previewed before joining via Membership Screening or the directory.
	GuildFeaturePreviewEnabled GuildFeature = "PREVIEW_ENABLED"
	// Guild has disabled alerts for join raids in the configured safety alerts channel
	GuildFeatureRaidAlertsDisabled GuildFeature = "RAID_ALERTS_DISABLED"
	// Guild is able to set role icons.
	GuildFeatureRoleIcons GuildFeature = "ROLE_ICONS"
	// Guild has role subscriptions that can be purchased.
	GuildFeatureRoleSubscriptionsAvailableForPurchase GuildFeature = "ROLE_SUBSCRIPTIONS_AVAILABLE_FOR_PURCHASE"
	// Guild has enabled role subscriptions.
	GuildFeatureRoleSubscriptionsEnabled GuildFeature = "ROLE_SUBSCRIPTIONS_ENABLED"
	// Guild has created soundboard sounds.
	GuildFeatureSoundboard GuildFeature = "SOUNDBOARD"
	// Guild has enabled ticketed events.
	GuildFeatureTicketedEventsEnabled GuildFeature = "TICKETED_EVENTS_ENABLED"
	// Guild has access to set a vanity URL.
	GuildFeatureVanityURL GuildFeature = "VANITY_URL"
	// Guild is verified.
	GuildFeatureVerified GuildFeature = "VERIFIED"
	// Guild has access to set 384kbps bitrate in voice (previously VIP voice servers).
	GuildFeatureVipRegions GuildFeature = "VIP_REGIONS"
	// Guild has enabled the welcome screen.
	GuildFeatureWelcomeScreenEnabled GuildFeature = "WELCOME_SCREEN_ENABLED"
	// Guild has access to guest invites.
	GuildFeatureGuestsEnabled GuildFeature = "GUESTS_ENABLED"
	// Guild has access to set guild tags.
	GuildFeatureGuildTags GuildFeature = "GUILD_TAGS"
	// Guild is able to set gradient colors to roles.
	GuildFeatureEnhancedRoleColors GuildFeature = "ENHANCED_ROLE_COLORS"
)

type GuildIncidentsData

type GuildIncidentsData struct {
	// InvitesDisabledUntil is when invites get enabled again,
	InvitesDisabledUntil *time.Time `json:"invites_disabled_until"`
	// DMsDisabledUntil is when direct messages get enabled again.
	DMsDisabledUntil *time.Time `json:"dms_disabled_until"`
	// DMSpamDetectedAt is when the dm spam was detected.
	DMSpamDetectedAt *time.Time `json:"dm_spam_detected_at"`
	// RaidDetectedAt is when the raid was detected.
	RaidDetectedAt *time.Time `json:"raid_detected_at"`
}

GuildWelcomeScreen represent incidents data of a Discord guild.

Reference: https://discord.com/developers/docs/resources/guild#incidents-data-object

type GuildMemberManager

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

GuildMemberManager manages members within a guild. It provides methods to get, fetch, search, and moderate members.

func NewGuildMemberManager

func NewGuildMemberManager(client *Client, guildID Snowflake) *GuildMemberManager

NewGuildMemberManager creates a new GuildMemberManager.

func (*GuildMemberManager) All

func (m *GuildMemberManager) All() []*Member

All returns all cached members.

func (*GuildMemberManager) Ban

func (m *GuildMemberManager) Ban(userID Snowflake, opts BanOptions, reason string) error

Ban bans a user from the guild. Requires BAN_MEMBERS permission.

func (*GuildMemberManager) ByNickname

func (m *GuildMemberManager) ByNickname(nickname string) (*Member, bool)

ByNickname finds a member by nickname.

func (*GuildMemberManager) ByUsername

func (m *GuildMemberManager) ByUsername(username string) (*Member, bool)

ByUsername finds a member by username.

func (*GuildMemberManager) Fetch

func (m *GuildMemberManager) Fetch(userID Snowflake) (*Member, error)

Fetch fetches a member from the API and updates the cache. Returns the member.

func (*GuildMemberManager) FetchAll

func (m *GuildMemberManager) FetchAll(opts ListMembersOptions) ([]*Member, error)

FetchAll fetches members from the API with pagination. Note: Requires GUILD_MEMBERS privileged intent.

func (*GuildMemberManager) Filter

func (m *GuildMemberManager) Filter(fn func(*Member) bool) []*Member

Filter returns members matching the predicate.

func (*GuildMemberManager) Find

func (m *GuildMemberManager) Find(fn func(*Member) bool) (*Member, bool)

Find returns the first member matching the predicate.

func (*GuildMemberManager) Get

func (m *GuildMemberManager) Get(userID Snowflake) (*Member, bool)

Get retrieves a member from the cache by user ID. Returns the member and true if found, or nil and false if not found.

func (*GuildMemberManager) Kick

func (m *GuildMemberManager) Kick(userID Snowflake, reason string) error

Kick kicks a member from the guild. Requires KICK_MEMBERS permission.

func (*GuildMemberManager) Search

func (m *GuildMemberManager) Search(query string, limit int) ([]*Member, error)

Search searches for members by username or nickname. Returns up to `limit` members.

func (*GuildMemberManager) Size

func (m *GuildMemberManager) Size() int

Size returns the number of cached members.

func (*GuildMemberManager) Unban

func (m *GuildMemberManager) Unban(userID Snowflake, reason string) error

Unban unbans a user from the guild. Requires BAN_MEMBERS permission.

func (*GuildMemberManager) WithRole

func (m *GuildMemberManager) WithRole(roleID Snowflake) []*Member

WithRole returns all members that have a specific role.

type GuildMessageChannel

type GuildMessageChannel interface {
	GuildChannel
	MessageChannel
	GetRateLimitPerUser() time.Duration
}

GuildMessageChannel represents a Discord text channel.

This interface extends the Channel interface and adds text-channel-specific fields, such as the ID of the last message and the rate limit (slowmode) per user.

Use this interface when you want to handle text channels specifically.

You can convert (assert) it to a concrete type using a type assertion or type switch:

Example usage:

var ch GuildMessageChannel

switch c := ch.(type) {
case *TextChannel:
    fmt.Println("Text channel name:", c.GetName())
    fmt.Println("Last message ID:", c.GetLastMessageID())
    fmt.Println("Rate limit per user:", c.GetRateLimitPerUser())
case *VoiceChannel:
    fmt.Println("Voiec channel name:", c.GetName())
    fmt.Println("Last message ID:", c.GetLastMessageID())
    fmt.Println("Rate limit per user:", c.GetRateLimitPerUser())
default:
    fmt.Println("Other text channel type:", c.GetType())
}

You can also use an if-condition to check a specific type:

if textCh, ok := ch.(*TextChannel); ok {
    fmt.Println("Text channel:", textCh.GetName())
}

type GuildMessageChannelFields

type GuildMessageChannelFields struct {
	MessageChannelFields
	// RateLimitPerUser is the amount of seconds a user has to wait before sending another message.
	// Bots, as well as users with the permission manageMessages or manageChannel, are unaffected.
	RateLimitPerUser time.Duration `json:"rate_limit_per_user"`
}

GuildMessageChannelFields holds fields related to text-based features like messaging.

func (*GuildMessageChannelFields) GetRateLimitPerUser

func (t *GuildMessageChannelFields) GetRateLimitPerUser() time.Duration

type GuildPreview

type GuildPreview struct {
	ID                       Snowflake `json:"id"`
	Name                     string    `json:"name"`
	Icon                     string    `json:"icon"`
	Splash                   string    `json:"splash"`
	DiscoverySplash          string    `json:"discovery_splash"`
	Emojis                   []Emoji   `json:"emojis"`
	Features                 []string  `json:"features"`
	ApproximateMemberCount   int       `json:"approximate_member_count"`
	ApproximatePresenceCount int       `json:"approximate_presence_count"`
	Description              string    `json:"description"`
	Stickers                 []Sticker `json:"stickers"`
}

GuildPreview represents a preview of a guild.

type GuildRoleManager

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

GuildRoleManager manages roles within a guild. It provides methods to get, create, and filter roles.

func NewGuildRoleManager

func NewGuildRoleManager(client *Client, guildID Snowflake) *GuildRoleManager

NewGuildRoleManager creates a new GuildRoleManager.

func (*GuildRoleManager) All

func (m *GuildRoleManager) All() []*Role

All returns all cached roles.

func (*GuildRoleManager) ByName

func (m *GuildRoleManager) ByName(name string) (*Role, bool)

ByName finds a role by name.

func (*GuildRoleManager) Create

func (m *GuildRoleManager) Create(opts RoleCreateOptions, reason string) (*Role, error)

Create creates a new role in the guild. Requires MANAGE_ROLES permission.

func (*GuildRoleManager) Delete

func (m *GuildRoleManager) Delete(roleID Snowflake, reason string) error

Delete deletes a role from the guild. Requires MANAGE_ROLES permission.

func (*GuildRoleManager) Everyone

func (m *GuildRoleManager) Everyone() (*Role, bool)

Everyone returns the @everyone role. The @everyone role ID is the same as the guild ID.

func (*GuildRoleManager) Fetch

func (m *GuildRoleManager) Fetch() ([]*Role, error)

Fetch fetches all roles from the API and updates the cache. Returns all roles.

func (*GuildRoleManager) Filter

func (m *GuildRoleManager) Filter(fn func(*Role) bool) []*Role

Filter returns roles matching the predicate.

func (*GuildRoleManager) Find

func (m *GuildRoleManager) Find(fn func(*Role) bool) (*Role, bool)

Find returns the first role matching the predicate.

func (*GuildRoleManager) Get

func (m *GuildRoleManager) Get(roleID Snowflake) (*Role, bool)

Get retrieves a role from the cache. Returns the role and true if found, or nil and false if not found.

func (*GuildRoleManager) Highest

func (m *GuildRoleManager) Highest() (*Role, bool)

Highest returns the role with the highest position.

func (*GuildRoleManager) Hoisted

func (m *GuildRoleManager) Hoisted() []*Role

Hoisted returns all roles that are displayed separately.

func (*GuildRoleManager) Mentionable

func (m *GuildRoleManager) Mentionable() []*Role

Mentionable returns all mentionable roles.

func (*GuildRoleManager) Size

func (m *GuildRoleManager) Size() int

Size returns the number of cached roles.

type GuildWelcomeChannel

type GuildWelcomeChannel struct {
	// ChannelID is the channel's id.
	ChannelID Snowflake `json:"channel_id"`

	// Description is the description shown for the channel.
	Description string `json:"description"`

	// EmojiID is the emoji id, if the emoji is custom
	//
	// Optional:
	//  - May be equal to 0 if no emoji is set.
	//  - May be equal to 0 if the emoji is set but its a unicode emoji.
	EmojiID Snowflake `json:"emoji_id,omitempty"`

	// EmojiID is the emoji name if custom, the unicode character if standard, or empty string if no emoji is set
	//
	// Optional:
	//  - May be empty string if no emoji is set.
	EmojiName string `json:"emoji_name,omitempty"`
}

GuildWelcomeChannel is one of the channels in a GuildWelcomeScreen

Reference: https://discord.com/developers/docs/resources/guild#welcome-screen-object-welcome-screen-channel-structure

func (*GuildWelcomeChannel) Mention

func (c *GuildWelcomeChannel) Mention() string

Mention returns a Discord mention string for the channel.

Example output: "<#123456789012345678>"

type GuildWelcomeScreen

type GuildWelcomeScreen struct {
	// Description is the server description shown in the welcome screen.
	Description string `json:"description,omitempty"`

	// WelcomeChannels is the channels shown in the welcome screen,
	//
	// Note:
	//  - Can be up to 5 channels.
	WelcomeChannels []GuildWelcomeChannel `json:"welcome_channels"`
}

GuildWelcomeScreen is the Welcome Screen of a Guild

Reference: https://discord.com/developers/docs/resources/guild#welcome-screen-object

type ImageConfig

type ImageConfig struct {
	Format ImageFormat
	Size   ImageSize
}

ImageConfig holds configuration for image format and size.

type ImageFile

type ImageFile string

ImageFile represents a base64-encoded image for Discord API requests. Used for guild icons, splashes, banners, role icons, etc.

type ImageFormat

type ImageFormat string

ImageFormat defines all possible image formats supported by Discord endpoints.

const (
	ImageFormatDefault ImageFormat = ".gif"
	ImageFormatPNG     ImageFormat = ".png"
	ImageFormatJPEG    ImageFormat = ".jpeg"
	ImageFormatWebP    ImageFormat = ".webp"
	ImageFormatGIF     ImageFormat = ".gif"
	ImageFormatAVIF    ImageFormat = ".avif"
	ImageFormatLottie  ImageFormat = ".json"
)

type ImageSize

type ImageSize int

ImageSize defines supported image sizes for Discord assets.

const (
	ImageSizeDefault ImageSize = 0
	ImageSize16      ImageSize = 16
	ImageSize32      ImageSize = 32
	ImageSize64      ImageSize = 64
	ImageSize128     ImageSize = 128
	ImageSize256     ImageSize = 256
	ImageSize512     ImageSize = 512
	ImageSize1024    ImageSize = 1024
	ImageSize2048    ImageSize = 2048
	ImageSize4096    ImageSize = 4096
)

type IntegerConstraints

type IntegerConstraints struct {
	// MinValue is the minimum value permitted for the integer.
	//
	// Info:
	//  - Must be between -2^53 and 2^53.
	//
	// Optional:
	//  - May be nil if no minimum value is specified.
	MinValue *int `json:"min_value,omitempty"`

	// MaxValue is the maximum value permitted for the integer.
	//
	// Info:
	//  - Must be between -2^53 and 2^53.
	//
	// Optional:
	//  - May be nil if no maximum value is specified.
	MaxValue *int `json:"max_value,omitempty"`
}

IntegerConstraints contains constraints for integer options.

type Integration

type Integration struct {
	ID                Snowflake    `json:"id"`
	Name              string       `json:"name"`
	Type              string       `json:"type"`
	Enabled           bool         `json:"enabled"`
	Syncing           bool         `json:"syncing"`
	RoleID            Snowflake    `json:"role_id"`
	EnableEmoticons   bool         `json:"enable_emoticons"`
	ExpireBehavior    int          `json:"expire_behavior"`
	ExpireGracePeriod int          `json:"expire_grace_period"`
	User              *User        `json:"user"`
	Account           Account      `json:"account"`
	SyncedAt          string       `json:"synced_at"`
	SubscriberCount   int          `json:"subscriber_count"`
	Revoked           bool         `json:"revoked"`
	Application       *Application `json:"application"`
}

Integration represents a guild integration.

type Interaction

type Interaction interface {
	GetID() Snowflake
	GetType() InteractionType
	GetApplicationID() Snowflake
	GetToken() string
}

Interaction is the interface representing a Discord interaction.

This interface can represent any type of interaction returned by Discord, including ping interactions, chat input commands, user commands, message commands, component interactions, autocomplete interactions, and modal submits.

Use this interface when you want to handle interactions generically without knowing the specific concrete type in advance.

You can convert (assert) it to a specific interaction type using a type assertion or a type switch, as described in the official Go documentation:

Example usage:

var i Interaction

switch in := i.(type) {
case *PingInteraction:
    fmt.Println("Ping interaction ID:", in.ID)
case *ChatInputCommandInteraction:
    fmt.Println("Chat input command name:", in.Data.Name)
case *UserCommandInteraction:
    fmt.Println("User command target ID:", in.Data.TargetID)
default:
    fmt.Println("Other interaction type:", in.GetType())
}

You can also use an if-condition to check a specific type:

if chatInputIn, ok := i.(*ChatInputCommandInteraction); ok {
    fmt.Println("Chat input command:", chatInputIntr.Data.Name)
}

func UnmarshalInteraction

func UnmarshalInteraction(buf []byte) (Interaction, error)

Helper func to Unmarshal any interaction type to a Interaction interface.

type InteractionContextType

type InteractionContextType int

InteractionContextType is the context in Discord where an interaction can be used, or where it was triggered from. Details about using interaction contexts for application commands is in the commands context documentation.

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

const (
	// Interaction can be used within servers
	InteractionContextTypeGuild InteractionContextType = iota

	// Interaction can be used within DMs with the app's bot user
	InteractionContextTypeBotDM

	// Interaction can be used within Group DMs and DMs other than the app's bot user
	InteractionContextTypePrivateChannel
)

func (InteractionContextType) Is

func (t InteractionContextType) Is(interactionType InteractionContextType) bool

Is returns true if the interaction context's Type matches the provided one.

type InteractionCreateEvent

type InteractionCreateEvent struct {
	ShardsID    int // shard that dispatched this event
	Interaction Interaction
}

InteractionCreateEvent Interaction created

func (*InteractionCreateEvent) UnmarshalJSON

func (c *InteractionCreateEvent) UnmarshalJSON(buf []byte) error

UnmarshalJSON implements json.Unmarshaler for InteractionCreateEvent.

type InteractionFields

type InteractionFields struct {
	// ID is the unique ID of the interaction.
	ID Snowflake `json:"id"`

	// Type is the type of the interaction.
	Type InteractionType `json:"type"`

	// ApplicationID is the ID of the application/bot this interaction belongs to.
	ApplicationID Snowflake `json:"application_id"`

	// Token is a token used to respond to the interaction.
	Token string `json:"token"`
}

InteractionFields holds fields common to all Discord interactions.

func (*InteractionFields) GetApplicationID

func (i *InteractionFields) GetApplicationID() Snowflake

func (*InteractionFields) GetID

func (i *InteractionFields) GetID() Snowflake

func (*InteractionFields) GetToken

func (i *InteractionFields) GetToken() string

func (*InteractionFields) GetType

func (i *InteractionFields) GetType() InteractionType

type InteractionMetadata

type InteractionMetadata struct {
	// ID is the unique Discord snowflake ID of the interaction.
	ID Snowflake `json:"id"`

	// Type is the type of the interaction (e.g., command, component).
	Type InteractionType `json:"type"`

	// User is the user who triggered the interaction.
	User User `json:"user"`

	// AuthorizingIntegrationOwners maps integration types to their owner IDs.
	AuthorizingIntegrationOwners map[ApplicationIntegrationType]Snowflake `json:"authorizing_integration_owners"`

	// OriginalResponseMessageID is the ID of the original response message for the interaction.
	//
	// Optional:
	//   - Will be 0 if no original response message exists.
	OriginalResponseMessageID Snowflake `json:"original_response_message_id"`

	// TargetUser is the user targeted by a user command interaction.
	//
	// Optional:
	//   - Will be nil unless the interaction is of type ApplicationCommandTypeUser.
	TargetUser *User `json:"target_user"`

	// TargetMessageID is the ID of the message targeted by a message command interaction.
	//
	// Optional:
	//   - Will be 0 unless the interaction is of type ApplicationCommandTypeMessage.
	TargetMessageID Snowflake `json:"target_message_id"`

	// InteractedMessageID is the ID of the message interacted with in a component interaction.
	//
	// Optional:
	//   - Will be 0 unless the interaction is of type InteractionTypeComponent.
	InteractedMessageID Snowflake `json:"interacted_message_id"`

	// TriggeringInteractionMetadata is the metadata of the interaction that triggered a modal submit.
	//
	// Optional:
	//   - Will be nil unless the interaction is of type InteractionTypeModalSubmit.
	TriggeringInteractionMetadata *InteractionMetadata `json:"triggering_interaction_metadata"`
}

InteractionMetadata represents metadata about an interaction that generated a message.

Reference: https://discord.com/developers/docs/resources/message#message-interaction-metadata-object

type InteractionResponse

type InteractionResponse struct {
	// Type is the type of response.
	Type InteractionResponseType `json:"type"`
	// Data is an optional response message.
	Data *InteractionResponseData `json:"data,omitempty"`
}

InteractionResponse is the response structure for an interaction.

type InteractionResponseData

type InteractionResponseData struct {
	// TTS indicates if the message is text-to-speech.
	TTS bool `json:"tts,omitempty"`
	// Content is the message content (up to 2000 characters).
	Content string `json:"content,omitempty"`
	// Embeds are the embeds for the message (up to 10).
	Embeds []Embed `json:"embeds,omitempty"`
	// AllowedMentions are allowed mentions for the message.
	AllowedMentions *AllowedMentions `json:"allowed_mentions,omitempty"`
	// Flags are message flags (only SUPPRESS_EMBEDS and EPHEMERAL can be set).
	Flags MessageFlags `json:"flags,omitempty"`
	// Components are message components.
	Components []LayoutComponent `json:"components,omitempty"`
	// Attachments are attachment objects with filename and description.
	Attachments []Attachment `json:"attachments,omitempty"`
	// Poll is a poll for the message.
	Poll *PollCreateOptions `json:"poll,omitempty"`
	// Choices are autocomplete choices (max 25).
	Choices []ApplicationCommandOptionChoice `json:"choices,omitempty"`
	// CustomID is the custom id for a modal.
	CustomID string `json:"custom_id,omitempty"`
	// Title is the title for a modal (max 45 characters).
	Title string `json:"title,omitempty"`
}

InteractionResponseData is the data payload for an interaction response.

type InteractionResponseType

type InteractionResponseType int

InteractionResponseType is the type of response to an interaction.

const (
	// InteractionResponseTypePong acknowledges a ping.
	InteractionResponseTypePong InteractionResponseType = 1
	// InteractionResponseTypeChannelMessageWithSource responds with a message, showing the user's input.
	InteractionResponseTypeChannelMessageWithSource InteractionResponseType = 4
	// InteractionResponseTypeDeferredChannelMessageWithSource acknowledges, showing a loading state.
	InteractionResponseTypeDeferredChannelMessageWithSource InteractionResponseType = 5
	// InteractionResponseTypeDeferredUpdateMessage acknowledges without updating.
	InteractionResponseTypeDeferredUpdateMessage InteractionResponseType = 6
	// InteractionResponseTypeUpdateMessage edits the message the component was attached to.
	InteractionResponseTypeUpdateMessage InteractionResponseType = 7
	// InteractionResponseTypeApplicationCommandAutocompleteResult responds to an autocomplete interaction.
	InteractionResponseTypeApplicationCommandAutocompleteResult InteractionResponseType = 8
	// InteractionResponseTypeModal responds with a popup modal.
	InteractionResponseTypeModal InteractionResponseType = 9
	// InteractionResponseTypePremiumRequired responds to an interaction with an upgrade button.
	InteractionResponseTypePremiumRequired InteractionResponseType = 10
	// InteractionResponseTypeLaunchActivity launches an activity.
	InteractionResponseTypeLaunchActivity InteractionResponseType = 12
)

type InteractionType

type InteractionType int

InteractionType represents the type of an interaction in Discord. It indicates how the interaction was triggered.

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

const (
	InteractionTypePing InteractionType = iota + 1
	// InteractionTypeApplicationCommand is triggered when a user invokes a slash command.
	InteractionTypeApplicationCommand

	// InteractionTypeComponent is triggered when a user interacts with a message component, like a button or select menu.
	InteractionTypeComponent

	// InteractionTypeAutocomplete is triggered when a user is typing in a command option that supports autocomplete.
	InteractionTypeAutocomplete

	// InteractionTypeModalSubmit is triggered when a user submits a modal dialog.
	InteractionTypeModalSubmit
)

type InteractiveComponent

type InteractiveComponent interface {
	Component
	GetCustomID() string
}

InteractiveComponent is an interface for components that can be included in an ActionRowComponent.

ButtonComponent, StringSelectMenuComponent, UserSelectMenuComponent, RoleSelectMenuComponent, MentionableSelectMenuComponent, ChannelSelectMenuComponent

type InteractiveComponentFields

type InteractiveComponentFields struct {
	ComponentFields

	// CustomID is a developer-defined identifier for interactive components, returned in interaction payloads.
	//
	// Note:
	//   - Max 100 characters.
	//   - Must be unique among components in the same message.
	//   - Used to maintain state or pass data when a user interacts with the component.
	CustomID string `json:"custom_id"`
}

InteractiveComponentFields holds common fields for interactive components, extending ComponentFields with a custom_id.

Interactive components (e.g., buttons, select menus) require a custom_id, which is a developer-defined identifier returned in interaction payloads. The custom_id must be unique per component within the same message and is used to maintain state or pass data.

Reference: https://discord.com/developers/docs/interactions/message-components#component-object

func (*InteractiveComponentFields) GetCustomID

func (c *InteractiveComponentFields) GetCustomID() string

type Invite

type Invite struct {
	// Code is the invite code (unique ID).
	Code string `json:"code"`
	// Guild is a partial guild object the invite is for.
	Guild *PartialGuild `json:"guild,omitempty"`
	// Channel is a partial channel object the invite is for.
	Channel *PartialChannel `json:"channel,omitempty"`
	// Inviter is the user who created the invite.
	Inviter *User `json:"inviter,omitempty"`
	// TargetType is the type of target for the invite.
	TargetType int `json:"target_type,omitempty"`
	// TargetUser is the user whose stream to display for this voice channel invite.
	TargetUser *User `json:"target_user,omitempty"`
	// ApproximatePresenceCount is the approximate count of online members.
	ApproximatePresenceCount int `json:"approximate_presence_count,omitempty"`
	// ApproximateMemberCount is the approximate count of total members.
	ApproximateMemberCount int `json:"approximate_member_count,omitempty"`
	// ExpiresAt is the expiration date of this invite.
	ExpiresAt *string `json:"expires_at,omitempty"`
	// Uses is the number of times this invite has been used.
	Uses int `json:"uses,omitempty"`
	// MaxUses is the max number of times this invite can be used.
	MaxUses int `json:"max_uses,omitempty"`
	// MaxAge is the duration (in seconds) after which the invite expires.
	MaxAge int `json:"max_age,omitempty"`
	// Temporary indicates whether this invite only grants temporary membership.
	Temporary bool `json:"temporary,omitempty"`
	// CreatedAt is when this invite was created.
	CreatedAt string `json:"created_at,omitempty"`
}

Invite represents a Discord invite.

type LabelComponent

type LabelComponent struct {
	ComponentFields

	// Label is the text displayed as the label for the component.
	//
	// Note:
	//   - Required.
	//   - Maximum of 45 characters.
	Label string `json:"label"`

	// Description is an optional text providing additional context for the component.
	//
	// Note:
	//   - Maximum of 100 characters.
	//   - May appear above or below the component depending on the platform.
	Description string `json:"description,omitempty"`

	// Components is an array containing a single child component.
	//
	// Valid components:
	//   - TextInputComponent
	//   - StringSelectMenuComponent
	Components []LabelSubComponent `json:"components"`
}

LabelComponent is a top-level layout component that wraps modal components with a label and an optional description.

It is used to provide context to a single child component (e.g., TextInputComponent or StringSelectMenuComponent) in modals. The description may appear above or below the component depending on the platform.

Note:

  • Only available in modals.
  • Supports only one child component.
  • The label field is required and must not exceed 45 characters.
  • The description field is optional and must not exceed 100 characters.

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

func (*LabelComponent) MarshalJSON

func (c *LabelComponent) MarshalJSON() ([]byte, error)

func (*LabelComponent) UnmarshalJSON

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

type LabelSubComponent

type LabelSubComponent interface {
	Component
}

LabelSubComponent is an interface for all components that can be present in a LabelComponent.

TextInputComponent, StringSelectMenuComponent

type LayoutComponent

type LayoutComponent interface {
	Component
}

LayoutComponent is an interface for all components that can be present as a top level component in a Message.

ActionRowComponent, SectionComponent, TextDisplayComponent, MediaGalleryComponent, FileComponent, SeparatorComponent, ContainerComponent, LabelComponent

type ListBansOptions

type ListBansOptions struct {
	// Limit is the number of users to return (1-1000). Default is 1000.
	Limit int
	// Before is the user id to get users before.
	Before Snowflake
	// After is the user id to get users after.
	After Snowflake
}

ListBansOptions are options for listing guild bans.

type ListMembersOptions

type ListMembersOptions struct {
	// Limit is the max number of members to return (1-1000). Default is 1.
	Limit int
	// After is the highest user id in the previous page.
	After Snowflake
}

ListMembersOptions are options for listing guild members.

type Locale

type Locale string

Locale represents a Discord supported locale code.

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

const (
	LocaleIndonesian       Locale = "id"     // Bahasa Indonesia
	LocaleDanish           Locale = "da"     // Dansk
	LocaleGerman           Locale = "de"     // Deutsch
	LocaleEnglishUK        Locale = "en-GB"  // English, UK
	LocaleEnglishUS        Locale = "en-US"  // English, US
	LocaleSpanishSpain     Locale = "es-ES"  // Español
	LocaleSpanishLatam     Locale = "es-419" // Español, LATAM
	LocaleFrench           Locale = "fr"     // Français
	LocaleCroatian         Locale = "hr"     // Hrvatski
	LocaleItalian          Locale = "it"     // Italiano
	LocaleLithuanian       Locale = "lt"     // Lietuviškai
	LocaleHungarian        Locale = "hu"     // Magyar
	LocaleDutch            Locale = "nl"     // Nederlands
	LocaleNorwegian        Locale = "no"     // Norsk
	LocalePolish           Locale = "pl"     // Polski
	LocalePortugueseBrazil Locale = "pt-BR"  // Português do Brasil
	LocaleRomanian         Locale = "ro"     // Română
	LocaleFinnish          Locale = "fi"     // Suomi
	LocaleSwedish          Locale = "sv-SE"  // Svenska
	LocaleVietnamese       Locale = "vi"     // Tiếng Việt
	LocaleTurkish          Locale = "tr"     // Türkçe
	LocaleCzech            Locale = "cs"     // Čeština
	LocaleGreek            Locale = "el"     // Ελληνικά
	LocaleBulgarian        Locale = "bg"     // български
	LocaleRussian          Locale = "ru"     // Pусский
	LocaleUkrainian        Locale = "uk"     // Українська
	LocaleHindi            Locale = "hi"     // हिन्दी
	LocaleChineseChina     Locale = "zh-CN"  // 中文
	LocaleJapanese         Locale = "ja"     // 日本語
	LocaleChineseTaiwan    Locale = "zh-TW"  // 繁體中文
	LocaleKorean           Locale = "ko"     // 한국어
)

type LogLevel

type LogLevel int

LogLevel defines the severity level

const (
	LogLevelDebugLevel LogLevel = iota
	LogLevelInfoLevel
	LogLevelWarnLevel
	LogLevelErrorLevel
	LogLevelFatalLevel
)

type Logger

type Logger interface {
	Info(msg string)
	Debug(msg string)
	Warn(msg string)
	Error(msg string)
	Fatal(msg string)

	// WithField adds a single field to the logger context
	WithField(key string, value any) Logger
	// WithFields adds multiple fields to the logger context
	WithFields(fields map[string]any) Logger
}

Logger defines the logging interface

type MFALevel

type MFALevel int

ExplicitContentFilterLevel represents the mfa level on a Discord guild.

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

const (
	// Guild has no MFA/2FA requirement for moderation actions.
	MFALevelNone MFALevel = iota
	// Guild has a 2FA requirement for moderation actions.
	MFALevelElevated
)

func (MFALevel) Is

func (l MFALevel) Is(level MFALevel) bool

Is returns true if the MFA level matches the provided one.

type MediaChannel

type MediaChannel struct {
	ForumChannel
}

MediaChannel represents a media channel.

func (*MediaChannel) Delete

func (c *MediaChannel) Delete(reason string) error

Delete deletes this media channel.

func (*MediaChannel) Edit

func (c *MediaChannel) Edit(opts ChannelEditOptions, reason string) (*MediaChannel, error)

Edit modifies this media channel's settings.

func (*MediaChannel) Guild

func (c *MediaChannel) Guild() (Guild, bool)

Guild returns the cached guild this media channel belongs to.

type MediaGalleryComponent

type MediaGalleryComponent struct {
	ComponentFields

	// Items is an array of 1 to 10 media gallery items.
	//
	// Valid components:
	//   - MediaGalleryItem (1 to 10)
	Items []MediaGalleryItem `json:"items"`
}

MediaGalleryComponent is a top-level content component that displays 1-10 media attachments in an organized gallery format.

Each item in the gallery can have an optional description and can be marked as a spoiler. Media Galleries require the IS_COMPONENTS_V2 message flag (1 << 15) to be set when sending the message.

Note:

  • Only available in messages.
  • Requires the IS_COMPONENTS_V2 message flag (1 << 15).
  • Contains 1 to 10 media gallery items.

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

func (*MediaGalleryComponent) MarshalJSON

func (c *MediaGalleryComponent) MarshalJSON() ([]byte, error)

type MediaGalleryItem

type MediaGalleryItem struct {
	// Media is a url or attachment provided as an unfurled media item.
	Media UnfurledMediaItem `json:"media"`

	// Description is an alt text for the media.
	//
	// Note:
	//   - Max 1024 characters.
	Description string `json:"description,omitempty"`

	// Spoiler is whether the media should be a spoiler (or blurred out). Defaults to false.
	Spoiler bool `json:"spoiler,omitempty"`
}

MediaGalleryItem represents an item in a MediaGallery component.

It contains a single media item with an optional description and spoiler flag.

Note:

  • Maximum of 1024 characters for the description.

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

type Member

type Member struct {
	// Large embedded struct first for alignment
	// User is the member's user object.
	User User `json:"user"`

	EntityBase // Embedded client reference for action methods (pointer, 8 bytes)

	// Snowflakes (uint64, 8 bytes each)
	// ID is the user's unique Discord snowflake ID.
	ID Snowflake `json:"id"`
	// GuildID is the member's guild id.
	GuildID Snowflake `json:"guild_id"`

	// Pointers (8 bytes each)
	// JoinedAt when the user joined the guild
	JoinedAt *time.Time `json:"joined_at"`
	// PremiumSince when the user started boosting the guild
	PremiumSince *time.Time `json:"premium_since,omitempty"`
	// CommunicationDisabledUntil is when the user's timeout will expire
	CommunicationDisabledUntil *time.Time `json:"communication_disabled_until"`
	// AvatarDecorationData is the data for the member's guild avatar decoration
	AvatarDecorationData *AvatarDecorationData `json:"avatar_decoration_data"`

	// Slice header (24 bytes)
	// RoleIDs is the ids of roles this member have
	RoleIDs []Snowflake `json:"roles,omitempty"`

	// Strings (24 bytes each)
	// Nickname is the user's nickname.
	Nickname string `json:"nick"`
	// Avatar is the member's avatar hash (guild-specific).
	Avatar string `json:"avatar"`
	// Banner is the member's banner hash (guild-specific).
	Banner string `json:"banner"`

	// Int (8 bytes on 64-bit)
	// Flags guild member flags represented as a bit set, defaults to 0
	Flags MemberFlags `json:"flags"`

	// Bools (1 byte each, grouped at end)
	// Deaf is whether the user is deafened in voice channels
	Deaf bool `json:"deaf,omitempty"`
	// Mute is whether the user is muted in voice channels
	Mute bool `json:"mute,omitempty"`
	// Pending is whether the user has not yet passed the guild's Membership Screening requirements
	Pending bool `json:"pending"`
}

Member is a discord GuildMember

NOTE: Fields are ordered for optimal memory alignment (largest to smallest) to minimize struct padding and improve cache efficiency.

func AcquireMember

func AcquireMember() *Member

AcquireMember gets a Member from the pool. The returned Member must be released back to the pool after use.

func (*Member) AddRole

func (m *Member) AddRole(roleID Snowflake, reason string) error

AddRole adds a role to this member. Requires MANAGE_ROLES permission.

Usage example:

err := member.AddRole(roleID, "Earned the role")

func (*Member) AvatarDecorationURL

func (m *Member) AvatarDecorationURL() string

AvatarDecorationURL returns the URL to the member's avatar decoration image.

If the member has no avatar decoration, it returns an empty string.

Example usage:

url := member.AvatarDecorationURL()

func (*Member) AvatarDecorationURLWith

func (m *Member) AvatarDecorationURLWith(size ImageSize) string

AvatarDecorationURLWith returns the URL to the member's avatar decoration image, allowing explicit specification of image size.

If the member has no avatar decoration, it returns an empty string.

Example usage:

url := member.AvatarDecorationURLWith(ImageSize512)

func (*Member) AvatarURL

func (m *Member) AvatarURL() string

AvatarURL returns the URL to the members's avatar image.

If the member has a custom avatar set, it returns the URL to that avatar. Otherwise it returns their global user avatar URL, By default, it uses GIF format if the avatar is animated, otherwise PNG.

Example usage:

url := member.AvatarURL()

func (*Member) AvatarURLWith

func (m *Member) AvatarURLWith(format ImageFormat, size ImageSize) string

AvatarURLWith returns the URL to the member's avatar image, allowing explicit specification of image format and size.

If the user has a custom avatar set, it returns the URL to that avatar. Otherwise it returns their global user avatar URL using the provided format and size.

Example usage:

url := member.AvatarURLWith(ImageFormatWebP, ImageSize512)

func (*Member) Ban

func (m *Member) Ban(opts BanOptions, reason string) error

Ban bans this member from the guild. Requires BAN_MEMBERS permission.

Usage example:

err := member.Ban(BanOptions{DeleteMessageSeconds: 86400}, "Severe violation")

func (*Member) BannerURL

func (m *Member) BannerURL() string

BannerURL returns the URL to the member's banner image.

If the member has a custom banner set, it returns the URL to that banner. Otherwise it returns their global user banner URL, By default, it uses GIF format if the banner is animated, otherwise PNG.

Example usage:

url := member.BannerURL()

func (*Member) BannerURLWith

func (m *Member) BannerURLWith(format ImageFormat, size ImageSize) string

BannerURLWith returns the URL to the member's banner image, allowing explicit specification of image format and size.

If the user has a custom banner set, it returns the URL to that avatar. Otherwise it returns their global user banner URL using the provided format and size.

Example usage:

url := member.BannerURLWith(ImageFormatWebP, ImageSize512)

func (*Member) CreatedAt

func (m *Member) CreatedAt() time.Time

CreatedAt returns the time when this member account is created.

func (*Member) DisplayName

func (m *Member) DisplayName() string

DisplayName returns the member's nickname if set, otherwise it returns their global display name if set, otherwise it falls back to their username.

- Nickname: a guild-specific name set by the user or server mods. - Globalname: the name shown across Discord (can differ from username). - Username: the original account username.

Example usage:

name := member.DisplayName()

func (*Member) Edit

func (m *Member) Edit(opts MemberEditOptions, reason string) (*Member, error)

Edit modifies this member's attributes. Returns the updated member.

Usage example:

nick := "New Nickname"
updated, err := member.Edit(MemberEditOptions{Nick: &nick}, "Nickname change")

func (*Member) Guild

func (m *Member) Guild() (Guild, bool)

Guild returns the cached guild this member belongs to.

Usage example:

if g, ok := member.Guild(); ok {
    fmt.Println("Guild:", g.Name)
}

func (*Member) HasRole

func (m *Member) HasRole(roleID Snowflake) bool

HasRole checks if this member has a specific role.

Usage example:

if member.HasRole(moderatorRoleID) {
    // Member is a moderator
}

func (*Member) IsTimedOut

func (m *Member) IsTimedOut() bool

IsTimedOut returns true if this member is currently timed out.

Usage example:

if member.IsTimedOut() {
    // Member is timed out
}

func (*Member) Kick

func (m *Member) Kick(reason string) error

Kick removes this member from the guild. Requires KICK_MEMBERS permission.

Usage example:

err := member.Kick("Rule violation")

func (*Member) Mention

func (m *Member) Mention() string

Mention returns a Discord mention string for the user.

Example output: "<@123456789012345678>"

func (*Member) RemoveRole

func (m *Member) RemoveRole(roleID Snowflake, reason string) error

RemoveRole removes a role from this member. Requires MANAGE_ROLES permission.

Usage example:

err := member.RemoveRole(roleID, "Role revoked")

func (*Member) RemoveTimeout

func (m *Member) RemoveTimeout(reason string) error

RemoveTimeout removes the timeout from this member. Requires MODERATE_MEMBERS permission.

Usage example:

err := member.RemoveTimeout("Timeout lifted")

func (*Member) Send

func (m *Member) Send(content string) (*Message, error)

Send sends a direct message to this member. Returns the sent message.

Usage example:

msg, err := member.Send("Hello!")

func (*Member) SendWith

func (m *Member) SendWith(opts MessageCreateOptions) (*Message, error)

SendWith sends a direct message to this member with full options. Returns the sent message.

Usage example:

msg, err := member.SendWith(MessageCreateOptions{
    Content: "Hello!",
    Embeds: []Embed{embed},
})

func (*Member) SetNickname

func (m *Member) SetNickname(nickname string, reason string) error

SetNickname sets this member's nickname. Pass an empty string to remove the nickname.

Usage example:

err := member.SetNickname("Cool Guy", "Requested nickname change")

func (*Member) Timeout

func (m *Member) Timeout(duration time.Duration, reason string) error

Timeout applies a timeout to this member for the specified duration. Requires MODERATE_MEMBERS permission. Maximum duration is 28 days.

Usage example:

err := member.Timeout(10*time.Minute, "Spam")

type MemberEditOptions

type MemberEditOptions struct {
	// Nick is the value to set the user's nickname to. Requires MANAGE_NICKNAMES permission.
	Nick *string `json:"nick,omitempty"`
	// Roles is an array of role ids the member is assigned. Requires MANAGE_ROLES permission.
	Roles []Snowflake `json:"roles,omitempty"`
	// Mute indicates whether the user is muted in voice channels. Requires MUTE_MEMBERS permission.
	Mute *bool `json:"mute,omitempty"`
	// Deaf indicates whether the user is deafened in voice channels. Requires DEAFEN_MEMBERS permission.
	Deaf *bool `json:"deaf,omitempty"`
	// ChannelID is the id of channel to move user to (if they are in voice). Requires MOVE_MEMBERS permission.
	ChannelID *Snowflake `json:"channel_id,omitempty"`
	// CommunicationDisabledUntil is when the user's timeout will expire (up to 28 days). Requires MODERATE_MEMBERS permission.
	CommunicationDisabledUntil *time.Time `json:"communication_disabled_until,omitempty"`
	// Flags are guild member flags.
	Flags *MemberFlags `json:"flags,omitempty"`
}

MemberEditOptions are options for editing a guild member.

type MemberFlags

type MemberFlags int

MemberFlags represents flags of a guild member.

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

const (
	// Member has left and rejoined the guild
	//  - Editable: false
	MemberFlagDidRejoin MemberFlags = 1 << iota

	// Member has completed onboarding
	//  - Editable: false
	MemberFlagCompletedOnboarding

	// Member is exempt from guild verification requirements
	//  - Editable: true
	MemberFlagBypassesVerification

	// Member has started onboarding
	//  - Editable: false
	MemberFlagStartedOnboarding

	// Member is a guest and can only access the voice channel they were invited to
	//  - Editable: false
	MemberFlagIsGuest

	// Member has started Server Guide new member actions
	//  - Editable: false
	MemberFlagStartedHomeActions

	// Member has completed Server Guide new member actions
	//  - Editable: false
	MemberFlagCompletedHomeActions

	// Member's username, display name, or nickname is blocked by AutoMod
	//  - Editable: false
	MemberFlagQuarantinedUsername

	// Member has dismissed the DM settings upsell
	//  - Editable: false
	MemberFlagDMSettingsUpsellAcknowledged

	// Member's guild tag is blocked by AutoMod
	//  - Editable: false
	MemberFlagQuarantinedGuildTag
)

func (MemberFlags) Has

func (f MemberFlags) Has(flags ...MemberFlags) bool

Has returns true if all provided flags are set.

type MembershipState

type MembershipState int

MembershipState represent a team member MembershipState.

Reference: https://discord.com/developers/docs/topics/teams#data-models-membership-state-enum

const (
	MembershipStateInvited MembershipState = iota + 1
	MembershipStateAccepted
)

func (MembershipState) Is

func (s MembershipState) Is(memberShipState MembershipState) bool

Is returns true if the team member's membership state matches the provided membership state.

type MentionChannel

type MentionChannel struct {
	// ID is the unique Discord snowflake ID of the channel.
	ID Snowflake `json:"id"`
	// GuildID is the ID of the guild containing the channel.
	//
	// Optional:
	//   - Will be 0 if the channel is not in a guild (e.g., a DM channel).
	GuildID Snowflake `json:"guild_id"`
	// Type is the type of the channel.
	Type ChannelType `json:"type"`
	// Name is the name of the channel.
	Name string `json:"name"`
}

MentionChannel represents a channel mentioned in a message.

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

func (*MentionChannel) Mention

func (c *MentionChannel) Mention() string

Mention returns the Discord mention string for the channel in the format "<#channel_id>".

type MentionableSelectMenuComponent

type MentionableSelectMenuComponent struct {
	InteractiveComponentFields

	// Placeholder is the text if nothing is selected.
	//
	// Note:
	//   - Max 150 characters.
	Placeholder string `json:"placeholder,omitempty"`

	// DefaultValues is a list of default values for auto-populated select menu components;
	// number of default values must be in the range defined by min_values and max_values.
	DefaultValues []SelectDefaultValue `json:"default_values,omitempty"`

	// MinValues is the minimum number of items that must be chosen (defaults to 1).
	//
	// Note:
	//   - Min 0, max 25.
	MinValues *int `json:"min_values,omitempty"`

	// MaxValues is the maximum number of items that can be chosen (defaults to 1).
	//
	// Note:
	//   - Min 1, max 25.
	MaxValues int `json:"max_values,omitempty"`

	// Disabled is whether select menu is disabled (defaults to false).
	Disabled bool `json:"disabled,omitempty"`
}

MentionableSelectMenuComponent represents a mentionable select menu component.

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

func (*MentionableSelectMenuComponent) MarshalJSON

func (c *MentionableSelectMenuComponent) MarshalJSON() ([]byte, error)

type Message

type Message struct {
	EntityBase // Embedded client reference for action methods

	// ID is the unique Discord snowflake ID of the message.
	ID Snowflake `json:"id"`

	// ChannelID is the ID of the channel where the message was sent.
	ChannelID Snowflake `json:"channel_id"`

	// Author is the user who authored the message.
	//
	// Note:
	//   - For webhook messages, this field reflects the webhook's ID, username, and avatar.
	Author User `json:"author"`

	// Content is the text content of the message.
	//
	// Note:
	//   - Will be empty if the bot lacks the GatewayIntentMessageContent privileged intent (1 << 15).
	Content string `json:"content"`

	// Timestamp is when the message was sent.
	Timestamp time.Time `json:"timestamp"`

	// EditedTimestamp is when the message was last edited.
	//
	// Optional:
	//   - Will be nil if the message has never been edited.
	EditedTimestamp *time.Time `json:"edited_timestamp"`

	// TTS indicates whether the message is a text-to-speech message.
	TTS bool `json:"tts"`

	// MentionEveryone indicates whether the message mentions @everyone or @here.
	MentionEveryone bool `json:"mention_everyone"`

	// Mentions is an array of users specifically mentioned in the message.
	Mentions []User `json:"mentions"`

	// MentionRoles is an array of roles specifically mentioned in the message.
	MentionRoles []Role `json:"mention_roles"`

	// MentionChannels is an array of channels specifically mentioned in the message.
	//
	// Note:
	//   - Not all channel mentions in this message will appear in this slice. Only textual
	//     channels that are visible to everyone in a lurkable guild will ever be included. Only
	//     crossposted messages (via Channel Following) currently include MentionChannels at all.
	//     If no mentions in the message meet these requirements, this field will be empty.
	MentionChannels []MentionChannel `json:"mention_channels"`

	// Attachments is an array of file attachments included with the message.
	//
	// Optional:
	//   - Will be empty if no attachments are included or if the bot lacks the GatewayIntentMessageContent privileged intent (1 << 15).
	Attachments []Attachment `json:"attachments"`

	// Embeds is an array of embedded content included with the message.
	//
	// Optional:
	//   - Will be empty if no embeds are included or if the bot lacks the GatewayIntentMessageContent privileged intent (1 << 15).
	Embeds []Embed `json:"embeds"`

	// Reactions is an array of reactions to the message.
	Reactions []MessageReaction `json:"reactions"`

	// Nonce is a value used to validate that a message was sent successfully.
	Nonce Nonce `json:"nonce"`

	// Pinned indicates whether the message is pinned in the channel.
	Pinned bool `json:"pinned"`

	// WebhookID is the ID of the webhook that generated the message.
	//
	// Optional:
	//   - Will be 0 if the message is not sent by a webhook.
	WebhookID Snowflake `json:"webhook_id"`

	// Type is the type of the message.
	Type MessageType `json:"type"`

	// Activity is the activity associated with the message, used for Rich Presence embeds.
	//
	// Optional:
	//   - Will be nil if the message is not associated with a Rich Presence activity.
	Activity *MessageActivity `json:"activity"`

	// Application is a partial application object sent with Rich Presence-related chat embeds.
	//
	// Optional:
	//   - Will be nil if the message is not associated with a Rich Presence-related chat embed.
	Application *MessageApplication `json:"application"`

	// ApplicationID is the unique Discord snowflake ID of the application.
	//
	// Optional:
	//   - Will be 0 if the message is not an interaction or application-owned webhook.
	ApplicationID Snowflake `json:"application_id"`

	// Flags is a bitfield of message flags.
	Flags MessageFlags `json:"flags"`

	// MessageReference contains data showing the source of a crosspost, channel follow add, pin, or reply message.
	//
	// Optional:
	//   - Will be nil if the message is not a crosspost, channel follow add, pin, or reply.
	MessageReference *MessageReference `json:"message_reference"`

	// MessageSnapshots is an array of message snapshot objects associated with the message_reference,
	// containing a minimal subset of message fields (e.g., excludes Author).
	//
	// Optional:
	//   - Will be empty if the message is not associated with message forwarding.
	MessageSnapshots []MessageSnapshot `json:"message_snapshots"`

	// ReferencedMessage is the message associated with the message_reference.
	//
	// Optional:
	//   - Will be nil if the message is not of type MessageTypeReply, MessageTypeThreadStarterMessage,
	//     or MessageTypeContextMenuCommand, or if the referenced message was deleted.
	//
	// Note:
	//   - Only included for messages of type MessageTypeReply, MessageTypeThreadStarterMessage, or MessageTypeContextMenuCommand.
	ReferencedMessage *Message `json:"referenced_message"`

	// InteractionMetadata contains metadata about the interaction that generated the message.
	//
	// Optional:
	//   - Will be nil if the message is not generated by an interaction.
	InteractionMetadata *InteractionMetadata `json:"interaction_metadata"`

	// Thread is the thread started from this message, including thread member data.
	//
	// Optional:
	//   - Will be nil if the message did not start a thread.
	Thread *ResolvedThread `json:"thread"`

	// Components is an array of interactive components (e.g., buttons, select menus) included with the message.
	//
	// Optional:
	//   - Will be empty if no components are included or if the bot lacks the GatewayIntentMessageContent privileged intent (1 << 15).
	Components []LayoutComponent `json:"components"`

	// StickerItems is an array of sticker items included with the message.
	StickerItems []StickerItem `json:"sticker_items"`

	// Position is the approximate position of the message in a thread.
	//
	// Optional:
	//   - Will be nil if the message is not in a thread.
	Position *int `json:"position"`

	// GuildID is the ID of the guild where the message was sent.
	//
	// Optional:
	//   - Will be 0 if the message is not in a guild (e.g., a DM).
	GuildID Snowflake `json:"guild_id"`

	// Poll is the poll object included with the message.
	//
	// Optional:
	//   - Will be nil if no poll is included or if the bot lacks the GatewayIntentMessageContent privileged intent (1 << 15).
	Poll *Poll `json:"poll"`

	// Call is the call associated with the message (e.g., voice or video call).
	//
	// Optional:
	//   - Will be nil if the message is not associated with a call.
	Call *MessageCall `json:"call"`
}

Message represents a message sent in a channel within Discord.

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

func AcquireMessage

func AcquireMessage() *Message

AcquireMessage gets a Message from the pool. The returned Message must be released back to the pool after use.

func (*Message) Channel

func (m *Message) Channel() (Channel, bool)

Channel returns the cached channel this message was sent in. Returns nil if the channel is not in cache or if the message has no client.

Usage example:

if ch, ok := message.Channel(); ok {
    fmt.Println("Channel:", ch.GetName())
}

func (*Message) Delete

func (m *Message) Delete() error

Delete deletes this message.

Usage example:

err := message.Delete()

func (*Message) DeleteWithReason

func (m *Message) DeleteWithReason(reason string) error

DeleteWithReason deletes this message with an audit log reason.

Usage example:

err := message.DeleteWithReason("Spam")

func (*Message) Edit

func (m *Message) Edit(content string) (*Message, error)

Edit edits this message's content. Returns the updated message.

Usage example:

updated, err := message.Edit("New content")

func (*Message) EditWith

func (m *Message) EditWith(opts MessageEditOptions) (*Message, error)

EditWith edits this message with full options. Returns the updated message.

Usage example:

updated, err := message.EditWith(MessageEditOptions{
    Content: "New content",
    Embeds: []Embed{embed},
})

func (*Message) FetchChannel

func (m *Message) FetchChannel() (Channel, error)

FetchChannel fetches and returns the channel this message was sent in. This makes an API call; for cached channels, use Channel() instead.

Usage example:

channel, err := message.FetchChannel()

func (*Message) Guild

func (m *Message) Guild() (Guild, bool)

Guild returns the cached guild this message was sent in. Returns nil if the message was sent in a DM or if the guild is not in cache.

Usage example:

if g, ok := message.Guild(); ok {
    fmt.Println("Guild:", g.Name)
}

func (*Message) InGuild

func (m *Message) InGuild() bool

InGuild returns true if this message was sent in a guild (not a DM).

Usage example:

if message.InGuild() {
    // Handle guild message
}

func (*Message) Pin

func (m *Message) Pin() error

Pin pins this message in its channel. Requires MANAGE_MESSAGES permission.

Usage example:

err := message.Pin()

func (*Message) PinWithReason

func (m *Message) PinWithReason(reason string) error

PinWithReason pins this message with an audit log reason.

Usage example:

err := message.PinWithReason("Important announcement")

func (*Message) React

func (m *Message) React(emoji string) error

React adds a reaction to this message. The emoji can be a unicode emoji or a custom emoji in the format "name:id".

Usage example:

err := message.React("👍")
err := message.React("custom_emoji:123456789")

func (*Message) RemoveReaction

func (m *Message) RemoveReaction(emoji string) error

RemoveReaction removes the bot's reaction from this message.

Usage example:

err := message.RemoveReaction("👍")

func (*Message) Reply

func (m *Message) Reply(content string) (*Message, error)

Reply sends a reply to this message. Returns the new message that was sent.

Usage example:

reply, err := message.Reply("Hello!")

func (*Message) ReplyEmbed

func (m *Message) ReplyEmbed(embed Embed) (*Message, error)

ReplyEmbed sends an embed as a reply to this message. Returns the new message that was sent.

Usage example:

embed := goda.NewEmbedBuilder().SetTitle("Hello").Build()
reply, err := message.ReplyEmbed(embed)

func (*Message) ReplyWith

func (m *Message) ReplyWith(opts MessageCreateOptions) (*Message, error)

ReplyWith sends a reply with full message options. Returns the new message that was sent.

Usage example:

reply, err := message.ReplyWith(MessageCreateOptions{
    Content: "Hello!",
    Embeds: []Embed{embed},
})

func (*Message) URL

func (m *Message) URL() string

URL returns the Discord URL for the message in the format "https://discord.com/channels/{guild_id}/{channel_id}/{message_id}". If GuildID is 0 (e.g., for DMs), "@me" is used instead of a guild ID.

func (*Message) UnmarshalJSON

func (m *Message) UnmarshalJSON(buf []byte) error

UnmarshalJSON unmarshals a JSON message into a Message struct, handling component deserialization.

func (*Message) Unpin

func (m *Message) Unpin() error

Unpin unpins this message from its channel. Requires MANAGE_MESSAGES permission.

Usage example:

err := message.Unpin()

func (*Message) UnpinWithReason

func (m *Message) UnpinWithReason(reason string) error

UnpinWithReason unpins this message with an audit log reason.

Usage example:

err := message.UnpinWithReason("No longer relevant")

type MessageActivity

type MessageActivity struct {
	// Type is the type of the activity (e.g., join, spectate).
	Type MessageActivityType `json:"type"`
	// PartyID is the party ID from a Rich Presence event.
	//
	// Optional:
	//   - Will be empty if no party is associated with the activity.
	PartyID string `json:"party_id"`
}

MessageActivity represents an activity associated with a message, used for Rich Presence.

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

type MessageActivityType

type MessageActivityType int

MessageActivityType represents the type of activity associated with a message.

Reference: https://discord.com/developers/docs/resources/message#message-object-message-activity-types

const (
	// MessageActivityTypeJoin indicates a join activity (e.g., for Rich Presence).
	MessageActivityTypeJoin MessageActivityType = iota + 1
	// MessageActivityTypeSpectate indicates a spectate activity.
	MessageActivityTypeSpectate
	// MessageActivityTypeListen indicates a listen activity.
	MessageActivityTypeListen

	// MessageActivityTypeJoinRequest indicates a join request activity.
	MessageActivityTypeJoinRequest
)

func (MessageActivityType) Is

func (t MessageActivityType) Is(messageActivityType MessageActivityType) bool

Is checks if the message activity type matches the provided type.

type MessageApplication

type MessageApplication struct {
	// ID is the unique Discord snowflake ID of the application.
	ID Snowflake `json:"id"`

	// CoverImage is the cover image hash of the application.
	//
	// Optional:
	//   - Will be empty if no cover image is set.
	CoverImage string `json:"cover_image"`

	// Description is the description of the application.
	Description string `json:"description"`

	// Icon is the icon hash of the application.
	//
	// Optional:
	//   - Will be empty if no icon is set.
	Icon string `json:"icon"`

	// Name is the name of the application.
	Name string `json:"name"`
}

MessageApplication represents a partial application object for Rich Presence or webhooks.

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

type MessageCall

type MessageCall struct {
	// Participants is an array of user IDs participating in the call.
	//
	// Optional:
	//   - Will be empty if no participants are present.
	Participants []Snowflake `json:"participants"`

	// EndedTimestamp is when the call ended.
	//
	// Optional:
	//   - Will be nil if the call is ongoing or not applicable.
	EndedTimestamp *time.Time `json:"ended_timestamp"`
}

MessageCall represents a call associated with a message.

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

type MessageChannel

type MessageChannel interface {
	Channel
	// GetLastMessageID returns the Snowflake ID to the last message sent in this channel.
	//
	// Note:
	//   - Will always return 0 if no Message has been sent yet.
	GetLastMessageID() Snowflake
}

MessageChannel represents a Discord text channel.

This interface extends the Channel interface and adds text-channel-specific fields, such as the ID of the last message and the rate limit (slowmode) per user.

Use this interface when you want to handle text channels specifically.

You can convert (assert) it to a concrete type using a type assertion or type switch:

Example usage:

var ch MessageChannel

switch c := ch.(type) {
case *TextChannel:
    fmt.Println("Text channel name:", c.GetName())
    fmt.Println("Last message ID:", c.GetLastMessageID())
case *VoiceChannel:
    fmt.Println("Voiec channel name:", c.GetName())
    fmt.Println("Last message ID:", c.GetLastMessageID())
case *DMChannel:
    fmt.Println("DM channel name:", c.GetName())
    fmt.Println("Last message ID:", c.GetLastMessageID())
default:
    fmt.Println("Other text channel type:", c.GetType())
}

You can also use an if-condition to check a specific type:

if textCh, ok := ch.(*TextChannel); ok {
    fmt.Println("Text channel:", textCh.GetName())
}

type MessageChannelFields

type MessageChannelFields struct {
	// LastMessageID is the id of the last message sent in this channel.
	LastMessageID Snowflake `json:"last_message_id"`
}

MessageChannelFields holds fields related to text-based features like messaging.

func (*MessageChannelFields) GetLastMessageID

func (t *MessageChannelFields) GetLastMessageID() Snowflake

type MessageCommandInteraction

type MessageCommandInteraction struct {
	ApplicationCommandInteractionFields

	// Data contains the payload of the interaction specific to message commands.
	Data MessageCommandInteractionData `json:"data"`
}

MessageCommandInteraction represents an interaction triggered by a message context menu command.

Reference: https://discord.com/developers/docs/interactions/application-commands

type MessageCommandInteractionData

type MessageCommandInteractionData struct {
	ApplicationCommandInteractionDataFields

	// Resolved contains the resolved objects referenced by the command, messages in this case.
	Resolved MessageCommandInteractionDataResolved `json:"resolved"`

	// TargetID is the id of the message targeted by the command.
	TargetID Snowflake `json:"target_id"`
}

MessageCommandInteractionData represents the data for a message command interaction.

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

type MessageCommandInteractionDataResolved

type MessageCommandInteractionDataResolved struct {
	// Messages is a map of message IDs to partial Message objects
	// referenced by the command.
	Messages map[Snowflake]Message `json:"messages"`
}

MessageCommandInteractionDataResolved represents the resolved data for a message command interaction.

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

type MessageCreateEvent

type MessageCreateEvent struct {
	ShardsID int // shard that dispatched this event
	Message  Message
}

MessageCreateEvent Message was created

type MessageCreateOptions

type MessageCreateOptions struct {
	Content          string             `json:"content,omitempty"`
	Nonce            string             `json:"nonce,omitempty"`
	TTS              bool               `json:"tts,omitempty"`
	Embeds           []Embed            `json:"embeds,omitempty"`
	AllowedMentions  *AllowedMentions   `json:"allowed_mentions,omitempty"`
	MessageReference *MessageReference  `json:"message_reference,omitempty"`
	Components       []LayoutComponent  `json:"components,omitempty"`
	StickerIDs       []Snowflake        `json:"sticker_ids,omitempty"`
	Flags            MessageFlags       `json:"flags,omitempty"`
	EnforceNonce     bool               `json:"enforce_nonce,omitempty"`
	Poll             *PollCreateOptions `json:"poll,omitempty"`
}

type MessageDeleteEvent

type MessageDeleteEvent struct {
	ShardsID int // shard that dispatched this event
	Message  Message
}

MessageDeleteEvent Message was deleted

type MessageEditOptions

type MessageEditOptions struct {
	// Content is the new message content (up to 2000 characters).
	Content string `json:"content,omitempty"`
	// Embeds are the new embedded rich content (up to 10 embeds).
	Embeds []Embed `json:"embeds,omitempty"`
	// Flags are edit flags to set on the message.
	Flags MessageFlags `json:"flags,omitempty"`
	// AllowedMentions are the allowed mentions for the message.
	AllowedMentions *AllowedMentions `json:"allowed_mentions,omitempty"`
	// Components are the components to include with the message.
	Components []LayoutComponent `json:"components,omitempty"`
	// Attachments are the attachments to keep or add.
	Attachments []Attachment `json:"attachments,omitempty"`
}

MessageEditOptions are options for editing a message.

type MessageFlags

type MessageFlags int

MessageFlags represents a bitfield of flags for a message.

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

const (
	// MessageFlagCrossposted indicates the message was published to subscribed channels via Channel Following.
	MessageFlagCrossposted MessageFlags = 1 << iota
	// MessageFlagIsCrosspost indicates the message originated from another channel via Channel Following.
	MessageFlagIsCrosspost
	// MessageFlagSuppressEmbeds indicates embeds should not be included when serializing the message.
	MessageFlagSuppressEmbeds
	// MessageFlagSourceMessageDeleted indicates the source message for a crosspost was deleted.
	MessageFlagSourceMessageDeleted
	// MessageFlagUrgent indicates the message came from the urgent message system.
	MessageFlagUrgent
	// MessageFlagHasThread indicates the message has an associated thread with the same ID.
	MessageFlagHasThread
	// MessageFlagEphemeral indicates the message is only visible to the user who invoked the interaction.
	MessageFlagEphemeral
	// MessageFlagLoading indicates the message is an interaction response and the bot is "thinking".
	MessageFlagLoading
	// MessageFlagFailedToMentionSomeRolesInThread indicates the message failed to mention some roles in a thread.
	MessageFlagFailedToMentionSomeRolesInThread

	// MessageFlagSuppressNotifications indicates the message will not trigger push or desktop notifications.
	MessageFlagSuppressNotifications
	// MessageFlagIsVoiceMessage indicates the message is a voice message.
	MessageFlagIsVoiceMessage
	// MessageFlagHasSnapshot indicates the message has a snapshot via Message Forwarding.
	MessageFlagHasSnapshot
	// MessageFlagIsComponentsV2 indicates the message supports fully component-driven interactions.
	MessageFlagIsComponentsV2

	// MessageFlagsNone represents no flags set.
	MessageFlagsNone MessageFlags = 0
)

func (*MessageFlags) Add

func (f *MessageFlags) Add(flags ...MessageFlags)

Add sets all provided flags in the bitfield.

func (MessageFlags) Has

func (f MessageFlags) Has(flags ...MessageFlags) bool

Has checks if all provided flags are set in the bitfield.

func (*MessageFlags) Remove

func (f *MessageFlags) Remove(flags ...MessageFlags)

Remove clears all provided flags from the bitfield.

type MessageNotificationsLevel

type MessageNotificationsLevel int

MessageNotificationLevel represents the default notification level on a Discord guild.

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

const (
	// Members will receive notifications for all messages by default.
	MessageNotificationsLevelAllMessages MessageNotificationsLevel = iota
	// Members will receive notifications only for messages that @mention them by default.
	MessageNotificationsLevelOnlyMentions
)

func (MessageNotificationsLevel) Is

func (l MessageNotificationsLevel) Is(messageNotificationLevel MessageNotificationsLevel) bool

Is returns true if the message notifaction level matches the provided one.

type MessageReaction

type MessageReaction struct {
	// Count is the total number of times this emoji has been used to react, including super reactions.
	Count int `json:"count"`
	// CountDetails provides detailed counts of normal and super reactions.
	CountDetails ReactionCountDetails `json:"count_details"`
	// Me indicates whether the current user reacted with this emoji.
	Me bool `json:"me"`
	// MeBurst indicates whether the current user used a super reaction with this emoji.
	MeBurst bool `json:"me_burst"`
	// Emoji is the emoji used for the reaction.
	Emoji Emoji `json:"emoji"`
	// BurstColors contains the HEX colors used for super reactions.
	//
	// Optional:
	//   - Will be empty if no super reactions are present.
	BurstColors []string `json:"burst_colors"`
}

MessageReaction represents a reaction to a message on Discord.

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

type MessageReference

type MessageReference struct {
	// Type is the type of reference (e.g., default, forward).
	//
	// Optional:
	//   - Will be omitted if not specified when sending a message.
	Type MessageReferenceType `json:"type,omitempty"`

	// MessageID is the ID of the referenced message.
	MessageID Snowflake `json:"message_id"`

	// ChannelID is the ID of the channel containing the referenced message.
	//
	// Optional:
	//   - Will be omitted if not specified when sending a message.
	ChannelID Snowflake `json:"channel_id,omitempty"`

	// GuildID is the ID of the guild containing the referenced message.
	//
	// Optional:
	//   - Will be 0 if the referenced message is not in a guild.
	GuildID Snowflake `json:"guild_id,omitempty"`

	// FailIfNotExists determines whether to error if the referenced message does not exist.
	//
	// Optional:
	//   - Defaults to true when sending a message.
	FailIfNotExists bool `json:"fail_if_not_exists,omitempty"`
}

MessageReference represents a reference to another message, such as for replies or crossposts.

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

type MessageReferenceType

type MessageReferenceType int

MessageReferenceType determines how associated data is populated for a message reference.

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

const (
	// MessageReferenceTypeDefault is a standard message reference (e.g., for replies).
	MessageReferenceTypeDefault MessageReferenceType = iota
	// MessageReferenceTypeForward is a reference for forwarded messages.
	MessageReferenceTypeForward
)

type MessageSnapshot

type MessageSnapshot struct {
	// Message is the partial message data for the snapshot.
	Message PartialMessage `json:"message"`
}

MessageSnapshot represents a snapshot of a message, used for message forwarding.

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

type MessageType

type MessageType int

MessageType represents the type of a message on Discord.

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

const (
	// MessageTypeDefault is a standard user-sent message.
	// Deletable: true
	MessageTypeDefault MessageType = iota
	// MessageTypeRecipientAdd is a system message indicating a user was added to a group DM.
	// Deletable: false
	MessageTypeRecipientAdd
	// MessageTypeRecipientRemove is a system message indicating a user was removed from a group DM.
	// Deletable: false
	MessageTypeRecipientRemove
	// MessageTypeCall is a system message indicating a call was started.
	// Deletable: false
	MessageTypeCall
	// MessageTypeChannelNameChange is a system message indicating a channel's name was changed.
	// Deletable: false
	MessageTypeChannelNameChange
	// MessageTypeChannelIconChange is a system message indicating a channel's icon was changed.
	// Deletable: false
	MessageTypeChannelIconChange
	// MessageTypeChannelPinnedMessage is a system message indicating a message was pinned.
	// Deletable: true
	MessageTypeChannelPinnedMessage
	// MessageTypeUserJoin is a system message indicating a user joined a guild.
	// Deletable: true
	MessageTypeUserJoin
	// MessageTypeGuildBoost is a system message indicating a guild received a boost.
	// Deletable: true
	MessageTypeGuildBoost
	// MessageTypeGuildBoostTier1 is a system message indicating a guild reached boost tier 1.
	// Deletable: true
	MessageTypeGuildBoostTier1
	// MessageTypeGuildBoostTier2 is a system message indicating a guild reached boost tier 2.
	// Deletable: true
	MessageTypeGuildBoostTier2
	// MessageTypeGuildBoostTier3 is a system message indicating a guild reached boost tier 3.
	// Deletable: true
	MessageTypeGuildBoostTier3
	// MessageTypeChannelFollowAdd is a system message indicating a channel was followed.
	// Deletable: true
	MessageTypeChannelFollowAdd

	// MessageTypeGuildDiscoveryDisqualified is a system message indicating a guild was disqualified from Discovery.
	// Deletable: true
	MessageTypeGuildDiscoveryDisqualified
	// MessageTypeGuildDiscoveryRequalified is a system message indicating a guild requalified for Discovery.
	// Deletable: true
	MessageTypeGuildDiscoveryRequalified
	// MessageTypeGuildDiscoveryGracePeriodInitialWarning is a system message for the initial Discovery grace period warning.
	// Deletable: true
	MessageTypeGuildDiscoveryGracePeriodInitialWarning
	// MessageTypeGuildDiscoveryGracePeriodFinalWarning is a system message for the final Discovery grace period warning.
	// Deletable: true
	MessageTypeGuildDiscoveryGracePeriodFinalWarning
	// MessageTypeThreadCreated is a system message indicating a thread was created.
	// Deletable: true
	MessageTypeThreadCreated
	// MessageTypeReply is a message sent as a reply to another message.
	// Deletable: true
	MessageTypeReply
	// MessageTypeSlashCommand is a message resulting from a slash command interaction.
	// Deletable: true
	MessageTypeSlashCommand
	// MessageTypeThreadStarterMessage is the initial message of a thread.
	// Deletable: false
	MessageTypeThreadStarterMessage
	// MessageTypeGuildInviteReminder is a system message reminding users to invite friends to the guild.
	// Deletable: true
	MessageTypeGuildInviteReminder
	// MessageTypeContextMenuCommand is a message resulting from a context menu command.
	// Deletable: true
	MessageTypeContextMenuCommand
	// MessageTypeAutoModerationAction is a system message generated by an AutoMod action.
	// Deletable: true
	MessageTypeAutoModerationAction
	// MessageTypeRoleSubscriptionPurchase is a system message for a role subscription purchase.
	// Deletable: true
	MessageTypeRoleSubscriptionPurchase
	// MessageTypeInteractionPremiumUpsell is a system message encouraging a premium subscription upsell.
	// Deletable: true
	MessageTypeInteractionPremiumUpsell
	// MessageTypeStageStart is a system message indicating a stage instance started.
	// Deletable: true
	MessageTypeStageStart
	// MessageTypeStageEnd is a system message indicating a stage instance ended.
	// Deletable: true
	MessageTypeStageEnd
	// MessageTypeStageSpeaker is a system message indicating a stage speaker was added.
	// Deletable: true
	MessageTypeStageSpeaker

	// MessageTypeStageTopic is a system message indicating a stage topic was changed.
	// Deletable: true
	MessageTypeStageTopic
	// MessageTypeGuildApplicationPremiumSubscription is a system message for a guild premium subscription via an app.
	// Deletable: true
	MessageTypeGuildApplicationPremiumSubscription

	// MessageTypeGuildIncidentAlertModeEnabled is a system message indicating incident alert mode was enabled.
	// Deletable: true
	MessageTypeGuildIncidentAlertModeEnabled
	// MessageTypeGuildIncidentAlertModeDisabled is a system message indicating incident alert mode was disabled.
	// Deletable: true
	MessageTypeGuildIncidentAlertModeDisabled
	// MessageTypeGuildIncidentReportRaid is a system message indicating a raid was reported.
	// Deletable: true
	MessageTypeGuildIncidentReportRaid
	// MessageTypeGuildIncidentReportFalseAlarm is a system message indicating a raid report was marked as false.
	// Deletable: true
	MessageTypeGuildIncidentReportFalseAlarm

	// MessageTypePurchaseNotification is a system message for a purchase notification.
	// Deletable: true
	MessageTypePurchaseNotification

	// MessageTypePollResult is a system message indicating the results of a poll.
	// Deletable: true
	MessageTypePollResult
)

func (MessageType) Deletable

func (t MessageType) Deletable() bool

Deletable indicates whether the message can be deleted.

func (MessageType) Is

func (t MessageType) Is(messageType MessageType) bool

Is checks if the message type matches the provided type.

func (MessageType) System

func (t MessageType) System() bool

System indicates whether the message is a system-generated message.

type MessageUpdateEvent

type MessageUpdateEvent struct {
	ShardsID   int // shard that dispatched this event
	OldMessage Message
	NewMessage Message
}

MessageCreateEvent Message was created

type ModalSubmitInteraction

type ModalSubmitInteraction struct {
	InteractionFields
}

type ModifyChannelPositionsEntry

type ModifyChannelPositionsEntry struct {
	// ID is the channel id.
	ID Snowflake `json:"id"`
	// Position is the sorting position of the channel.
	Position *int `json:"position,omitempty"`
	// LockPermissions syncs the permission overwrites with the parent category.
	LockPermissions *bool `json:"lock_permissions,omitempty"`
	// ParentID is the new parent ID for the channel.
	ParentID *Snowflake `json:"parent_id,omitempty"`
}

ModifyChannelPositionsEntry represents a channel position modification.

type ModifyCurrentMemberOptions

type ModifyCurrentMemberOptions struct {
	// Nick is the value to set the bot's nickname to. Requires CHANGE_NICKNAME permission.
	Nick *string `json:"nick,omitempty"`
}

ModifyCurrentMemberOptions are options for modifying the current member (bot).

type ModifyRolePositionsEntry

type ModifyRolePositionsEntry struct {
	// ID is the role id.
	ID Snowflake `json:"id"`
	// Position is the sorting position of the role.
	Position *int `json:"position,omitempty"`
}

ModifyRolePositionsEntry represents a role position modification.

type NSFWLevel

type NSFWLevel int

NSFWLevel represent the NSFW level on a Discord guild.

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

const (
	NSFWLevelDefault NSFWLevel = iota
	NSFWLevelExplicit
	NSFWLevelSafe
	NSFWLevelAgeRestricted
)

func (NSFWLevel) Is

func (l NSFWLevel) Is(level NSFWLevel) bool

Is returns true if the guild's NSFW level matches the provided NSFW level.

type NamedChannel

type NamedChannel interface {
	Channel
	GetName() string
}

NamedChannel represents a Discord channel that has a name.

This interface is used for channel types that expose a name, such as text channels, voice channels, forum channels, thread channels, DM channels, and Group DM channels.

Use this interface when you want to handle channels generically by their name without knowing the specific concrete type in advance.

You can convert (assert) it to a specific channel type using a type assertion or a type switch, as described in the official Go documentation:

Example usage:

var ch NamedChannel

// Using a type switch to handle specific channel types
switch c := ch.(type) {
case *TextChannel:
    fmt.Println("Text channel name:", c.GetName())
case *VoiceChannel:
    fmt.Println("Voice channel name:", c.GetName())
default:
    fmt.Println("Other named channel type:", c.GetType())
}

// Using a type assertion to check a specific type
if textCh, ok := ch.(*TextChannel); ok {
    fmt.Println("Text channel name:", textCh.GetName())
}

type Nameplate

type Nameplate struct {
	// SkuID is the Discord snowflake ID of the nameplate SKU.
	SkuID Snowflake `json:"sku_id"`

	// Asset is the path to the nameplate asset.
	Asset string `json:"asset"`

	// Label is the label of this nameplate.
	//
	// Optional:
	//  - May be empty string.
	Label string `json:"label"`

	// Palette is the background color of the nameplate.
	//
	// Values possible:
	// "crimson", "berry", "sky", "teal", "forest",
	// "bubble_gum", "violet", "cobalt", "clover", "lemon", "white"
	Palette string `json:"palette"`
}

Nameplate represents the nameplate the user has.

Reference: https://discord.com/developers/docs/resources/user#nameplate

type Nonce

type Nonce string

Nonce represents a string or integer used to validate message sending.

func (*Nonce) UnmarshalJSON

func (n *Nonce) UnmarshalJSON(b []byte) error

type NsfwChannelFields

type NsfwChannelFields struct {
	// Nsfw indicates whether the channel is NSFW.
	Nsfw bool `json:"nsfw"`
}

NsfwChannelFields holds the NSFW indicator field.

type OAuth2Scope

type OAuth2Scope string

OAuth2Scope represent the scopes you can request in the OAuth2 flow.

Referenceflag flag://discord.com/developers/docs/topics/oauth2#shared-resources-oauth2-flag

const (
	// OAuth2ScopeActivitiesRead allows your app to fetch data from a
	// user's "Now Playing/Recently Played" list - requires Discord approval.
	OAuth2ScopeActivitiesRead OAuth2Scope = "activities.read"
	// OAuth2ScopeActivitiesWrite allows your app to update a user's activity - requires
	// Discord approval (NOT REQUIRED FOR GAMESDK ACTIVITY MANAGER).
	OAuth2ScopeActivitiesWrite OAuth2Scope = "activities.write"
	// OAuth2ScopeApplicationsBuildsRead allows your app to read build data for a user's applications.
	OAuth2ScopeApplicationsBuildsRead OAuth2Scope = "applications.builds.read"
	// OAuth2ScopeApplicationsBuildsUpload allows your app to upload/update builds for a user's
	// applications - requires Discord approval.
	OAuth2ScopeApplicationsBuildsUpload OAuth2Scope = "applications.builds.upload"
	// OAuth2ScopeApplicationsCommands allows your app to add commands to a
	// guild - included by default with the bot scope.
	OAuth2ScopeApplicationsCommands OAuth2Scope = "applications.commands"
	// OAuth2ScopeApplicationsCommandsUpdate allows your app to update its commands
	// using a Bearer token - client credentials grant only.
	OAuth2ScopeApplicationsCommandsUpdate OAuth2Scope = "applications.commands.update"
	// OAuth2ScopeApplicationsCommandsPermissionsUpdate allows your app to update permissions
	// for its commands in a guild a user has permissions to.
	OAuth2ScopeApplicationsCommandsPermissionsUpdate OAuth2Scope = "applications.commands.permissions.update"
	// OAuth2ScopeApplicationsEntitlements allows your app to read entitlements for a user's applications.
	OAuth2ScopeApplicationsEntitlements OAuth2Scope = "applications.entitlements"
	// OAuth2ScopeApplicationsStoreUpdate allows your app to read and update store data
	// (SKUs, store listings, achievements, etc.) for a user's applications.
	OAuth2ScopeApplicationsStoreUpdate OAuth2Scope = "applications.store.update"
	// OAuth2ScopeBot for oauth2 bots, this puts the bot in the user's selected guild by default.
	OAuth2ScopeBot OAuth2Scope = "bot"
	// OAuth2ScopeConnections allows /users/@me/connections to return linked third-party accounts.
	OAuth2ScopeConnections OAuth2Scope = "connections"
	// OAuth2ScopeDMChannelsRead allows your app to see information about the user's DMs and
	// group DMs - requires Discord approval.
	OAuth2ScopeDMChannelsRead OAuth2Scope = "dm_channels.read"
	// OAuth2ScopeEmail enables /users/@me to return an email.
	OAuth2ScopeEmail OAuth2Scope = "email"
	// OAuth2ScopeGDMJoin allows your app to join users to a group dm.
	OAuth2ScopeGDMJoin OAuth2Scope = "gdm.join"
	// OAuth2ScopeGuilds allows /users/@me/guilds to return basic information about all of a user's guilds.
	OAuth2ScopeGuilds OAuth2Scope = "guilds"
	// OAuth2ScopeGuildsJoin allows /guilds/{guild.id}/members/{user.id} to be used for joining users to a guild.
	OAuth2ScopeGuildsJoin OAuth2Scope = "guilds.join"
	// OAuth2ScopeGuildsMembersRead allows /users/@me/guilds/{guild.id}/member to return
	// a user's member information in a guild.
	OAuth2ScopeGuildsMembersRead OAuth2Scope = "guilds.members.read"
	// OAuth2ScopeIdentify allows /users/@me without email.
	OAuth2ScopeIdentify OAuth2Scope = "identify"
	// OAuth2ScopeMessagesRead for local rpc server api access, this allows you to read messages
	// from all client channels (otherwise restricted to channels/guilds your app creates).
	OAuth2ScopeMessagesRead OAuth2Scope = "messages.read"
	// OAuth2ScopeRelationshipsRead allows your app to know a user's friends and implicit
	// relationships - requires Discord approval.
	OAuth2ScopeRelationshipsRead OAuth2Scope = "relationships.read"
	// OAuth2ScopeRoleConnectionsWrite allows your app to update a user's connection and metadata for the app.
	OAuth2ScopeRoleConnectionsWrite OAuth2Scope = "role_connections.write"
	// OAuth2ScopeRPC for local rpc server access, this allows you to control a user's local
	// Discord client - requires Discord approval.
	OAuth2ScopeRPC OAuth2Scope = "rpc"
	// OAuth2ScopeRPCActivitiesWrite for local rpc server access, this allows you to update
	// a user's activity - requires Discord approval.
	OAuth2ScopeRPCActivitiesWrite OAuth2Scope = "rpc.activities.write"
	// OAuth2ScopeRPCNotificationsRead for local rpc server access, this allows you to
	// receive notifications pushed out to the user - requires Discord approval.
	OAuth2ScopeRPCNotificationsRead OAuth2Scope = "rpc.notifications.read"
	// OAuth2ScopeRPCVoiceRead for local rpc server access, this allows you to read
	// a user's voice settings and listen for voice events - requires Discord approval.
	OAuth2ScopeRPCVoiceRead OAuth2Scope = "rpc.voice.read"
	// OAuth2ScopeRPCVoiceWrite for local rpc server access, this allows you to update
	// a user's voice settings - requires Discord approval.
	OAuth2ScopeRPCVoiceWrite OAuth2Scope = "rpc.voice.write"
	// OAuth2ScopeVoice allows your app to connect to voice on user's behalf
	// and see all the voice members - requires Discord approval.
	OAuth2ScopeVoice OAuth2Scope = "voice"
	// OAuth2ScopeWebhookIncoming this generates a webhook that is returned in
	// the oauth token response for authorization code grants.
	OAuth2ScopeWebhookIncoming OAuth2Scope = "webhook.incoming"
)

type OAuth2User

type OAuth2User struct {
	User

	// Flags are internal user account flags.
	Flags UserFlags `json:"flags"`

	// Locale is the user's chosen language/locale.
	Locale Locale `json:"locale"`

	// MFAEnabled indicates if the user has two-factor authentication enabled.
	MFAEnabled bool `json:"mfa_enabled"`

	// Verified indicates if the user's email is verified.
	Verified bool `json:"verified"`

	// Email is the user's email address.
	Email string `json:"email"`
}

type OptionBase

type OptionBase struct {
	// Type is the type of the option.
	Type ApplicationCommandOptionType `json:"type"`

	// Name is the name of the option.
	//
	// Info:
	//  - Must be 1-32 characters.
	//  - Must be unique within an array of application command options.
	Name string `json:"name"`

	// Description is the description of the option.
	//
	// Info:
	//  - Must be 1-100 characters.
	Description string `json:"description"`

	// NameLocalizations is a localization dictionary for the name field.
	//
	// Info:
	//  - Keys are available locales.
	//  - Values follow the same restrictions as Name (1-32 characters).
	NameLocalizations map[Locale]string `json:"name_localizations,omitempty"`

	// DescriptionLocalizations is a localization dictionary for the description field.
	//
	// Info:
	//  - Keys are available locales.
	//  - Values follow the same restrictions as Description (1-100 characters).
	DescriptionLocalizations map[Locale]string `json:"description_localizations,omitempty"`
}

OptionBase contains fields common to all application command option types.

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

func (*OptionBase) GetDescription

func (o *OptionBase) GetDescription() string

func (*OptionBase) GetName

func (o *OptionBase) GetName() string

func (*OptionBase) GetType

type PartialChannel

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

PartialChannel represents a partial channel object.

type PartialEmoji

type PartialEmoji struct {
	// ID is the unique identifier for a custom emoji.
	// When sending a poll request with a custom emoji, provide only the ID and leave Name empty.
	//
	// Optional:
	//  - Will be 0 if no ID is set (e.g., for Unicode emojis or when not provided in a response).
	ID Snowflake `json:"id,omitempty"`

	// Name is the name of the emoji, used for Unicode emojis (e.g., "😊").
	// When sending a poll request with a Unicode emoji, provide only the Name and leave ID as 0.
	//
	// Optional:
	//  - Will be empty if no name is set (e.g., for custom emojis or when not provided in a response).
	Name string `json:"name,omitempty"`

	// Animated indicates whether the emoji is animated.
	Animated bool `json:"animated"`
}

PartialEmoji represents a partial emoji object used in a Discord poll, typically within a PollMedia object for poll answers, or when sending a message with a poll request.

When creating a poll answer, provide only the ID for a custom emoji or only the Name for a Unicode emoji.

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

type PartialGuild

type PartialGuild struct {
	// ID is the guild's unique Discord snowflake ID.
	ID Snowflake `json:"id"`

	// Locale is the preferred locale of the guild;
	Locale Locale `json:"locale"`

	// Features is the enabled guild features.
	Features []GuildFeature `json:"features"`
}

PartialGuild represents a partial struct of a Discord guild.

Reference: https://discord.com/developers/docs/resources/guild

type PartialMessage

type PartialMessage struct {
	// Type is the type of the message (e.g., default, reply).
	Type MessageType `json:"type"`

	// Content is the text content of the message.
	Content string `json:"content"`

	// Embeds is an array of embedded content in the message.
	//
	// Optional:
	//   - Will be empty if no embeds are included.
	Embeds []Embed `json:"embeds"`

	// Attachments is an array of file attachments in the message.
	//
	// Optional:
	//   - Will be empty if no attachments are included.
	Attachments []Attachment `json:"attachments"`

	// Timestamp is when the message was sent.
	Timestamp time.Time `json:"timestamp"`

	// EditedTimestamp is when the message was last edited.
	//
	// Optional:
	//   - Will be nil if the message has never been edited.
	EditedTimestamp *time.Time `json:"edited_timestamp"`

	// Flags is a bitfield of message flags (e.g., crossposted, ephemeral).
	Flags MessageFlags `json:"flags"`

	// Mentions is an array of users mentioned in the message.
	//
	// Optional:
	//   - Will be empty if no users are mentioned.
	Mentions []User `json:"mentions"`

	// MentionRoles is an array of roles mentioned in the message.
	//
	// Optional:
	//   - Will be empty if no roles are mentioned.
	MentionRoles []Snowflake `json:"mention_roles"`

	// Stickers is an array of stickers included in the message.
	//
	// Optional:
	//   - Will be empty if no stickers are included.
	Stickers []Sticker `json:"stickers"`
}

PartialMessage represents a lightweight version of a Discord message.

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

type PermissionName

type PermissionName = string

PermissionName is a human-readable name for a Discord permission.

const (
	PermissionNameCreateInstantInvite              PermissionName = "CreateInstantInvite"
	PermissionNameKickMembers                      PermissionName = "KickMembers"
	PermissionNameBanMembers                       PermissionName = "BanMembers"
	PermissionNameAdministrator                    PermissionName = "Administrator"
	PermissionNameManageChannels                   PermissionName = "ManageChannels"
	PermissionNameManageGuild                      PermissionName = "ManageGuild"
	PermissionNameAddReactions                     PermissionName = "AddReactions"
	PermissionNameViewAuditLog                     PermissionName = "ViewAuditLog"
	PermissionNamePrioritySpeaker                  PermissionName = "PrioritySpeaker"
	PermissionNameStream                           PermissionName = "Stream"
	PermissionNameViewChannel                      PermissionName = "ViewChannel"
	PermissionNameSendMessages                     PermissionName = "SendMessages"
	PermissionNameSendTTSMessages                  PermissionName = "SendTTSMessages"
	PermissionNameManageMessages                   PermissionName = "ManageMessages"
	PermissionNameEmbedLinks                       PermissionName = "EmbedLinks"
	PermissionNameAttachFiles                      PermissionName = "AttachFiles"
	PermissionNameReadMessageHistory               PermissionName = "ReadMessageHistory"
	PermissionNameMentionEveryone                  PermissionName = "MentionEveryone"
	PermissionNameUseExternalEmojis                PermissionName = "UseExternalEmojis"
	PermissionNameViewGuildInsights                PermissionName = "ViewGuildInsights"
	PermissionNameConnect                          PermissionName = "Connect"
	PermissionNameSpeak                            PermissionName = "Speak"
	PermissionNameMuteMembers                      PermissionName = "MuteMembers"
	PermissionNameDeafenMembers                    PermissionName = "DeafenMembers"
	PermissionNameMoveMembers                      PermissionName = "MoveMembers"
	PermissionNameUseVAD                           PermissionName = "UseVAD"
	PermissionNameChangeNickname                   PermissionName = "ChangeNickname"
	PermissionNameManageNicknames                  PermissionName = "ManageNicknames"
	PermissionNameManageRoles                      PermissionName = "ManageRoles"
	PermissionNameManageWebhooks                   PermissionName = "ManageWebhooks"
	PermissionNameManageGuildExpressions           PermissionName = "ManageGuildExpressions"
	PermissionNameUseApplicationCommands           PermissionName = "UseApplicationCommands"
	PermissionNameRequestToSpeak                   PermissionName = "RequestToSpeak"
	PermissionNameManageEvents                     PermissionName = "ManageEvents"
	PermissionNameManageThreads                    PermissionName = "ManageThreads"
	PermissionNameCreatePublicThreads              PermissionName = "CreatePublicThreads"
	PermissionNameCreatePrivateThreads             PermissionName = "CreatePrivateThreads"
	PermissionNameUseExternalStickers              PermissionName = "UseExternalStickers"
	PermissionNameSendMessagesInThreads            PermissionName = "SendMessagesInThreads"
	PermissionNameUseEmbeddedActivities            PermissionName = "UseEmbeddedActivities"
	PermissionNameModerateMembers                  PermissionName = "ModerateMembers"
	PermissionNameViewCreatorMonetizationAnalytics PermissionName = "ViewCreatorMonetizationAnalytics"
	PermissionNameUseSoundboard                    PermissionName = "UseSoundboard"
	PermissionNameCreateGuildExpressions           PermissionName = "CreateGuildExpressions"
	PermissionNameCreateEvents                     PermissionName = "CreateEvents"
	PermissionNameUseExternalSounds                PermissionName = "UseExternalSounds"
	PermissionNameSendVoiceMessages                PermissionName = "SendVoiceMessages"
	PermissionNameSendPolls                        PermissionName = "SendPolls"
	PermissionNameUseExternalApps                  PermissionName = "UseExternalApps"
)

type PermissionOverwrite

type PermissionOverwrite struct {
	// ID is the role or user ID the overwrite applies to.
	ID Snowflake `json:"id"`

	// Type specifies whether this overwrite is for a role or a member.
	Type PermissionOverwriteType `json:"type"`

	// Allow is the permission bit set explicitly allowed.
	Allow Permissions `json:"allow,omitempty"`

	// Deny is the permission bit set explicitly denied.
	Deny Permissions `json:"deny,omitempty"`
}

PermissionOverwrite represents a permission overwrite for a role or member.

Used to grant or deny specific permissions in a channel.

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

type PermissionOverwriteType

type PermissionOverwriteType int

PermissionOverwriteType defines the type of permission overwrite target.

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

const (
	// PermissionOverwriteTypeRole indicates the overwrite applies to a role.
	PermissionOverwriteTypeRole PermissionOverwriteType = 0

	// PermissionOverwriteTypeMember indicates the overwrite applies to a member.
	PermissionOverwriteTypeMember PermissionOverwriteType = 1
)

func (PermissionOverwriteType) Is

Is returns true if the overWrite's Type matches the provided one.

type Permissions

type Permissions uint64

Permissions flags for roles and channels permissions.

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

const (
	// CreateInstantInvite allows creation of instant invites.
	//
	// Channel types: Text, Voice, Stage
	PermissionCreateInstantInvite Permissions = 1 << 0

	// KickMembers allows kicking members.
	PermissionKickMembers Permissions = 1 << 1

	// BanMembers allows banning members.
	PermissionBanMembers Permissions = 1 << 2

	// Administrator allows all permissions and bypasses channel permission overwrites.
	PermissionAdministrator Permissions = 1 << 3

	// ManageChannels allows management and editing of channels.
	//
	// Channel types: Text, Voice, Stage
	PermissionManageChannels Permissions = 1 << 4

	// ManageGuild allows management and editing of the guild.
	PermissionManageGuild Permissions = 1 << 5

	// AddReactions allows adding new reactions to messages.
	// Does not apply to reacting with an existing reaction.
	//
	// Channel types: Text, Voice, Stage
	PermissionAddReactions Permissions = 1 << 6

	// ViewAuditLog allows viewing audit logs.
	PermissionViewAuditLog Permissions = 1 << 7

	// PrioritySpeaker allows using priority speaker in a voice channel.
	//
	// Channel types: Voice
	PermissionPrioritySpeaker Permissions = 1 << 8

	// Stream allows the user to go live.
	//
	// Channel types: Voice, Stage
	PermissionStream Permissions = 1 << 9

	// ViewChannel allows viewing a channel, reading messages, or joining voice channels.
	//
	// Channel types: Text, Voice, Stage
	PermissionViewChannel Permissions = 1 << 10

	// SendMessages allows sending messages and creating threads in forums.
	// Does not allow sending messages in threads.
	//
	// Channel types: Text, Voice, Stage
	PermissionSendMessages Permissions = 1 << 11

	// SendTTSMessages allows sending /tts messages.
	//
	// Channel types: Text, Voice, Stage
	PermissionSendTTSMessages Permissions = 1 << 12

	// ManageMessages allows deletion of other users' messages.
	//
	// Channel types: Text, Voice, Stage
	PermissionManageMessages Permissions = 1 << 13

	// EmbedLinks allows links to be auto-embedded.
	//
	// Channel types: Text, Voice, Stage
	PermissionEmbedLinks Permissions = 1 << 14

	// AttachFiles allows uploading images and files.
	//
	// Channel types: Text, Voice, Stage
	PermissionAttachFiles Permissions = 1 << 15

	// ReadMessageHistory allows reading message history.
	//
	// Channel types: Text, Voice, Stage
	PermissionReadMessageHistory Permissions = 1 << 16

	// MentionEveryone allows using @everyone and @here tags.
	//
	// Channel types: Text, Voice, Stage
	PermissionMentionEveryone Permissions = 1 << 17

	// UseExternalEmojis allows using custom emojis from other servers.
	//
	// Channel types: Text, Voice, Stage
	PermissionUseExternalEmojis Permissions = 1 << 18

	// ViewGuildInsights allows viewing guild insights.
	PermissionViewGuildInsights Permissions = 1 << 19

	// Connect allows joining a voice channel.
	//
	// Channel types: Voice, Stage
	PermissionConnect Permissions = 1 << 20

	// Speak allows speaking in a voice channel.
	//
	// Channel types: Voice
	PermissionSpeak Permissions = 1 << 21

	// MuteMembers allows muting members in a voice channel.
	//
	// Channel types: Voice, Stage
	PermissionMuteMembers Permissions = 1 << 22

	// DeafenMembers allows deafening members in a voice channel.
	//
	// Channel types: Voice
	PermissionDeafenMembers Permissions = 1 << 23

	// MoveMembers allows moving members between voice channels.
	//
	// Channel types: Voice, Stage
	PermissionMoveMembers Permissions = 1 << 24

	// UseVAD allows using voice activity detection in a voice channel.
	//
	// Channel types: Voice
	PermissionUseVAD Permissions = 1 << 25

	// ChangeNickname allows modification of own nickname.
	PermissionChangeNickname Permissions = 1 << 26

	// ManageNicknames allows modification of other users' nicknames.
	PermissionManageNicknames Permissions = 1 << 27

	// ManageRoles allows management and editing of roles.
	//
	// Channel types: Text, Voice, Stage
	PermissionManageRoles Permissions = 1 << 28

	// ManageWebhooks allows management and editing of webhooks.
	//
	// Channel types: Text, Voice, Stage
	PermissionManageWebhooks Permissions = 1 << 29

	// ManageGuildExpressions allows editing/deleting emojis, stickers, and soundboard sounds created by all users.
	PermissionManageGuildExpressions Permissions = 1 << 30

	// UseApplicationCommands allows using application (slash) commands.
	//
	// Channel types: Text, Voice, Stage
	PermissionUseApplicationCommands Permissions = 1 << 31

	// RequestToSpeak allows requesting to speak in stage channels.
	//
	// Channel types: Stage
	PermissionRequestToSpeak Permissions = 1 << 32
	// ManageEvents allows editing and deleting scheduled events created by all users.
	//
	// Channel types: Voice, Stage
	PermissionManageEvents Permissions = 1 << 33

	// ManageThreads allows deleting, archiving, and viewing all private threads.
	//
	// Channel types: Text
	PermissionManageThreads Permissions = 1 << 34

	// CreatePublicThreads allows creating public and announcement threads.
	//
	// Channel types: Text
	PermissionCreatePublicThreads Permissions = 1 << 35

	// CreatePrivateThreads allows creating private threads.
	//
	// Channel types: Text
	PermissionCreatePrivateThreads Permissions = 1 << 36

	// UseExternalStickers allows using custom stickers from other servers.
	//
	// Channel types: Text, Voice, Stage
	PermissionUseExternalStickers Permissions = 1 << 37

	// SendMessagesInThreads allows sending messages in threads.
	//
	// Channel types: Text
	PermissionSendMessagesInThreads Permissions = 1 << 38

	// UseEmbeddedActivities allows using Activities (applications with the EMBEDDED flag).
	//
	// Channel types: Text, Voice
	PermissionUseEmbeddedActivities Permissions = 1 << 39

	// ModerateMembers allows timing out users to prevent sending/reacting to messages or speaking.
	PermissionModerateMembers Permissions = 1 << 40

	// ViewCreatorMonetizationAnalytics allows viewing role subscription insights.
	PermissionViewCreatorMonetizationAnalytics Permissions = 1 << 41

	// UseSoundboard allows using soundboard in a voice channel.
	//
	// Channel types: Voice
	PermissionUseSoundboard Permissions = 1 << 42

	// CreateGuildExpressions allows creating emojis, stickers, and soundboard sounds, and editing/deleting those created by self.
	PermissionCreateGuildExpressions Permissions = 1 << 43

	// CreateEvents allows creating scheduled events, editing, and deleting those created by self.
	//
	// Channel types: Voice, Stage
	PermissionCreateEvents Permissions = 1 << 44

	// UseExternalSounds allows using custom soundboard sounds from other servers.
	//
	// Channel types: Voice
	PermissionUseExternalSounds Permissions = 1 << 45

	// SendVoiceMessages allows sending voice messages.
	//
	// Channel types: Text, Voice, Stage
	PermissionSendVoiceMessages Permissions = 1 << 46

	// SendPolls allows sending polls.
	//
	// Channel types: Text, Voice, Stage
	PermissionSendPolls Permissions = 1 << 49

	// UseExternalApps allows user-installed apps to send public responses.
	//
	// Channel types: Text, Voice, Stage
	PermissionUseExternalApps Permissions = 1 << 50
)

func (*Permissions) Add

func (p *Permissions) Add(perms ...Permissions)

Add sets all given permissions.

func (Permissions) Has

func (p Permissions) Has(perms ...Permissions) bool

Has returns true if all given permissions are set.

func (Permissions) MarshalJSON

func (p Permissions) MarshalJSON() ([]byte, error)

Method used internally by the library.

func (Permissions) Missing

func (p Permissions) Missing(perms ...Permissions) Permissions

Missing returns a Permissions bitmask containing the permissions that are present in the input perms but missing from p.

Example:

p := PermissionSendMessages
missing := p.Missing(PermissionSendMessages, PermissionManageChannels)
// missing will contain PermissionManageChannels

func (Permissions) Names

func (p Permissions) Names() []PermissionName

PermissionsToNames returns a slice of PermissionName for all permissions set in the mask.

func (*Permissions) Remove

func (p *Permissions) Remove(perms ...Permissions)

Remove clears all given permissions.

func (*Permissions) UnmarshalJSON

func (p *Permissions) UnmarshalJSON(data []byte) error

type PingInteraction

type PingInteraction struct {
	InteractionFields
}

PingInteraction represents a Discord Ping interaction.

Reference: https://discord.com/developers/docs/interactions/receiving-and-responding

type Poll

type Poll struct {
	// Question is the question of the poll. Only text is supported.
	Question PollMedia `json:"question"`

	// Answers is a list of each answer available in the poll.
	//
	// Note:
	//   - Currently, there is a maximum of 10 answers per poll.
	Answers []PollAnswer `json:"answers"`

	// Expiry is the time when the poll ends. Nullable to support potential
	// future non-expiring polls. Will be nil if the poll has no expiry, but currently all polls expire.
	// This is designed for future Discord updates to support never-expiring polls.
	//
	// Optional:
	//  - Will be nil if the poll has no expiry.
	Expiry *time.Time `json:"expiry"`

	// AllowMultiselect indicates whether a user can select multiple answers.
	AllowMultiselect bool `json:"allow_multiselect"`

	// LayoutType is an integer defining the visual layout of the poll.
	LayoutType PollLayoutType `json:"layout_type"`

	// Results contains the results of the poll, if available. Optional and nullable.
	//
	// Optional:
	//  - Will be nil if the poll has no results.
	Results *PollResults `json:"results"`
}

Poll represents a message poll sent in a channel within Discord.

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

type PollAnswer

type PollAnswer struct {
	// AnswerID is the ID of the answer, a number that labels each answer.
	// Currently, it is always set for poll answers, but future updates may allow it to be
	// unset. Will be nil if not provided.
	// As an implementation detail, it currently starts at 1 for the first answer and
	// increments sequentially. It is recommended not to depend on this sequence.
	//
	// Optional:
	//  - Will be nil if no ID is set.
	AnswerID *int `json:"answer_id,omitempty"`

	// PollMedia is the data of the answer.
	PollMedia PollMedia `json:"poll_media"`
}

PollAnswer represents an answer option in a Discord poll. It contains the answer's ID and its media content.

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

type PollAnswerCount

type PollAnswerCount struct {
	// ID is the answer_id of the poll answer, corresponding to the unique identifier of the answer option.
	ID int `json:"id"`

	// Count is the number of votes cast for this answer.
	// Note:
	//   - While a poll is in progress, this count may not be perfectly accurate due to the complexities
	//     of counting at scale. Once the poll is finalized (as indicated by PollResults.IsFinalized),
	//     the count reflects the accurate tally.
	Count int `json:"count"`

	// MeVoted indicates whether the current user has voted for this answer.
	MeVoted bool `json:"me_voted"`
}

PollAnswerCount represents the vote count and user voting status for a specific answer in a Discord poll. It is part of the Poll Results Object, which contains the number of votes for each answer.

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

type PollCreateOptions

type PollCreateOptions struct {
	// Question defines the main question of the poll.
	Question PollMedia `json:"question"`

	// Answers is the list of possible answers a user can select from.
	Answers []PollAnswer `json:"answers"`

	// Duration specifies the number of hours the poll should remain open.
	//
	// Defaults to 24 hours if omitted.
	// Constraints:
	//   - Minimum: 1 hour
	//   - Maximum: 768 hours (32 days)
	Duration int `json:"duration,omitempty"`

	// AllowMultiselect indicates whether users may select more than one answer.
	//
	// Defaults to false if omitted.
	AllowMultiselect bool `json:"allow_multiselect,omitempty"`

	// LayoutType specifies how the poll is visually arranged.
	//
	// Defaults to PollLayoutTypeDefault if omitted.
	LayoutType PollLayoutType `json:"layout_type,omitempty"`
}

PollCreateOptions represents the request payload for creating a poll in a message.

Reference:

Note:

This object is similar to the main Poll object, but differs in that it
specifies a `duration` field (how long the poll remains open), which later
becomes an `expiry` field in the resulting poll object.

type PollLayoutType

type PollLayoutType int

PollLayoutType represents the layout type of a Discord poll. It defines the visual or structural arrangement of the poll. Currently, only the default layout is supported, but additional layouts may be introduced in the future.

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

const (
	// PollLayoutTypeDefault represents the default layout type for a poll, with an ID of 1.
	// This is currently the only supported layout type.
	PollLayoutTypeDefault PollLayoutType = iota + 1
)

func (PollLayoutType) Is

func (t PollLayoutType) Is(pollLayoutType PollLayoutType) bool

Is returns true if the pool layout's type matches the provided layout type.

type PollMedia

type PollMedia struct {
	// Text is the text content of the poll question or answer.
	// Currently, it is always non-empty, with a max length of 300
	// characters for questions and 55 for answers. Future Discord
	// updates may allow empty text to indicate no text content.
	// Use an empty string ("") to represent no text.
	//
	// Optional:
	//  - Will be empty if no text is set.
	Text string `json:"text"`

	// Emoji is an optional partial emoji for the poll question or answer.
	// When creating a poll answer with an emoji, only the emoji's ID
	// (for custom emojis) or name (for default emojis) needs to be provided.
	//
	// Optional:
	//  - Will be nil if no emoji is set.
	Emoji *PartialEmoji `json:"emoji,omitempty"`
}

PollMedia represents the media content of a poll question or answer in Discord. It encapsulates the text and optional emoji associated with a poll's question or answer.

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

type PollResults

type PollResults struct {
	// IsFinalized indicates whether the votes for the poll have been precisely counted.
	// If true, the vote counts are final; if false, the counts may still be updating.
	IsFinalized bool `json:"is_finalized"`

	// AnswerCounts is a list of PollAnswerCount objects, each containing the count
	// of votes for a specific answer option in the poll.
	AnswerCounts []PollAnswerCount `json:"answer_counts"`
}

PollResults represents the results of a Discord poll, including whether the votes have been finalized and the counts for each answer option.

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

type PositionedChannel

type PositionedChannel interface {
	NamedChannel
	GetPosition() int
}

PositionedChannel represents a Discord channel that has a sorting position within its parent category.

This interface is used for guild channels that have a defined position, such as category channels, text channels, voice channels, announcement channels, stage voice channels, forum channels, and media channels. The position determines the order in which channels appear within their parent category in the Discord client. If the channel is not under a parent category, the position is relative to other top-level channels in the guild.

Use this interface when you want to handle channels generically by their position without knowing the specific concrete type in advance.

You can convert (assert) it to a specific channel type using a type assertion or a type switch, as described in the official Go documentation:

Example usage:

var ch PositionedChannel

// Using a type switch to handle specific channel types
switch c := ch.(type) {
case *TextChannel:
    fmt.Println("Text channel position:", c.GetPosition())
case *VoiceChannel:
    fmt.Println("Voice channel position:", c.GetPosition())
case *ForumChannel:
    fmt.Println("Forum channel position:", c.GetPosition())
default:
    fmt.Println("Other positioned channel type:", c.GetType())
}

// Using a type assertion to check a specific type
if textCh, ok := ch.(*TextChannel); ok {
    fmt.Println("Text channel position:", textCh.GetPosition())
}

type PremiumTier

type PremiumTier int

PremiumTier represents the boost level of a Discord guild.

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

const (
	// Guild has not unlocked any Server Boost perks.
	PremiumTierNone PremiumTier = iota
	// Guild has unlocked Server Boost level 1 perks.
	PremiumTierOne
	// Guild has unlocked Server Boost level 2 perks.
	PremiumTierTwo
	// Guild has unlocked Server Boost level 3 perks.
	PremiumTierThree
)

func (PremiumTier) Is

func (p PremiumTier) Is(premiumTier PremiumTier) bool

Is returns true if the guild's premium tier matches the provided premium tier.

type ReactionCountDetails

type ReactionCountDetails struct {
	// Burst is the count of super reactions.
	Burst int `json:"burst"`
	// Normal is the count of normal reactions.
	Normal int `json:"normal"`
}

ReactionCountDetails provides counts for normal and super reactions to a message.

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

type ReadyEvent

type ReadyEvent struct {
	ShardsID int // shard that dispatched this event
	Guilds   []Guild
}

ReadyCreateEvent Shard is ready

type RequiredBase

type RequiredBase struct {
	// Required indicates whether the parameter is required or optional.
	//
	// Info:
	//  - Defaults to false.
	//  - Required options must be listed before optional options in an array of options.
	Required bool `json:"required,omitempty"`
}

RequiredBase contains the required field for value-based options.

type ResolvedChannel

type ResolvedChannel struct {
	Channel
	Permissions Permissions `json:"permissions"`
}

func (*ResolvedChannel) UnmarshalJSON

func (c *ResolvedChannel) UnmarshalJSON(buf []byte) error

UnmarshalJSON implements json.Unmarshaler for ResolvedChannel.

type ResolvedMember

type ResolvedMember struct {
	Member
	// Permissions is the total permissions of the member in the channel, including overwrites.
	Permissions Permissions `json:"permissions,omitempty"`
}

ResolvedMember represents a member with additional permissions field, typically included in an interaction object.

Info:

  • It embeds the Member struct and adds a Permissions field to describe the member's permissions in the context of the interaction.

type ResolvedMessageChannel

type ResolvedMessageChannel struct {
	MessageChannel
	Permissions Permissions `json:"permissions"`
}

func (*ResolvedMessageChannel) UnmarshalJSON

func (c *ResolvedMessageChannel) UnmarshalJSON(buf []byte) error

UnmarshalJSON implements json.Unmarshaler for ResolvedMessageChannel.

type ResolvedThread

type ResolvedThread struct {
	ThreadChannel
	Permissions Permissions `json:"permissions"`
}

type RestGuild

type RestGuild struct {
	Guild

	// Stickers contains the custom stickers available in the guild.
	Stickers []Sticker `json:"stickers"`

	// Roles contains all roles defined in the guild.
	Roles []Role `json:"roles"`

	// Emojis contains the custom emojis available in the guild.
	Emojis []Emoji `json:"emojis"`
}

RestGuild represents a guild object returned by the Discord API. It embeds Guild and adds additional fields provided by the REST endpoint.

Reference: https://discord.com/developers/docs/resources/guild

type Role

type Role struct {
	EntityBase // Embedded client reference for action methods

	// ID is the role ID.
	ID Snowflake `json:"id"`

	// GuildID is the id of the guild this role is in.
	GuildID Snowflake `json:"guild_id"`

	// Name is the role name.
	Name string `json:"name"`

	// Colors contains the role's color definitions.
	Colors RoleColors `json:"colors"`

	// Hoist indicates if this role is pinned in the user listing.
	Hoist bool `json:"hoist"`

	// Icon is the role's icon hash.
	//
	// Optional:
	//   - Will be empty string if no icon.
	Icon string `json:"icon"`

	// UnicodeEmoji is the role's unicode emoji.
	//
	// Optional:
	//   - Will be empty string if not set.
	UnicodeEmoji string `json:"unicode_emoji"`

	// Position is the position of this role (roles with same position are sorted by ID).
	//
	// Note:
	//   - Roles with same position are sorted by ID.
	Position int `json:"position"`

	// Permissions is the permission bit set for this role.
	Permissions Permissions `json:"permissions"`

	// Managed indicates whether this role is managed by an integration.
	Managed bool `json:"managed"`

	// Mentionable indicates whether this role is mentionable.
	Mentionable bool `json:"mentionable"`

	// Tags contains the tags this role has.
	//
	// Optional:
	//   - Will be nil if no tags.
	Tags *RoleTags `json:"tags,omitempty"`

	// Flags are role flags combined as a bitfield.
	Flags RoleFlags `json:"flags"`
}

Role represents a Discord role.

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

func (*Role) Delete

func (r *Role) Delete(reason string) error

Delete deletes this role from the guild. Requires MANAGE_ROLES permission.

Usage example:

err := role.Delete("Role no longer needed")

func (*Role) Edit

func (r *Role) Edit(opts RoleEditOptions, reason string) (*Role, error)

Edit modifies this role's attributes. Returns the updated role. Requires MANAGE_ROLES permission.

Usage example:

updated, err := role.Edit(RoleEditOptions{Name: "New Name"}, "Renaming role")

func (*Role) Guild

func (r *Role) Guild() (Guild, bool)

Guild returns the cached guild this role belongs to.

Usage example:

if g, ok := role.Guild(); ok {
    fmt.Println("Guild:", g.Name)
}

func (*Role) IconURL

func (u *Role) IconURL() string

IconURL returns the URL to the role's icon image in PNG format.

If the role has a custom icon set, it returns the URL to that icon, Otherwise it returns an empty string.

Example usage:

url := role.IconURL()

func (*Role) IconURLWith

func (u *Role) IconURLWith(format ImageFormat, size ImageSize) string

IconURLWith returns the URL to the role's icon image, allowing explicit specification of image format and size.

If the role has a custom icon set, it returns the URL to that icon using the provided format and size, Otherwise it returns an empty string.

Example usage:

url := role.IconURLWith(ImageFormatWebP, ImageSize512)

func (*Role) IsEveryone

func (r *Role) IsEveryone() bool

IsEveryone returns true if this is the @everyone role. The @everyone role ID is the same as the guild ID.

Usage example:

if role.IsEveryone() {
    // This is the @everyone role
}

func (*Role) IsManaged

func (r *Role) IsManaged() bool

IsManaged returns true if this role is managed by an integration (bot, boosts, etc). Managed roles cannot be manually assigned or modified.

Usage example:

if role.IsManaged() {
    // Cannot manually assign this role
}

func (*Role) Mention

func (r *Role) Mention() string

Mention returns a Discord mention string for the role.

Example output: "<@&123456789012345678>"

func (*Role) SetColor

func (r *Role) SetColor(color Color, reason string) error

SetColor changes this role's color. Requires MANAGE_ROLES permission.

Usage example:

err := role.SetColor(0x3498db, "New color")

func (*Role) SetHoist

func (r *Role) SetHoist(hoist bool, reason string) error

SetHoist sets whether this role is displayed separately in the member list. Requires MANAGE_ROLES permission.

Usage example:

err := role.SetHoist(true, "Display role separately")

func (*Role) SetMentionable

func (r *Role) SetMentionable(mentionable bool, reason string) error

SetMentionable sets whether this role can be mentioned. Requires MANAGE_ROLES permission.

Usage example:

err := role.SetMentionable(true, "Allow mentions")

func (*Role) SetName

func (r *Role) SetName(name string, reason string) error

SetName changes this role's name. Requires MANAGE_ROLES permission.

Usage example:

err := role.SetName("Moderator", "Renaming role")

type RoleColors

type RoleColors struct {
	// PrimaryColor is the primary color for the role.
	PrimaryColor Color `json:"primary_color"`

	// SecondaryColor is the secondary color for the role.
	//
	// Optional:
	//   - Will be nil if not set.
	SecondaryColor *Color `json:"secondary_color"`

	// TertiaryColor is the tertiary color for the role.
	//
	// Optional:
	//   - Will be nil if not set.
	TertiaryColor *Color `json:"tertiary_color"`
}

RoleColors represents a role's color definitions.

Reference: https://discord.com/developers/docs/resources/guild#role-object-role-colors-object

type RoleCreateOptions

type RoleCreateOptions struct {
	// Name is the name of the role (max 100 characters). Default is "new role".
	Name string `json:"name,omitempty"`
	// Permissions is the bitwise value of the enabled/disabled permissions.
	Permissions *Permissions `json:"permissions,omitempty,string"`
	// Color is the RGB color value. Default is 0 (no color).
	Color Color `json:"color,omitempty"`
	// Hoist indicates whether the role should be displayed separately in the sidebar.
	Hoist bool `json:"hoist,omitempty"`
	// Icon is the role's icon image (if the guild has the feature).
	Icon *ImageFile `json:"icon,omitempty"`
	// UnicodeEmoji is the role's unicode emoji as a standard emoji.
	UnicodeEmoji string `json:"unicode_emoji,omitempty"`
	// Mentionable indicates whether the role should be mentionable.
	Mentionable bool `json:"mentionable,omitempty"`
}

RoleCreateOptions are options for creating a role.

type RoleEditOptions

type RoleEditOptions struct {
	// Name is the name of the role (max 100 characters).
	Name string `json:"name,omitempty"`
	// Permissions is the bitwise value of the enabled/disabled permissions.
	Permissions *Permissions `json:"permissions,omitempty,string"`
	// Color is the RGB color value.
	Color *Color `json:"color,omitempty"`
	// Hoist indicates whether the role should be displayed separately in the sidebar.
	Hoist *bool `json:"hoist,omitempty"`
	// Icon is the role's icon image (if the guild has the feature).
	Icon *ImageFile `json:"icon,omitempty"`
	// UnicodeEmoji is the role's unicode emoji as a standard emoji.
	UnicodeEmoji *string `json:"unicode_emoji,omitempty"`
	// Mentionable indicates whether the role should be mentionable.
	Mentionable *bool `json:"mentionable,omitempty"`
}

RoleEditOptions are options for editing a role.

type RoleFlags

type RoleFlags int

RoleFlags represents flags on a Discord guild role.

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

const (
	// Role can be selected by members in an onboarding prompt.
	RoleFlagInPrompt RoleFlags = 1 << 0
)

func (RoleFlags) Has

func (f RoleFlags) Has(flag RoleFlags) bool

Has returns true if all provided flags are set.

type RoleSelectMenuComponent

type RoleSelectMenuComponent struct {
	InteractiveComponentFields

	// Placeholder is the custom placeholder text displayed when no role is selected.
	//
	// Note:
	//   - Maximum of 150 characters.
	Placeholder string `json:"placeholder,omitempty"`

	// DefaultValues is an array of default roles for the select menu.
	//
	// Note:
	//   - Number of default values must be within the range defined by MinValues and MaxValues.
	DefaultValues []SelectDefaultValue `json:"default_values,omitempty"`

	// MinValues is the minimum number of roles that must be selected.
	//
	// Note:
	//   - Defaults to 1.
	//   - Minimum 0, maximum 25.
	MinValues *int `json:"min_values,omitempty"`

	// MaxValues is the maximum number of roles that can be selected.
	//
	// Note:
	//   - Defaults to 1.
	//   - Maximum 25.
	MaxValues int `json:"max_values,omitempty"`

	// Disabled specifies whether the select menu is disabled in a message.
	//
	// Note:
	//   - Defaults to false.
	Disabled bool `json:"disabled,omitempty"`
}

RoleSelectMenuComponent represents a role select menu, an interactive component allowing users to select one or more roles in a message. Options are automatically populated based on the server's available roles.

It supports both single-select and multi-select behavior, sending an interaction to the application when a user makes their selection(s). RoleSelectMenuComponent must be placed inside an ActionRowComponent and is only available in messages. An ActionRowComponent containing a RoleSelectMenuComponent cannot include buttons.

Note:

  • Maximum of 25 selections can be allowed (via MaxValues).
  • Options are auto-populated by Discord based on server roles.

Reference: https://discord.com/developers/docs/interactions/message-components#select-menu-object-select-menu-structure

func (*RoleSelectMenuComponent) MarshalJSON

func (c *RoleSelectMenuComponent) MarshalJSON() ([]byte, error)

type RoleSubscriptionData

type RoleSubscriptionData struct {
	// RoleSubscriptionListingID is the ID of the role subscription listing.
	RoleSubscriptionListingID Snowflake `json:"role_subscription_listing_id"`

	// TierName is the name of the subscription tier.
	TierName string `json:"tier_name"`

	// TotalMonthsSubscribed is the total number of months subscribed.
	TotalMonthsSubscribed int `json:"total_months_subscribed"`

	// IsRenewal indicates whether the subscription is a renewal.
	IsRenewal bool `json:"is_renewal"`
}

RoleSubscriptionData represents data for a role subscription purchase.

type RoleTags

type RoleTags struct {
	// BotID is the ID of the bot that this role belongs to.
	// It is set for roles automatically created when adding a bot
	// to a guild with specific permissions.
	//
	// Optional:
	//   - Will be 0 if the role is not associated with a bot.
	BotID Snowflake `json:"bot_id"`

	// IntegrationID is the ID of the integration that this role belongs to.
	//
	// Optional:
	//   - Will be 0 if the role is not associated with an integration.
	IntegrationID Snowflake `json:"integration_id"`

	// PremiumSubscriber indicates whether this is the guild's Booster role.
	//
	// True if present (not nil), false otherwise (nil).
	PremiumSubscriber *struct{} `json:"premium_subscriber,omitempty"`

	// SubscriptionListingID is the ID of this role's subscription SKU and listing.
	//
	// Optional:
	//   - Will be 0 if the role is not linked to a subscription.
	SubscriptionListingID Snowflake `json:"subscription_listing_id"`

	// AvailableForPurchase indicates whether this role is available for purchase.
	//
	// True if present (not nil), false otherwise (nil).
	AvailableForPurchase *struct{} `json:"available_for_purchase,omitempty"`

	// GuildConnections indicates whether this role is a guild's linked role.
	//
	// True if present (not nil), false otherwise (nil).
	GuildConnections *struct{} `json:"guild_connections,omitempty"`
}

RoleTags represents the tags object attached to a role.

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

type SectionAccessoryComponent

type SectionAccessoryComponent interface {
	Component
}

SectionAccessoryComponent is an interface for all components that can be present in a SectionComponent.

ButtonComponent, ThumbnailComponent

type SectionComponent

type SectionComponent struct {
	ComponentFields

	// Components is an array of one to three child components representing the content of the section.
	//
	// Valid components:
	//   - TextDisplayComponent
	Components []SectionSubComponent `json:"components"`

	// Accessory is a component contextually associated with the content of the section.
	//
	// Valid components:
	//   - ButtonComponent
	//   - ThumbnailComponent
	Accessory SectionAccessoryComponent `json:"accessory,omitempty"`
}

SectionComponent is a top-level layout component that contextually associates content with an accessory component.

It is typically used to associate text content with an accessory, such as a button or thumbnail. Sections require the IS_COMPONENTS_V2 message flag (1 << 15) to be set when sending the message. Additional component types for content and accessories may be supported in the future.

Note:

  • Only available in messages.
  • Requires the IS_COMPONENTS_V2 message flag (1 << 15).
  • Contains one to three child components for content.

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

func (*SectionComponent) MarshalJSON

func (c *SectionComponent) MarshalJSON() ([]byte, error)

func (*SectionComponent) UnmarshalJSON

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

type SectionSubComponent

type SectionSubComponent interface {
	Component
}

SectionSubComponent is an interface for all components that can be present in a SectionComponent.

TextDisplayComponent

type SelectDefaultValue

type SelectDefaultValue struct {
	// ID is the identifier of the default value (e.g., user ID, role ID, or channel ID).
	ID Snowflake `json:"id"`

	// Type is the type of the default value (user, role, or channel).
	Type SelectDefaultValueType `json:"type"`
}

SelectDefaultValue represents a default value in a select menu component (e.g., UserSelectMenuComponent, RoleSelectMenuComponent, ChannelSelectMenuComponent, MentionableSelectMenuComponent).

It specifies the ID and type of the default selected entity (user, role, or channel).

Reference: https://discord.com/developers/docs/interactions/message-components#select-menu-object-select-default-value-structure

type SelectDefaultValueType

type SelectDefaultValueType string

SelectDefaultValueType represents the type of a default value in a select menu component.

Reference: https://discord.com/developers/docs/interactions/message-components#select-menu-object-select-default-value-structure

const (
	// SelectDefaultValueTypeUser indicates the default value is a user ID.
	SelectDefaultValueTypeUser SelectDefaultValueType = "user"

	// SelectDefaultValueTypeRole indicates the default value is a role ID.
	SelectDefaultValueTypeRole SelectDefaultValueType = "role"

	// SelectDefaultValueTypeChannel indicates the default value is a channel ID.
	SelectDefaultValueTypeChannel SelectDefaultValueType = "channel"
)

func (SelectDefaultValueType) Is

Is returns true if the value Type matches the provided one.

type SelectOptionStructure

type SelectOptionStructure struct {
	// Label is the user-facing name of the option.
	//
	// Note:
	//   - Maximum of 100 characters.
	Label string `json:"label"`

	// Value is the developer-defined value of the option.
	//
	// Note:
	//   - Maximum of 100 characters.
	Value string `json:"value"`

	// Description is an additional description of the option.
	//
	// Note:
	//   - Maximum of 100 characters.
	Description string `json:"description,omitempty"`

	// Emoji is the emoji displayed alongside the option.
	Emoji *PartialEmoji `json:"emoji,omitempty"`

	// Default specifies whether this option is selected by default.
	Default bool `json:"default,omitempty"`
}

SelectOptionStructure represents an option in a StringSelectMenuComponent.

It defines the user-facing label, developer-defined value, and optional description and emoji for a selectable option.

Reference: https://discord.com/developers/docs/interactions/message-components#select-menu-object-select-option-structure

type SeparatorComponent

type SeparatorComponent struct {
	ComponentFields

	// Divider indicates whether a visual divider line should be displayed.
	//
	// Note:
	//   - Defaults to true.
	Divider bool `json:"divider,omitempty"`

	// Spacing determines the size of the vertical padding.
	//
	// Note:
	//   - 1 for small padding, 2 for large padding.
	//   - Defaults to 1.
	Spacing SeperatorComponentSpacing `json:"spacing,omitempty"`
}

SeparatorComponent is a top-level layout component that adds vertical padding and an optional visual divider between other components.

It is used to create spacing or visual separation in messages. Separators require the IS_COMPONENTS_V2 message flag (1 << 15) to be set when sending the message.

Note:

  • Only available in messages.
  • Requires the IS_COMPONENTS_V2 message flag (1 << 15).
  • The divider field defaults to true, indicating whether a visual divider is displayed.
  • The spacing field defaults to 1 (small padding), with 2 indicating large padding.

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

func (*SeparatorComponent) MarshalJSON

func (c *SeparatorComponent) MarshalJSON() ([]byte, error)

type SeperatorComponentSpacing

type SeperatorComponentSpacing int
const (
	SeperatorComponentSpacingSmall SeperatorComponentSpacing = 1 + iota
	SeperatorComponentSpacingLarge
)

type Shard

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

Shard manages a single WebSocket connection to Discord Gateway, including session state, event handling, heartbeats, and reconnects.

func (*Shard) Latency

func (s *Shard) Latency() int64

Latency returns the current heartbeat latency in milliseconds

func (*Shard) Shutdown

func (s *Shard) Shutdown() error

Shutdown cleanly closes the shard's websocket connection.

Call this when you want to stop the shard gracefully.

type ShardMap

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

ShardMap is a concurrent map implementation using 256-way sharding. It reduces lock contention by distributing entries across multiple shards, each with its own RWMutex. This is particularly effective for high-throughput scenarios like Discord bots with 10,000+ guilds.

Performance: ~99.6% reduction in lock contention vs single mutex.

func NewShardMap

func NewShardMap[K comparable, V any](hasher func(K) uint8) *ShardMap[K, V]

NewShardMap creates a new ShardMap with the given hash function. The hash function should distribute keys evenly across 0-255.

func NewSnowflakePairShardMap

func NewSnowflakePairShardMap[V any]() *ShardMap[SnowflakePairKey, V]

NewSnowflakePairShardMap creates a ShardMap for SnowflakePairKey keys. Uses XOR of both snowflake low bits for distribution.

func NewSnowflakeShardMap

func NewSnowflakeShardMap[V any]() *ShardMap[Snowflake, V]

NewSnowflakeShardMap creates a ShardMap optimized for Snowflake keys. Uses the low 8 bits of the snowflake for sharding, which provides excellent distribution since Discord snowflakes are sequential with embedded sequence numbers.

func (*ShardMap[K, V]) Clear

func (m *ShardMap[K, V]) Clear()

Clear removes all entries from the map.

func (*ShardMap[K, V]) Delete

func (m *ShardMap[K, V]) Delete(key K) bool

Delete removes a value from the map. Returns true if the key existed, false otherwise.

func (*ShardMap[K, V]) Get

func (m *ShardMap[K, V]) Get(key K) (V, bool)

Get retrieves a value from the map. Returns the value and true if found, zero value and false otherwise.

func (*ShardMap[K, V]) GetOrSet

func (m *ShardMap[K, V]) GetOrSet(key K, value V) (V, bool)

GetOrSet retrieves a value or sets it if not present. Returns the existing value and true, or the new value and false.

func (*ShardMap[K, V]) Has

func (m *ShardMap[K, V]) Has(key K) bool

Has checks if a key exists in the map.

func (*ShardMap[K, V]) Keys

func (m *ShardMap[K, V]) Keys() []K

Keys returns all keys in the map. Note: This is a snapshot and may be stale immediately after return.

func (*ShardMap[K, V]) Len

func (m *ShardMap[K, V]) Len() int

Len returns the total number of entries across all shards. Note: This acquires read locks on all shards sequentially, so the result may be slightly stale in concurrent scenarios.

func (*ShardMap[K, V]) Range

func (m *ShardMap[K, V]) Range(fn func(K, V) bool)

Range calls the given function for each key-value pair in the map. If the function returns false, iteration stops. The function is called with the shard lock held, so it should be fast. Do not call ShardMap methods from within the function to avoid deadlock.

func (*ShardMap[K, V]) Set

func (m *ShardMap[K, V]) Set(key K, value V)

Set stores a value in the map.

func (*ShardMap[K, V]) Update

func (m *ShardMap[K, V]) Update(key K, fn func(V, bool) V) V

Update atomically updates a value using the provided function. The function receives the current value (or zero value if not present) and a boolean indicating if the key existed. Returns the new value.

func (*ShardMap[K, V]) Values

func (m *ShardMap[K, V]) Values() []V

Values returns all values in the map. Note: This is a snapshot and may be stale immediately after return.

type ShardsIdentifyRateLimiter

type ShardsIdentifyRateLimiter interface {
	// Wait blocks until the shard is allowed to send an Identify payload.
	Wait()
}

ShardsIdentifyRateLimiter defines the interface for a rate limiter that controls the frequency of Identify payloads sent per shard.

Implementations block the caller in Wait() until an Identify token is available.

type Snowflake

type Snowflake uint64

Snowflake is a Discord unique identifier.

func MustParseSnowflake

func MustParseSnowflake(id string) Snowflake

MustParseSnowflake parses a string into a Snowflake, panicking on error. Use this for hardcoded snowflake values or testing.

func ParseSnowflake

func ParseSnowflake(id string) (Snowflake, error)

ParseSnowflake parses a string into a Snowflake. This is the safe version with full error checking.

func ParseSnowflakeUnsafe

func ParseSnowflakeUnsafe(id string) Snowflake

ParseSnowflakeUnsafe parses a string into a Snowflake using branchless parsing. This function assumes the input is a valid decimal string from Discord's API. Invalid input produces undefined results but will not panic.

Performance: ~3-5ns compared to ~30-50ns for ParseSnowflake. Use this for trusted input from Discord API responses.

func (Snowflake) MarshalJSON

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

func (Snowflake) ProcessID

func (s Snowflake) ProcessID() uint64

ProcessID extracts the internal Discord process ID from the snowflake.

func (Snowflake) Sequence

func (s Snowflake) Sequence() uint64

Sequence extracts the sequence number (increment part) of the snowflake.

func (Snowflake) String

func (s Snowflake) String() string

String returns the Snowflake as string.

func (Snowflake) Timestamp

func (s Snowflake) Timestamp() time.Time

Timestamp returns the creation time of the snowflake as time.Time.

func (Snowflake) UnSet

func (s Snowflake) UnSet() bool

UnSet returns true if the Snowflake is zero (unset).

func (*Snowflake) UnmarshalJSON

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

func (Snowflake) WorkerID

func (s Snowflake) WorkerID() uint64

WorkerID extracts the internal Discord worker ID from the snowflake.

type SnowflakePairKey

type SnowflakePairKey struct {
	A Snowflake
	B Snowflake
}

type SoundBoardSound

type SoundBoardSound struct {
	// SoundID is the sound's unique Discord snowflake ID.
	SoundID Snowflake `json:"id"`

	// Name is the sound's name.
	Name string `json:"name"`

	// Volumek is the volume of this sound, from 0 to 1.
	Volume float64 `json:"volume"`

	// EmojiID is the id of this sound's custom emoji
	//
	// Optional:
	//   - Will be 0 if the emoji is Unicode (standard emoji).
	EmojiID Snowflake `json:"emoji_id"`

	// EmojiName is the name of this sound's standard emoji.
	//
	// Optional:
	//   - Will be empty string if the emoji is custom (not standard emoji).
	EmojiName string `json:"emoji_name"`

	// Available is whether this sound can be used, may be false due to loss of Server Boosts.
	Available bool `json:"available"`

	// GuildID is the ID of the guild this sound belongs to.
	//
	// Optional:
	//   - Will be absent if the sound is global (not guild-specific).
	GuildID Snowflake `json:"guild_id"`

	// User is the user who created this sound.
	//
	// Optional:
	//   - Will be absent if the sound is global (not guild-specific).
	User *User `json:"user"`
}

func (*SoundBoardSound) Save

func (s *SoundBoardSound) Save(fileName, dir string) (string, error)

Save downloads the soundboard's sound from its URL and saves it to disk.

If fileName is not provided (empty string), it saves the file in the given directory using Attachment.Filename

Info:

  • The extension is replaced based on the Content-Type of the file.

Example:

err := sound.Save("mysound", "./downloads")
if err != nil {
    // handle error
}

Returns:

  • string: full path to the downloaded file.
  • error: non-nil if any operation fails.

func (*SoundBoardSound) URL

func (s *SoundBoardSound) URL() string

type StageInstance

type StageInstance struct {
	// ID is the stageInstance's unique Discord snowflake ID.
	ID Snowflake `json:"id"`

	// GuildID is the guild id of the associated Stage channel
	GuildID Snowflake `json:"guild_id"`

	// ChannelID is the id of the associated Stage channel
	ChannelID Snowflake `json:"channel_id"`

	// Topic is the topic of the Stage instance (1-120 characters)
	Topic string `json:"topic"`

	// PrivacyLevel is the privacy level of the Stage instance
	PrivacyLevel StagePrivacyLevel `json:"privacy_level"`

	// DiscoverableDisabled is whether or not Stage Discovery is disabled (deprecated)
	DiscoverableDisabled bool `json:"discoverable_disabled"`
}

StageInstance represent a Discord stage instance.

Reference: https://discord.com/developers/docs/resources/stage-instance#stage-instance-object

func (*StageInstance) CreatedAt

func (s *StageInstance) CreatedAt() time.Time

CreatedAt returns the time when this stage instance is created.

type StagePrivacyLevel

type StagePrivacyLevel int

StagePrivacyLevel represents the privacy level of a Discord stage instance.

Reference: https://discord.com/developers/docs/resources/stage-instance#stage-instance-object-privacy-level

const (
	// The Stage instance is visible publicly. (deprecated)
	StagePrivacyLevelPublic StagePrivacyLevel = iota + 1

	// The Stage instance is visible to only guild members.
	StagePrivacyLevelGuildOnly
)

type StageVoiceChannel

type StageVoiceChannel struct {
	EntityBase // Embedded client reference for action methods
	GuildChannelFields
	CategorizedChannelFields
	GuildMessageChannelFields
	NsfwChannelFields
	AudioChannelFields
	TopicChannelFields
}

StageVoiceChannel represents a stage voice channel.

func (*StageVoiceChannel) Delete

func (c *StageVoiceChannel) Delete(reason string) error

Delete deletes this stage voice channel.

func (*StageVoiceChannel) Edit

Edit modifies this stage voice channel's settings.

func (*StageVoiceChannel) FetchMessage

func (c *StageVoiceChannel) FetchMessage(messageID Snowflake) (*Message, error)

FetchMessage retrieves a single message from this stage voice channel.

func (*StageVoiceChannel) FetchMessages

func (c *StageVoiceChannel) FetchMessages(opts FetchMessagesOptions) ([]*Message, error)

FetchMessages retrieves messages from this stage voice channel.

func (*StageVoiceChannel) Guild

func (c *StageVoiceChannel) Guild() (Guild, bool)

Guild returns the cached guild this stage voice channel belongs to.

func (*StageVoiceChannel) MarshalJSON

func (c *StageVoiceChannel) MarshalJSON() ([]byte, error)

func (*StageVoiceChannel) Send

func (c *StageVoiceChannel) Send(content string) (*Message, error)

Send sends a message to this stage voice channel.

func (*StageVoiceChannel) SendEmbed

func (c *StageVoiceChannel) SendEmbed(embed Embed) (*Message, error)

SendEmbed sends an embed message to this stage voice channel.

func (*StageVoiceChannel) SendWith

func (c *StageVoiceChannel) SendWith(opts MessageCreateOptions) (*Message, error)

SendWith sends a message with full options to this stage voice channel.

type Sticker

type Sticker struct {
	// Unique ID of the sticker.
	ID Snowflake `json:"id"`

	// ID of the pack for standard stickers.
	PackID Snowflake `json:"pack_id,omitempty"`

	// Name of the sticker.
	Name string `json:"name"`

	// Description of the sticker (optional).
	Description string `json:"description,omitempty"`

	// Autocomplete/suggestion tags (max 200 characters).
	Tags string `json:"tags"`

	// Type of the sticker (standard or guild).
	Type StickerType `json:"type"`

	// Format type of the sticker.
	FormatType StickerFormatType `json:"format_type"`

	// Whether the guild sticker is available for use.
	Available *bool `json:"available,omitempty"`

	// ID of the guild that owns this sticker.
	GuildID Snowflake `json:"guild_id,omitempty"`

	// The user that uploaded the guild sticker.
	User *User `json:"user,omitempty"`

	// Sort order of the standard sticker in its pack.
	SortValue *int `json:"sort_value,omitempty"`
}

Sticker represents a sticker that can be sent in messages.

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

func (*Sticker) CreatedAt

func (s *Sticker) CreatedAt() time.Time

CreatedAt returns the time when this sticker was created.

func (*Sticker) URL

func (s *Sticker) URL() string

URL returns the URL to the sticker's image.

func (*Sticker) URLWith

func (s *Sticker) URLWith(format ImageFormat) string

URLWith returns the URL to the sticker's image with custom format.

type StickerFormatType

type StickerFormatType int

StickerFormatType defines the format of a sticker's image.

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

const (
	// StickerFormatTypePNG represents a PNG format sticker.
	StickerFormatTypePNG StickerFormatType = iota + 1

	// StickerFormatTypeAPNG represents an APNG format sticker.
	StickerFormatTypeAPNG

	// StickerFormatTypeLottie represents a Lottie format sticker.
	StickerFormatTypeLottie

	// StickerFormatTypeGIF represents a GIF format sticker.
	StickerFormatTypeGIF
)

type StickerItem

type StickerItem struct {
	// ID is the unique Discord snowflake ID of the sticker.
	ID Snowflake `json:"id"`
	// Name is the name of the sticker.
	Name string `json:"name"`
	// FormatType is the format type of the sticker (e.g., PNG, APNG, Lottie).
	FormatType StickerFormatType `json:"format_type"`
}

StickerItem represents a sticker included in a message.

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

type StickerPack

type StickerPack struct {
	// Unique ID of the sticker pack.
	ID Snowflake `json:"id"`

	// Array of stickers in the pack.
	Stickers []Sticker `json:"stickers"`

	// Name of the sticker pack.
	Name string `json:"name"`

	// SKU ID of the pack.
	SkuID Snowflake `json:"sku_id"`

	// ID of a sticker shown as icon.
	CoverStickerID Snowflake `json:"cover_sticker_id,omitempty"`

	// Description of the sticker pack.
	Description string `json:"description"`

	// Banner image ID.
	BannerAssetID Snowflake `json:"banner_asset_id,omitempty"`
}

StickerPack represents a pack of standard stickers.

Reference: https://discord.com/developers/docs/resources/sticker#sticker-pack-object

func (*StickerPack) BannerURL

func (p *StickerPack) BannerURL() string

BannerURL returns the banner URL in PNG format, or empty string if none.

func (*StickerPack) BannerURLWith

func (p *StickerPack) BannerURLWith(format ImageFormat, size ImageSize) string

BannerURLWith returns the banner URL with a custom format and size.

type StickerType

type StickerType int

StickerType defines whether the sticker is a standard or guild sticker.

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

const (
	// StickerTypeStandard represents an official sticker in a pack.
	StickerTypeStandard StickerType = iota + 1

	// StickerTypeGuild represents a sticker uploaded to a guild.
	StickerTypeGuild
)

type StringConstraints

type StringConstraints struct {
	// MinLength is the minimum allowed length for the string.
	//
	// Info:
	//  - Minimum of 0, maximum of 6000.
	//
	// Optional:
	//  - May be nil if no minimum length is specified.
	MinLength *int `json:"min_length,omitempty"`

	// MaxLength is the maximum allowed length for the string.
	//
	// Info:
	//  - Minimum of 1, maximum of 6000.
	//
	// Optional:
	//  - May be nil if no maximum length is specified.
	MaxLength *int `json:"max_length,omitempty"`
}

StringConstraints contains constraints for string options.

type StringMap

type StringMap map[string]string

StringMap is a map of locale codes to strings for localizations.

type StringSelectMenuComponent

type StringSelectMenuComponent struct {
	InteractiveComponentFields

	// Options is an array of choices available in the select menu.
	//
	// Note:
	//   - Maximum of 25 options.
	Options []SelectOptionStructure `json:"options,omitempty"`

	// Placeholder is the custom placeholder text displayed when no option is selected.
	//
	// Note:
	//   - Maximum of 150 characters.
	Placeholder string `json:"placeholder,omitempty"`

	// MinValues is the minimum number of options that must be selected.
	//
	// Note:
	//   - Defaults to 1.
	//   - Minimum 0, maximum 25.
	MinValues *int `json:"min_values,omitempty"`

	// MaxValues is the maximum number of options that can be selected.
	//
	// Note:
	//   - Defaults to 1.
	//   - Maximum 25.
	MaxValues int `json:"max_values,omitempty"`

	// Required specifies whether the select menu must be filled in a modal.
	//
	// Note:
	//   - Defaults to true.
	//   - Only applicable in modals; ignored in messages.
	Required bool `json:"required,omitempty"`

	// Disabled specifies whether the select menu is disabled in a message.
	//
	// Note:
	//   - Defaults to false.
	//   - Causes an error if set to true in modals.
	Disabled bool `json:"disabled,omitempty"`
}

StringSelectMenuComponent represents a string select menu, an interactive component allowing users to select one or more predefined text options.

It supports both single-select and multi-select behavior, sending an interaction to the application when a user makes their selection(s). StringSelectMenuComponent must be placed inside an ActionRowComponent for messages or a LabelComponent for modals.

Note:

  • Maximum of 25 options can be provided.
  • In messages, it must be the only component in an ActionRowComponent (cannot coexist with buttons).
  • In modals, the `Disabled` field will cause an error if set to true, as modals do not support disabled components.

Reference: https://discord.com/developers/docs/interactions/message-components#select-menu-object-select-menu-structure

func (*StringSelectMenuComponent) MarshalJSON

func (c *StringSelectMenuComponent) MarshalJSON() ([]byte, error)

type SystemChannelFlags

type SystemChannelFlags int

SystemChannelFlags contains the settings for the Guild(s) system channel

Reference: https://discord.com/developers/docs/resources/guild#guild-object-system-channel-flags

const (
	// Suppress member join notifications.
	SystemChannelFlagSuppressJoinNotifications SystemChannelFlags = 1 << iota
	// Suppress server boost notifications.
	SystemChannelFlagSuppressPremiumSubscriptions
	// Suppress server setup tips.
	SystemChannelFlagSuppressGuildReminderNotifications
	// Hide member join sticker reply buttons.
	SystemChannelFlagSuppressJoinNotificationReplies
	// Suppress role subscription purchase and renewal notifications.
	SystemChannelFlagSuppressRoleSubscriptionPurchaseNotifications
	// Hide role subscription sticker reply buttons
	SystemChannelFlagSuppressRoleSubscriptionPurchaseNotificationReplies
)

func (SystemChannelFlags) Has

func (f SystemChannelFlags) Has(flags ...SystemChannelFlags) bool

Has returns true if all provided flags are set.

type Team

type Team struct {
	// ID is the team's unique Discord snowflake ID.
	ID Snowflake `json:"id"`

	// Icon is the team's icon hash.
	//
	// Optional:
	//  - May be empty string if no icon.
	Icon string `json:"icon"`

	// Members are the members of the team.
	Members []TeamMember `json:"members"`

	// Name is the name of the team.
	Name string `json:"name"`

	// OwnerID is the user ID of the current team owner.
	OwnerID Snowflake `json:"owner_user_id"`
}

Team represent a Discord team object.

Reference: https://discord.com/developers/docs/topics/teams#data-models-team-object

func (*Team) CreatedAt

func (t *Team) CreatedAt() time.Time

CreatedAt returns the time when this team is created.

func (*Team) IconURL

func (t *Team) IconURL() string

IconURL returns the URL to the team's icon image.

If the team has a custom icon set, it returns the URL to that icon, otherwise empty string. By default, it uses PNG format.

Example usage:

url := team.IconURL()

func (*Team) IconURLWith

func (t *Team) IconURLWith(format ImageFormat, size ImageSize) string

IconURLWith returns the URL to the team's icon image, allowing explicit specification of image format and size.

If the team has a custom icon set, it returns the URL to that icon (otherwise empty string) using the provided format and size.

Example usage:

url := team.IconURLWith(ImageFormatWebP, ImageSize512)

type TeamMember

type TeamMember struct {
	// MembershipState is the user's membership state on the team.
	MembershipState MembershipState `json:"membership_state"`

	// TeamID is the team member's unique Discord snowflake ID.
	TeamID Snowflake `json:"team_id"`

	// User is the partial user object of the team member.
	// Avatar, discriminator, ID, and Username of the user.
	User User `json:"user"`

	// Role is the role of the team member.
	Role TeamRole `json:"role"`
}

TeamMember represent a member of a Discord team.

Reference: https://discord.com/developers/docs/topics/teams#data-models-team-member-object

type TeamRole

type TeamRole string

TeamRole represent a team member role.

Reference: https://discord.com/developers/docs/topics/teams#team-member-roles-team-member-role-types

const (
	// Admins have similar access as owners, except they cannot take
	// destructive actions on the team or team-owned apps.
	TeamRoleAdmin TeamRole = "admin"

	// Developers can access information about team-owned apps, like the client secret or public key.
	// They can also take limited actions on team-owned apps, like configuring interaction endpoints
	// or resetting the bot token. Members with the Developer role cannot manage the team or its members,
	// or take destructive actions on team-owned apps.
	TeamRoleDeveloper TeamRole = "developer"

	// Read-only members can access information about a team and any team-owned apps.
	// Some examples include getting the IDs of applications and exporting payout records.
	// Members can also invite bots associated with team-owned apps that are marked private.
	TeamRoleReadOnly TeamRole = "read_only"
)

func (TeamRole) Is

func (r TeamRole) Is(teamRole TeamRole) bool

Is returns true if the team member's role matches the provided role.

type TextChannel

type TextChannel struct {
	EntityBase // Embedded client reference for action methods
	GuildChannelFields
	CategorizedChannelFields
	GuildMessageChannelFields
	NsfwChannelFields
	TopicChannelFields
}

TextChannel represents a guild text channel.

func AcquireTextChannel

func AcquireTextChannel() *TextChannel

AcquireTextChannel gets a TextChannel from the pool.

func (*TextChannel) BulkDelete

func (c *TextChannel) BulkDelete(messageIDs []Snowflake, reason string) error

BulkDelete deletes multiple messages from this channel. Messages must be less than 2 weeks old. Between 2 and 100 messages may be deleted.

Usage example:

err := channel.BulkDelete(messageIDs, "Cleanup")

func (*TextChannel) Delete

func (c *TextChannel) Delete(reason string) error

Delete deletes this channel. Requires MANAGE_CHANNELS permission.

Usage example:

err := channel.Delete("No longer needed")

func (*TextChannel) Edit

func (c *TextChannel) Edit(opts ChannelEditOptions, reason string) (*TextChannel, error)

Edit modifies this channel's settings. Requires MANAGE_CHANNELS permission.

Usage example:

updated, err := channel.Edit(ChannelEditOptions{Name: "new-name"}, "Renaming")

func (*TextChannel) FetchMessage

func (c *TextChannel) FetchMessage(messageID Snowflake) (*Message, error)

FetchMessage retrieves a single message from this channel.

Usage example:

msg, err := channel.FetchMessage(messageID)

func (*TextChannel) FetchMessages

func (c *TextChannel) FetchMessages(opts FetchMessagesOptions) ([]*Message, error)

FetchMessages retrieves messages from this channel.

Usage example:

messages, err := channel.FetchMessages(FetchMessagesOptions{Limit: 10})

func (*TextChannel) Guild

func (c *TextChannel) Guild() (Guild, bool)

Guild returns the cached guild this channel belongs to.

Usage example:

if guild, ok := channel.Guild(); ok {
    fmt.Println("Guild:", guild.Name)
}

func (*TextChannel) MarshalJSON

func (c *TextChannel) MarshalJSON() ([]byte, error)

func (*TextChannel) Send

func (c *TextChannel) Send(content string) (*Message, error)

Send sends a message to this channel.

Usage example:

msg, err := channel.Send("Hello, world!")

func (*TextChannel) SendEmbed

func (c *TextChannel) SendEmbed(embed Embed) (*Message, error)

SendEmbed sends an embed message to this channel.

Usage example:

embed := goda.NewEmbedBuilder().SetTitle("Hello").Build()
msg, err := channel.SendEmbed(embed)

func (*TextChannel) SendWith

func (c *TextChannel) SendWith(opts MessageCreateOptions) (*Message, error)

SendWith sends a message with full options to this channel.

Usage example:

msg, err := channel.SendWith(MessageCreateOptions{
    Content: "Hello!",
    Embeds: []Embed{embed},
})

type TextDisplayComponent

type TextDisplayComponent struct {
	ComponentFields

	// Content is the markdown-formatted text to be displayed, similar to a message's content field.
	Content string `json:"content,omitempty"`
}

TextDisplayComponent is a content component that displays markdown-formatted text, including mentions and emojis.

It behaves similarly to the content field of a message, allowing multiple text components to control message layout. Pingable mentions (@user, @role, etc.) in this component will trigger notifications based on the message's allowed_mentions field. Text Displays require the IS_COMPONENTS_V2 message flag (1 << 15) to be set when sending the message.

Note:

  • Only available in messages.
  • Requires the IS_COMPONENTS_V2 message flag (1 << 15).
  • Supports markdown formatting, user/role mentions, and emojis.

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

func (*TextDisplayComponent) MarshalJSON

func (c *TextDisplayComponent) MarshalJSON() ([]byte, error)

type TextInputComponent

type TextInputComponent struct {
	InteractiveComponentFields

	// Style specifies the text input style (short or paragraph).
	Style TextInputStyle `json:"style,omitempty"`

	// MinLength is the minimum input length for the text input.
	//
	// Note:
	//   - Minimum 0, maximum 4000.
	MinLength *int `json:"min_length,omitempty"`

	// MaxLength is the maximum input length for the text input.
	//
	// Note:
	//   - Minimum 1, maximum 4000.
	MaxLength int `json:"max_length,omitempty"`

	// Required specifies whether this component must be filled in a modal.
	//
	// Note:
	//   - Defaults to true.
	Required bool `json:"required,omitempty"`

	// Value is the pre-filled text for this component.
	//
	// Note:
	//   - Maximum of 4000 characters.
	Value string `json:"value,omitempty"`

	// Placeholder is the custom placeholder text displayed when the input is empty.
	//
	// Note:
	//   - Maximum of 100 characters.
	Placeholder string `json:"placeholder,omitempty"`
}

TextInputComponent is an interactive component that allows users to enter free-form text responses in modals. It supports both short (single-line) and long (multi-line) input styles.

TextInputComponent must be placed inside a LabelComponent in modals.

Note:

  • Only available in modals.

Reference: https://discord.com/developers/docs/interactions/message-components#text-inputs

func (*TextInputComponent) MarshalJSON

func (c *TextInputComponent) MarshalJSON() ([]byte, error)

type TextInputStyle

type TextInputStyle int

TextInputStyle represents the style of a TextInputComponent.

Reference: https://discord.com/developers/docs/interactions/message-components#text-inputs-text-input-styles

const (
	// TextInputStyleShort represents a single-line text input.
	TextInputStyleShort TextInputStyle = 1 + iota

	// TextInputStyleLong represents a multi-line text input.
	TextInputStyleLong
)

func (TextInputStyle) Is

func (s TextInputStyle) Is(style TextInputStyle) bool

Is returns true if the text input style matches the provided one.

type ThreadChannel

type ThreadChannel struct {
	EntityBase // Embedded client reference for action methods
	ThreadChannelFields
	CategorizedChannelFields
	GuildMessageChannelFields
	// OwnerID is the id of this thread owner
	OwnerID Snowflake `json:"owner_id"`
	// ThreadMetadata is the metadata that contains a number of thread-specific channel fields.
	ThreadMetadata ThreadMetaData `json:"thread_metadata"`
}

ThreadChannel represents the base for thread channels.

func (*ThreadChannel) BulkDelete

func (c *ThreadChannel) BulkDelete(messageIDs []Snowflake, reason string) error

BulkDelete deletes multiple messages from this thread.

func (*ThreadChannel) Delete

func (c *ThreadChannel) Delete(reason string) error

Delete deletes this thread.

func (*ThreadChannel) Edit

func (c *ThreadChannel) Edit(opts ChannelEditOptions, reason string) (*ThreadChannel, error)

Edit modifies this thread's settings.

func (*ThreadChannel) FetchMessage

func (c *ThreadChannel) FetchMessage(messageID Snowflake) (*Message, error)

FetchMessage retrieves a single message from this thread.

func (*ThreadChannel) FetchMessages

func (c *ThreadChannel) FetchMessages(opts FetchMessagesOptions) ([]*Message, error)

FetchMessages retrieves messages from this thread.

func (*ThreadChannel) Guild

func (c *ThreadChannel) Guild() (Guild, bool)

Guild returns the cached guild this thread belongs to.

func (*ThreadChannel) MarshalJSON

func (c *ThreadChannel) MarshalJSON() ([]byte, error)

func (*ThreadChannel) Send

func (c *ThreadChannel) Send(content string) (*Message, error)

Send sends a message to this thread.

func (*ThreadChannel) SendEmbed

func (c *ThreadChannel) SendEmbed(embed Embed) (*Message, error)

SendEmbed sends an embed message to this thread.

func (*ThreadChannel) SendWith

func (c *ThreadChannel) SendWith(opts MessageCreateOptions) (*Message, error)

SendWith sends a message with full options to this thread.

type ThreadChannelFields

type ThreadChannelFields struct {
	ChannelFields

	// GuildID is the id of the guild.
	GuildID Snowflake `json:"guild_id"`

	// Name is the name of the channel.
	//
	// Info:
	//  - can be 1 to 100 characters.
	Name string `json:"name,omitempty"`

	// PermissionOverwrites are explicit permission overwrites for members and roles.
	PermissionOverwrites []PermissionOverwrite `json:"permission_overwrites,omitempty"`

	// Flags are combined channel flags.
	Flags ChannelFlags `json:"flags,omitempty"`
}

ThreadChannelFields embeds BaseChannel and adds fields common to thread channels.

func (*ThreadChannelFields) GetFlags

func (c *ThreadChannelFields) GetFlags() ChannelFlags

func (*ThreadChannelFields) GetGuildID

func (c *ThreadChannelFields) GetGuildID() Snowflake

func (*ThreadChannelFields) GetName

func (c *ThreadChannelFields) GetName() string

func (*ThreadChannelFields) GetPermissionOverwrites

func (c *ThreadChannelFields) GetPermissionOverwrites() []PermissionOverwrite

func (*ThreadChannelFields) JumpURL

func (c *ThreadChannelFields) JumpURL() string

type ThreadMember

type ThreadMember struct {
	// ThreadID is the id of the thread.
	ThreadID Snowflake `json:"id"`

	// UserID is the id of the member.
	UserID Snowflake `json:"user_id"`

	// JoinTimestamp is the time the user last joined the thread.
	JoinTimestamp time.Time `json:"join_timestamp"`

	// Flags are any user-thread settings, currently only used for notifications.
	Flags ThreadMemberFlags `json:"flags"`

	// Member is the guild member object of this thread member.
	//
	// Optional:
	//   - This field is only present when 'with_member' is set to true when calling [ListThreadMembers] or [GetThreadMember].
	//
	// [ListThreadMembers]: https://discord.com/developers/docs/resources/channel#list-thread-members
	// [GetThreadMember]: https://discord.com/developers/docs/resources/channel#get-thread-member
	Member *Member `json:"member"`
}

ThreadMember represents Discord thread channel member.

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

type ThreadMemberFlags

type ThreadMemberFlags int

type ThreadMetaData

type ThreadMetaData struct {
	// Archived is whether the thread is archived
	Archived bool `json:"archived"`

	// AutoArchiveDuration is the duration will thread need to stop showing in the channel list.
	AutoArchiveDuration AutoArchiveDuration `json:"auto_archive_duration"`

	// ArchiveTimestamp is the timestamp when the thread's archive status was last changed,
	// used for calculating recent activity
	ArchiveTimestamp time.Time `json:"archive_timestamp"`

	// Locked is whether the thread is locked; when a thread is locked,
	// only users with MANAGE_THREADS can unarchive it
	Locked bool `json:"locked"`

	// Invitable is whether non-moderators can add other non-moderators to a thread.
	Invitable bool `json:"invitable"`
}

ThreadMetaData represents the metadata object that contains a number of thread-specific channel fields.

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

type ThumbnailComponent

type ThumbnailComponent struct {
	ComponentFields

	// Description is an alt text for the media.
	//
	// Note:
	//   - Max 1024 characters.
	Description string `json:"description,omitempty"`

	// Media is a url or attachment provided as an unfurled media item.
	Media UnfurledMediaItem `json:"media"`

	// Spoiler is whether the thumbnail should be a spoiler (or blurred out). Defaults to false.
	Spoiler bool `json:"spoiler,omitempty"`
}

ThumbnailComponent represents a Thumbnail component.

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

func (*ThumbnailComponent) MarshalJSON

func (c *ThumbnailComponent) MarshalJSON() ([]byte, error)

type TopicChannelFields

type TopicChannelFields struct {
	// Topic is the channel topic.
	//
	// Length:
	//  - 0-1024 characters for text, announcement, and stage voice channels.
	//  - 0-4096 characters for forum and media channels.
	//
	// Optional:
	//  - May be empty string if the channel has no topic.
	Topic string `json:"topic"`
}

TopicChannelFields holds the topic field.

type UnfurledMediaItem

type UnfurledMediaItem struct {
	// URL is the url of the media item.
	//
	// Note:
	//   - Supports arbitrary urls and 'attachment://filename' references.
	URL string `json:"url"`

	// ProxyURL is the proxied url of the media item. This field is ignored
	// and provided by the API as part of the response.
	ProxyURL string `json:"proxy_url"`

	// Height is the height of the media item. This field is ignored
	// and provided by the API as part of the response.
	Height int `json:"height,omitempty"`

	// Width is the width of the media item. This field is ignored
	// and provided by the API as part of the response.
	Width int `json:"width,omitempty"`

	// ContentType is the [media type] of the content. This field is ignored
	// and provided by the API as part of the response.
	//
	// [media type]: https://en.wikipedia.org/wiki/Media_type
	ContentType string `json:"content_type,omitempty"`

	// AttachmentID is the id of the uploaded attachment. This field is ignored
	// and provided by the API as part of the response.
	AttachmentID Snowflake `json:"attachment_id,omitempty"`
}

UnfurledMediaItem represents an unfurled media item.

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

type UnfurledMediaItemLoadingState

type UnfurledMediaItemLoadingState int
const (
	UnfurledMediaItemLoadingStateUnknown UnfurledMediaItemLoadingState = iota
	UnfurledMediaItemLoadingStateLoading
	UnfurledMediaItemLoadingStateLoadedSuccess
	UnfurledMediaItemLoadingStateLoadedNotFound
)

type UpdateSelfUserOptions

type UpdateSelfUserOptions struct {
	Username string `json:"username,omitempty"`
	// Use:
	//
	//  avatar, err := goda.NewImageFile("path/to/your/image.png")
	//  if err != nil {
	// 		// handler err
	//  }
	Avatar Base64Image `json:"avatar,omitempty"`
	// Use:
	//
	//  banner, err := goda.NewImageFile("path/to/your/banner.png")
	//  if err != nil {
	// 		// handler err
	//  }
	Banner Base64Image `json:"banner,omitempty"`
}

UpdateSelfUserOptions defines the parameters to update the current user account.

All fields are optional:

  • If a field is not set (left empty), it will remain unchanged.

type User

type User struct {
	EntityBase // Embedded client reference for action methods (pointer, 8 bytes)

	// ID is the user's unique Discord snowflake ID.
	ID Snowflake `json:"id"` // uint64, 8 bytes

	// Pointers (8 bytes each, grouped for alignment)
	// AvatarDecorationData holds avatar decoration info.
	AvatarDecorationData *AvatarDecorationData `json:"avatar_decoration_data,omitempty"`
	// Collectibles holds user's collectibles.
	Collectibles *Collectibles `json:"collectibles,omitempty"`
	// PrimaryGuild holds the user's primary guild info.
	PrimaryGuild *UserPrimaryGuild `json:"primary_guild,omitempty"`
	// AccentColor is the user's banner color encoded as an integer.
	AccentColor *Color `json:"accent_color"`

	// Strings (24 bytes each: ptr + len + cap)
	// Username is the user's username (not unique).
	Username string `json:"username"`
	// Discriminator is the user's 4-digit Discord tag suffix.
	Discriminator string `json:"discriminator"`
	// GlobalName is the user's display name. For bots, this is the application name.
	GlobalName string `json:"global_name"`
	// Avatar is the user's avatar hash.
	Avatar string `json:"avatar"`
	// Banner is the user's banner hash.
	Banner string `json:"banner"`

	// Ints (8 bytes on 64-bit)
	// PremiumType is the Nitro subscription type.
	PremiumType UserPremiumType `json:"premium_type,omitempty"`
	// PublicFlags are the public flags on the user account.
	PublicFlags UserFlags `json:"public_flags,omitempty"`

	// Bools (1 byte each, grouped at end to minimize padding)
	// Bot indicates if the user is a bot account.
	Bot bool `json:"bot,omitempty"`
	// System indicates if the user is an official Discord system user.
	System bool `json:"system,omitempty"`
}

User represents a Discord user object.

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

NOTE: Fields are ordered for optimal memory alignment (largest to smallest) to minimize struct padding and improve cache efficiency.

func AcquireUser

func AcquireUser() *User

AcquireUser gets a User from the pool. The returned User must be released back to the pool after use.

func (*User) AvatarDecorationURL

func (u *User) AvatarDecorationURL() string

AvatarDecorationURL returns the URL to the user's avatar decoration.

If the user has no avatar decoration, it returns an empty string.

Example usage:

url := user.AvatarDecorationURL()

func (*User) AvatarDecorationURLWith

func (u *User) AvatarDecorationURLWith(size ImageSize) string

AvatarDecorationURLWith returns the URL to the user's avatar decoration, allowing explicit specification of image size.

If the user has no avatar decoration, it returns an empty string.

Example usage:

url := user.AvatarDecorationURL(ImageSize512)

func (*User) AvatarURL

func (u *User) AvatarURL() string

AvatarURL returns the URL to the user's avatar image.

If the user has a custom avatar set, it returns the URL to that avatar, otherwise empty string. By default, it uses GIF format if the avatar is animated, otherwise PNG.

If the user has no custom avatar, it returns the URL to their default avatar based on their discriminator or ID, using PNG format.

Example usage:

url := user.AvatarURL()

func (*User) AvatarURLWith

func (u *User) AvatarURLWith(format ImageFormat, size ImageSize) string

AvatarURLWith returns the URL to the user's avatar image, allowing explicit specification of image format and size.

If the user has a custom avatar set, it returns the URL to that avatar using the provided format and size, otherwise empty string.

If the user has no custom avatar, it returns the URL to their default avatar, using PNG format (size parameter is ignored for default avatars).

Example usage:

url := user.AvatarURLWith(ImageFormatWebP, ImageSize1024)

func (*User) BannerURL

func (u *User) BannerURL() string

BannerURL returns the URL to the user's banner image.

If the user has a custom banner set, it returns the URL to that banner. By default, it uses GIF format if the banner is animated, otherwise PNG.

If the user has no custom banner, it returns an empty string.

Example usage:

url := user.BannerURL()

func (*User) BannerURLWith

func (u *User) BannerURLWith(format ImageFormat, size ImageSize) string

BannerURLWith returns the URL to the member's avatar image, allowing explicit specification of image format and size.

If the user has no custom banner, it returns an empty string.

Example usage:

url := user.BannerURLWith(ImageFormatWebP, ImageSize1024)

func (*User) CreateDM

func (u *User) CreateDM() (*DMChannel, error)

CreateDM creates or retrieves a DM channel with this user. Returns the DM channel.

Usage example:

dm, err := user.CreateDM()

func (*User) CreatedAt

func (u *User) CreatedAt() time.Time

CreatedAt returns the time when this user account is created.

func (*User) DefaultAvatarIndex

func (u *User) DefaultAvatarIndex() int

DefaultAvatarIndex returns the index (0-5) used to determine which default avatar is assigned to the user.

For users with discriminator "0" (new Discord usernames), it uses the user's snowflake ID shifted right by 22 bits modulo 6.

For legacy users with a numeric discriminator, it parses the discriminator as an integer and returns modulo 5.

This logic follows Discord's default avatar assignment rules.

Example usage:

index := user.DefaultAvatarIndex()

func (*User) DisplayName

func (u *User) DisplayName() string

DisplayName returns the user's global name if set, otherwise it returns their username.

The global name is their profile display name visible across Discord, while Username is their original account username.

Example usage:

name := user.DisplayName()

func (*User) Fetch

func (u *User) Fetch() (*User, error)

Fetch fetches fresh user data from the API. Returns a new User object with updated data.

Usage example:

freshUser, err := user.Fetch()

func (*User) GuildTagBadgeURL

func (u *User) GuildTagBadgeURL() string

GuildTagBadgeURL returns the URL to the user's PrimaryGuild badge image.

If the user has no PrimaryGuild badge, it returns an empty string.

Example usage:

url := user.GuildTagBadgeURL()

func (*User) IsBot

func (u *User) IsBot() bool

IsBot returns true if this user is a bot account.

Usage example:

if user.IsBot() {
    // User is a bot
}

func (*User) IsSystem

func (u *User) IsSystem() bool

IsSystem returns true if this user is an official Discord system user.

Usage example:

if user.IsSystem() {
    // User is a Discord system user
}

func (*User) Mention

func (u *User) Mention() string

Mention returns a Discord mention string for the user.

Example output: "<@123456789012345678>"

func (*User) Send

func (u *User) Send(content string) (*Message, error)

Send sends a direct message to this user. Returns the sent message.

Usage example:

msg, err := user.Send("Hello!")

func (*User) SendEmbed

func (u *User) SendEmbed(embed Embed) (*Message, error)

SendEmbed sends an embed as a direct message to this user. Returns the sent message.

Usage example:

embed := goda.NewEmbedBuilder().SetTitle("Hello").Build()
msg, err := user.SendEmbed(embed)

func (*User) SendWith

func (u *User) SendWith(opts MessageCreateOptions) (*Message, error)

SendWith sends a direct message to this user with full options. Returns the sent message.

Usage example:

msg, err := user.SendWith(MessageCreateOptions{
    Content: "Hello!",
    Embeds: []Embed{embed},
})

func (*User) Tag

func (u *User) Tag() string

Tag returns the user's tag in the format "username#discriminator".

Example output: "bob#1337"

Note: For users with no discriminator (new Discord accounts), this returns only the username (Example output: "bob").

type UserCommandInteraction

type UserCommandInteraction struct {
	ApplicationCommandInteractionFields

	// Data contains the payload of the interaction specific to user commands.
	Data UserCommandInteractionData `json:"data"`
}

UserCommandInteraction represents an interaction triggered by a user context menu command.

Reference: https://discord.com/developers/docs/interactions/application-commands

type UserCommandInteractionData

type UserCommandInteractionData struct {
	ApplicationCommandInteractionDataFields

	// Resolved contains the resolved objects referenced by the command, members and users in this case.
	Resolved UserCommandInteractionDataResolved `json:"resolved"`

	// TargetID is the id of the user targeted by the command.
	TargetID Snowflake `json:"target_id"`
}

UserCommandInteractionData represents the data for a user command interaction.

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

type UserCommandInteractionDataResolved

type UserCommandInteractionDataResolved struct {
	// Users is a map of user IDs to User objects referenced by the command.
	Users map[Snowflake]User `json:"users"`

	// Members is a map of user IDs to partial Member objects for the guild.
	Members map[Snowflake]ResolvedMember `json:"members"`
}

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

type UserFlags

type UserFlags int

UserFlags represents flags on a Discord user account.

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

const (
	// Discord Employee
	UserFlagStaff UserFlags = 1 << 0

	// Partnered Server Owner
	UserFlagPartner UserFlags = 1 << 1

	// HypeSquad Events Member
	UserFlagHypeSquad UserFlags = 1 << 2

	// Bug Hunter Level 1
	UserFlagBugHunterLevel1 UserFlags = 1 << 3

	// House Bravery Member
	UserFlagHypeSquadOnlineHouse1 UserFlags = 1 << 6

	// House Brilliance Member
	UserFlagHypeSquadOnlineHouse2 UserFlags = 1 << 7

	// House Balance Member
	UserFlagHypeSquadOnlineHouse3 UserFlags = 1 << 8

	// Early Nitro Supporter
	UserFlagPremiumEarlySupporter UserFlags = 1 << 9

	// User is a team
	UserFlagTeamPseudoUser UserFlags = 1 << 10

	// Bug Hunter Level 2
	UserFlagBugHunterLevel2 UserFlags = 1 << 14

	// Verified Bot
	UserFlagVerifiedBot UserFlags = 1 << 16

	// Early Verified Bot Developer
	UserFlagVerifiedDeveloper UserFlags = 1 << 17

	// Moderator Programs Alumni
	UserFlagCertifiedModerator UserFlags = 1 << 18

	// Bot uses only HTTP interactions and is shown in the online member list
	UserFlagBotHTTPInteractions UserFlags = 1 << 19

	// User is an Active Developer
	UserFlagActiveDeveloper UserFlags = 1 << 22
)

func (UserFlags) Has

func (f UserFlags) Has(flags ...UserFlags) bool

Has returns true if all provided flags are set.

type UserPremiumType

type UserPremiumType int

UserPremiumType is the type of premium (nitro) subscription a user has (see UserPremiumType* consts). https://discord.com/developers/docs/resources/user#user-object-premium-types

const (
	UserPremiumTypeNone         UserPremiumType = 0
	UserPremiumTypeNitroClassic UserPremiumType = 1
	UserPremiumTypeNitro        UserPremiumType = 2
	UserPremiumTypeNitroBasic   UserPremiumType = 3
)

Valid UserPremiumType values.

func (UserPremiumType) Is

func (t UserPremiumType) Is(premiumType UserPremiumType) bool

Is returns true if the user's premium type matches the provided premium type.

type UserPrimaryGuild

type UserPrimaryGuild struct {
	// IdentityGuildID is the Discord snowflake ID of the user's primary guild.
	//
	// Optional:
	//  - May be nil if the user has no primary guild set.
	//  - May be nil if the system cleared the identity due to guild tag support removal or privacy.
	IdentityGuildID *Snowflake `json:"identity_guild_id,omitempty"`

	// IdentityEnabled indicates if the user currently displays the primary guild's server tag.
	//
	// Optional:
	//  - May be nil if the identity was cleared by the system (e.g., guild tag disabled).
	//  - May be false if the user explicitly disabled showing the tag.
	IdentityEnabled *bool `json:"identity_enabled,omitempty"`

	// Tag is the text of the user's server tag.
	//
	// Optional:
	//  - May be nil or empty string if no tag is set.
	//  - Limited to 4 characters.
	//  - May be cleared if tag data is invalid or unavailable.
	Tag *string `json:"tag,omitempty"`

	// Badge is the hash string of the user's server tag badge.
	//
	// Optional:
	//  - May be nil if user has no badge or badge info unavailable.
	Badge *string `json:"badge,omitempty"`
}

UserPrimaryGuild represents the user's primary guild info.

Optionally included by Discord API.

Reference: https://discord.com/developers/docs/resources/user#user-primary-guild-object

type UserSelectMenuComponent

type UserSelectMenuComponent struct {
	InteractiveComponentFields

	// Placeholder is the custom placeholder text if the input is empty.
	//
	// Note:
	//   - Max 150 characters.
	Placeholder string `json:"placeholder,omitempty"`

	// DefaultValues is a list of default values for auto-populated select menu components;
	// number of default values must be in the range defined by min_values and max_values.
	DefaultValues []SelectDefaultValue `json:"default_values,omitempty"`

	// MinValues is the minimum number of items that must be chosen (defaults to 1).
	//
	// Note:
	//   - Min 0, max 25.
	MinValues *int `json:"min_values,omitempty"`

	// MaxValues is the maximum number of items that can be chosen (defaults to 1).
	//
	// Note:
	//   - Min 1, max 25.
	MaxValues int `json:"max_values,omitempty"`

	// Disabled is whether select menu is disabled (defaults to false).
	Disabled bool `json:"disabled,omitempty"`
}

UserSelectMenuComponent represents a user select menu component.

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

func (*UserSelectMenuComponent) MarshalJSON

func (c *UserSelectMenuComponent) MarshalJSON() ([]byte, error)

type VerificationLevel

type VerificationLevel int

VerificationLevel represents the verification level required on a Discord guild.

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

const (
	// Unrestricted.
	VerificationLevelNone VerificationLevel = iota
	// Must have verified email on account.
	VerificationLevelLow
	// Must be registered on Discord for longer than 5 minutes.
	VerificationLevelMedium
	// Must be a member of the server for longer than 10 minutes.
	VerificationLevelHigh
	// Must have a verified phone number
	VerificationLevelVeryHigh
)

func (VerificationLevel) Is

func (l VerificationLevel) Is(verifLevel VerificationLevel) bool

Is returns true if the verification level matches the provided one.

type VideoQualityModes

type VideoQualityModes int
const (
	VideoQualityModesAuto VideoQualityModes = iota + 1
	VideoQualityModesFull
)

type VoiceChannel

type VoiceChannel struct {
	EntityBase // Embedded client reference for action methods
	GuildChannelFields
	CategorizedChannelFields
	GuildMessageChannelFields
	NsfwChannelFields
	AudioChannelFields
}

VoiceChannel represents a guild voice channel.

func AcquireVoiceChannel

func AcquireVoiceChannel() *VoiceChannel

AcquireVoiceChannel gets a VoiceChannel from the pool.

func (*VoiceChannel) Delete

func (c *VoiceChannel) Delete(reason string) error

Delete deletes this voice channel.

func (*VoiceChannel) Edit

func (c *VoiceChannel) Edit(opts ChannelEditOptions, reason string) (*VoiceChannel, error)

Edit modifies this voice channel's settings.

func (*VoiceChannel) FetchMessage

func (c *VoiceChannel) FetchMessage(messageID Snowflake) (*Message, error)

FetchMessage retrieves a single message from this voice channel.

func (*VoiceChannel) FetchMessages

func (c *VoiceChannel) FetchMessages(opts FetchMessagesOptions) ([]*Message, error)

FetchMessages retrieves messages from this voice channel.

func (*VoiceChannel) Guild

func (c *VoiceChannel) Guild() (Guild, bool)

Guild returns the cached guild this voice channel belongs to.

func (*VoiceChannel) MarshalJSON

func (c *VoiceChannel) MarshalJSON() ([]byte, error)

func (*VoiceChannel) Send

func (c *VoiceChannel) Send(content string) (*Message, error)

Send sends a message to this voice channel.

func (*VoiceChannel) SendEmbed

func (c *VoiceChannel) SendEmbed(embed Embed) (*Message, error)

SendEmbed sends an embed message to this voice channel.

func (*VoiceChannel) SendWith

func (c *VoiceChannel) SendWith(opts MessageCreateOptions) (*Message, error)

SendWith sends a message with full options to this voice channel.

type VoiceRegion

type VoiceRegion struct {
	// ID is the unique identifier for the voice region.
	ID string `json:"id"`

	// Name is the name of the voice region.
	Name string `json:"name"`

	// Optimal indicates whether this region is optimal for the current user.
	//
	// True if this is the single server closest to the current user's client.
	Optimal bool `json:"optimal"`

	// Deprecated indicates whether this voice region is deprecated.
	//
	// Avoid switching to these regions.
	Deprecated bool `json:"deprecated"`

	// Custom indicates whether this is a custom voice region.
	//
	// Used for special events or similar use cases.
	Custom bool `json:"custom"`
}

VoiceRegion represents a Discord voice region.

Reference: https://discord.com/developers/docs/resources/voice#voice-region-object

type VoiceState

type VoiceState struct {
	// GuildID is the ID of the guild this voice state is for.
	GuildID Snowflake `json:"guild_id"`

	// ChannelID is the ID of the voice channel the user is connected to.
	ChannelID Snowflake `json:"channel_id,omitempty"`

	// UserID is the ID of the user this voice state is for.
	UserID Snowflake `json:"user_id"`

	// SessionID is the session identifier for this voice state.
	SessionID string `json:"session_id"`

	// GuildDeaf indicates whether the user is deafened by the server.
	GuildDeaf bool `json:"deaf"`

	// GuildMute indicates whether the user is muted by the server.
	GuildMute bool `json:"mute"`

	// SelfDeaf indicates whether the user is locally deafened.
	SelfDeaf bool `json:"self_deaf"`

	// SelfMute indicates whether the user is locally muted.
	SelfMute bool `json:"self_mute"`

	// SelfStream indicates whether the user is streaming using "Go Live".
	SelfStream bool `json:"self_stream,omitempty"`

	// SelfVideo indicates whether the user's camera is enabled.
	SelfVideo bool `json:"self_video"`

	// Suppress indicates whether the user's permission to speak is denied.
	Suppress bool `json:"suppress"`

	// RequestToSpeakTimestamp is the time at which the user requested to speak.
	//
	// Optional:
	//  - May be nil if the user has not requested to speak.
	RequestToSpeakTimestamp *time.Time `json:"request_to_speak_timestamp,omitempty"`
}

VoiceState represents a user's voice connection status in a guild.

Reference: https://discord.com/developers/docs/resources/voice#voice-state-object

type VoiceStateUpdateEvent

type VoiceStateUpdateEvent struct {
	ShardsID int // shard that dispatched this event
	OldState VoiceState
	NewState VoiceState
}

VoiceStateUpdateEvent VoiceState was updated

type WebhookEventTypes

type WebhookEventTypes string

WebhookEventTypes represent the webhook event types your app can subscribe to.

Reference: https://discord.com/developers/docs/events/webhook-events#event-types

const (
	// Sent when an app was authorized by a user to a server or their account.
	//
	// See: https://discord.com/developers/docs/events/webhook-events#application-authorized
	WebhookEventTypesApplicationAuthorized WebhookEventTypes = "APPLICATION_AUTHORIZED"

	// Sent when an app was deauthorized by a user.
	//
	// See: https://discord.com/developers/docs/events/webhook-events#application-deauthorized
	WebhookEventTypesApplicationApplicationDeauthorized WebhookEventTypes = "APPLICATION_DEAUTHORIZED"

	// Entitlement was created.
	//
	// See: https://discord.com/developers/docs/events/webhook-events#entitlement-create
	WebhookEventTypesApplicationApplicationEntitlementCreate WebhookEventTypes = "ENTITLEMENT_CREATE"

	// User was added to a Quest (currently unavailable).
	//
	// See: https://discord.com/developers/docs/events/webhook-events#quest-user-enrollment
	WebhookEventTypesApplicationApplicationQuestUserEnrollment WebhookEventTypes = "QUEST_USER_ENROLLMENT"
)

func (WebhookEventTypes) Is

func (t WebhookEventTypes) Is(webhookEventType WebhookEventTypes) bool

Is returns true if the webhook event type matches the provided webhook event type.

type WorkerPool

type WorkerPool interface {
	// returns false if task dropped
	Submit(task WorkerTask) bool
	Shutdown()
}

func NewDefaultWorkerPool

func NewDefaultWorkerPool(logger Logger, opts ...workerOption) WorkerPool

NewDefaultWorkerPool creates a new worker pool with options.

type WorkerTask

type WorkerTask func()

Jump to

Keyboard shortcuts

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