Documentation
¶
Overview ¶
Package starlings provides a Discord gateway, REST, state, interactions, and voice client. Common bot paths stay short while raw REST, gateway, dispatch, sharding, and state controls remain available to applications that need them.
Index ¶
- Constants
- Variables
- func AuthorizeURL(appID Snowflake, redirectURI string, scopes ...string) string
- func BearerToken(token string) string
- func CustomID(parts ...any) string
- func DiscordCode(err error) int
- func FailFast(ctx context.Context) context.Context
- func GuardCompare[T any](g *Guard, feature string, equal func(T, T) bool, ...) (T, error)
- func HTTPStatus(err error) int
- func IsDiscordCode(err error, codes ...int) bool
- func IsForbidden(err error) bool
- func IsModerationDenial(err error) bool
- func IsNotFound(err error) bool
- func IsUnauthorized(err error) bool
- func Listen[E Event](c *Client, h func(*E)) func()
- func On[E Event](c *Client, h func(*E))
- func OnOrdered[E Event](c *Client, h func(*E))
- func Once[E Event](c *Client, h func(*E)) func()
- func ParseDuration(s string) (time.Duration, error)
- func Ref[T any](value T) *T
- func RegisterStarPetArt(variant StarPetVariant, png []byte)
- func UserErrorf(format string, args ...any) error
- func VerifyInteraction(publicKey ed25519.PublicKey, signatureHex, timestamp string, body []byte) bool
- type APIError
- type Activity
- type ActivityInstance
- type ActivityType
- type AllowedMentions
- type AppInfo
- type AppTeam
- type ApplicationCommand
- type ApplicationCommandPermissionsUpdate
- type ApplicationCommandType
- type ApplicationIdentity
- type ApplicationIntegrationType
- type ApplicationParams
- type ArchivedThreadsQuery
- type Attachment
- type AttachmentUpload
- type AuditLog
- type AuditLogChange
- type AuditLogEntry
- type AuditLogQuery
- type AutoModerationActionExecution
- type AutoModerationRuleCreate
- type AutoModerationRuleDelete
- type AutoModerationRuleUpdate
- type AutomodAction
- type AutomodActionMeta
- type AutomodRule
- type AutomodTriggerMeta
- type Ban
- type BansQuery
- type BulkBanResult
- type ButtonStyle
- type CallbackType
- type Channel
- func (ch *Channel) Delete(reason string) error
- func (c *Channel) Mention() string
- func (ch *Channel) Purge(opts PurgeOptions) (PurgeResult, error)
- func (ch *Channel) Send(content string) (*Message, error)
- func (ch *Channel) SendComplex(data SendData) (*Message, error)
- func (ch *Channel) SendEmbed(e *Embed) (*Message, error)
- func (ch *Channel) Typing() error
- func (ch *Channel) WithContext(ctx context.Context) *Channel
- type ChannelCreate
- type ChannelDelete
- type ChannelInfo
- type ChannelInfoChannel
- type ChannelInfoField
- type ChannelMention
- type ChannelParams
- type ChannelPinsUpdate
- type ChannelPosition
- type ChannelType
- type ChannelUpdate
- type Client
- func (c *Client) ActiveThreads(ctx context.Context, guildID Snowflake) ([]Channel, []ThreadMember, error)
- func (c *Client) ActivityInstance(ctx context.Context, appID Snowflake, instanceID string) (*ActivityInstance, error)
- func (c *Client) AddGroupDMRecipient(ctx context.Context, channelID, userID Snowflake, accessToken, nick string) error
- func (c *Client) AddInviteTargetUser(ctx context.Context, code string, userID Snowflake) error
- func (c *Client) AddLobbyMember(ctx context.Context, lobbyID, userID Snowflake, data LobbyMemberInput) (*LobbyMember, error)
- func (c *Client) AddMember(ctx context.Context, guildID, userID Snowflake, accessToken string, ...) (*Member, error)
- func (c *Client) AddMemberRole(ctx context.Context, guildID, userID, roleID Snowflake, reason string) error
- func (c *Client) AddThreadMember(ctx context.Context, threadID, userID Snowflake) error
- func (c *Client) Application(ctx context.Context, appID Snowflake) (*CurrentApplication, error)
- func (c *Client) ApplicationCommand(ctx context.Context, appID, commandID Snowflake) (*ApplicationCommand, error)
- func (c *Client) ApplicationCommands(ctx context.Context, appID Snowflake) ([]ApplicationCommand, error)
- func (c *Client) ApplicationEmoji(ctx context.Context, appID, emojiID Snowflake) (*GuildEmoji, error)
- func (c *Client) ApplicationEmojis(ctx context.Context, appID Snowflake) ([]GuildEmoji, error)
- func (c *Client) ApplicationID() Snowflake
- func (c *Client) AuditLog(ctx context.Context, guildID Snowflake, q AuditLogQuery) (*AuditLog, error)
- func (c *Client) AutomodRule(ctx context.Context, guildID, ruleID Snowflake) (*AutomodRule, error)
- func (c *Client) AutomodRules(ctx context.Context, guildID Snowflake) ([]AutomodRule, error)
- func (c *Client) Ban(ctx context.Context, guildID, userID Snowflake) (*Ban, error)
- func (c *Client) Bans(ctx context.Context, guildID Snowflake, q BansQuery) ([]Ban, error)
- func (c *Client) BulkAddInviteTargetUsers(ctx context.Context, code string, userIDs []Snowflake) (*InviteTargetUsersJob, error)
- func (c *Client) BulkBan(ctx context.Context, guildID Snowflake, userIDs []Snowflake, ...) (*BulkBanResult, error)
- func (c *Client) BulkDeleteInviteTargetUsers(ctx context.Context, code string, userIDs []Snowflake) (*InviteTargetUsersJob, error)
- func (c *Client) BulkDeleteMessages(ctx context.Context, channelID Snowflake, ids []Snowflake, reason string) error
- func (c *Client) BulkUpdateLobbyMembers(ctx context.Context, lobbyID Snowflake, members []LobbyMemberInput) ([]LobbyMember, error)
- func (c *Client) Button(pattern string, handler any) func()
- func (c *Client) Channel(ctx context.Context, channelID Snowflake) (*Channel, error)
- func (c *Client) ChannelInvites(ctx context.Context, channelID Snowflake) ([]Invite, error)
- func (c *Client) ChannelWebhooks(ctx context.Context, channelID Snowflake) ([]Webhook, error)
- func (c *Client) ClearReactions(ctx context.Context, channelID, messageID Snowflake) error
- func (c *Client) ClearReactionsFor(ctx context.Context, channelID, messageID Snowflake, emoji Emoji) error
- func (c *Client) ClearTimeout(ctx context.Context, guildID, userID Snowflake, reason string) (*Member, error)
- func (c *Client) Close() error
- func (c *Client) Command(name string, fn CommandFunc) *CommandRoute
- func (c *Client) Commands() []string
- func (c *Client) ConsumeEntitlement(ctx context.Context, appID, entitlementID Snowflake) error
- func (c *Client) CreateApplicationCommand(ctx context.Context, appID Snowflake, cmd ApplicationCommand) (*ApplicationCommand, error)
- func (c *Client) CreateApplicationEmoji(ctx context.Context, appID Snowflake, name, image string) (*GuildEmoji, error)
- func (c *Client) CreateAutomodRule(ctx context.Context, guildID Snowflake, rule AutomodRule, reason string) (*AutomodRule, error)
- func (c *Client) CreateBan(ctx context.Context, guildID, userID Snowflake, deleteMessageSeconds int, ...) error
- func (c *Client) CreateChannel(ctx context.Context, guildID Snowflake, params ChannelParams, reason string) (*Channel, error)
- func (c *Client) CreateDM(ctx context.Context, userID Snowflake) (*Channel, error)
- func (c *Client) CreateGuildCommand(ctx context.Context, appID, guildID Snowflake, cmd ApplicationCommand) (*ApplicationCommand, error)
- func (c *Client) CreateGuildEmoji(ctx context.Context, guildID Snowflake, name, image string, roles []Snowflake, ...) (*GuildEmoji, error)
- func (c *Client) CreateGuildTemplate(ctx context.Context, guildID Snowflake, name, description string) (*GuildTemplate, error)
- func (c *Client) CreateInvite(ctx context.Context, channelID Snowflake, params InviteParams, reason string) (*Invite, error)
- func (c *Client) CreateLobby(ctx context.Context, data LobbyCreate) (*Lobby, error)
- func (c *Client) CreateRole(ctx context.Context, guildID Snowflake, params RoleParams, reason string) (*Role, error)
- func (c *Client) CreateScheduledEvent(ctx context.Context, guildID Snowflake, e ScheduledEvent, reason string) (*ScheduledEvent, error)
- func (c *Client) CreateScheduledEventException(ctx context.Context, guildID, eventID Snowflake, e ScheduledEventException) (*ScheduledEventException, error)
- func (c *Client) CreateSoundboardSound(ctx context.Context, guildID Snowflake, s NewSoundboardSound, reason string) (*SoundboardSound, error)
- func (c *Client) CreateStageInstance(ctx context.Context, s StageInstance, reason string) (*StageInstance, error)
- func (c *Client) CreateSticker(ctx context.Context, guildID Snowflake, name, description, tags string, ...) (*Sticker, error)
- func (c *Client) CreateTestEntitlement(ctx context.Context, appID, skuID, ownerID Snowflake, ownerType int) (*Entitlement, error)
- func (c *Client) CreateWebhook(ctx context.Context, channelID Snowflake, name, reason string) (*Webhook, error)
- func (c *Client) CreateWidgetConfig(ctx context.Context, appID Snowflake, displayName string) (*WidgetConfig, error)
- func (c *Client) Crosspost(ctx context.Context, channelID, messageID Snowflake) (*Message, error)
- func (c *Client) CurrentApplication(ctx context.Context) (*CurrentApplication, error)
- func (c *Client) CurrentAuthorization(ctx context.Context, bearerToken string) (*OAuth2Authorization, error)
- func (c *Client) CurrentOAuth2Application(ctx context.Context) (*CurrentApplication, error)
- func (c *Client) CurrentUser(ctx context.Context) (*User, error)
- func (c *Client) CurrentUserGuildMember(ctx context.Context, guildID Snowflake) (*Member, error)
- func (c *Client) CurrentUserGuilds(ctx context.Context, q CurrentUserGuildsQuery) ([]Guild, error)
- func (c *Client) CurrentVoiceState(ctx context.Context, guildID Snowflake) (*VoiceState, error)
- func (c *Client) DefaultSoundboardSounds(ctx context.Context) ([]SoundboardSound, error)
- func (c *Client) DeleteApplicationCommand(ctx context.Context, appID, commandID Snowflake) error
- func (c *Client) DeleteApplicationEmoji(ctx context.Context, appID, emojiID Snowflake) error
- func (c *Client) DeleteApplicationIdentity(ctx context.Context, userID, appID Snowflake, ...) error
- func (c *Client) DeleteAutomodRule(ctx context.Context, guildID, ruleID Snowflake, reason string) error
- func (c *Client) DeleteChannel(ctx context.Context, channelID Snowflake, reason string) (*Channel, error)
- func (c *Client) DeleteGuildCommand(ctx context.Context, appID, guildID, commandID Snowflake) error
- func (c *Client) DeleteGuildEmoji(ctx context.Context, guildID, emojiID Snowflake, reason string) error
- func (c *Client) DeleteGuildTemplate(ctx context.Context, guildID Snowflake, code string) (*GuildTemplate, error)
- func (c *Client) DeleteIntegration(ctx context.Context, guildID, integrationID Snowflake, reason string) error
- func (c *Client) DeleteInvite(ctx context.Context, code, reason string) (*Invite, error)
- func (c *Client) DeleteLobby(ctx context.Context, lobbyID Snowflake) error
- func (c *Client) DeleteMessage(ctx context.Context, channelID, messageID Snowflake, reason string) error
- func (c *Client) DeletePermissionOverwrite(ctx context.Context, channelID, overwriteID Snowflake, reason string) error
- func (c *Client) DeleteRole(ctx context.Context, guildID, roleID Snowflake, reason string) error
- func (c *Client) DeleteScheduledEvent(ctx context.Context, guildID, eventID Snowflake) error
- func (c *Client) DeleteScheduledEventException(ctx context.Context, guildID, eventID, exceptionID Snowflake) error
- func (c *Client) DeleteSoundboardSound(ctx context.Context, guildID, soundID Snowflake, reason string) error
- func (c *Client) DeleteStageInstance(ctx context.Context, channelID Snowflake, reason string) error
- func (c *Client) DeleteSticker(ctx context.Context, guildID, stickerID Snowflake, reason string) error
- func (c *Client) DeleteTestEntitlement(ctx context.Context, appID, entitlementID Snowflake) error
- func (c *Client) DeleteUserRoleConnection(ctx context.Context, bearerToken string, appID Snowflake) error
- func (c *Client) DeleteWebhook(ctx context.Context, webhookID Snowflake, reason string) error
- func (c *Client) DeleteWebhookMessage(ctx context.Context, webhookID Snowflake, token string, messageID Snowflake) error
- func (c *Client) DeleteWebhookWithToken(ctx context.Context, webhookID Snowflake, token string) error
- func (c *Client) DownloadAttachment(ctx context.Context, a Attachment, limit int64) ([]byte, error)
- func (c *Client) EditApplication(ctx context.Context, params ApplicationParams) (*CurrentApplication, error)
- func (c *Client) EditApplicationByID(ctx context.Context, appID Snowflake, params ApplicationParams) (*CurrentApplication, error)
- func (c *Client) EditApplicationCommand(ctx context.Context, appID, commandID Snowflake, cmd ApplicationCommand) (*ApplicationCommand, error)
- func (c *Client) EditGuildCommand(ctx context.Context, appID, guildID, commandID Snowflake, ...) (*ApplicationCommand, error)
- func (c *Client) EditLobby(ctx context.Context, lobbyID Snowflake, data LobbyEdit) (*Lobby, error)
- func (c *Client) EditMessage(ctx context.Context, channelID, messageID Snowflake, data SendData) (*Message, error)
- func (c *Client) EditWebhookMessage(ctx context.Context, webhookID Snowflake, token string, messageID Snowflake, ...) (*Message, error)
- func (c *Client) EditWebhookMessageFiles(ctx context.Context, webhookID Snowflake, token string, messageID Snowflake, ...) (*Message, error)
- func (c *Client) Entitlement(ctx context.Context, appID, entitlementID Snowflake) (*Entitlement, error)
- func (c *Client) Entitlements(ctx context.Context, appID Snowflake, q EntitlementsQuery) ([]Entitlement, error)
- func (c *Client) ExchangeBotProvisionalToken(ctx context.Context, externalUserID, preferredGlobalName string, ...) (*ProvisionalToken, error)
- func (c *Client) ExchangeProvisionalToken(ctx context.Context, credentials ProvisionalCredentials) (*ProvisionalToken, error)
- func (c *Client) ExecuteGitHubWebhook(ctx context.Context, webhookID Snowflake, token string, payload any, wait bool) error
- func (c *Client) ExecuteSlackWebhook(ctx context.Context, webhookID Snowflake, token string, payload any, wait bool) error
- func (c *Client) ExecuteWebhook(ctx context.Context, webhookID Snowflake, token string, msg WebhookMessage, ...) (*Message, error)
- func (c *Client) ExecuteWebhookFiles(ctx context.Context, webhookID Snowflake, token string, msg WebhookMessage, ...) (*Message, error)
- func (c *Client) ExpirePoll(ctx context.Context, channelID, messageID Snowflake) (*Message, error)
- func (c *Client) Extension(key any, create func() (any, error)) (any, error)
- func (c *Client) FetchChannel(ctx context.Context, channelID Snowflake) (*Channel, error)
- func (c *Client) FetchGuild(ctx context.Context, guildID Snowflake) (*Guild, error)
- func (c *Client) FetchMember(ctx context.Context, guildID, userID Snowflake) (*Member, error)
- func (c *Client) FollowChannel(ctx context.Context, channelID, targetID Snowflake) error
- func (c *Client) Gateway(ctx context.Context) (string, error)
- func (c *Client) GatewayBot(ctx context.Context) (*GatewayInfo, error)
- func (c *Client) Guard() *Guard
- func (c *Client) Guild(ctx context.Context, guildID Snowflake) (*Guild, error)
- func (c *Client) GuildChannels(ctx context.Context, guildID Snowflake) ([]Channel, error)
- func (c *Client) GuildCommand(ctx context.Context, appID, guildID, commandID Snowflake) (*ApplicationCommand, error)
- func (c *Client) GuildCommandPermissions(ctx context.Context, appID, guildID, commandID Snowflake) (*GuildCommandPermissions, error)
- func (c *Client) GuildCommands(ctx context.Context, appID, guildID Snowflake) ([]ApplicationCommand, error)
- func (c *Client) GuildCommandsPermissions(ctx context.Context, appID, guildID Snowflake) ([]GuildCommandPermissions, error)
- func (c *Client) GuildEmoji(ctx context.Context, guildID, emojiID Snowflake) (*GuildEmoji, error)
- func (c *Client) GuildEmojis(ctx context.Context, guildID Snowflake) ([]GuildEmoji, error)
- func (c *Client) GuildInvites(ctx context.Context, guildID Snowflake) ([]Invite, error)
- func (c *Client) GuildJoinRequests(ctx context.Context, guildID Snowflake, status string, limit int) ([]GuildJoinRequest, error)
- func (c *Client) GuildMember(ctx context.Context, guildID, userID Snowflake) (*Member, error)
- func (c *Client) GuildPreview(ctx context.Context, guildID Snowflake) (*GuildPreview, error)
- func (c *Client) GuildSoundboardSound(ctx context.Context, guildID, soundID Snowflake) (*SoundboardSound, error)
- func (c *Client) GuildSoundboardSounds(ctx context.Context, guildID Snowflake) ([]SoundboardSound, error)
- func (c *Client) GuildSticker(ctx context.Context, guildID, stickerID Snowflake) (*Sticker, error)
- func (c *Client) GuildStickers(ctx context.Context, guildID Snowflake) ([]Sticker, error)
- func (c *Client) GuildTemplate(ctx context.Context, code string) (*GuildTemplate, error)
- func (c *Client) GuildTemplates(ctx context.Context, guildID Snowflake) ([]GuildTemplate, error)
- func (c *Client) GuildVoiceRegions(ctx context.Context, guildID Snowflake) ([]VoiceRegion, error)
- func (c *Client) GuildWebhooks(ctx context.Context, guildID Snowflake) ([]Webhook, error)
- func (c *Client) GuildWidgetImage(ctx context.Context, guildID Snowflake, style string) error
- func (c *Client) GuildWidgetImageURL(guildID Snowflake, style string) string
- func (c *Client) GuildWidgetJSON(ctx context.Context, guildID Snowflake) (*GuildWidgetJSON, error)
- func (c *Client) HandleGatewayFrame(ctx context.Context, frame []byte) error
- func (c *Client) IdentityProfile(ctx context.Context, appID, userID Snowflake, providerIssuedUserID string) (*IdentityProfile, error)
- func (c *Client) Integrations(ctx context.Context, guildID Snowflake) ([]Integration, error)
- func (c *Client) InteractionHandler(publicKey string) (http.Handler, error)
- func (c *Client) InvalidRequests() int
- func (c *Client) Invite(ctx context.Context, code string, withCounts bool) (*Invite, error)
- func (c *Client) InviteTargetUsers(ctx context.Context, code string, limit int, after Snowflake) ([]InviteTargetUser, error)
- func (c *Client) InviteTargetUsersJobStatus(ctx context.Context, code string) (*InviteTargetUsersJob, error)
- func (c *Client) JoinThread(ctx context.Context, threadID Snowflake) error
- func (c *Client) JoinVoice(ctx context.Context, guildID, channelID Snowflake, mute, deaf bool) error
- func (c *Client) Kick(ctx context.Context, guildID, userID Snowflake, reason string) error
- func (c *Client) LeaveGuild(ctx context.Context, guildID Snowflake) error
- func (c *Client) LeaveThread(ctx context.Context, threadID Snowflake) error
- func (c *Client) LeaveVoice(ctx context.Context, guildID Snowflake) error
- func (c *Client) Listen(handler any) func()
- func (c *Client) Lobby(ctx context.Context, lobbyID Snowflake) (*Lobby, error)
- func (c *Client) LobbyInviteForUser(ctx context.Context, lobbyID, userID Snowflake) (string, error)
- func (c *Client) Logger() *slog.Logger
- func (c *Client) LookupApplicationIdentity(ctx context.Context, appID Snowflake, ...) (*ApplicationIdentity, error)
- func (c *Client) Members(ctx context.Context, guildID Snowflake, q MembersQuery) ([]Member, error)
- func (c *Client) Message(ctx context.Context, channelID, messageID Snowflake) (*Message, error)
- func (c *Client) MessageHistory(ctx context.Context, channelID, before Snowflake) iter.Seq2[Message, error]
- func (c *Client) Messages(ctx context.Context, channelID Snowflake, q MessagesQuery) ([]Message, error)
- func (c *Client) Modal(pattern string, handler any) func()
- func (c *Client) ModifyApplicationEmoji(ctx context.Context, appID, emojiID Snowflake, name string) (*GuildEmoji, error)
- func (c *Client) ModifyAutomodRule(ctx context.Context, guildID, ruleID Snowflake, rule AutomodRule, ...) (*AutomodRule, error)
- func (c *Client) ModifyChannel(ctx context.Context, channelID Snowflake, params ChannelParams, reason string) (*Channel, error)
- func (c *Client) ModifyCurrentUser(ctx context.Context, username, avatar string) (*User, error)
- func (c *Client) ModifyGuild(ctx context.Context, guildID Snowflake, params GuildParams, reason string) (*Guild, error)
- func (c *Client) ModifyGuildEmoji(ctx context.Context, guildID, emojiID Snowflake, name string, ...) (*GuildEmoji, error)
- func (c *Client) ModifyGuildTemplate(ctx context.Context, guildID Snowflake, code, name, description string) (*GuildTemplate, error)
- func (c *Client) ModifyMember(ctx context.Context, guildID, userID Snowflake, m ModifyMember, reason string) (*Member, error)
- func (c *Client) ModifyRole(ctx context.Context, guildID, roleID Snowflake, params RoleParams, ...) (*Role, error)
- func (c *Client) ModifyScheduledEvent(ctx context.Context, guildID, eventID Snowflake, e ScheduledEvent, ...) (*ScheduledEvent, error)
- func (c *Client) ModifyScheduledEventException(ctx context.Context, guildID, eventID, exceptionID Snowflake, ...) (*ScheduledEventException, error)
- func (c *Client) ModifySoundboardSound(ctx context.Context, guildID, soundID Snowflake, s NewSoundboardSound, ...) (*SoundboardSound, error)
- func (c *Client) ModifyStageInstance(ctx context.Context, channelID Snowflake, topic, reason string) (*StageInstance, error)
- func (c *Client) ModifySticker(ctx context.Context, guildID, stickerID Snowflake, ...) (*Sticker, error)
- func (c *Client) ModifyWebhook(ctx context.Context, webhookID Snowflake, params WebhookParams, reason string) (*Webhook, error)
- func (c *Client) ModifyWebhookWithToken(ctx context.Context, webhookID Snowflake, token, name, avatar string) (*Webhook, error)
- func (c *Client) ModifyWelcomeScreen(ctx context.Context, guildID Snowflake, s WelcomeScreen, reason string) (*WelcomeScreen, error)
- func (c *Client) ModifyWidgetSettings(ctx context.Context, guildID Snowflake, s GuildWidgetSettings, reason string) (*GuildWidgetSettings, error)
- func (c *Client) MyPrivateArchivedThreads(ctx context.Context, channelID Snowflake, q ArchivedThreadsQuery) ([]Channel, bool, error)
- func (c *Client) NewMemberWelcome(ctx context.Context, guildID Snowflake) (*NewMemberWelcome, error)
- func (c *Client) OAuth2Keys(ctx context.Context) (map[string]any, error)
- func (c *Client) On(handler any)
- func (c *Client) OnComponent(customID string, fn SlashFunc) func()
- func (c *Client) OnModal(customID string, fn SlashFunc) func()
- func (c *Client) OnRaw(fn func(*RawEvent)) func()
- func (c *Client) Onboarding(ctx context.Context, guildID Snowflake) (*GuildOnboarding, error)
- func (c *Client) Online() bool
- func (c *Client) OriginalWebhookMessage(ctx context.Context, webhookID Snowflake, token string) (*Message, error)
- func (c *Client) Pacing() time.Duration
- func (c *Client) Pager(name string, render PageFunc) *Pager
- func (c *Client) PinMessage(ctx context.Context, channelID, messageID Snowflake, reason string) error
- func (c *Client) PinMessageV2(ctx context.Context, channelID, messageID Snowflake, reason string) error
- func (c *Client) PinnedMessages(ctx context.Context, channelID Snowflake, before string, limit int) (*MessagePins, error)
- func (c *Client) Pins(ctx context.Context, channelID Snowflake) ([]Message, error)
- func (c *Client) PollAnswerVoters(ctx context.Context, channelID, messageID Snowflake, answerID int, ...) ([]User, error)
- func (c *Client) Prefix() string
- func (c *Client) PrivateArchivedThreads(ctx context.Context, channelID Snowflake, q ArchivedThreadsQuery) ([]Channel, bool, error)
- func (c *Client) Prune(ctx context.Context, guildID Snowflake, days int, computeCount bool, ...) (int, error)
- func (c *Client) PruneCount(ctx context.Context, guildID Snowflake, days int, includeRoles []Snowflake) (int, error)
- func (c *Client) PublicArchivedThreads(ctx context.Context, channelID Snowflake, q ArchivedThreadsQuery) ([]Channel, bool, error)
- func (c *Client) PublishWidgetConfig(ctx context.Context, appID Snowflake, configID string) error
- func (c *Client) Purge(ctx context.Context, channelID Snowflake, opts PurgeOptions) (PurgeResult, error)
- func (c *Client) React(ctx context.Context, channelID, messageID Snowflake, emoji Emoji) error
- func (c *Client) Reactions(ctx context.Context, channelID, messageID Snowflake, emoji Emoji, ...) ([]User, error)
- func (c *Client) RegisterRoleConnectionMetadata(ctx context.Context, appID Snowflake, records []RoleConnectionMetadata) ([]RoleConnectionMetadata, error)
- func (c *Client) RemoveBan(ctx context.Context, guildID, userID Snowflake, reason string) error
- func (c *Client) RemoveGroupDMRecipient(ctx context.Context, channelID, userID Snowflake) error
- func (c *Client) RemoveInviteTargetUser(ctx context.Context, code string, userID Snowflake) error
- func (c *Client) RemoveLobbyMember(ctx context.Context, lobbyID, userID Snowflake) error
- func (c *Client) RemoveMemberRole(ctx context.Context, guildID, userID, roleID Snowflake, reason string) error
- func (c *Client) RemoveThreadMember(ctx context.Context, threadID, userID Snowflake) error
- func (c *Client) RemoveUserReaction(ctx context.Context, channelID, messageID, userID Snowflake, emoji Emoji) error
- func (c *Client) ReorderChannels(ctx context.Context, guildID Snowflake, positions []ChannelPosition, ...) error
- func (c *Client) ReorderRoles(ctx context.Context, guildID Snowflake, positions []RolePosition, ...) ([]Role, error)
- func (c *Client) Reply(ctx context.Context, channelID, messageID Snowflake, content string) (*Message, error)
- func (c *Client) Request(ctx context.Context, req RESTRequest, out any) error
- func (c *Client) RequestAllMembers(ctx context.Context, guildID Snowflake, nonce string) error
- func (c *Client) RequestChannelInfo(ctx context.Context, guildID Snowflake, fields ...ChannelInfoField) error
- func (c *Client) RequestMembers(ctx context.Context, req MemberRequest) error
- func (c *Client) RequestRaw(ctx context.Context, req RESTRequest) ([]byte, error)
- func (c *Client) RequestSoundboardSounds(ctx context.Context, guildIDs ...Snowflake) error
- func (c *Client) ResolveJoinRequest(ctx context.Context, guildID, requestID Snowflake, ...) error
- func (c *Client) Role(ctx context.Context, guildID, roleID Snowflake) (*Role, error)
- func (c *Client) RoleConnectionMetadataRecords(ctx context.Context, appID Snowflake) ([]RoleConnectionMetadata, error)
- func (c *Client) RoleMemberCounts(ctx context.Context, guildID Snowflake) (map[Snowflake]int, error)
- func (c *Client) Roles(ctx context.Context, guildID Snowflake) ([]Role, error)
- func (c *Client) Run() error
- func (c *Client) RunContext(ctx context.Context) error
- func (c *Client) SKUs(ctx context.Context, appID Snowflake) ([]SKU, error)
- func (c *Client) ScheduledEvent(ctx context.Context, guildID, eventID Snowflake, withUserCount bool) (*ScheduledEvent, error)
- func (c *Client) ScheduledEventExceptionUsers(ctx context.Context, guildID, eventID, exceptionID Snowflake, ...) ([]ScheduledEventUser, error)
- func (c *Client) ScheduledEventUserCounts(ctx context.Context, guildID, eventID Snowflake) (map[string]int, error)
- func (c *Client) ScheduledEventUsers(ctx context.Context, guildID, eventID Snowflake, limit int, withMember bool) ([]ScheduledEventUser, error)
- func (c *Client) ScheduledEvents(ctx context.Context, guildID Snowflake, withUserCount bool) ([]ScheduledEvent, error)
- func (c *Client) SearchGuildMessages(ctx context.Context, guildID Snowflake, params url.Values) (*MessageSearchResult, error)
- func (c *Client) SearchMembers(ctx context.Context, guildID Snowflake, name string, limit int) ([]Member, error)
- func (c *Client) SearchThreads(ctx context.Context, channelID Snowflake, params url.Values) (*ThreadSearchResult, error)
- func (c *Client) Self() *User
- func (c *Client) Send(ctx context.Context, channelID Snowflake, content string) (*Message, error)
- func (c *Client) SendComplex(ctx context.Context, channelID Snowflake, data SendData) (*Message, error)
- func (c *Client) SendDM(ctx context.Context, userID Snowflake, content string) (*Message, error)
- func (c *Client) SendFiles(ctx context.Context, channelID Snowflake, data SendData, files ...File) (*Message, error)
- func (c *Client) SendGateway(ctx context.Context, op Opcode, data any) error
- func (c *Client) SendGatewayRaw(ctx context.Context, frame []byte) error
- func (c *Client) SendGuildGateway(ctx context.Context, guildID Snowflake, op Opcode, data any) error
- func (c *Client) SendGuildGatewayRaw(ctx context.Context, guildID Snowflake, frame []byte) error
- func (c *Client) SendSoundboardSound(ctx context.Context, channelID, soundID, sourceGuildID Snowflake) error
- func (c *Client) SetActivity(ctx context.Context, status Status, activity Activity) error
- func (c *Client) SetApplicationCommands(ctx context.Context, appID Snowflake, cmds []ApplicationCommand) ([]ApplicationCommand, error)
- func (c *Client) SetCurrentVoiceState(ctx context.Context, guildID, channelID Snowflake, suppress bool, ...) error
- func (c *Client) SetGuildCommandPermissions(ctx context.Context, bearerToken string, appID, guildID, commandID Snowflake, ...) (*GuildCommandPermissions, error)
- func (c *Client) SetGuildCommands(ctx context.Context, appID, guildID Snowflake, cmds []ApplicationCommand) ([]ApplicationCommand, error)
- func (c *Client) SetIdentityProfile(ctx context.Context, appID, userID Snowflake, providerIssuedUserID string, ...) (*IdentityProfile, error)
- func (c *Client) SetIncidentActions(ctx context.Context, guildID Snowflake, ...) error
- func (c *Client) SetInviteTargetUsers(ctx context.Context, code string, userIDs []Snowflake) error
- func (c *Client) SetNickname(ctx context.Context, guildID Snowflake, nick string) error
- func (c *Client) SetOnboarding(ctx context.Context, guildID Snowflake, o GuildOnboarding, reason string) (*GuildOnboarding, error)
- func (c *Client) SetPermissionOverwrite(ctx context.Context, channelID, overwriteID Snowflake, allow, deny Permissions, ...) error
- func (c *Client) SetStatus(ctx context.Context, status Status) error
- func (c *Client) SetVoiceState(ctx context.Context, guildID, userID, channelID Snowflake, suppress bool) error
- func (c *Client) SetVoiceStatus(ctx context.Context, channelID Snowflake, status string) error
- func (c *Client) ShardCount() int
- func (c *Client) ShardIDForGuild(guildID Snowflake) int
- func (c *Client) ShardStatuses() []ShardStatus
- func (c *Client) Slash(name, description string, handler any, options ...CommandOption) *SlashRoute
- func (c *Client) SlashCommand(cmd ApplicationCommand, fn SlashFunc) *SlashRoute
- func (c *Client) SlashDefinitions() []ApplicationCommand
- func (c *Client) SlashTask(name, description string, fn TaskFunc, options ...CommandOption) *SlashRoute
- func (c *Client) Social(accessToken string) *SocialClient
- func (c *Client) StageInstance(ctx context.Context, channelID Snowflake) (*StageInstance, error)
- func (c *Client) Starlog() *Starlog
- func (c *Client) StartThread(ctx context.Context, channelID Snowflake, params ThreadParams, reason string) (*Channel, error)
- func (c *Client) StartThreadFromMessage(ctx context.Context, channelID, messageID Snowflake, params ThreadParams, ...) (*Channel, error)
- func (c *Client) Sticker(ctx context.Context, stickerID Snowflake) (*Sticker, error)
- func (c *Client) StickerPack(ctx context.Context, packID Snowflake) (*StickerPack, error)
- func (c *Client) StickerPacks(ctx context.Context) ([]StickerPack, error)
- func (c *Client) Subscription(ctx context.Context, skuID, subscriptionID Snowflake) (*Subscription, error)
- func (c *Client) Subscriptions(ctx context.Context, skuID Snowflake, q SubscriptionsQuery) ([]Subscription, error)
- func (c *Client) SyncCommands(ctx context.Context, guildID Snowflake) error
- func (c *Client) SyncGuildTemplate(ctx context.Context, guildID Snowflake, code string) (*GuildTemplate, error)
- func (c *Client) ThreadMember(ctx context.Context, threadID, userID Snowflake, withMember bool) (*ThreadMember, error)
- func (c *Client) ThreadMembers(ctx context.Context, threadID Snowflake, withMember bool) ([]ThreadMember, error)
- func (c *Client) Timeout(ctx context.Context, guildID, userID Snowflake, until time.Time, reason string) (*Member, error)
- func (c *Client) Typing(ctx context.Context, channelID Snowflake) error
- func (c *Client) UnmergeBotProvisionalAccount(ctx context.Context, externalUserID string) error
- func (c *Client) UnmergeProvisionalAccount(ctx context.Context, credentials ProvisionalCredentials) error
- func (c *Client) UnpinMessage(ctx context.Context, channelID, messageID Snowflake, reason string) error
- func (c *Client) UnpinMessageV2(ctx context.Context, channelID, messageID Snowflake, reason string) error
- func (c *Client) Unreact(ctx context.Context, channelID, messageID Snowflake, emoji Emoji) error
- func (c *Client) UpdateDirectMessageModeration(ctx context.Context, user1, user2, messageID Snowflake, ...) error
- func (c *Client) UpdateLobbyMessageModeration(ctx context.Context, lobbyID, messageID Snowflake, metadata map[string]string) error
- func (c *Client) UpdatePresence(ctx context.Context, p Presence) error
- func (c *Client) UpdateScheduledEvent(ctx context.Context, guildID, eventID Snowflake, update ScheduledEventUpdate, ...) (*ScheduledEvent, error)
- func (c *Client) UpdateUserRoleConnection(ctx context.Context, bearerToken string, appID Snowflake, conn RoleConnection) (*RoleConnection, error)
- func (c *Client) UpdateWidgetConfig(ctx context.Context, appID Snowflake, configID string, ...) (*WidgetConfig, error)
- func (c *Client) UploadActivityAttachment(ctx context.Context, appID Snowflake, file File) (*AttachmentUpload, error)
- func (c *Client) User(ctx context.Context, userID Snowflake) (*User, error)
- func (c *Client) UserApplicationIdentities(ctx context.Context, userID, appID Snowflake) ([]ApplicationIdentity, error)
- func (c *Client) UserConnections(ctx context.Context) ([]Connection, error)
- func (c *Client) UserEntitlements(ctx context.Context, bearerToken string, appID Snowflake) ([]Entitlement, error)
- func (c *Client) UserInfo(ctx context.Context, bearerToken string) (*OpenIDUserInfo, error)
- func (c *Client) UserRoleConnection(ctx context.Context, bearerToken string, appID Snowflake) (*RoleConnection, error)
- func (c *Client) VanityURL(ctx context.Context, guildID Snowflake) (*VanityURL, error)
- func (c *Client) VoiceRegions(ctx context.Context) ([]VoiceRegion, error)
- func (c *Client) VoiceStateOf(ctx context.Context, guildID, userID Snowflake) (*VoiceState, error)
- func (c *Client) WaitReady(ctx context.Context) error
- func (c *Client) Webhook(ctx context.Context, webhookID Snowflake) (*Webhook, error)
- func (c *Client) WebhookMessageByID(ctx context.Context, webhookID Snowflake, token string, messageID Snowflake) (*Message, error)
- func (c *Client) WebhookWithToken(ctx context.Context, webhookID Snowflake, token string) (*Webhook, error)
- func (c *Client) WelcomeScreen(ctx context.Context, guildID Snowflake) (*WelcomeScreen, error)
- func (c *Client) WidgetConfigs(ctx context.Context, appID Snowflake) ([]WidgetConfig, error)
- func (c *Client) WidgetSettings(ctx context.Context, guildID Snowflake) (*GuildWidgetSettings, error)
- type ClientIdentity
- type CloseCode
- type CommandChoice
- type CommandFunc
- type CommandOption
- func BoolOption(name, description string, required bool) CommandOption
- func ChannelOption(name, description string, required bool) CommandOption
- func IntOption(name, description string, required bool) CommandOption
- func RoleOption(name, description string, required bool) CommandOption
- func StringOption(name, description string, required bool) CommandOption
- func UserOption(name, description string, required bool) CommandOption
- type CommandPermission
- type CommandRoute
- type Component
- func AccentContainer(color int, components ...Component) Component
- func ActionRow(components ...Component) Component
- func Button(style ButtonStyle, label, customID string) Component
- func Checkbox(customID string, checked bool) Component
- func CheckboxGroup(customID string, options ...SelectOption) Component
- func Container(components ...Component) Component
- func EntitySelect(kind ComponentType, customID string) Component
- func FileDisplay(filename string) Component
- func FileUpload(customID string, required bool) Component
- func Label(label, description string, input Component) Component
- func LinkButton(label, url string) Component
- func MediaGallery(items ...MediaGalleryItem) Component
- func PremiumButton(skuID Snowflake) Component
- func RadioGroup(customID string, options ...SelectOption) Component
- func Section(accessory Component, text ...Component) Component
- func Separator(divider bool, spacing SeparatorSpacing) Component
- func StringSelect(customID string, options ...SelectOption) Component
- func TextDisplay(content string) Component
- func TextInput(style TextInputStyle, customID, placeholder string, required bool) Component
- func Thumbnail(url, description string) Component
- type ComponentType
- type Connect
- type Connection
- type CurrentApplication
- type CurrentUserGuildsQuery
- type Disconnect
- type DynamicField
- type DynamicFieldType
- type Embed
- func (e *Embed) AddField(name, value string, inline bool) *Embed
- func (e *Embed) SetAuthor(name, url, iconURL string) *Embed
- func (e *Embed) SetColor(color int) *Embed
- func (e *Embed) SetDescription(text string) *Embed
- func (e *Embed) SetFooter(text, iconURL string) *Embed
- func (e *Embed) SetImage(url string) *Embed
- func (e *Embed) SetThumbnail(url string) *Embed
- func (e *Embed) SetTimestamp(t time.Time) *Embed
- func (e *Embed) SetURL(url string) *Embed
- type EmbedAuthor
- type EmbedField
- type EmbedFooter
- type EmbedMedia
- type EmbedProvider
- type Emoji
- type Entitlement
- type EntitlementCreate
- type EntitlementDelete
- type EntitlementType
- type EntitlementUpdate
- type EntitlementsQuery
- type EntryPointHandlerType
- type Event
- type EventWaiter
- type ExternalAuthType
- type FatalError
- type FieldError
- type File
- type ForumReaction
- type ForumTag
- type GatewayCloseError
- type GatewayInfo
- type Guard
- type GuardAdvice
- type GuardFinding
- type GuardImplementation
- type GuardMetric
- type GuardOption
- type GuardReport
- type GuardRuntime
- type Guild
- func (g *Guild) Ban(userID Snowflake, reason string, deleteHistory time.Duration) error
- func (g *Guild) IconURL(size int) string
- func (g *Guild) Member(userID Snowflake) (*Member, error)
- func (g *Guild) Role(id Snowflake) *Role
- func (g *Guild) Unban(userID Snowflake, reason string) error
- func (g *Guild) WithContext(ctx context.Context) *Guild
- type GuildAuditLogEntryCreate
- type GuildBanAdd
- type GuildBanRemove
- type GuildCommandPermissions
- type GuildCreate
- type GuildDelete
- type GuildEmoji
- type GuildEmojisUpdate
- type GuildIntegrationsUpdate
- type GuildJoinRequest
- type GuildMemberAdd
- type GuildMemberRemove
- type GuildMemberUpdate
- type GuildMembersChunk
- type GuildOnboarding
- type GuildParams
- type GuildPreview
- type GuildProductPurchase
- type GuildRoleCreate
- type GuildRoleDelete
- type GuildRoleUpdate
- type GuildScheduledEventCreate
- type GuildScheduledEventDelete
- type GuildScheduledEventUpdate
- type GuildScheduledEventUserAdd
- type GuildScheduledEventUserRemove
- type GuildSoundboardSoundCreate
- type GuildSoundboardSoundDelete
- type GuildSoundboardSoundUpdate
- type GuildSoundboardSoundsUpdate
- type GuildStickersUpdate
- type GuildTemplate
- type GuildUpdate
- type GuildWidgetJSON
- type GuildWidgetSettings
- type HandlerFunc
- type IdentityProfile
- type Integration
- type IntegrationCreate
- type IntegrationDelete
- type IntegrationUpdate
- type Intent
- type Interaction
- type InteractionContextType
- type InteractionCreate
- func (i *InteractionCreate) Answered() bool
- func (i *InteractionCreate) AttachmentOption(name string) *Attachment
- func (i *InteractionCreate) Autocomplete(choices ...CommandChoice) error
- func (i *InteractionCreate) Bool(name string) bool
- func (i *InteractionCreate) ChannelOption(name string) *Channel
- func (e *InteractionCreate) Client() *Client
- func (i *InteractionCreate) Defer(ephemeral bool) error
- func (i *InteractionCreate) DeferUpdate() error
- func (i *InteractionCreate) Deferred() bool
- func (i *InteractionCreate) DeleteFollowup(ctx context.Context, messageID Snowflake) error
- func (i *InteractionCreate) DeleteResponse(ctx context.Context) error
- func (i *InteractionCreate) EditFollowup(ctx context.Context, messageID Snowflake, data InteractionResponseData) (*Message, error)
- func (i *InteractionCreate) EditFollowupFiles(ctx context.Context, messageID Snowflake, data InteractionResponseData, ...) (*Message, error)
- func (i *InteractionCreate) EditResponse(ctx context.Context, data InteractionResponseData) (*Message, error)
- func (i *InteractionCreate) EditResponseFiles(ctx context.Context, data InteractionResponseData, files ...File) (*Message, error)
- func (i *InteractionCreate) Float(name string) float64
- func (i *InteractionCreate) Focused() *InteractionOption
- func (i *InteractionCreate) Followup(ctx context.Context, data InteractionResponseData) (*Message, error)
- func (i *InteractionCreate) FollowupFiles(ctx context.Context, data InteractionResponseData, files ...File) (*Message, error)
- func (i *InteractionCreate) FollowupMessage(ctx context.Context, messageID Snowflake) (*Message, error)
- func (i *InteractionCreate) Int(name string) int64
- func (i *InteractionCreate) MemberOption(name string) *Member
- func (i *InteractionCreate) Modal(customID, title string, components ...Component) error
- func (i *InteractionCreate) OptionID(name string) Snowflake
- func (i *InteractionCreate) Param(name string) string
- func (i *InteractionCreate) ParamID(name string) Snowflake
- func (i *InteractionCreate) ParamInt(name string) int64
- func (i *InteractionCreate) Reply(content string) error
- func (i *InteractionCreate) ReplyComplex(data InteractionResponseData) error
- func (i *InteractionCreate) ReplyContext(ctx context.Context, content string) error
- func (i *InteractionCreate) ReplyEmbed(e *Embed) error
- func (i *InteractionCreate) ReplyEmbedEphemeral(e *Embed) error
- func (i *InteractionCreate) ReplyEphemeral(content string) error
- func (i *InteractionCreate) ReplyEphemeralContext(ctx context.Context, content string) error
- func (i *InteractionCreate) ReplyFiles(data InteractionResponseData, files ...File) error
- func (i *InteractionCreate) Respond(ctx context.Context, resp InteractionResponse) error
- func (i *InteractionCreate) RespondFiles(ctx context.Context, resp InteractionResponse, files ...File) error
- func (i *InteractionCreate) Response(ctx context.Context) (*Message, error)
- func (i *InteractionCreate) RoleOption(name string) *Role
- func (i *InteractionCreate) String(name string) string
- func (i *InteractionCreate) TextValue(customID string) string
- func (i *InteractionCreate) UpdateMessage(data InteractionResponseData) error
- func (i *InteractionCreate) UpdateMessageFiles(data InteractionResponseData, files ...File) error
- func (i *InteractionCreate) UserOption(name string) *User
- type InteractionData
- type InteractionOption
- type InteractionResponse
- type InteractionResponseData
- type InteractionType
- type Invite
- type InviteCreate
- type InviteDelete
- type InviteParams
- type InviteTargetUser
- type InviteTargetUsersJob
- type Lobby
- type LobbyCreate
- type LobbyEdit
- type LobbyFlags
- type LobbyJoin
- type LobbyMember
- type LobbyMemberFlags
- type LobbyMemberInput
- type LobbyMessage
- type LobbyMessageData
- type Media
- type MediaGalleryItem
- type Member
- func (m *Member) AddRole(roleID Snowflake, reason string) error
- func (m *Member) AvatarURL(guildID Snowflake, size int) string
- func (m *Member) Ban(reason string, deleteHistory time.Duration) error
- func (m *Member) CanModerate(target *Member) error
- func (m *Member) ClearTimeout(reason string) error
- func (m *Member) DisplayName() string
- func (m *Member) GuildID() Snowflake
- func (m *Member) Kick(reason string) error
- func (m *Member) Mention() string
- func (m *Member) RemoveRole(roleID Snowflake, reason string) error
- func (m *Member) Send(content string) (*Message, error)
- func (m *Member) SendComplex(data SendData) (*Message, error)
- func (m *Member) SendEmbed(e *Embed) (*Message, error)
- func (m *Member) SetNick(nick, reason string) error
- func (m *Member) TimedOut() bool
- func (m *Member) Timeout(d time.Duration, reason string) error
- func (m *Member) WithContext(ctx context.Context) *Member
- type MemberRequest
- type MembersQuery
- type Mentionable
- type Message
- func (msg *Message) Delete() error
- func (msg *Message) Edit(content string) (*Message, error)
- func (msg *Message) Link() string
- func (msg *Message) Pin(reason string) error
- func (msg *Message) React(emoji string) error
- func (msg *Message) Reply(content string) (*Message, error)
- func (msg *Message) ReplyComplex(data SendData) (*Message, error)
- func (msg *Message) ReplyEmbed(e *Embed) (*Message, error)
- func (msg *Message) Unpin(reason string) error
- func (msg *Message) Unreact(emoji string) error
- func (msg *Message) WithContext(ctx context.Context) *Message
- type MessageActivity
- type MessageActivityType
- type MessageApplication
- type MessageCallInfo
- type MessageCreate
- func (e *MessageCreate) Client() *Client
- func (m *MessageCreate) Delete() error
- func (m *MessageCreate) IsFromBot() bool
- func (m *MessageCreate) IsFromSelf() bool
- func (m *MessageCreate) React(emoji string) error
- func (m *MessageCreate) Reply(content string) (*Message, error)
- func (m *MessageCreate) ReplyComplex(data SendData) (*Message, error)
- func (m *MessageCreate) ReplyFiles(data SendData, files ...File) (*Message, error)
- func (m *MessageCreate) Send(content string) (*Message, error)
- type MessageDelete
- type MessageDeleteBulk
- type MessageFlags
- type MessageInteraction
- type MessageInteractionMetadata
- type MessageLobbyMember
- type MessagePin
- type MessagePins
- type MessagePollVoteAdd
- type MessagePollVoteRemove
- type MessageReactionAdd
- type MessageReactionRemove
- type MessageReactionRemoveAll
- type MessageReactionRemoveEmoji
- type MessageRef
- type MessageReferenceType
- type MessageSearchResult
- type MessageSnapshot
- type MessageType
- type MessageUpdate
- type MessagesQuery
- type MetadataType
- type ModerationDenial
- type ModerationError
- type ModifyMember
- type NewMemberWelcome
- type NewSoundboardSound
- type OAuth2Authorization
- type OnboardingOption
- type OnboardingPrompt
- type Opcode
- type OpenIDUserInfo
- type Option
- func Explicit() Option
- func WithAsyncEvents(enabled bool) Option
- func WithAutoDefer(after time.Duration) Option
- func WithAutoSharding(enabled bool) Option
- func WithAutoSync(enabled bool) Option
- func WithCommandSync(guildID Snowflake) Option
- func WithGatewayCompression(enabled bool) Option
- func WithGlobalRateLimit(perSecond int) Option
- func WithGuard(options ...GuardOption) Option
- func WithHTTPClient(h *http.Client) Option
- func WithIdentity(id ClientIdentity) Option
- func WithIntents(i Intent) Option
- func WithLogger(l *slog.Logger) Option
- func WithMemberChunking(enabled bool) Option
- func WithMemoryTrim(enabled bool) Option
- func WithPacing(gap time.Duration) Option
- func WithPanicRecovery(enabled bool) Option
- func WithPrefix(prefix string) Option
- func WithRequestTimeout(d time.Duration) Option
- func WithShard(id, total int) Option
- func WithStarlog(log *Starlog) Option
- func WithStateCache(config StateConfig) Option
- func WithStateMode(mode StateMode) Option
- func WithStatus(status Status, activity Activity) Option
- func WithTaskConcurrency(limit int) Option
- func WithToken(token string) Option
- type OptionType
- type Overwrite
- type Page
- type PageFunc
- type Pager
- type Permissions
- func (p Permissions) Add(other Permissions) Permissions
- func (p Permissions) Has(other Permissions) bool
- func (p Permissions) HumanString() string
- func (p Permissions) Missing(required Permissions) Permissions
- func (p Permissions) Names() []string
- func (p Permissions) Remove(other Permissions) Permissions
- func (p Permissions) String() string
- type Poll
- type PollAnswer
- type PollAnswerCount
- type PollLayoutType
- type PollMedia
- type PollResults
- type PollVotersQuery
- type Presence
- type PresenceUpdate
- type PresencesReplace
- type PrimaryProfileData
- type ProfileData
- type ProvisionalCredentials
- type ProvisionalToken
- type PurchaseNotification
- type PurgeOptions
- type PurgeResult
- type RESTRequest
- type RateLimit
- type RateLimitError
- type RateLimitWait
- type RateLimited
- type RawEvent
- type Reaction
- type ReactionCountDetails
- type ReactionsQuery
- type Ready
- type ResolvedData
- type Response
- type Resumed
- type Role
- type RoleConnection
- type RoleConnectionMetadata
- type RoleParams
- type RolePosition
- type RoleSubscriptionData
- type SKU
- type SKUFlags
- type SKUType
- type ScheduledEvent
- type ScheduledEventException
- type ScheduledEventMetadata
- type ScheduledEventUpdate
- type ScheduledEventUser
- type SelectDefaultValue
- type SelectOption
- type SendData
- type Sendable
- type SeparatorSpacing
- type ShardStatus
- type SharedClientTheme
- type SlashFunc
- type SlashRoute
- func (r *SlashRoute) Autocomplete(fn SlashFunc) *SlashRoute
- func (r *SlashRoute) BotNeeds(permissions Permissions) *SlashRoute
- func (r *SlashRoute) Contexts(contexts ...InteractionContextType) *SlashRoute
- func (r *SlashRoute) Ephemeral() *SlashRoute
- func (r *SlashRoute) GuildOnly() *SlashRoute
- func (r *SlashRoute) InstallTypes(types ...ApplicationIntegrationType) *SlashRoute
- func (r *SlashRoute) NoAutoDefer() *SlashRoute
- func (r *SlashRoute) Permissions(permissions Permissions) *SlashRoute
- func (r *SlashRoute) Require(permissions Permissions) *SlashRoute
- func (r *SlashRoute) Run(fn HandlerFunc) *SlashRoute
- func (r *SlashRoute) Timeout(timeout time.Duration) *SlashRoute
- type Snowflake
- func (s Snowflake) IsZero() bool
- func (s Snowflake) MarshalJSON() ([]byte, error)
- func (s Snowflake) MarshalJSONTo(enc *jsontext.Encoder) error
- func (s Snowflake) MarshalText() ([]byte, error)
- func (s *Snowflake) Scan(src any) error
- func (s Snowflake) String() string
- func (s Snowflake) Time() time.Time
- func (s *Snowflake) UnmarshalJSON(b []byte) error
- func (s *Snowflake) UnmarshalJSONFrom(dec *jsontext.Decoder) error
- func (s *Snowflake) UnmarshalText(b []byte) error
- func (s Snowflake) Value() (driver.Value, error)
- type SocialClient
- func (s *SocialClient) CreateOrJoinLobby(ctx context.Context, data LobbyJoin) (*Lobby, error)
- func (s *SocialClient) LeaveLobby(ctx context.Context, lobbyID Snowflake) error
- func (s *SocialClient) LinkLobbyChannel(ctx context.Context, lobbyID, channelID Snowflake) (*Lobby, error)
- func (s *SocialClient) LobbyInvite(ctx context.Context, lobbyID Snowflake) (string, error)
- func (s *SocialClient) LobbyMessages(ctx context.Context, lobbyID Snowflake, limit int) ([]LobbyMessage, error)
- func (s *SocialClient) SendLobbyMessage(ctx context.Context, lobbyID Snowflake, content string) (*LobbyMessage, error)
- func (s *SocialClient) SendLobbyMessageComplex(ctx context.Context, lobbyID Snowflake, data LobbyMessageData) (*LobbyMessage, error)
- func (s *SocialClient) UnlinkLobbyChannel(ctx context.Context, lobbyID Snowflake) (*Lobby, error)
- type SoundboardSound
- type SoundboardSounds
- type StageInstance
- type StageInstanceCreate
- type StageInstanceDelete
- type StageInstanceUpdate
- type StarPetVariant
- type Starlog
- func (s *Starlog) Active() bool
- func (s *Starlog) AddSink(sink *StarlogSink) (remove func())
- func (s *Starlog) Attach(c *Client)
- func (s *Starlog) Build(message string, args ...any)
- func (s *Starlog) BuildWriter(source string) io.WriteCloser
- func (s *Starlog) Close() error
- func (s *Starlog) Debug(message string, args ...any)
- func (s *Starlog) Error(message string, args ...any)
- func (s *Starlog) Errors(output io.Writer, options ...StarlogSinkOption) *StarlogSink
- func (s *Starlog) FollowLogs()
- func (s *Starlog) FollowPlayback(source StarlogPlaybackSource)
- func (s *Starlog) Info(message string, args ...any)
- func (s *Starlog) Log(ctx context.Context, level slog.Level, message string, args ...any)
- func (s *Starlog) Logger() *slog.Logger
- func (s *Starlog) Metrics() StarlogMetrics
- func (s *Starlog) Scroll(lines int)
- func (s *Starlog) ScrollOffset() int
- func (s *Starlog) SetLevel(level slog.Level)
- func (s *Starlog) Snapshot() []StarlogEntry
- func (s *Starlog) Start(ctx context.Context) bool
- func (s *Starlog) Styled(output io.Writer, color int, options ...StarlogSinkOption) *StarlogSink
- func (s *Starlog) Warn(message string, args ...any)
- func (s *Starlog) Warnings(output io.Writer, options ...StarlogSinkOption) *StarlogSink
- func (s *Starlog) Write(p []byte) (int, error)
- func (s *Starlog) Writer(level slog.Level, source string) io.WriteCloser
- type StarlogColorPolicy
- type StarlogEntry
- type StarlogField
- type StarlogFrame
- type StarlogMediaReader
- type StarlogMetrics
- type StarlogMood
- type StarlogOption
- func StarlogColor(enabled bool) StarlogOption
- func StarlogDashboard() StarlogOption
- func StarlogHistory(entries int) StarlogOption
- func StarlogMediaSource(open func() (StarlogMediaReader, error)) StarlogOption
- func StarlogNoPets() StarlogOption
- func StarlogOutput(w io.Writer) StarlogOption
- func StarlogRefresh(period time.Duration) StarlogOption
- func StarlogStreamArt(enabled bool) StarlogOption
- func StarlogStreaming() StarlogOption
- func StarlogTUI(enabled bool) StarlogOption
- func StarlogWithPet(pet StarlogPet) StarlogOption
- func StarlogWithPets(pets ...StarlogPet) StarlogOption
- func StarlogWithPlayback(source StarlogPlaybackSource) StarlogOption
- type StarlogPet
- type StarlogPlayback
- type StarlogPlaybackSource
- type StarlogSink
- type StarlogSinkOption
- func StarlogSinkArt(enabled bool) StarlogSinkOption
- func StarlogSinkColor(color int) StarlogSinkOption
- func StarlogSinkColorPolicy(policy StarlogColorPolicy) StarlogSinkOption
- func StarlogSinkLevels(minimum, maximum slog.Level) StarlogSinkOption
- func StarlogSinkMinLevel(level slog.Level) StarlogSinkOption
- func StarlogSinkPet(pet StarlogPet) StarlogSinkOption
- type StarlogSpriteSheet
- type State
- func (s *State) Apply(event Event) (err error)
- func (s *State) BasePermissions(guildID, userID Snowflake) (value Permissions, err error)
- func (s *State) CanModerate(guildID, actorID, targetID Snowflake) error
- func (s *State) Channel(id Snowflake) (value Channel, ok bool)
- func (s *State) ChannelPermissions(channelID, userID Snowflake) (value Permissions, err error)
- func (s *State) Channels() []Channel
- func (s *State) Config() StateConfig
- func (s *State) Emoji(guildID, emojiID Snowflake) (value GuildEmoji, ok bool)
- func (s *State) Emojis(guildID Snowflake) (out []GuildEmoji)
- func (s *State) Guild(id Snowflake) (value Guild, ok bool)
- func (s *State) GuildInfo(id Snowflake) (value Guild, ok bool)
- func (s *State) Guilds() []Guild
- func (s *State) Member(guildID, userID Snowflake) (value Member, ok bool)
- func (s *State) MemberCount(guildID Snowflake) (count int)
- func (s *State) Members(guildID Snowflake) []Member
- func (s *State) Message(channelID, messageID Snowflake) (value Message, ok bool)
- func (s *State) MessageColor(message *Message) (int, error)
- func (s *State) MessagePermissions(message *Message) (Permissions, error)
- func (s *State) Messages(channelID Snowflake) (out []Message)
- func (s *State) Mode() StateMode
- func (s *State) Permissions(guildID, channelID, userID Snowflake) (value Permissions, err error)
- func (s *State) Presence(guildID, userID Snowflake) (value PresenceUpdate, ok bool)
- func (s *State) Presences(guildID Snowflake) []PresenceUpdate
- func (s *State) Role(guildID, roleID Snowflake) (value Role, ok bool)
- func (s *State) Roles(guildID Snowflake) []Role
- func (s *State) Stats() StateStats
- func (s *State) Sticker(guildID, stickerID Snowflake) (value Sticker, ok bool)
- func (s *State) Stickers(guildID Snowflake) (out []Sticker)
- func (s *State) ThreadMember(threadID, userID Snowflake) (value ThreadMember, ok bool)
- func (s *State) ThreadMembers(threadID Snowflake) (out []ThreadMember)
- func (s *State) User(id Snowflake) (value User, ok bool)
- func (s *State) UserColor(guildID, userID Snowflake) (value int, err error)
- func (s *State) Users() []User
- func (s *State) VoiceState(guildID, userID Snowflake) (value VoiceState, ok bool)
- func (s *State) VoiceStates(guildID Snowflake) (out []VoiceState)
- type StateConfig
- type StateMode
- type StateStats
- type Status
- type Sticker
- type StickerItem
- type StickerPack
- type Subscription
- type SubscriptionCreate
- type SubscriptionDelete
- type SubscriptionStatus
- type SubscriptionUpdate
- type SubscriptionsQuery
- type TaskFunc
- type TextInputStyle
- type ThreadCreate
- type ThreadDelete
- type ThreadListSync
- type ThreadMember
- type ThreadMemberUpdate
- type ThreadMembersUpdate
- type ThreadMeta
- type ThreadParams
- type ThreadSearchResult
- type ThreadUpdate
- type TypingStart
- type UnfurledMedia
- type User
- func (u *User) AvatarURL(size int) string
- func (u *User) Mention() string
- func (u *User) Send(content string) (*Message, error)
- func (u *User) SendComplex(data SendData) (*Message, error)
- func (u *User) SendEmbed(e *Embed) (*Message, error)
- func (u *User) Tag() string
- func (u *User) WithContext(ctx context.Context) *User
- type UserError
- type UserUpdate
- type VanityURL
- type VoiceChannelEffectSend
- type VoiceChannelStartTimeUpdate
- type VoiceChannelStatusUpdate
- type VoiceRegion
- type VoiceServerUpdate
- type VoiceState
- type VoiceStateUpdate
- type Webhook
- type WebhookMessage
- type WebhookParams
- type WebhookType
- type WebhooksUpdate
- type WelcomeScreen
- type WelcomeScreenChannel
- type WidgetAsset
- type WidgetComponent
- type WidgetConfig
- type WidgetField
- type WidgetStat
- type WidgetSurface
Constants ¶
const ( CommandPermissionRole = 1 CommandPermissionUser = 2 CommandPermissionChannel = 3 )
CommandPermissionType says what a permission override applies to.
const ( TriggerKeyword = 1 // custom words and patterns TriggerSpam = 4 // Discord's own spam detection TriggerKeywordPreset = 5 // Discord's curated word lists TriggerMentionSpam = 6 // too many mentions in one message TriggerMemberProfile = 7 // matches in usernames and bios )
AutomodTriggerType says what an auto-moderation rule watches for.
const ( EventMessageSend = 1 EventMemberUpdate = 2 )
AutomodEventType says when a rule is evaluated.
const ( ActionBlockMessage = 1 ActionSendAlertMessage = 2 ActionTimeout = 3 ActionBlockInteraction = 4 )
AutomodActionType is what happens when a rule matches.
const ( PresetProfanity = 1 PresetSexualContent = 2 PresetSlurs = 3 )
Keyword preset lists Discord maintains.
const ( OverwriteRole = 0 OverwriteMember = 1 )
OverwriteType distinguishes a role overwrite from a member one.
const ( ColorBlurple = 0x5865F2 ColorGreen = 0x57F287 ColorYellow = 0xFEE75C ColorRed = 0xED4245 ColorFuchsia = 0xEB459E ColorGrey = 0x99AAB5 )
Colours for Embed.Color, matching Discord's own palette.
const ( ErrorUnknownAccount = 10001 ErrorUnknownApplication = 10002 ErrorUnknownChannel = 10003 ErrorUnknownGuild = 10004 ErrorUnknownIntegration = 10005 ErrorUnknownInvite = 10006 ErrorUnknownMember = 10007 ErrorUnknownMessage = 10008 ErrorUnknownPermissionOverwrite = 10009 ErrorUnknownProvider = 10010 ErrorUnknownRole = 10011 ErrorUnknownToken = 10012 ErrorUnknownUser = 10013 ErrorUnknownEmoji = 10014 ErrorUnknownWebhook = 10015 ErrorUnknownBan = 10026 ErrorUnknownInteraction = 10062 ErrorUnknownScheduledEvent = 10070 ErrorMaximumGuilds = 30001 ErrorMaximumFriends = 30002 ErrorMaximumPins = 30003 ErrorMaximumRecipients = 30004 ErrorMaximumGuildRoles = 30005 ErrorMaximumWebhooks = 30007 ErrorMaximumEmojis = 30008 ErrorMaximumReactions = 30010 ErrorMaximumChannels = 30013 ErrorInteractionAlreadyAcknowledged = 40060 ErrorMissingAccess = 50001 ErrorInvalidAccountType = 50002 ErrorCannotExecuteOnDM = 50003 ErrorWidgetDisabled = 50004 ErrorCannotEditOtherUserMessage = 50005 ErrorCannotSendEmptyMessage = 50006 ErrorCannotMessageUser = 50007 ErrorCannotSendInVoiceChannel = 50008 ErrorChannelVerificationTooHigh = 50009 ErrorOAuth2ApplicationHasNoBot = 50010 ErrorOAuth2ApplicationLimit = 50011 ErrorInvalidOAuth2State = 50012 ErrorMissingPermissions = 50013 ErrorInvalidAuthenticationToken = 50014 ErrorNoteTooLong = 50015 ErrorBulkDeleteTooOld = 50034 ErrorInvalidFormBody = 50035 ErrorInvalidAPIVersion = 50041 )
Common Discord JSON error codes. The raw integer remains available through APIError.Code so newly introduced codes never require a library update.
const ( EventScheduled = 1 EventActive = 2 EventCompleted = 3 EventCancelled = 4 )
ScheduledEventStatus tracks an event through its lifecycle.
const ( EventStageInstance = 1 EventVoice = 2 EventExternal = 3 // somewhere outside Discord; needs EntityMetadata )
ScheduledEventEntityType says where an event happens.
const ( ArchiveOneHour = 60 ArchiveOneDay = 1440 ArchiveThreeDays = 4320 ArchiveOneWeek = 10080 )
Auto-archive durations Discord accepts, in minutes.
const ( // WidgetData pulls from the player's identity profile; the field's value // is the key to read. Discord's editor calls this "User Data". WidgetData = "data" // WidgetCustomString is a literal, identical for every player. Max 256. WidgetCustomString = "custom_string" // WidgetApplicationAsset is an image uploaded to the developer portal; // the value is its asset key. The asset must be set Public. WidgetApplicationAsset = "application_asset" )
WidgetValueType says where a field's content comes from.
const ( PresentText = "text" // as-is; numbers are not rendered PresentNumber = "number" // compact notation, 1500 -> 1.5K PresentDuration = "duration" // milliseconds -> "6h 30m" PresentImage = "image" // image fields only )
WidgetPresentationType is how a field renders.
const ( LayoutTopHero = "widget_top_hero" // hero_image, title, subtitle_1..3 LayoutBottomStats = "widget_bottom_stats" // stat_1..stat_6, each value+label LayoutBottomCollection = "widget_bottom_collection" // item_1..item_4, each image+name+description LayoutPreviewHero = "add_widget_preview_hero" // hero_image LayoutMiniProfileStat = "mini_profile_hero_stat" // hero_image, stat )
Known layout names, one per surface.
const BaseURL = "https://discord.com/api/v" + Version
BaseURL is the root of Discord's REST API.
const DefaultPrefix = "!"
DefaultPrefix is what Command matches when WithPrefix is not used.
const IntentsAll = IntentsAllUnprivileged | IntentsPrivileged
IntentsAll is every intent there is, privileged ones included. Convenient while developing, when you would rather see every event than work out which intent carries the one you want.
The privileged three still have to be switched on in the developer portal, and Discord closes the connection with an Invalid Intents code if they are not, so narrow this down to what you actually handle before shipping.
const IntentsAllUnprivileged = IntentGuilds | IntentGuildModeration | IntentGuildExpressions | IntentGuildIntegrations | IntentGuildWebhooks | IntentGuildInvites | IntentGuildVoiceStates | IntentGuildMessages | IntentGuildMessageReactions | IntentGuildMessageTyping | IntentDirectMessages | IntentDirectMessageReactions | IntentDirectMessageTyping | IntentGuildScheduledEvents | IntentAutoModerationConfiguration | IntentAutoModerationExecution | IntentGuildMessagePolls | IntentDirectMessagePolls
IntentsAllUnprivileged is every intent that works without special approval.
const IntentsPrivileged = IntentGuildMembers | IntentGuildPresences | IntentMessageContent
IntentsPrivileged is the set Discord gates behind extra approval. A bot in more than 100 guilds must be verified and have these switched on in the developer portal; below that, they still have to be enabled there manually.
const MaxRoleConnectionMetadata = 5
MaxRoleConnectionMetadata is the number of metadata records one application may register. Discord rejects anything above it.
const MaxTimeout = 28 * 24 * time.Hour
MaxTimeout is the longest timeout Discord accepts.
const ScopeApplicationIdentitiesWrite = "application_identities.write"
ScopeApplicationIdentitiesWrite is the OAuth2 scope a player must grant before an application may read or write their identity profile. The Social SDK's own scope set already includes it.
const Version = "10"
Version is the Discord API version starlings speaks.
Variables ¶
var ( ErrGuildNotCached = errors.New("starlings: guild is not cached") ErrChannelNotCached = errors.New("starlings: channel is not cached") ErrMemberNotCached = errors.New("starlings: member is not cached") )
var ErrAutoDeferred = errors.New("starlings: the interaction was already deferred because the handler was slow; " +
"open modals before slow work, or use NoAutoDefer")
ErrAutoDeferred is returned when a handler opens a modal or answers autocomplete after Starlings already deferred the interaction for it.
var ErrClosed = errors.New("starlings: client closed")
ErrClosed is returned by operations on a Client whose gateway connection has been shut down.
var ErrInteractionAlreadyAnswered = errors.New(
"starlings: this interaction has already been answered - use Followup instead")
ErrInteractionAlreadyAnswered is returned when a second initial response is attempted. Discord accepts exactly one callback per interaction; everything after it must be a follow-up.
var ErrNoToken = errors.New("starlings: no bot token: set DISCORD_TOKEN in the environment or in a .env file " +
"(copy it from discord.com/developers/applications > your app > Bot)")
ErrNoToken is returned by Run when the client was created without a token and DISCORD_TOKEN is not set in the environment or a .env file.
var ErrTokenRejected = errors.New("starlings: Discord rejected the bot token; requests are stopped until the client is recreated")
ErrTokenRejected is returned for every bot-token request after Discord has answered one with 401 Unauthorized. Discord asks clients to stop using a rejected token, and repeated 401s count toward a temporary IP block.
var ErrTooManyMetadataRecords = errors.New(
"starlings: an application may register at most 5 role connection metadata records")
ErrTooManyMetadataRecords is returned before the request is sent when more than MaxRoleConnectionMetadata records are supplied.
var ErrUnbound = errors.New("starlings: this value did not come from a client; use the Client method instead")
ErrUnbound is returned by a resource method when the value was not produced by a client, such as a struct literal. Use the Client method.
var ErrUnsupportedStateEvent = errors.New("starlings: event does not change cached state")
ErrUnsupportedStateEvent is returned when Apply receives an event with no state mutation. Generic dispatchers may safely ignore this sentinel.
var ErrUntrustedAttachmentURL = errors.New("starlings: attachment URL is not on Discord's CDN")
ErrUntrustedAttachmentURL is returned by DownloadAttachment for a URL that is not on Discord's CDN.
Functions ¶
func AuthorizeURL ¶
AuthorizeURL builds the OAuth2 URL a player visits to grant an application the given scopes. For game stats widgets that is ScopeApplicationIdentitiesWrite, and the redirect URI must already be registered on the application.
func BearerToken ¶
BearerToken formats an OAuth2 access token as an Authorization header value. It is idempotent, so a token that already carries the prefix is left alone.
func CustomID ¶ added in v0.2.0
CustomID joins parts into a component custom ID, such as CustomID("ticket", "close", ticketID) == "ticket:close:42". Values are escaped so a value containing ":" cannot add segments, which routes with {parameters} rely on. It panics if the result is longer than Discord's 100 characters, because the component could never be sent.
func DiscordCode ¶ added in v0.2.0
DiscordCode reports Discord's JSON error code, or zero when err is not an APIError. It is distinct from the HTTP status.
func FailFast ¶ added in v0.2.0
FailFast returns a context under which REST calls return a *RateLimitError instead of waiting for a rate limit. Use it for work that is pointless later, such as renaming a channel inside a three-second interaction window. Other calls keep waiting as usual.
func GuardCompare ¶
func GuardCompare[T any](g *Guard, feature string, equal func(T, T) bool, manual, automatic func() (T, error)) (T, error)
GuardCompare runs and profiles two pure implementations and returns the manual result. It must not be used for code with side effects: both functions are intentionally executed.
func HTTPStatus ¶
HTTPStatus reports the HTTP status of err if it is an APIError, and 0 otherwise. Useful with errors.As-free call sites:
if starlings.HTTPStatus(err) == http.StatusNotFound { ... }
func IsDiscordCode ¶ added in v0.2.0
IsDiscordCode reports whether err carries one of the supplied Discord JSON error codes.
func IsForbidden ¶
IsForbidden reports whether err is a 403, which means the token is valid but the bot lacks the permission for this action.
func IsModerationDenial ¶ added in v0.2.0
IsModerationDenial reports whether err is a CanModerate refusal rather than a cache miss.
func IsNotFound ¶
IsNotFound reports whether err is a 404 from Discord.
func IsUnauthorized ¶
IsUnauthorized reports whether err is a 401, which almost always means the bot token is wrong or has been reset.
func Listen ¶
Listen registers a handler and returns an idempotent function that removes it. Use On when the handler lives for the entire client lifetime.
func On ¶
On registers a handler for a gateway event. The event type determines which Discord event it listens to, so there is no name to get wrong:
starlings.On(bot, func(m *starlings.MessageCreate) {
m.Reply("hello")
})
Handlers for the same event run in registration order. An event is skipped only when neither application handlers nor an enabled internal consumer, such as the state cache or voice bookkeeping, needs it.
Client.On is the same thing with lighter syntax; use this form when you want the compiler to check the event type.
func OnOrdered ¶ added in v0.2.0
OnOrdered registers a handler that runs on the gateway goroutine, in event order, after the state cache and before application handlers. It keeps that order even with WithAsyncEvents.
It exists for packages that track gateway state, such as voice. The handler must return quickly: while it runs, the shard reads no further events. Ordered handlers stay registered for the life of the client.
func Once ¶
Once registers a handler that automatically removes itself before its first invocation, so even concurrent dispatch can call it at most once.
func ParseDuration ¶ added in v0.2.0
ParseDuration reads a length of time as people type it in Discord. It accepts Go durations such as 90s, 10m, or 1h30m, plus d for days and w for weeks, as in 3d or 1w2d. A bare number is seconds.
func Ref ¶ added in v0.2.0
func Ref[T any](value T) *T
Ref returns a pointer to value. It keeps optional request fields readable:
ModifyMember{Nick: starlings.Ref("new name")}
Use nil when the field should be omitted. APIs that support an explicit JSON null provide a named Clear flag or helper so callers do not need **T.
func RegisterStarPetArt ¶ added in v0.2.0
func RegisterStarPetArt(variant StarPetVariant, png []byte)
RegisterStarPetArt sets the pixel-art sheet NewStarPet uses for variant. The starpets package registers Starlings' bundled art when it is imported; without it, pets draw with terminal characters only. The slice is shared, not copied, so the caller must not modify it afterwards.
func UserErrorf ¶ added in v0.2.0
UserErrorf builds a UserError with fmt.Sprintf formatting:
return starlings.UserErrorf("Warning #%d does not exist.", id)
func VerifyInteraction ¶
func VerifyInteraction(publicKey ed25519.PublicKey, signatureHex, timestamp string, body []byte) bool
VerifyInteraction verifies Discord's Ed25519 request signature. Most bots can use InteractionHandler; this function is available for custom routers, middleware stacks, and servers that manage request bodies themselves.
Types ¶
type APIError ¶
type APIError struct {
Status int // HTTP status code
Code int // Discord JSON error code, 0 if absent
Message string // Discord's human-readable message
Errors []FieldError
Body []byte // raw response body, for anything not modelled above
}
APIError is returned when Discord answers a REST call with a non-2xx status. Discord's own error code (distinct from the HTTP status) is in Code, and per-field validation failures land in Errors.
func (*APIError) UserMessage ¶ added in v0.2.0
UserMessage explains a common Discord refusal in words the person who used a command can act on, or returns "" for codes without a safe explanation. Error-returning handlers show it instead of a generic failure, and the full error still goes to the log.
type Activity ¶
type Activity struct {
Name string `json:"name"`
Type ActivityType `json:"type"`
URL string `json:"url,omitzero"` // required for ActivityStreaming
State string `json:"state,omitzero"`
}
Activity is the line under a bot's name in the member list.
type ActivityInstance ¶
type ActivityInstance struct {
ApplicationID Snowflake `json:"application_id"`
InstanceID string `json:"instance_id"`
LaunchID Snowflake `json:"launch_id"`
Location struct {
ID string `json:"id"`
Kind string `json:"kind"` // "gc" guild channel, "pc" private channel
ChannelID Snowflake `json:"channel_id"`
GuildID Snowflake `json:"guild_id,omitzero"`
} `json:"location"`
Users []Snowflake `json:"users"`
}
ActivityInstance is a running session of an embedded Activity - the games and apps that run inside a voice channel.
type ActivityType ¶
type ActivityType int
ActivityType selects the verb Discord shows before an activity's name.
const ( ActivityPlaying ActivityType = iota ActivityStreaming ActivityListening ActivityWatching ActivityCustom ActivityCompeting )
type AllowedMentions ¶
type AllowedMentions struct {
Parse []string `json:"parse"` // "roles", "users", "everyone"
Roles []Snowflake `json:"roles,omitzero"`
Users []Snowflake `json:"users,omitzero"`
RepliedUser bool `json:"replied_user,omitzero"`
}
AllowedMentions controls which mentions in a message actually ping people.
Without it, a bot echoing user input can be made to ping @everyone. Passing an empty AllowedMentions{} suppresses every ping, which is the safe default for anything built from untrusted text.
func NoMentions ¶
func NoMentions() *AllowedMentions
NoMentions is an AllowedMentions that lets nothing ping. Use it whenever a message includes text a user supplied.
type AppTeam ¶
type AppTeam struct {
ID Snowflake `json:"id"`
Name string `json:"name"`
OwnerUserID Snowflake `json:"owner_user_id"`
}
AppTeam is the team that owns an application. When an app is team-owned the "owner" user Discord returns is a synthetic team account, not a person, so OwnerUserID is the only field that names a human.
type ApplicationCommand ¶
type ApplicationCommand struct {
ID Snowflake `json:"id,omitzero"`
ApplicationID Snowflake `json:"application_id,omitzero"`
GuildID Snowflake `json:"guild_id,omitzero"`
Type ApplicationCommandType `json:"type,omitzero"`
// Name must be 1-32 characters. For CommandChat it must be lowercase and
// contain no spaces.
Name string `json:"name"`
NameLocalizations map[string]string `json:"name_localizations,omitzero"`
NameLocalized string `json:"name_localized,omitzero"`
// Description is required for CommandChat and must be empty for the
// right-click command types.
Description string `json:"description,omitzero"` // max 100
DescriptionLocalizations map[string]string `json:"description_localizations,omitzero"`
DescriptionLocalized string `json:"description_localized,omitzero"`
Options []CommandOption `json:"options,omitzero"` // max 25
IntegrationTypes []ApplicationIntegrationType `json:"integration_types,omitzero"`
Contexts []InteractionContextType `json:"contexts,omitzero"`
Handler EntryPointHandlerType `json:"handler,omitzero"`
// DefaultMemberPermissions restricts who sees the command. Discord sends
// it as a decimal string, and nil means no restriction.
DefaultMemberPermissions *Permissions `json:"default_member_permissions,string,omitzero"`
NSFW bool `json:"nsfw,omitzero"`
Version Snowflake `json:"version,omitzero"`
DMPermission *bool `json:"dm_permission,omitzero"` // deprecated; use Contexts
DefaultPermission *bool `json:"default_permission,omitzero"` // deprecated
}
ApplicationCommand is a command registered with Discord.
Registering is separate from handling: this declares the command so it shows up in the client, while HandleCommand says what to do when it is used.
type ApplicationCommandPermissionsUpdate ¶
type ApplicationCommandPermissionsUpdate struct {
ID Snowflake `json:"id"`
ApplicationID Snowflake `json:"application_id"`
GuildID Snowflake `json:"guild_id"`
Permissions []struct {
ID Snowflake `json:"id"`
Type int `json:"type"`
Permission bool `json:"permission"`
} `json:"permissions"`
// contains filtered or unexported fields
}
ApplicationCommandPermissionsUpdate fires when a guild changes who may use one of the application's commands.
type ApplicationCommandType ¶
type ApplicationCommandType int
ApplicationCommandType selects where a command appears in the Discord UI.
const ( // CommandChat is a slash command, typed after "/". CommandChat ApplicationCommandType = iota + 1 // CommandUser appears when right-clicking a user. CommandUser // CommandMessage appears when right-clicking a message. CommandMessage // CommandPrimaryEntryPoint is the main way to launch an Activity. CommandPrimaryEntryPoint )
type ApplicationIdentity ¶
type ApplicationIdentity struct {
ProviderType string `json:"provider_type"`
ProviderID string `json:"provider_id,omitzero"`
ProviderIssuedUserID string `json:"provider_issued_user_id"`
}
ApplicationIdentity is a user's identity in an application, keyed by which external system vouched for them.
type ApplicationIntegrationType ¶
type ApplicationIntegrationType int
ApplicationIntegrationType says how an application was installed.
const ( IntegrationGuildInstall ApplicationIntegrationType = iota IntegrationUserInstall )
type ApplicationParams ¶
type ApplicationParams struct {
Description *string `json:"description,omitzero"`
Icon *string `json:"icon,omitzero"` // data URI
CoverImage *string `json:"cover_image,omitzero"`
Tags *[]string `json:"tags,omitzero"` // max 5
InteractionsEndpointURL *string `json:"interactions_endpoint_url,omitzero"`
RoleConnectionsVerificationURL *string `json:"role_connections_verification_url,omitzero"`
Flags *int `json:"flags,omitzero"`
CustomInstallURL *string `json:"custom_install_url,omitzero"`
RedirectURIs *[]string `json:"redirect_uris,omitzero"`
}
ApplicationParams are the settable fields of an application.
type ArchivedThreadsQuery ¶
ArchivedThreadsQuery pages backwards through archived threads.
type Attachment ¶
type Attachment struct {
ID Snowflake `json:"id"`
Filename string `json:"filename"`
Description string `json:"description"`
ContentType string `json:"content_type"`
Size int `json:"size"`
URL string `json:"url"`
ProxyURL string `json:"proxy_url"`
Height int `json:"height"`
Width int `json:"width"`
Ephemeral bool `json:"ephemeral"`
Title string `json:"title"`
DurationSecs float64 `json:"duration_secs"`
Waveform string `json:"waveform"`
Flags int `json:"flags"`
Application *MessageApplication `json:"application"`
ClipCreatedAt *time.Time `json:"clip_created_at"`
ClipParticipants []User `json:"clip_participants"`
Placeholder string `json:"placeholder"`
PlaceholderVersion int `json:"placeholder_version"`
}
Attachment is a file uploaded alongside a message.
type AttachmentUpload ¶
type AttachmentUpload struct {
URL string `json:"url"`
}
AttachmentUpload is an ephemeral CDN URL an Activity can share images through, since an Activity cannot post messages itself.
type AuditLog ¶
type AuditLog struct {
Entries []AuditLogEntry `json:"audit_log_entries"`
Users []User `json:"users"`
Webhooks []Webhook `json:"webhooks"`
Integrations []Integration `json:"integrations"`
Threads []Channel `json:"threads"`
}
AuditLog is a page of audit log entries plus the objects they refer to.
type AuditLogChange ¶
type AuditLogChange struct {
Key string `json:"key"`
OldValue any `json:"old_value"`
NewValue any `json:"new_value"`
}
AuditLogChange records one field that an action altered.
type AuditLogEntry ¶
type AuditLogEntry struct {
ID Snowflake `json:"id"`
TargetID string `json:"target_id"`
UserID Snowflake `json:"user_id"`
ActionType int `json:"action_type"`
Reason string `json:"reason"`
Changes []AuditLogChange `json:"changes"`
}
AuditLogEntry is one recorded administrative action.
type AuditLogQuery ¶
type AuditLogQuery struct {
UserID Snowflake // only entries caused by this user
ActionType int // only this kind of change
Before Snowflake
After Snowflake
Limit int // 1-100
}
AuditLogQuery narrows an audit log request.
type AutoModerationActionExecution ¶
type AutoModerationActionExecution struct {
GuildID Snowflake `json:"guild_id"`
Action AutomodAction `json:"action"`
RuleID Snowflake `json:"rule_id"`
RuleTriggerType int `json:"rule_trigger_type"`
UserID Snowflake `json:"user_id"`
ChannelID Snowflake `json:"channel_id"`
MessageID Snowflake `json:"message_id"`
AlertSystemMessageID Snowflake `json:"alert_system_message_id"`
Content string `json:"content"`
MatchedKeyword string `json:"matched_keyword"`
MatchedContent string `json:"matched_content"`
// contains filtered or unexported fields
}
AutoModerationActionExecution fires when a rule matches and acts. Needs the AutoModerationExecution intent, which is separate from the configuration one.
type AutoModerationRuleCreate ¶
type AutoModerationRuleCreate struct {
AutomodRule
// contains filtered or unexported fields
}
AutoModerationRuleCreate fires when a rule is added.
type AutoModerationRuleDelete ¶
type AutoModerationRuleDelete struct {
AutomodRule
// contains filtered or unexported fields
}
AutoModerationRuleDelete fires when a rule is removed.
type AutoModerationRuleUpdate ¶
type AutoModerationRuleUpdate struct {
AutomodRule
// contains filtered or unexported fields
}
AutoModerationRuleUpdate fires when a rule changes.
type AutomodAction ¶
type AutomodAction struct {
Type int `json:"type"`
Metadata *AutomodActionMeta `json:"metadata,omitzero"`
}
AutomodAction is one consequence of a rule matching.
type AutomodActionMeta ¶
type AutomodActionMeta struct {
ChannelID Snowflake `json:"channel_id,omitzero"` // where to send alerts
DurationSeconds int `json:"duration_seconds,omitzero"` // timeout length, max 4 weeks
CustomMessage string `json:"custom_message,omitzero"` // shown to the blocked user
}
AutomodActionMeta configures an action.
type AutomodRule ¶
type AutomodRule struct {
ID Snowflake `json:"id,omitzero"`
GuildID Snowflake `json:"guild_id,omitzero"`
Name string `json:"name"`
CreatorID Snowflake `json:"creator_id,omitzero"`
EventType int `json:"event_type"`
TriggerType int `json:"trigger_type"`
TriggerMetadata *AutomodTriggerMeta `json:"trigger_metadata,omitzero"`
Actions []AutomodAction `json:"actions"`
Enabled bool `json:"enabled"`
ExemptRoles []Snowflake `json:"exempt_roles,omitzero"`
ExemptChannels []Snowflake `json:"exempt_channels,omitzero"`
}
AutomodRule is one auto-moderation rule.
type AutomodTriggerMeta ¶
type AutomodTriggerMeta struct {
KeywordFilter []string `json:"keyword_filter,omitzero"`
RegexPatterns []string `json:"regex_patterns,omitzero"`
Presets []int `json:"presets,omitzero"`
AllowList []string `json:"allow_list,omitzero"`
MentionTotalLimit int `json:"mention_total_limit,omitzero"`
MentionRaidProtectionEnabled bool `json:"mention_raid_protection_enabled,omitzero"`
}
AutomodTriggerMeta refines what a rule matches. Which fields apply depends on the trigger type.
type BulkBanResult ¶
type BulkBanResult struct {
BannedUsers []Snowflake `json:"banned_users"`
FailedUsers []Snowflake `json:"failed_users"`
}
BulkBanResult reports which users a bulk ban actually affected.
type ButtonStyle ¶
type ButtonStyle int
ButtonStyle sets a button's colour and behaviour. ButtonLink renders as a hyperlink and produces no interaction event.
const ( ButtonPrimary ButtonStyle = iota + 1 ButtonSecondary ButtonSuccess ButtonDanger ButtonLink ButtonPremium )
type CallbackType ¶
type CallbackType int
CallbackType is how an interaction is answered.
const ( CallbackPong CallbackType = 1 CallbackChannelMessageWithSource CallbackType = 4 // reply now CallbackDeferredChannelMessage CallbackType = 5 // "thinking...", reply later CallbackDeferredUpdateMessage CallbackType = 6 // component: ack, edit later CallbackUpdateMessage CallbackType = 7 // component: edit the message now CallbackAutocompleteResult CallbackType = 8 CallbackModal CallbackType = 9 CallbackLaunchActivity CallbackType = 12 )
type Channel ¶
type Channel struct {
ID Snowflake `json:"id"`
Type ChannelType `json:"type"`
GuildID Snowflake `json:"guild_id"`
Position int `json:"position"`
PermissionOverwrites []Overwrite `json:"permission_overwrites"`
Name string `json:"name"`
Topic string `json:"topic"`
NSFW bool `json:"nsfw"`
LastMessageID Snowflake `json:"last_message_id"`
Bitrate int `json:"bitrate"`
UserLimit int `json:"user_limit"`
RateLimitPerUser int `json:"rate_limit_per_user"` // slow mode, in seconds
Recipients []User `json:"recipients"` // DM and group DM only
OwnerID Snowflake `json:"owner_id"`
ParentID Snowflake `json:"parent_id"` // category, or the parent of a thread
LastPinTimestamp *time.Time `json:"last_pin_timestamp"`
Flags int `json:"flags"`
ThreadMetadata *ThreadMeta `json:"thread_metadata"`
AvailableTags []ForumTag `json:"available_tags"`
AppliedTags []Snowflake `json:"applied_tags"`
DefaultReaction *ForumReaction `json:"default_reaction_emoji"`
Status string `json:"status"`
VoiceStartTime *time.Time `json:"voice_start_time"`
// contains filtered or unexported fields
}
Channel is any place messages can live: a guild text channel, a voice channel, a DM, a category, a thread or a forum. Which fields are populated depends on Type.
func (*Channel) Purge ¶ added in v0.2.0
func (ch *Channel) Purge(opts PurgeOptions) (PurgeResult, error)
Purge deletes recent messages in this channel. See Client.Purge.
func (*Channel) SendComplex ¶ added in v0.2.0
SendComplex posts a message with embeds, components, or other fields.
type ChannelCreate ¶
type ChannelCreate struct {
Channel
// contains filtered or unexported fields
}
ChannelCreate fires when a channel is created.
type ChannelDelete ¶
type ChannelDelete struct {
Channel
BeforeDelete *Channel `json:"-"`
// contains filtered or unexported fields
}
ChannelDelete fires when a channel is deleted.
type ChannelInfo ¶
type ChannelInfo struct {
GuildID Snowflake `json:"guild_id"`
Channels []ChannelInfoChannel `json:"channels"`
// contains filtered or unexported fields
}
ChannelInfo answers RequestChannelInfo with ephemeral voice-channel data.
type ChannelInfoChannel ¶
type ChannelInfoChannel struct {
ID Snowflake `json:"id"`
Status *string `json:"status"`
VoiceStartTime *int64 `json:"voice_start_time"`
}
ChannelInfoChannel is the ephemeral subset returned by ChannelInfo. VoiceStartTime is a Unix timestamp in seconds.
type ChannelInfoField ¶
type ChannelInfoField string
ChannelInfoField selects ephemeral fields for RequestChannelInfo.
const ( ChannelInfoStatus ChannelInfoField = "status" ChannelInfoVoiceStartTime ChannelInfoField = "voice_start_time" )
type ChannelMention ¶
type ChannelMention struct {
ID Snowflake `json:"id"`
GuildID Snowflake `json:"guild_id"`
Type ChannelType `json:"type"`
Name string `json:"name"`
}
ChannelMention is the small channel shape embedded in crossposted messages.
type ChannelParams ¶
type ChannelParams struct {
Name *string `json:"name,omitzero"`
Type *ChannelType `json:"type,omitzero"`
Topic *string `json:"topic,omitzero"`
Position *int `json:"position,omitzero"`
NSFW *bool `json:"nsfw,omitzero"`
RateLimitPerUser *int `json:"rate_limit_per_user,omitzero"` // slow mode, seconds
Bitrate *int `json:"bitrate,omitzero"` // voice
UserLimit *int `json:"user_limit,omitzero"` // voice
ParentID *Snowflake `json:"parent_id,omitzero"` // category
PermissionOverwrites *[]Overwrite `json:"permission_overwrites,omitzero"`
DefaultAutoArchive *int `json:"default_auto_archive_duration,omitzero"`
}
ChannelParams are the settable fields of a channel. All are optional: on create, omitted fields take Discord's defaults; on edit they are left alone.
type ChannelPinsUpdate ¶
type ChannelPinsUpdate struct {
GuildID Snowflake `json:"guild_id"`
ChannelID Snowflake `json:"channel_id"`
LastPinTimestamp *time.Time `json:"last_pin_timestamp"`
BeforeUpdate *Channel `json:"-"`
// contains filtered or unexported fields
}
ChannelPinsUpdate fires when a message is pinned or unpinned. It carries no message, only the fact that the pins changed.
type ChannelPosition ¶
type ChannelPosition struct {
ID Snowflake `json:"id"`
Position *int `json:"position,omitzero"`
LockPermissions *bool `json:"lock_permissions,omitzero"`
ParentID *Snowflake `json:"parent_id,omitzero"`
}
ChannelPosition is one entry of a channel reordering request.
type ChannelType ¶
type ChannelType int
ChannelType distinguishes the kinds of channel Discord models with one type.
const ( ChannelGuildText ChannelType = iota ChannelDM ChannelGuildVoice ChannelGroupDM ChannelGuildCategory ChannelGuildAnnouncement ChannelAnnouncementThread ChannelPublicThread ChannelPrivateThread ChannelGuildStageVoice ChannelGuildDirectory ChannelGuildForum ChannelGuildMedia )
func (ChannelType) IsThread ¶
func (t ChannelType) IsThread() bool
IsThread reports whether the type is one of the three thread kinds.
type ChannelUpdate ¶
type ChannelUpdate struct {
Channel
BeforeUpdate *Channel `json:"-"`
// contains filtered or unexported fields
}
ChannelUpdate fires when a channel's settings change.
type Client ¶
type Client struct {
// State is the gateway-maintained cache. It is ready immediately and safe
// to read from handlers and other goroutines.
State *State
// contains filtered or unexported fields
}
Client is a bot: a REST client and a gateway connection sharing one token.
The zero Client is not usable - build one with New.
func New ¶
New builds a client:
bot := starlings.New()
bot.Slash("ping", "Is the bot alive?", ping)
bot.Run()
The token comes from WithToken, or else from DISCORD_TOKEN in the environment or a .env file in the working directory. Register handlers, then call Run.
Some behaviour is automatic: intents are chosen from the handlers, slow interaction handlers are deferred, and handler panics are logged instead of stopping the process. Each has its own option to turn it off, and Explicit turns them all off.
func NewCommandBot ¶ added in v0.2.0
NewCommandBot is the zero-boilerplate constructor for prefix-command bots. It is New with the guild-message, direct-message, and message-content intents selected and resource caching disabled. Options are applied afterward, so WithIntents and WithStateCache can replace either preset.
func (*Client) ActiveThreads ¶
func (c *Client) ActiveThreads(ctx context.Context, guildID Snowflake) ([]Channel, []ThreadMember, error)
ActiveThreads lists a guild's threads that have not been archived.
func (*Client) ActivityInstance ¶
func (c *Client) ActivityInstance(ctx context.Context, appID Snowflake, instanceID string) (*ActivityInstance, error)
ActivityInstance reads a running Activity session, which is how a game server confirms a client's claimed session really exists and sees who is in it.
func (*Client) AddGroupDMRecipient ¶
func (c *Client) AddGroupDMRecipient(ctx context.Context, channelID, userID Snowflake, accessToken, nick string) error
AddGroupDMRecipient adds a user to a group DM. Needs an OAuth2 token with the gdm.join scope for that user.
func (*Client) AddInviteTargetUser ¶
AddInviteTargetUser adds one user to a targeted invite's allow-list.
func (*Client) AddLobbyMember ¶
func (c *Client) AddLobbyMember(ctx context.Context, lobbyID, userID Snowflake, data LobbyMemberInput) (*LobbyMember, error)
AddLobbyMember adds a user or updates their lobby metadata.
func (*Client) AddMember ¶
func (c *Client) AddMember(ctx context.Context, guildID, userID Snowflake, accessToken string, nick string, roles []Snowflake, mute, deaf bool) (*Member, error)
AddMember adds a user to a guild using an OAuth2 access token that carries the guilds.join scope.
func (*Client) AddMemberRole ¶
func (c *Client) AddMemberRole(ctx context.Context, guildID, userID, roleID Snowflake, reason string) error
AddMemberRole grants a role.
func (*Client) AddThreadMember ¶
AddThreadMember adds someone else to a thread.
func (*Client) Application ¶
Application fetches any application by ID.
func (*Client) ApplicationCommand ¶
func (c *Client) ApplicationCommand(ctx context.Context, appID, commandID Snowflake) (*ApplicationCommand, error)
ApplicationCommand fetches one global command.
func (*Client) ApplicationCommands ¶
func (c *Client) ApplicationCommands(ctx context.Context, appID Snowflake) ([]ApplicationCommand, error)
Commands lists an application's global commands.
func (*Client) ApplicationEmoji ¶
func (c *Client) ApplicationEmoji(ctx context.Context, appID, emojiID Snowflake) (*GuildEmoji, error)
ApplicationEmoji fetches one application emoji.
func (*Client) ApplicationEmojis ¶
ApplicationEmojis lists emoji owned by the application rather than a guild. These work in every guild the bot is in, with no slot limit shared with servers.
func (*Client) ApplicationID ¶
ApplicationID returns the bot's application ID, which the slash command endpoints need. It is zero before READY.
func (*Client) AuditLog ¶
func (c *Client) AuditLog(ctx context.Context, guildID Snowflake, q AuditLogQuery) (*AuditLog, error)
AuditLog reads a guild's audit log, newest first.
func (*Client) AutomodRule ¶
AutomodRule fetches one rule.
func (*Client) AutomodRules ¶
AutomodRules lists a guild's auto-moderation rules.
func (*Client) BulkAddInviteTargetUsers ¶
func (c *Client) BulkAddInviteTargetUsers(ctx context.Context, code string, userIDs []Snowflake) (*InviteTargetUsersJob, error)
BulkAddInviteTargetUsers adds many users at once. The change is applied in the background; poll InviteTargetUsersJobStatus to see when it lands.
func (*Client) BulkBan ¶
func (c *Client) BulkBan(ctx context.Context, guildID Snowflake, userIDs []Snowflake, deleteMessageSeconds int, reason string) (*BulkBanResult, error)
BulkBan bans up to 200 users in one call, which is far cheaper than a ban each when clearing a raid.
func (*Client) BulkDeleteInviteTargetUsers ¶
func (c *Client) BulkDeleteInviteTargetUsers(ctx context.Context, code string, userIDs []Snowflake) (*InviteTargetUsersJob, error)
BulkDeleteInviteTargetUsers removes many users at once.
func (*Client) BulkDeleteMessages ¶
func (c *Client) BulkDeleteMessages(ctx context.Context, channelID Snowflake, ids []Snowflake, reason string) error
BulkDeleteMessages removes 2 to 100 messages in one call.
Discord refuses messages older than two weeks, and refuses a list of one - use DeleteMessage for a single message. Duplicated IDs also fail.
func (*Client) BulkUpdateLobbyMembers ¶
func (c *Client) BulkUpdateLobbyMembers(ctx context.Context, lobbyID Snowflake, members []LobbyMemberInput) ([]LobbyMember, error)
BulkUpdateLobbyMembers adds, updates, or removes up to 25 users atomically.
func (*Client) Button ¶ added in v0.2.0
Button handles a button or select whose custom ID matches pattern, which may capture {parameters}. See the handler shapes above; a struct parameter is filled from the captured values:
bot.Button("ticket:close:{id}", func(p struct{ ID int64 }) starlings.Response {
...
})
func (*Client) ChannelInvites ¶
ChannelInvites lists the invites pointing at a channel.
func (*Client) ChannelWebhooks ¶
ChannelWebhooks lists a channel's webhooks.
func (*Client) ClearReactions ¶
ClearReactions removes every reaction from a message.
func (*Client) ClearReactionsFor ¶
func (c *Client) ClearReactionsFor(ctx context.Context, channelID, messageID Snowflake, emoji Emoji) error
ClearReactionsFor removes every reaction of one emoji from a message.
func (*Client) ClearTimeout ¶ added in v0.2.0
func (c *Client) ClearTimeout(ctx context.Context, guildID, userID Snowflake, reason string) (*Member, error)
ClearTimeout lifts a member's timeout early.
func (*Client) Command ¶
func (c *Client) Command(name string, fn CommandFunc) *CommandRoute
Command registers a text command triggered by the bot's prefix:
bot.Command("ping", func(m *starlings.MessageCreate, args []string) {
m.Reply("pong")
})
That responds to `!ping`. Change the prefix with WithPrefix.
Messages from bots - including this one - are ignored, so a command that replies cannot trigger itself. Names are matched case-insensitively.
Reading message text needs the privileged MessageContent intent unless the message mentions the bot or is a DM. Run warns when that intent is missing, because the symptom otherwise is a bot that silently ignores every command.
func (*Client) Commands ¶
Commands lists the registered command names, which is handy for building a help command.
func (*Client) ConsumeEntitlement ¶
ConsumeEntitlement marks a one-off purchase as used up, which is what makes a consumable buyable again.
func (*Client) CreateApplicationCommand ¶
func (c *Client) CreateApplicationCommand(ctx context.Context, appID Snowflake, cmd ApplicationCommand) (*ApplicationCommand, error)
CreateApplicationCommand registers one global command.
Global commands can take up to an hour to appear. While developing, register against a single guild with CreateGuildCommand instead - those update instantly.
func (*Client) CreateApplicationEmoji ¶
func (c *Client) CreateApplicationEmoji(ctx context.Context, appID Snowflake, name, image string) (*GuildEmoji, error)
CreateApplicationEmoji uploads an emoji owned by the application.
func (*Client) CreateAutomodRule ¶
func (c *Client) CreateAutomodRule(ctx context.Context, guildID Snowflake, rule AutomodRule, reason string) (*AutomodRule, error)
CreateAutomodRule adds an auto-moderation rule.
A guild may hold a limited number of rules per trigger type - currently six keyword rules and one each of spam, preset and mention-spam.
func (*Client) CreateBan ¶
func (c *Client) CreateBan(ctx context.Context, guildID, userID Snowflake, deleteMessageSeconds int, reason string) error
CreateBan bans a user, optionally deleting their recent messages.
deleteMessageSeconds may be up to 7 days (604800). The user need not be in the guild - banning an absent user pre-empts them joining.
func (*Client) CreateChannel ¶
func (c *Client) CreateChannel(ctx context.Context, guildID Snowflake, params ChannelParams, reason string) (*Channel, error)
CreateChannel adds a channel to a guild.
func (*Client) CreateDM ¶
CreateDM opens a direct-message channel with a user.
Discord caches these, so calling it repeatedly for the same user returns the same channel rather than creating duplicates. Note that a DM can still fail to send if the recipient shares no guild with the bot or blocks DMs.
func (*Client) CreateGuildCommand ¶
func (c *Client) CreateGuildCommand(ctx context.Context, appID, guildID Snowflake, cmd ApplicationCommand) (*ApplicationCommand, error)
CreateGuildCommand registers a command in one guild, where it appears immediately rather than after Discord's global propagation delay.
func (*Client) CreateGuildEmoji ¶
func (c *Client) CreateGuildEmoji(ctx context.Context, guildID Snowflake, name, image string, roles []Snowflake, reason string) (*GuildEmoji, error)
CreateGuildEmoji uploads a custom emoji.
image is a data URI - "data:image/png;base64,..." - of at most 256 KiB.
func (*Client) CreateGuildTemplate ¶
func (c *Client) CreateGuildTemplate(ctx context.Context, guildID Snowflake, name, description string) (*GuildTemplate, error)
CreateGuildTemplate snapshots a guild into a new template.
func (*Client) CreateInvite ¶
func (c *Client) CreateInvite(ctx context.Context, channelID Snowflake, params InviteParams, reason string) (*Invite, error)
CreateInvite makes a new invite to a channel.
func (*Client) CreateLobby ¶
CreateLobby creates a server-managed lobby with the bot token.
func (*Client) CreateRole ¶
func (c *Client) CreateRole(ctx context.Context, guildID Snowflake, params RoleParams, reason string) (*Role, error)
CreateRole adds a role to a guild.
A bot can only grant permissions it holds itself, and can only manage roles below its own highest role - both of which surface as a 403.
func (*Client) CreateScheduledEvent ¶
func (c *Client) CreateScheduledEvent(ctx context.Context, guildID Snowflake, e ScheduledEvent, reason string) (*ScheduledEvent, error)
CreateScheduledEvent schedules a guild event.
An EventExternal event must supply both EntityMetadata.Location and ScheduledEndTime; the other kinds need ChannelID instead.
func (*Client) CreateScheduledEventException ¶
func (c *Client) CreateScheduledEventException(ctx context.Context, guildID, eventID Snowflake, e ScheduledEventException) (*ScheduledEventException, error)
CreateScheduledEventException moves or cancels one occurrence of a recurring event without touching the rest of the series.
func (*Client) CreateSoundboardSound ¶
func (c *Client) CreateSoundboardSound(ctx context.Context, guildID Snowflake, s NewSoundboardSound, reason string) (*SoundboardSound, error)
CreateSoundboardSound uploads a sound to a guild.
func (*Client) CreateStageInstance ¶
func (c *Client) CreateStageInstance(ctx context.Context, s StageInstance, reason string) (*StageInstance, error)
CreateStageInstance opens a stage channel to listeners.
func (*Client) CreateSticker ¶
func (c *Client) CreateSticker(ctx context.Context, guildID Snowflake, name, description, tags string, file File, reason string) (*Sticker, error)
CreateSticker uploads a sticker to a guild.
Discord takes stickers as multipart rather than a data URI, so the file travels as an attachment alongside the metadata.
func (*Client) CreateTestEntitlement ¶
func (c *Client) CreateTestEntitlement(ctx context.Context, appID, skuID, ownerID Snowflake, ownerType int) (*Entitlement, error)
CreateTestEntitlement grants a SKU to a user or guild without payment, for testing premium features. ownerType is 1 for a guild, 2 for a user.
func (*Client) CreateWebhook ¶
func (c *Client) CreateWebhook(ctx context.Context, channelID Snowflake, name, reason string) (*Webhook, error)
CreateWebhook adds a webhook to a channel.
func (*Client) CreateWidgetConfig ¶
func (c *Client) CreateWidgetConfig(ctx context.Context, appID Snowflake, displayName string) (*WidgetConfig, error)
CreateWidgetConfig registers a new widget config and returns its ID.
Requires a claimed game on the application's team; without one Discord returns 40128, and that gate applies even to applications that already have a published config from before it was introduced.
func (*Client) Crosspost ¶
Crosspost publishes a message from an announcement channel to every server following it.
func (*Client) CurrentApplication ¶
func (c *Client) CurrentApplication(ctx context.Context) (*CurrentApplication, error)
CurrentApplication returns the application behind the bot token, which is how a program learns its own application ID without being told.
func (*Client) CurrentAuthorization ¶
func (c *Client) CurrentAuthorization(ctx context.Context, bearerToken string) (*OAuth2Authorization, error)
CurrentAuthorization describes the current OAuth2 token. Useful for checking which scopes a bearer token actually carries before relying on it.
func (*Client) CurrentOAuth2Application ¶
func (c *Client) CurrentOAuth2Application(ctx context.Context) (*CurrentApplication, error)
CurrentOAuth2Application returns the application behind the token, through the OAuth2 endpoint rather than the applications one.
func (*Client) CurrentUser ¶
CurrentUser fetches the account the token belongs to - for a bot token, the bot's own user.
func (*Client) CurrentUserGuildMember ¶
CurrentUserGuildMember fetches the bot's own member object in a guild, which is the cheapest way to read its own roles and permissions there.
func (*Client) CurrentUserGuilds ¶
CurrentUserGuilds lists the guilds the bot is a member of.
The Guild objects are partial - enough for ID, name, icon and permissions, but not channels or members.
func (*Client) CurrentVoiceState ¶
CurrentVoiceState reads the bot's own voice state in a guild.
func (*Client) DefaultSoundboardSounds ¶
func (c *Client) DefaultSoundboardSounds(ctx context.Context) ([]SoundboardSound, error)
DefaultSoundboardSounds lists the sounds Discord ships, which every guild can play without uploading anything.
func (*Client) DeleteApplicationCommand ¶
DeleteApplicationCommand removes one global command.
func (*Client) DeleteApplicationEmoji ¶
DeleteApplicationEmoji removes an application emoji.
func (*Client) DeleteApplicationIdentity ¶
func (c *Client) DeleteApplicationIdentity(ctx context.Context, userID, appID Snowflake, providerType, providerIssuedUserID string) error
DeleteApplicationIdentity removes a user's identity, and the profile stored against it, for this application.
func (*Client) DeleteAutomodRule ¶
func (c *Client) DeleteAutomodRule(ctx context.Context, guildID, ruleID Snowflake, reason string) error
DeleteAutomodRule removes a rule.
func (*Client) DeleteChannel ¶
func (c *Client) DeleteChannel(ctx context.Context, channelID Snowflake, reason string) (*Channel, error)
DeleteChannel removes a channel, or closes a DM. Deleting a category does not delete the channels inside it; they simply lose their parent.
func (*Client) DeleteGuildCommand ¶
DeleteGuildCommand removes one guild command.
func (*Client) DeleteGuildEmoji ¶
func (c *Client) DeleteGuildEmoji(ctx context.Context, guildID, emojiID Snowflake, reason string) error
DeleteGuildEmoji removes a custom emoji.
func (*Client) DeleteGuildTemplate ¶
func (c *Client) DeleteGuildTemplate(ctx context.Context, guildID Snowflake, code string) (*GuildTemplate, error)
DeleteGuildTemplate removes a template.
func (*Client) DeleteIntegration ¶
func (c *Client) DeleteIntegration(ctx context.Context, guildID, integrationID Snowflake, reason string) error
DeleteIntegration removes an integration, along with any subscriptions and synced roles it created.
func (*Client) DeleteInvite ¶
DeleteInvite revokes an invite.
func (*Client) DeleteLobby ¶
DeleteLobby permanently removes a server-managed lobby. Discord treats an already-deleted lobby as success.
func (*Client) DeleteMessage ¶
func (c *Client) DeleteMessage(ctx context.Context, channelID, messageID Snowflake, reason string) error
DeleteMessage removes a message.
func (*Client) DeletePermissionOverwrite ¶
func (c *Client) DeletePermissionOverwrite(ctx context.Context, channelID, overwriteID Snowflake, reason string) error
DeletePermissionOverwrite removes an overwrite, restoring inheritance.
func (*Client) DeleteRole ¶
DeleteRole removes a role from a guild.
func (*Client) DeleteScheduledEvent ¶
DeleteScheduledEvent cancels and removes an event.
func (*Client) DeleteScheduledEventException ¶
func (c *Client) DeleteScheduledEventException(ctx context.Context, guildID, eventID, exceptionID Snowflake) error
DeleteScheduledEventException restores one occurrence of a recurring event.
func (*Client) DeleteSoundboardSound ¶
func (c *Client) DeleteSoundboardSound(ctx context.Context, guildID, soundID Snowflake, reason string) error
DeleteSoundboardSound removes a sound from a guild.
func (*Client) DeleteStageInstance ¶
DeleteStageInstance ends a live stage.
func (*Client) DeleteSticker ¶
func (c *Client) DeleteSticker(ctx context.Context, guildID, stickerID Snowflake, reason string) error
DeleteSticker removes a guild sticker.
func (*Client) DeleteTestEntitlement ¶
DeleteTestEntitlement revokes a test entitlement.
func (*Client) DeleteUserRoleConnection ¶
func (c *Client) DeleteUserRoleConnection(ctx context.Context, bearerToken string, appID Snowflake) error
DeleteUserRoleConnection removes the card from the user's profile.
func (*Client) DeleteWebhook ¶
DeleteWebhook removes a webhook.
func (*Client) DeleteWebhookMessage ¶
func (c *Client) DeleteWebhookMessage(ctx context.Context, webhookID Snowflake, token string, messageID Snowflake) error
DeleteWebhookMessage removes a message a webhook posted.
func (*Client) DeleteWebhookWithToken ¶
func (c *Client) DeleteWebhookWithToken(ctx context.Context, webhookID Snowflake, token string) error
DeleteWebhookWithToken removes a webhook using its own token.
func (*Client) DownloadAttachment ¶ added in v0.2.0
DownloadAttachment reads an attachment's bytes, up to limit. It only fetches from Discord's CDN hosts, so a URL taken from user input cannot make the bot request internal addresses. A limit of zero or less uses the attachment's reported size, plus a small margin.
func (*Client) EditApplication ¶
func (c *Client) EditApplication(ctx context.Context, params ApplicationParams) (*CurrentApplication, error)
EditApplication updates the application the token belongs to.
func (*Client) EditApplicationByID ¶
func (c *Client) EditApplicationByID(ctx context.Context, appID Snowflake, params ApplicationParams) (*CurrentApplication, error)
EditApplicationByID updates a specific application.
func (*Client) EditApplicationCommand ¶
func (c *Client) EditApplicationCommand(ctx context.Context, appID, commandID Snowflake, cmd ApplicationCommand) (*ApplicationCommand, error)
EditApplicationCommand updates one global command in place, which avoids the propagation delay of deleting and recreating it.
func (*Client) EditGuildCommand ¶
func (c *Client) EditGuildCommand(ctx context.Context, appID, guildID, commandID Snowflake, cmd ApplicationCommand) (*ApplicationCommand, error)
EditGuildCommand updates one guild command.
func (*Client) EditMessage ¶
func (c *Client) EditMessage(ctx context.Context, channelID, messageID Snowflake, data SendData) (*Message, error)
EditMessage replaces a message's content. A bot may only edit its own messages.
func (*Client) EditWebhookMessage ¶
func (c *Client) EditWebhookMessage(ctx context.Context, webhookID Snowflake, token string, messageID Snowflake, msg WebhookMessage) (*Message, error)
EditWebhookMessage rewrites a message a webhook posted.
func (*Client) EditWebhookMessageFiles ¶
func (c *Client) EditWebhookMessageFiles(ctx context.Context, webhookID Snowflake, token string, messageID Snowflake, msg WebhookMessage, files ...File) (*Message, error)
EditWebhookMessageFiles edits a webhook message and uploads attachments.
func (*Client) Entitlement ¶
func (c *Client) Entitlement(ctx context.Context, appID, entitlementID Snowflake) (*Entitlement, error)
Entitlement fetches one entitlement.
func (*Client) Entitlements ¶
func (c *Client) Entitlements(ctx context.Context, appID Snowflake, q EntitlementsQuery) ([]Entitlement, error)
Entitlements lists who has access to an application's premium SKUs.
func (*Client) ExchangeBotProvisionalToken ¶
func (c *Client) ExchangeBotProvisionalToken(ctx context.Context, externalUserID, preferredGlobalName string, provisionalUserID Snowflake) (*ProvisionalToken, error)
ExchangeBotProvisionalToken creates or refreshes a provisional user using a bot-authorized application identity.
func (*Client) ExchangeProvisionalToken ¶
func (c *Client) ExchangeProvisionalToken(ctx context.Context, credentials ProvisionalCredentials) (*ProvisionalToken, error)
ExchangeProvisionalToken exchanges an external identity credential without attaching the client's bot authorization.
func (*Client) ExecuteGitHubWebhook ¶
func (c *Client) ExecuteGitHubWebhook(ctx context.Context, webhookID Snowflake, token string, payload any, wait bool) error
ExecuteGitHubWebhook posts a GitHub webhook payload through a Discord webhook, giving the same rendering GitHub's own integration produces.
func (*Client) ExecuteSlackWebhook ¶
func (c *Client) ExecuteSlackWebhook(ctx context.Context, webhookID Snowflake, token string, payload any, wait bool) error
ExecuteSlackWebhook posts a Slack-formatted payload through a Discord webhook, which Discord translates. Useful for pointing existing Slack integrations at Discord unchanged.
func (*Client) ExecuteWebhook ¶
func (c *Client) ExecuteWebhook(ctx context.Context, webhookID Snowflake, token string, msg WebhookMessage, wait bool, threadID Snowflake) (*Message, error)
ExecuteWebhook posts a message through a webhook.
By default Discord returns no body; pass wait to have it return the created message instead, which is the only way to learn its ID.
func (*Client) ExecuteWebhookFiles ¶
func (c *Client) ExecuteWebhookFiles(ctx context.Context, webhookID Snowflake, token string, msg WebhookMessage, wait bool, threadID Snowflake, files ...File) (*Message, error)
ExecuteWebhookFiles posts a webhook message with attachments.
func (*Client) ExpirePoll ¶
ExpirePoll ends a poll early, freezing the results.
func (*Client) Extension ¶ added in v0.2.0
Extension returns the value stored under key, calling create to make it on first use. Every shard of an auto-sharded client shares the same value.
Packages that add optional features, such as voice, use it to keep one manager per client without the core package importing them. Use an unexported key type so values from different packages cannot collide.
When the client closes, a stored value that implements interface{ Close(context.Context) } is closed with a five-second deadline. If create returns an error, nothing is stored and the next call tries again.
func (*Client) FetchChannel ¶ added in v0.2.0
FetchChannel returns a channel from State, or from Discord when it is not cached.
func (*Client) FetchGuild ¶ added in v0.2.0
FetchGuild returns a guild from State, or from Discord when it is not cached.
func (*Client) FetchMember ¶ added in v0.2.0
FetchMember returns a member from State, or from Discord when it is not cached. Use State.Member when a network request is not acceptable.
func (*Client) FollowChannel ¶
FollowChannel makes an announcement channel's posts crosspost into target.
func (*Client) Gateway ¶
Gateway returns the public websocket URL, with no authentication and no shard recommendation.
func (*Client) GatewayBot ¶
func (c *Client) GatewayBot(ctx context.Context) (*GatewayInfo, error)
GatewayBot returns the connection details for this bot, including the recommended shard count.
starlings calls this itself when connecting; it is exported so a bot can check its remaining session budget before restarting.
func (*Client) GuildChannels ¶
GuildChannels lists every channel in a guild, excluding threads.
func (*Client) GuildCommand ¶
func (c *Client) GuildCommand(ctx context.Context, appID, guildID, commandID Snowflake) (*ApplicationCommand, error)
GuildCommand fetches one guild command.
func (*Client) GuildCommandPermissions ¶
func (c *Client) GuildCommandPermissions(ctx context.Context, appID, guildID, commandID Snowflake) (*GuildCommandPermissions, error)
GuildCommandPermissions reads one command's overrides in a guild.
func (*Client) GuildCommands ¶
func (c *Client) GuildCommands(ctx context.Context, appID, guildID Snowflake) ([]ApplicationCommand, error)
GuildCommands lists an application's commands in one guild.
func (*Client) GuildCommandsPermissions ¶
func (c *Client) GuildCommandsPermissions(ctx context.Context, appID, guildID Snowflake) ([]GuildCommandPermissions, error)
GuildCommandsPermissions lists the permission overrides for every command the application has in a guild.
func (*Client) GuildEmoji ¶
GuildEmoji fetches one custom emoji.
func (*Client) GuildEmojis ¶
GuildEmojis lists a guild's custom emoji.
func (*Client) GuildInvites ¶
GuildInvites lists every invite in a guild.
func (*Client) GuildJoinRequests ¶
func (c *Client) GuildJoinRequests(ctx context.Context, guildID Snowflake, status string, limit int) ([]GuildJoinRequest, error)
GuildJoinRequests lists pending membership applications.
func (*Client) GuildMember ¶
GuildMember fetches one member of a guild.
func (*Client) GuildPreview ¶
GuildPreview reads a discoverable guild's public preview.
func (*Client) GuildSoundboardSound ¶
func (c *Client) GuildSoundboardSound(ctx context.Context, guildID, soundID Snowflake) (*SoundboardSound, error)
GuildSoundboardSound fetches one sound.
func (*Client) GuildSoundboardSounds ¶
func (c *Client) GuildSoundboardSounds(ctx context.Context, guildID Snowflake) ([]SoundboardSound, error)
GuildSoundboardSounds lists a guild's soundboard sounds.
func (*Client) GuildSticker ¶
GuildSticker fetches one guild sticker.
func (*Client) GuildStickers ¶
GuildStickers lists a guild's custom stickers.
func (*Client) GuildTemplate ¶
GuildTemplate looks up a template by its share code.
func (*Client) GuildTemplates ¶
GuildTemplates lists a guild's templates. A guild may have only one.
func (*Client) GuildVoiceRegions ¶
GuildVoiceRegions lists the voice regions available to one guild, which can include VIP regions the guild has unlocked.
func (*Client) GuildWebhooks ¶
GuildWebhooks lists every webhook in a guild.
func (*Client) GuildWidgetImage ¶
GuildWidgetImage fetches the widget PNG through the client, which is only necessary when the guild's widget is not public.
func (*Client) GuildWidgetImageURL ¶
GuildWidgetImageURL returns the URL of a guild's widget PNG banner.
style is one of "shield", "banner1", "banner2", "banner3" or "banner4". The image needs no authentication, so this returns a URL rather than fetching it - put it straight in an <img> tag or an embed.
func (*Client) GuildWidgetJSON ¶
GuildWidgetJSON reads a guild's public widget.
func (*Client) HandleGatewayFrame ¶
HandleGatewayFrame runs one already-decoded websocket frame through Starlings' normal dispatcher, including raw handlers and internal state consumers. It is intended for deterministic replay, testing, and advanced transports. Ordinary bots should use Run instead.
Dispatch frames are safe to replay offline. Control opcodes such as heartbeat and reconnect retain their live gateway behavior and should not be injected without an attached transport.
func (*Client) IdentityProfile ¶
func (c *Client) IdentityProfile(ctx context.Context, appID, userID Snowflake, providerIssuedUserID string) (*IdentityProfile, error)
IdentityProfile reads back a player's stored stats.
func (*Client) Integrations ¶
Integrations lists a guild's integrations.
func (*Client) InteractionHandler ¶
InteractionHandler returns a normal net/http handler for Discord's Interactions Endpoint URL. It verifies every request and sends interactions through the same handlers registered with Slash and On.
publicKey is the hex value shown on the application's General Information page. Construct the handler once, then mount it wherever you like:
h, err := bot.InteractionHandler(os.Getenv("DISCORD_PUBLIC_KEY"))
if err != nil { log.Fatal(err) }
http.Handle("/interactions", h)
func (*Client) InvalidRequests ¶ added in v0.2.0
InvalidRequests reports how many 401, 403, and 429 responses Discord counted against the bot in the current ten-minute window. At 10,000, Cloudflare blocks the bot's IP address for a while.
func (*Client) Invite ¶
Invite looks up an invite by its code. Counts are only included when withCounts is set.
func (*Client) InviteTargetUsers ¶
func (c *Client) InviteTargetUsers(ctx context.Context, code string, limit int, after Snowflake) ([]InviteTargetUser, error)
InviteTargetUsers lists who may use a targeted invite.
func (*Client) InviteTargetUsersJobStatus ¶
func (c *Client) InviteTargetUsersJobStatus(ctx context.Context, code string) (*InviteTargetUsersJob, error)
InviteTargetUsersJobStatus reports how a bulk allow-list change is going.
func (*Client) JoinThread ¶
JoinThread adds the bot to a thread, which is required before it can post.
func (*Client) JoinVoice ¶
func (c *Client) JoinVoice(ctx context.Context, guildID, channelID Snowflake, mute, deaf bool) error
JoinVoice puts the bot into a voice channel, or moves it if it is already in one. Passing a zero channelID disconnects it.
This is the gateway's Voice State Update (opcode 4). It is all that is needed to play soundboard sounds; a full voice connection is only required to stream audio yourself.
func (*Client) LeaveGuild ¶
LeaveGuild removes the bot from a guild.
func (*Client) LeaveThread ¶
LeaveThread removes the bot from a thread.
func (*Client) LeaveVoice ¶
LeaveVoice disconnects the bot from voice in a guild.
func (*Client) Listen ¶
Listen registers a handler for a gateway event, inferring which event from the handler's argument type:
bot.On(func(m *starlings.MessageCreate) { m.Reply("hi") })
bot.On(func(r *starlings.Ready) { log.Println("online as", r.User.Tag()) })
It panics if handler is not a func taking exactly one pointer-to-event argument, because that is a mistake in the program rather than a runtime condition worth returning.
It resolves the type once, at registration, and dispatches through the same reflection-free path as the generic starlings.Listen.
func (*Client) LobbyInviteForUser ¶
LobbyInviteForUser creates a one-use invite to the lobby's linked channel.
func (*Client) Logger ¶
Logger returns the client's logger, so bots can log through the same handler.
func (*Client) LookupApplicationIdentity ¶
func (c *Client) LookupApplicationIdentity(ctx context.Context, appID Snowflake, providerType, providerIssuedUserID string) (*ApplicationIdentity, error)
LookupApplicationIdentity finds the identity matching an external account, which is how a game maps its own user ID back to a Discord user.
func (*Client) Members ¶
Members lists a guild's members.
This needs the privileged GuildMembers intent. Without it Discord returns only the bot itself, which looks like an empty guild rather than an error.
func (*Client) MessageHistory ¶ added in v0.2.0
func (c *Client) MessageHistory(ctx context.Context, channelID, before Snowflake) iter.Seq2[Message, error]
MessageHistory walks a channel's history from newest to oldest, fetching 100 messages per request. Start at before, or at the newest message when before is zero. Stop early by breaking out of the loop; no further requests are made.
for msg, err := range bot.MessageHistory(ctx, channelID, 0) {
if err != nil {
return err
}
fmt.Println(msg.Content)
}
An error ends the iteration after it is yielded.
func (*Client) Messages ¶
func (c *Client) Messages(ctx context.Context, channelID Snowflake, q MessagesQuery) ([]Message, error)
Messages fetches a page of a channel's history, newest first.
func (*Client) Modal ¶ added in v0.2.0
Modal handles a submitted modal whose custom ID matches pattern. A struct parameter is filled from the modal's text inputs and the first choice of its selects, matched by custom ID.
func (*Client) ModifyApplicationEmoji ¶
func (c *Client) ModifyApplicationEmoji(ctx context.Context, appID, emojiID Snowflake, name string) (*GuildEmoji, error)
ModifyApplicationEmoji renames an application emoji.
func (*Client) ModifyAutomodRule ¶
func (c *Client) ModifyAutomodRule(ctx context.Context, guildID, ruleID Snowflake, rule AutomodRule, reason string) (*AutomodRule, error)
ModifyAutomodRule edits a rule.
func (*Client) ModifyChannel ¶
func (c *Client) ModifyChannel(ctx context.Context, channelID Snowflake, params ChannelParams, reason string) (*Channel, error)
ModifyChannel edits a channel.
func (*Client) ModifyCurrentUser ¶
ModifyCurrentUser changes the bot's username or avatar. Leave a field empty to keep it; avatar is a data URI.
func (*Client) ModifyGuild ¶
func (c *Client) ModifyGuild(ctx context.Context, guildID Snowflake, params GuildParams, reason string) (*Guild, error)
ModifyGuild changes a guild's settings.
func (*Client) ModifyGuildEmoji ¶
func (c *Client) ModifyGuildEmoji(ctx context.Context, guildID, emojiID Snowflake, name string, roles []Snowflake, reason string) (*GuildEmoji, error)
ModifyGuildEmoji renames an emoji or changes which roles may use it.
func (*Client) ModifyGuildTemplate ¶
func (c *Client) ModifyGuildTemplate(ctx context.Context, guildID Snowflake, code, name, description string) (*GuildTemplate, error)
ModifyGuildTemplate renames a template.
func (*Client) ModifyMember ¶
func (c *Client) ModifyMember(ctx context.Context, guildID, userID Snowflake, m ModifyMember, reason string) (*Member, error)
ModifyMember changes a member's nickname, roles, voice state or timeout.
func (*Client) ModifyRole ¶
func (c *Client) ModifyRole(ctx context.Context, guildID, roleID Snowflake, params RoleParams, reason string) (*Role, error)
ModifyRole edits a role.
func (*Client) ModifyScheduledEvent ¶
func (c *Client) ModifyScheduledEvent(ctx context.Context, guildID, eventID Snowflake, e ScheduledEvent, reason string) (*ScheduledEvent, error)
ModifyScheduledEvent edits an event. Setting Status to EventActive starts it and EventCompleted ends it.
func (*Client) ModifyScheduledEventException ¶
func (c *Client) ModifyScheduledEventException(ctx context.Context, guildID, eventID, exceptionID Snowflake, e ScheduledEventException) (*ScheduledEventException, error)
ModifyScheduledEventException edits an existing exception.
func (*Client) ModifySoundboardSound ¶
func (c *Client) ModifySoundboardSound(ctx context.Context, guildID, soundID Snowflake, s NewSoundboardSound, reason string) (*SoundboardSound, error)
ModifySoundboardSound edits a sound's name, volume or emoji.
func (*Client) ModifyStageInstance ¶
func (c *Client) ModifyStageInstance(ctx context.Context, channelID Snowflake, topic, reason string) (*StageInstance, error)
ModifyStageInstance changes a live stage's topic.
func (*Client) ModifySticker ¶
func (c *Client) ModifySticker(ctx context.Context, guildID, stickerID Snowflake, name, description, tags, reason string) (*Sticker, error)
ModifySticker edits a guild sticker's name, description or tags.
func (*Client) ModifyWebhook ¶
func (c *Client) ModifyWebhook(ctx context.Context, webhookID Snowflake, params WebhookParams, reason string) (*Webhook, error)
ModifyWebhook edits a webhook.
func (*Client) ModifyWebhookWithToken ¶
func (c *Client) ModifyWebhookWithToken(ctx context.Context, webhookID Snowflake, token, name, avatar string) (*Webhook, error)
ModifyWebhookWithToken edits a webhook using its own token rather than the bot token. The channel cannot be changed this way.
func (*Client) ModifyWelcomeScreen ¶
func (c *Client) ModifyWelcomeScreen(ctx context.Context, guildID Snowflake, s WelcomeScreen, reason string) (*WelcomeScreen, error)
ModifyWelcomeScreen edits a guild's welcome screen.
func (*Client) ModifyWidgetSettings ¶
func (c *Client) ModifyWidgetSettings(ctx context.Context, guildID Snowflake, s GuildWidgetSettings, reason string) (*GuildWidgetSettings, error)
ModifyWidgetSettings changes the server widget settings.
func (*Client) MyPrivateArchivedThreads ¶
func (c *Client) MyPrivateArchivedThreads(ctx context.Context, channelID Snowflake, q ArchivedThreadsQuery) ([]Channel, bool, error)
MyPrivateArchivedThreads lists archived private threads the bot has joined.
func (*Client) NewMemberWelcome ¶
func (c *Client) NewMemberWelcome(ctx context.Context, guildID Snowflake) (*NewMemberWelcome, error)
NewMemberWelcome reads a guild's new-member welcome panel.
func (*Client) OAuth2Keys ¶
OAuth2Keys returns Discord's JWKS, used to verify the identity tokens the Social SDK issues.
func (*Client) On ¶
On registers a handler for the client's lifetime. Listen is the same convenient inferred form and returns a function that removes the handler.
func (*Client) OnComponent ¶ added in v0.2.0
OnComponent handles a button or select with this custom ID. It returns an unsubscribe function. Check the invoking user before handling controls intended for one person; custom IDs are routing data, not authority.
A route can capture parts of the ID: "ticket:close:{id}" matches "ticket:close:42", and i.Param("id") returns "42". Build such IDs with CustomID so values cannot add segments.
func (*Client) OnModal ¶ added in v0.2.0
OnModal handles submissions of the modal with exactly this custom ID. Use i.TextValue to read a text input without walking component layouts.
func (*Client) OnRaw ¶
OnRaw listens to every gateway dispatch, including events Starlings does not yet model. It returns an idempotent unsubscribe function.
func (*Client) Onboarding ¶
Onboarding reads a guild's onboarding configuration.
func (*Client) Online ¶ added in v0.2.0
Online reports whether every shard currently has a ready session. Unlike WaitReady, which only waits for the first READY, it becomes false while any shard is disconnected or still identifying.
func (*Client) OriginalWebhookMessage ¶
func (c *Client) OriginalWebhookMessage(ctx context.Context, webhookID Snowflake, token string) (*Message, error)
OriginalWebhookMessage reads the first message a webhook posted, which for an interaction webhook is the original response.
func (*Client) Pager ¶ added in v0.2.0
Pager registers a paged view under name, which must be unique:
warnings := bot.Pager("warnings", func(i *starlings.InteractionCreate, page int, userID string) (starlings.Page, error) {
...
})
return warnings.Show(i, user.ID.String(), true)
func (*Client) PinMessage ¶
func (c *Client) PinMessage(ctx context.Context, channelID, messageID Snowflake, reason string) error
PinMessage pins a message. A channel holds at most 50 pins.
func (*Client) PinMessageV2 ¶
func (c *Client) PinMessageV2(ctx context.Context, channelID, messageID Snowflake, reason string) error
PinMessageV2 pins a message through the newer pins endpoint.
func (*Client) PinnedMessages ¶
func (c *Client) PinnedMessages(ctx context.Context, channelID Snowflake, before string, limit int) (*MessagePins, error)
PinnedMessages lists a channel's pins, newest pin first.
func (*Client) PollAnswerVoters ¶
func (c *Client) PollAnswerVoters(ctx context.Context, channelID, messageID Snowflake, answerID int, q PollVotersQuery) ([]User, error)
PollAnswerVoters lists who voted for one answer on a poll.
func (*Client) PrivateArchivedThreads ¶
func (c *Client) PrivateArchivedThreads(ctx context.Context, channelID Snowflake, q ArchivedThreadsQuery) ([]Channel, bool, error)
PrivateArchivedThreads lists archived private threads the bot can see.
func (*Client) Prune ¶
func (c *Client) Prune(ctx context.Context, guildID Snowflake, days int, computeCount bool, includeRoles []Snowflake, reason string) (int, error)
Prune removes members with no roles who have been inactive for the given number of days.
Set computeCount to false on a large guild: counting is expensive, and Discord recommends skipping it, in which case the returned count is zero.
func (*Client) PruneCount ¶
func (c *Client) PruneCount(ctx context.Context, guildID Snowflake, days int, includeRoles []Snowflake) (int, error)
PruneCount reports how many members would be removed by a prune.
func (*Client) PublicArchivedThreads ¶
func (c *Client) PublicArchivedThreads(ctx context.Context, channelID Snowflake, q ArchivedThreadsQuery) ([]Channel, bool, error)
PublicArchivedThreads lists archived public threads in a channel, newest first. The boolean reports whether more pages remain.
The two archive listings repeat their request literal rather than sharing one, because internal/apidoc reads Route straight out of the AST: a route passed in as a variable measures as uncovered even though it is not.
func (*Client) PublishWidgetConfig ¶
PublishWidgetConfig makes a config live. Widget Top, Widget Bottom and Add Widget Preview must all have a layout and their required fields set.
func (*Client) Purge ¶ added in v0.2.0
func (c *Client) Purge(ctx context.Context, channelID Snowflake, opts PurgeOptions) (PurgeResult, error)
Purge deletes recent messages in a channel. Messages under 14 days old are removed with bulk deletes; older ones are removed one at a time, up to MaxOld, because Discord refuses them in bulk. The bot needs Manage Messages and Read Message History.
func (*Client) Reactions ¶
func (c *Client) Reactions(ctx context.Context, channelID, messageID Snowflake, emoji Emoji, q ReactionsQuery) ([]User, error)
Reactions lists who reacted to a message with a particular emoji.
func (*Client) RegisterRoleConnectionMetadata ¶
func (c *Client) RegisterRoleConnectionMetadata(ctx context.Context, appID Snowflake, records []RoleConnectionMetadata) ([]RoleConnectionMetadata, error)
RegisterRoleConnectionMetadata replaces an application's metadata schema. This is the first half of publishing a profile card: it declares which fields exist. It authenticates with the bot token.
At most MaxRoleConnectionMetadata records are allowed, which is checked here so the failure is legible rather than a 400 from Discord.
func (*Client) RemoveGroupDMRecipient ¶
RemoveGroupDMRecipient removes a user from a group DM.
func (*Client) RemoveInviteTargetUser ¶
RemoveInviteTargetUser removes one user from the allow-list.
func (*Client) RemoveLobbyMember ¶
RemoveLobbyMember removes a user. Removing an absent user is successful.
func (*Client) RemoveMemberRole ¶
func (c *Client) RemoveMemberRole(ctx context.Context, guildID, userID, roleID Snowflake, reason string) error
RemoveMemberRole takes a role away.
func (*Client) RemoveThreadMember ¶
RemoveThreadMember removes someone from a thread.
func (*Client) RemoveUserReaction ¶
func (c *Client) RemoveUserReaction(ctx context.Context, channelID, messageID, userID Snowflake, emoji Emoji) error
RemoveUserReaction deletes someone else's reaction. Needs Manage Messages.
func (*Client) ReorderChannels ¶
func (c *Client) ReorderChannels(ctx context.Context, guildID Snowflake, positions []ChannelPosition, reason string) error
ReorderChannels moves channels within a guild.
func (*Client) ReorderRoles ¶
func (c *Client) ReorderRoles(ctx context.Context, guildID Snowflake, positions []RolePosition, reason string) ([]Role, error)
ReorderRoles changes where roles sit in the hierarchy, which is what decides permission precedence as well as sidebar order.
func (*Client) Reply ¶
func (c *Client) Reply(ctx context.Context, channelID, messageID Snowflake, content string) (*Message, error)
Reply posts a message as a reply to another one.
func (*Client) RequestAllMembers ¶
RequestAllMembers is the common full-list request.
func (*Client) RequestChannelInfo ¶
func (c *Client) RequestChannelInfo(ctx context.Context, guildID Snowflake, fields ...ChannelInfoField) error
RequestChannelInfo fetches ephemeral voice-channel data for a guild. Results arrive as ChannelInfo events.
func (*Client) RequestMembers ¶
func (c *Client) RequestMembers(ctx context.Context, req MemberRequest) error
RequestMembers asks Discord to send GuildMembersChunk events. The GuildMembers intent is needed for a full member list.
func (*Client) RequestRaw ¶
RequestRaw performs an arbitrary request and returns the response bytes.
func (*Client) RequestSoundboardSounds ¶
RequestSoundboardSounds asks Discord for a guild's soundboard sounds. Results arrive as SoundboardSounds events.
func (*Client) ResolveJoinRequest ¶
func (c *Client) ResolveJoinRequest(ctx context.Context, guildID, requestID Snowflake, action, rejectionReason string) error
ResolveJoinRequest approves or rejects a membership application. action is "APPROVED" or "REJECTED".
func (*Client) RoleConnectionMetadataRecords ¶
func (c *Client) RoleConnectionMetadataRecords(ctx context.Context, appID Snowflake) ([]RoleConnectionMetadata, error)
RoleConnectionMetadataRecords returns the metadata schema an application has registered. It authenticates with the bot token.
func (*Client) RoleMemberCounts ¶
func (c *Client) RoleMemberCounts(ctx context.Context, guildID Snowflake) (map[Snowflake]int, error)
RoleMemberCounts returns how many members hold each role, keyed by role ID.
func (*Client) Run ¶
Run connects to the gateway and blocks until the process is interrupted with Ctrl-C or SIGTERM, then disconnects cleanly.
This is the whole lifecycle for most bots:
bot := starlings.New(token, starlings.WithIntents(starlings.IntentGuildMessages))
bot.On(func(m *starlings.MessageCreate) { m.Reply("hi") })
log.Fatal(bot.Run())
func (*Client) RunContext ¶
RunContext connects to the gateway and blocks until ctx is cancelled or the connection fails in a way that cannot be retried.
It reconnects on its own through network drops, Discord asking for a reconnect, and expired sessions, resuming where it can and starting a fresh session where it cannot. It gives up only on a configuration error - a bad token, or intents the bot has not been granted - because retrying those would fail identically forever.
func (*Client) ScheduledEvent ¶
func (c *Client) ScheduledEvent(ctx context.Context, guildID, eventID Snowflake, withUserCount bool) (*ScheduledEvent, error)
ScheduledEvent fetches one scheduled event.
func (*Client) ScheduledEventExceptionUsers ¶
func (c *Client) ScheduledEventExceptionUsers(ctx context.Context, guildID, eventID, exceptionID Snowflake, params url.Values) ([]ScheduledEventUser, error)
ScheduledEventExceptionUsers lists who is interested in one occurrence of a recurring event.
func (*Client) ScheduledEventUserCounts ¶
func (c *Client) ScheduledEventUserCounts(ctx context.Context, guildID, eventID Snowflake) (map[string]int, error)
ScheduledEventUserCounts returns how many people are interested in an event.
func (*Client) ScheduledEventUsers ¶
func (c *Client) ScheduledEventUsers(ctx context.Context, guildID, eventID Snowflake, limit int, withMember bool) ([]ScheduledEventUser, error)
ScheduledEventUsers lists who is interested in an event.
func (*Client) ScheduledEvents ¶
func (c *Client) ScheduledEvents(ctx context.Context, guildID Snowflake, withUserCount bool) ([]ScheduledEvent, error)
ScheduledEvents lists a guild's scheduled events.
func (*Client) SearchGuildMessages ¶
func (c *Client) SearchGuildMessages(ctx context.Context, guildID Snowflake, params url.Values) (*MessageSearchResult, error)
SearchGuildMessages searches a guild's message history.
Search is not available to most bots - Discord gates it - so expect a 403 unless the application has been granted access.
func (*Client) SearchMembers ¶
func (c *Client) SearchMembers(ctx context.Context, guildID Snowflake, name string, limit int) ([]Member, error)
SearchMembers finds members whose username or nickname starts with the given text. Limit is 1-1000.
func (*Client) SearchThreads ¶
func (c *Client) SearchThreads(ctx context.Context, channelID Snowflake, params url.Values) (*ThreadSearchResult, error)
SearchThreads searches a forum or media channel's posts.
func (*Client) SendComplex ¶
func (c *Client) SendComplex(ctx context.Context, channelID Snowflake, data SendData) (*Message, error)
SendComplex posts a message with embeds, components or a reply reference.
func (*Client) SendFiles ¶
func (c *Client) SendFiles(ctx context.Context, channelID Snowflake, data SendData, files ...File) (*Message, error)
SendFiles posts a message with attachments.
Files are limited by the guild's boost tier - 10 MiB by default. Pass an empty content to send attachments alone.
func (*Client) SendGateway ¶
SendGateway writes an arbitrary opcode and payload to every active shard. It is the low-level escape hatch used before Starlings has a typed helper.
func (*Client) SendGatewayRaw ¶
SendGatewayRaw writes an already encoded gateway frame to every shard.
func (*Client) SendGuildGateway ¶
func (c *Client) SendGuildGateway(ctx context.Context, guildID Snowflake, op Opcode, data any) error
SendGuildGateway sends an arbitrary payload only through the shard that owns guildID.
func (*Client) SendGuildGatewayRaw ¶
SendGuildGatewayRaw writes an encoded frame to the guild's owning shard.
func (*Client) SendSoundboardSound ¶
func (c *Client) SendSoundboardSound(ctx context.Context, channelID, soundID, sourceGuildID Snowflake) error
SendSoundboardSound plays a sound into a voice channel.
The bot must be connected to that voice channel - but "connected" here means a gateway voice-state update, not an actual voice websocket, so this works without implementing the voice protocol.
sourceGuildID is required only when playing a sound that belongs to a different guild than the channel; pass zero otherwise.
func (*Client) SetActivity ¶
SetActivity sets the status and the activity line in one call, e.g.
bot.SetActivity(ctx, starlings.StatusOnline, starlings.Playing("with starlings"))
func (*Client) SetApplicationCommands ¶
func (c *Client) SetApplicationCommands(ctx context.Context, appID Snowflake, cmds []ApplicationCommand) ([]ApplicationCommand, error)
SetApplicationCommands replaces every global command in one call. Commands absent from the list are deleted.
func (*Client) SetCurrentVoiceState ¶
func (c *Client) SetCurrentVoiceState(ctx context.Context, guildID, channelID Snowflake, suppress bool, requestToSpeak *time.Time) error
SetCurrentVoiceState updates the bot's own voice state, which is how a bot un-suppresses itself on a stage or asks to speak.
func (*Client) SetGuildCommandPermissions ¶
func (c *Client) SetGuildCommandPermissions(ctx context.Context, bearerToken string, appID, guildID, commandID Snowflake, perms []CommandPermission) (*GuildCommandPermissions, error)
SetGuildCommandPermissions replaces a command's overrides in a guild.
This one is unusual: it needs a *bearer* token from a user who can manage roles in that guild, not the bot token - so pass one obtained through OAuth2 rather than relying on the client's own credentials.
func (*Client) SetGuildCommands ¶
func (c *Client) SetGuildCommands(ctx context.Context, appID, guildID Snowflake, cmds []ApplicationCommand) ([]ApplicationCommand, error)
SetGuildCommands replaces every command in one guild.
func (*Client) SetIdentityProfile ¶
func (c *Client) SetIdentityProfile(ctx context.Context, appID, userID Snowflake, providerIssuedUserID string, profile IdentityProfile) (*IdentityProfile, error)
SetIdentityProfile writes a player's stats.
providerIssuedUserID is the player's ID in the game's own system. When the user has no identity for this application yet, the first successful write creates one with provider type NONE using this value; when they already have one, it must match an identity they already have.
Data is replaced wholesale: any field left out of profile.Data is erased, so always send the complete set. Leaving profile.Data nil instead updates the surrounding fields and leaves the stored stats untouched.
func (*Client) SetIncidentActions ¶
func (c *Client) SetIncidentActions(ctx context.Context, guildID Snowflake, invitesDisabledUntil, dmsDisabledUntil *time.Time) error
SetIncidentActions pauses invites or DMs during a raid. Both timestamps may be at most 24 hours ahead; pass nil to clear a pause.
func (*Client) SetInviteTargetUsers ¶
SetInviteTargetUsers replaces the whole allow-list for a targeted invite.
func (*Client) SetNickname ¶
SetNickname changes the bot's own nickname in a guild.
func (*Client) SetOnboarding ¶
func (c *Client) SetOnboarding(ctx context.Context, guildID Snowflake, o GuildOnboarding, reason string) (*GuildOnboarding, error)
SetOnboarding replaces a guild's onboarding configuration.
func (*Client) SetPermissionOverwrite ¶
func (c *Client) SetPermissionOverwrite(ctx context.Context, channelID, overwriteID Snowflake, allow, deny Permissions, kind int, reason string) error
SetPermissionOverwrite adds or replaces a channel permission overwrite for one role or member.
Deny is applied before Allow. Permissions left out of both are inherited from the category or the guild.
func (*Client) SetStatus ¶
SetStatus is the one-line presence toggle: it sets the status and clears the activity line. For "Playing ..." text, use UpdatePresence directly.
func (*Client) SetVoiceState ¶
func (c *Client) SetVoiceState(ctx context.Context, guildID, userID, channelID Snowflake, suppress bool) error
SetVoiceState updates another member's voice state - used to invite someone to speak on a stage, or move them back to the audience.
func (*Client) SetVoiceStatus ¶
SetVoiceStatus sets the status line shown on a voice channel.
func (*Client) ShardCount ¶
ShardCount returns the number of gateway shards currently configured.
func (*Client) ShardIDForGuild ¶
ShardIDForGuild reports which shard owns a guild using Discord's official snowflake routing formula.
func (*Client) ShardStatuses ¶
func (c *Client) ShardStatuses() []ShardStatus
ShardStatuses returns a stable snapshot suitable for dashboards and health endpoints. It never exposes the live gateway objects.
func (*Client) Slash ¶
func (c *Client) Slash(name, description string, handler any, options ...CommandOption) *SlashRoute
Slash registers a slash command and its handler in one step:
bot.Slash("ping", "Check the bot is alive", func(i *starlings.InteractionCreate) {
i.Reply("pong")
})
Add parameters with the option builders:
bot.Slash("say", "Repeat something", handler,
starlings.StringOption("text", "What to say", true))
This only registers it in the program. Call SyncCommands once connected to publish the definitions to Discord, which is what makes them appear in the client.
The handler can take any of the shapes described on Response: for example func() string, or func(*InteractionCreate, Args) (string, error), where the fields of Args become the command's options.
func (*Client) SlashCommand ¶
func (c *Client) SlashCommand(cmd ApplicationCommand, fn SlashFunc) *SlashRoute
SlashCommand is Slash with a fully specified command, for the cases the shorthand does not cover - context-menu commands, permission gates, localisations.
func (*Client) SlashDefinitions ¶
func (c *Client) SlashDefinitions() []ApplicationCommand
SlashDefinitions returns the registered command definitions, in no particular order.
func (*Client) SlashTask ¶ added in v0.2.0
func (c *Client) SlashTask(name, description string, fn TaskFunc, options ...CommandOption) *SlashRoute
SlashTask registers a command that acknowledges immediately, runs work outside the gateway loop, and sends the returned text without mentions. Tasks get a one-minute deadline by default and cancellation on shutdown. The callback must honor its context; Go cannot forcibly stop user code.
func (*Client) Social ¶
func (c *Client) Social(accessToken string) *SocialClient
Social creates a user-scoped Social SDK client from an OAuth2 access token.
func (*Client) StageInstance ¶
StageInstance fetches the live stage for a channel.
func (*Client) Starlog ¶ added in v0.2.0
Starlog returns the Starlog attached with WithStarlog, or nil.
func (*Client) StartThread ¶
func (c *Client) StartThread(ctx context.Context, channelID Snowflake, params ThreadParams, reason string) (*Channel, error)
StartThread creates a thread that is not attached to a message.
Set Type to ChannelPrivateThread for a private one; the default is a public thread.
func (*Client) StartThreadFromMessage ¶
func (c *Client) StartThreadFromMessage(ctx context.Context, channelID, messageID Snowflake, params ThreadParams, reason string) (*Channel, error)
StartThreadFromMessage creates a thread hanging off an existing message.
func (*Client) Sticker ¶
Sticker fetches any sticker by ID, including ones from Discord's own packs.
func (*Client) StickerPack ¶
StickerPack fetches one sticker pack.
func (*Client) StickerPacks ¶
func (c *Client) StickerPacks(ctx context.Context) ([]StickerPack, error)
StickerPacks lists the sticker packs Discord offers.
func (*Client) Subscription ¶
func (c *Client) Subscription(ctx context.Context, skuID, subscriptionID Snowflake) (*Subscription, error)
Subscription fetches one subscription.
func (*Client) Subscriptions ¶
func (c *Client) Subscriptions(ctx context.Context, skuID Snowflake, q SubscriptionsQuery) ([]Subscription, error)
Subscriptions lists the subscriptions for one SKU.
func (*Client) SyncCommands ¶
SyncCommands publishes every registered slash command to Discord, replacing whatever was there before.
Pass a guild ID while developing: guild commands appear immediately, whereas global ones (guildID zero) can take up to an hour to propagate.
The usual place to call this is a Ready handler, because it needs the application ID that READY provides:
bot.On(func(r *starlings.Ready) {
if err := bot.SyncCommands(context.Background(), guildID); err != nil {
log.Printf("syncing commands: %v", err)
}
})
func (*Client) SyncGuildTemplate ¶
func (c *Client) SyncGuildTemplate(ctx context.Context, guildID Snowflake, code string) (*GuildTemplate, error)
SyncGuildTemplate refreshes a template from the guild's current state, clearing IsDirty.
func (*Client) ThreadMember ¶
func (c *Client) ThreadMember(ctx context.Context, threadID, userID Snowflake, withMember bool) (*ThreadMember, error)
ThreadMember looks up one member of a thread.
func (*Client) ThreadMembers ¶
func (c *Client) ThreadMembers(ctx context.Context, threadID Snowflake, withMember bool) ([]ThreadMember, error)
ThreadMembers lists everyone in a thread.
Populating Member on each entry needs the privileged GuildMembers intent.
func (*Client) Timeout ¶
func (c *Client) Timeout(ctx context.Context, guildID, userID Snowflake, until time.Time, reason string) (*Member, error)
Timeout mutes a member until the given time, up to MaxTimeout ahead. Pass the zero time, or call ClearTimeout, to lift a timeout early.
func (*Client) Typing ¶
Typing shows the "Bot is typing..." indicator for about ten seconds. Useful before a slow reply.
func (*Client) UnmergeBotProvisionalAccount ¶
UnmergeBotProvisionalAccount detaches an external identity using bot auth.
func (*Client) UnmergeProvisionalAccount ¶
func (c *Client) UnmergeProvisionalAccount(ctx context.Context, credentials ProvisionalCredentials) error
UnmergeProvisionalAccount detaches an external identity using confidential client credentials.
func (*Client) UnpinMessage ¶
func (c *Client) UnpinMessage(ctx context.Context, channelID, messageID Snowflake, reason string) error
UnpinMessage removes a pin.
func (*Client) UnpinMessageV2 ¶
func (c *Client) UnpinMessageV2(ctx context.Context, channelID, messageID Snowflake, reason string) error
UnpinMessageV2 unpins a message through the newer pins endpoint.
func (*Client) UpdateDirectMessageModeration ¶
func (c *Client) UpdateDirectMessageModeration(ctx context.Context, user1, user2, messageID Snowflake, metadata map[string]string) error
UpdateDirectMessageModeration sets moderation metadata for a Social SDK DM.
func (*Client) UpdateLobbyMessageModeration ¶
func (c *Client) UpdateLobbyMessageModeration(ctx context.Context, lobbyID, messageID Snowflake, metadata map[string]string) error
UpdateLobbyMessageModeration sets application-visible moderation metadata.
func (*Client) UpdatePresence ¶
UpdatePresence changes the bot's status without reconnecting.
func (*Client) UpdateScheduledEvent ¶ added in v0.2.0
func (c *Client) UpdateScheduledEvent(ctx context.Context, guildID, eventID Snowflake, update ScheduledEventUpdate, reason string) (*ScheduledEvent, error)
UpdateScheduledEvent edits only the supplied fields. Prefer this over ModifyScheduledEvent, whose whole-object payload is retained for v0.1.0 compatibility.
func (*Client) UpdateUserRoleConnection ¶
func (c *Client) UpdateUserRoleConnection(ctx context.Context, bearerToken string, appID Snowflake, conn RoleConnection) (*RoleConnection, error)
UpdateUserRoleConnection publishes the card onto the profile of the user that bearerToken belongs to. This is the half that actually makes something appear.
The keys in conn.Metadata must match keys registered with RegisterRoleConnectionMetadata; unregistered keys are dropped.
func (*Client) UpdateWidgetConfig ¶
func (c *Client) UpdateWidgetConfig(ctx context.Context, appID Snowflake, configID string, surfaces map[string]WidgetSurface) (*WidgetConfig, error)
UpdateWidgetConfig rewrites a config's surfaces.
Send every surface you want to keep, not only the ones being changed: "surfaces" is replaced wholesale, so omitting a required surface unpublishes the widget.
func (*Client) UploadActivityAttachment ¶
func (c *Client) UploadActivityAttachment(ctx context.Context, appID Snowflake, file File) (*AttachmentUpload, error)
UploadActivityAttachment uploads an image on behalf of an embedded Activity and returns a temporary CDN URL for it.
The URL expires, so it is meant to be handed straight to whatever will display it rather than stored.
func (*Client) UserApplicationIdentities ¶
func (c *Client) UserApplicationIdentities(ctx context.Context, userID, appID Snowflake) ([]ApplicationIdentity, error)
UserApplicationIdentities lists the identities a user holds for one application. A bot may only ask about its own application.
func (*Client) UserConnections ¶
func (c *Client) UserConnections(ctx context.Context) ([]Connection, error)
UserConnections lists the current account's linked third-party accounts. Needs an OAuth2 token with the connections scope; a bot token returns an empty list.
func (*Client) UserEntitlements ¶
func (c *Client) UserEntitlements(ctx context.Context, bearerToken string, appID Snowflake) ([]Entitlement, error)
UserEntitlements lists the current user's entitlements for an application. Needs a bearer token.
func (*Client) UserRoleConnection ¶
func (c *Client) UserRoleConnection(ctx context.Context, bearerToken string, appID Snowflake) (*RoleConnection, error)
UserRoleConnection reads the card currently published for the user that bearerToken belongs to.
This endpoint is per-user, not per-bot: it needs an OAuth2 access token with the role_connections.write scope, which BearerToken wraps. A bot token works too, but then "@me" is the bot's own account and the card lands on the bot's profile.
func (*Client) VoiceRegions ¶
func (c *Client) VoiceRegions(ctx context.Context) ([]VoiceRegion, error)
VoiceRegions lists the voice regions available generally.
func (*Client) VoiceStateOf ¶
VoiceStateOf reads a member's voice state in a guild.
func (*Client) WaitReady ¶
WaitReady blocks until the gateway has sent READY, or ctx is cancelled. Useful when something has to happen right after connecting but you are not driving it from a Ready handler.
func (*Client) WebhookMessageByID ¶
func (c *Client) WebhookMessageByID(ctx context.Context, webhookID Snowflake, token string, messageID Snowflake) (*Message, error)
WebhookMessageByID fetches a message a webhook posted.
func (*Client) WebhookWithToken ¶
func (c *Client) WebhookWithToken(ctx context.Context, webhookID Snowflake, token string) (*Webhook, error)
WebhookWithToken fetches a webhook using its token instead of the bot token, which needs no permissions at all.
func (*Client) WelcomeScreen ¶
WelcomeScreen reads a guild's welcome screen.
func (*Client) WidgetConfigs ¶
WidgetConfigs lists an application's widget configs.
This works for any application, not just the token's own, which is the only practical way to inspect a layout Discord does not document.
func (*Client) WidgetSettings ¶
func (c *Client) WidgetSettings(ctx context.Context, guildID Snowflake) (*GuildWidgetSettings, error)
WidgetSettings reads the server widget settings.
type ClientIdentity ¶
ClientIdentity is what the client tells Discord it is: the browser and device strings in the gateway identify payload, and the User-Agent on REST calls. An empty OS falls back to the runtime OS at identify time.
type CloseCode ¶
type CloseCode int
CloseCode is a websocket close code from Discord's gateway.
const ( CloseUnknownError CloseCode = 4000 + iota CloseUnknownOpcode CloseDecodeError CloseNotAuthenticated CloseAuthenticationFailed CloseAlreadyAuthenticated CloseInvalidSeq CloseRateLimited CloseSessionTimedOut CloseInvalidShard CloseShardingRequired CloseInvalidAPIVersion CloseInvalidIntents CloseDisallowedIntents )
func (CloseCode) Fatal ¶
Fatal reports whether reconnecting at all is pointless - the bot is misconfigured and will fail the same way every time.
type CommandChoice ¶
type CommandChoice struct {
Name string `json:"name"`
NameLocalizations map[string]string `json:"name_localizations,omitzero"`
NameLocalized string `json:"name_localized,omitzero"`
Value any `json:"value"`
}
CommandChoice is one preset value for an option. Value must be a string or a number, matching the option's type.
type CommandFunc ¶
type CommandFunc func(m *MessageCreate, args []string)
CommandFunc handles one prefix command. args holds the whitespace-separated words after the command name, so `!say hello there` arrives as args = ["hello", "there"].
type CommandOption ¶
type CommandOption struct {
Type OptionType `json:"type"`
Name string `json:"name"`
NameLocalizations map[string]string `json:"name_localizations,omitzero"`
NameLocalized string `json:"name_localized,omitzero"`
Description string `json:"description"`
DescriptionLocalizations map[string]string `json:"description_localizations,omitzero"`
DescriptionLocalized string `json:"description_localized,omitzero"`
Required bool `json:"required,omitzero"`
// Choices restricts the option to a fixed set. Max 25.
Choices []CommandChoice `json:"choices,omitzero"`
// Options holds nested parameters, for OptionSubCommand and
// OptionSubCommandGroup.
Options []CommandOption `json:"options,omitzero"`
// ChannelTypes narrows an OptionChannel to particular kinds of channel.
ChannelTypes []ChannelType `json:"channel_types,omitzero"`
MinValue *float64 `json:"min_value,omitzero"`
MaxValue *float64 `json:"max_value,omitzero"`
MinLength *int `json:"min_length,omitzero"`
MaxLength *int `json:"max_length,omitzero"`
// Autocomplete asks Discord to send an autocomplete interaction as the
// user types. It cannot be combined with Choices.
Autocomplete bool `json:"autocomplete,omitzero"`
}
CommandOption is one parameter of a slash command, or a subcommand.
func BoolOption ¶
func BoolOption(name, description string, required bool) CommandOption
BoolOption builds a true/false parameter.
func ChannelOption ¶
func ChannelOption(name, description string, required bool) CommandOption
ChannelOption builds a channel picker.
func IntOption ¶
func IntOption(name, description string, required bool) CommandOption
IntOption builds an integer parameter.
func RoleOption ¶
func RoleOption(name, description string, required bool) CommandOption
RoleOption builds a role picker.
func StringOption ¶
func StringOption(name, description string, required bool) CommandOption
StringOption builds a required-or-optional text parameter.
func UserOption ¶
func UserOption(name, description string, required bool) CommandOption
UserOption builds a user picker.
type CommandPermission ¶
type CommandPermission struct {
ID Snowflake `json:"id"`
Type int `json:"type"`
Permission bool `json:"permission"`
}
CommandPermission allows or denies one role, user or channel access to a command.
The guild ID itself as a role ID means @everyone; the guild ID minus one as a channel ID means "all channels".
type CommandRoute ¶ added in v0.2.0
type CommandRoute struct {
// contains filtered or unexported fields
}
CommandRoute adds optional conveniences to a prefix command. Ignoring the value returned by Command keeps the one-line form.
func (*CommandRoute) Aliases ¶ added in v0.2.0
func (r *CommandRoute) Aliases(names ...string) *CommandRoute
Aliases registers more names for the same handler.
type Component ¶
type Component struct {
Type ComponentType `json:"type"`
ID int `json:"id,omitzero"`
// Action rows only.
Components []Component `json:"components,omitempty"`
// Buttons and select menus.
CustomID string `json:"custom_id,omitempty"` // echoed back on interaction, max 100 chars
Disabled bool `json:"disabled,omitzero"`
// Buttons only.
Style ButtonStyle `json:"style,omitzero"`
Label string `json:"label,omitempty"`
Emoji *Emoji `json:"emoji,omitempty"`
URL string `json:"url,omitempty"` // ButtonLink only
SKUID Snowflake `json:"sku_id,omitzero"` // ButtonPremium only
// Select menus only.
Options []SelectOption `json:"options,omitempty"`
DefaultValues []SelectDefaultValue `json:"default_values,omitempty"`
ChannelTypes []ChannelType `json:"channel_types,omitempty"`
Placeholder string `json:"placeholder,omitempty"`
MinValues *int `json:"min_values,omitempty"`
MaxValues int `json:"max_values,omitzero"`
// Text inputs (modals) only.
Value any `json:"value,omitempty"`
Values []string `json:"values,omitempty"`
Required *bool `json:"required,omitempty"`
Default *bool `json:"default,omitempty"`
MinLength *int `json:"min_length,omitempty"`
MaxLength int `json:"max_length,omitzero"`
// Components V2 display and layout fields.
Content string `json:"content,omitempty"`
Accessory *Component `json:"accessory,omitempty"`
Media *UnfurledMedia `json:"media,omitempty"`
File *UnfurledMedia `json:"file,omitempty"`
Items []MediaGalleryItem `json:"items,omitempty"`
Component *Component `json:"component,omitempty"`
Description string `json:"description,omitempty"`
Spoiler bool `json:"spoiler,omitzero"`
Divider *bool `json:"divider,omitempty"`
Spacing SeparatorSpacing `json:"spacing,omitzero"`
AccentColor *int `json:"accent_color,omitempty"`
FileTypes []string `json:"file_types,omitempty"`
Name string `json:"name,omitempty"`
Size int `json:"size,omitzero"`
}
Component is one entry in a message's interactive layout. Discord models every kind of component with a single JSON shape, so this struct is a union: which fields are meaningful depends on Type.
Legacy messages use action rows at the top level. Components V2 messages may instead use sections, text, galleries, files, separators and containers.
func AccentContainer ¶
AccentContainer builds a container with its left accent colour set.
func ActionRow ¶
ActionRow wraps components in the row container Discord requires at the top level of a message.
func Button ¶
func Button(style ButtonStyle, label, customID string) Component
Button builds a clickable button. The customID is echoed back to your interaction handler when someone presses it.
func CheckboxGroup ¶
func CheckboxGroup(customID string, options ...SelectOption) Component
CheckboxGroup builds a multiple-choice modal input.
func EntitySelect ¶
func EntitySelect(kind ComponentType, customID string) Component
EntitySelect builds a user, role, mentionable, or channel select menu.
func FileDisplay ¶
FileDisplay renders an uploaded attachment in a Components V2 layout.
func FileUpload ¶
FileUpload builds a modal file picker.
func LinkButton ¶
LinkButton builds a button that opens a URL. It never fires an interaction, so it has no custom ID.
func MediaGallery ¶
func MediaGallery(items ...MediaGalleryItem) Component
MediaGallery displays up to ten image or video items.
func PremiumButton ¶
PremiumButton builds a button that opens Discord's SKU purchase flow.
func RadioGroup ¶
func RadioGroup(customID string, options ...SelectOption) Component
RadioGroup builds a single-choice modal input.
func Separator ¶
func Separator(divider bool, spacing SeparatorSpacing) Component
Separator adds an optional rule and vertical spacing to a V2 layout.
func StringSelect ¶
func StringSelect(customID string, options ...SelectOption) Component
StringSelect builds a select menu whose choices are supplied by the bot.
func TextDisplay ¶
TextDisplay adds markdown text to a Components V2 message.
func TextInput ¶
func TextInput(style TextInputStyle, customID, placeholder string, required bool) Component
TextInput builds a modal text field. Wrap it in Label for modern modals or ActionRow for the legacy modal layout.
func (Component) SelectedValues ¶
SelectedValues returns values submitted by a select, file upload, or checkbox group inside a modal.
func (Component) StringValue ¶
StringValue returns a submitted text-input value without a type assertion.
type ComponentType ¶
type ComponentType int
ComponentType identifies which interactive element a Component describes.
const ( ComponentActionRow ComponentType = iota + 1 ComponentButton ComponentStringSelect ComponentTextInput ComponentUserSelect ComponentRoleSelect ComponentMentionableSelect ComponentChannelSelect ComponentSection ComponentTextDisplay ComponentThumbnail ComponentMediaGallery ComponentFile ComponentSeparator ComponentContainer ComponentLabel ComponentFileUpload ComponentRadioGroup ComponentCheckboxGroup ComponentCheckbox )
type Connect ¶
type Connect struct {
ShardID int `json:"shard_id"`
// contains filtered or unexported fields
}
Connect fires after a gateway shard has completed its websocket handshake and sent Identify or Resume. It is a Starlings lifecycle event, not a Discord dispatch.
type Connection ¶
type Connection struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"` // "github", "spotify", "steam", ...
Revoked bool `json:"revoked"`
Verified bool `json:"verified"`
FriendSync bool `json:"friend_sync"`
ShowActivity bool `json:"show_activity"`
Visibility int `json:"visibility"`
}
Connection is a third-party account a user has linked to Discord.
type CurrentApplication ¶
type CurrentApplication struct {
ID Snowflake `json:"id"`
Name string `json:"name"`
Icon string `json:"icon"`
Description string `json:"description"`
Owner *User `json:"owner"`
Team *AppTeam `json:"team"`
}
CurrentApplication describes the application a bot token belongs to.
func (*CurrentApplication) HumanOwnerID ¶
func (a *CurrentApplication) HumanOwnerID() Snowflake
HumanOwnerID returns the user ID of the person who owns the application, resolving through the team when there is one, and zero if neither is set.
type CurrentUserGuildsQuery ¶
type CurrentUserGuildsQuery struct {
Before Snowflake
After Snowflake
Limit int // 1-200
WithCounts bool
}
CurrentUserGuildsQuery pages through the guilds a bot is in.
type Disconnect ¶
type Disconnect struct {
ShardID int `json:"shard_id"`
// CloseCode and CloseReason are set when Discord closed the connection.
// They are zero for network failures and for a client shutting down.
CloseCode CloseCode `json:"close_code,omitzero"`
CloseReason string `json:"close_reason,omitzero"`
// contains filtered or unexported fields
}
Disconnect fires when an established gateway shard closes, including when Starlings is about to reconnect it.
type DynamicField ¶
type DynamicField struct {
Type DynamicFieldType `json:"type"`
Name string `json:"name"`
Value any `json:"value"` // string, number, or Media
}
DynamicField is a custom stat, for anything the primary fields do not cover.
Name is the key referenced by a User Data field in the widget editor. It is never shown to players - display labels live on the widget's fields, not here.
func MediaField ¶
func MediaField(name, url string) DynamicField
MediaField builds an image stat - the mechanism behind widget tiles that show a thumbnail alongside their text.
func NumberField ¶
func NumberField(name string, value float64) DynamicField
NumberField builds a numeric stat. The widget editor can render one with compact notation, or as a duration when the value is milliseconds.
func StringField ¶
func StringField(name, value string) DynamicField
StringField builds a text stat.
type DynamicFieldType ¶
type DynamicFieldType int
DynamicFieldType identifies the value shape of a custom stat.
const ( DynamicString DynamicFieldType = iota + 1 DynamicNumber DynamicMedia )
type Embed ¶
type Embed struct {
Title string `json:"title,omitempty"` // max 256
Type string `json:"type,omitempty"` // always "rich" for bot-sent embeds
Description string `json:"description,omitempty"` // max 4096
URL string `json:"url,omitempty"` // makes the title a link
Timestamp *time.Time `json:"timestamp,omitempty"`
Color int `json:"color,omitzero"` // 0xRRGGBB
Image *EmbedMedia `json:"image,omitempty"`
Thumbnail *EmbedMedia `json:"thumbnail,omitempty"`
Video *EmbedMedia `json:"video,omitempty"`
Provider *EmbedProvider `json:"provider,omitempty"`
Author *EmbedAuthor `json:"author,omitempty"`
Fields []EmbedField `json:"fields,omitempty"` // max 25
}
Embed is the rich card that can accompany a message: a title, description, coloured bar, fields, images and footer.
Discord caps the total text across every embed on one message at 6000 characters, on top of the individual limits noted below.
func NewEmbed ¶ added in v0.2.0
NewEmbed starts an embed with a title:
e := starlings.NewEmbed("Warning issued").
SetDescription(reason).
SetColor(starlings.ColorYellow).
AddField("Moderator", mod.Mention(), true)
func (*Embed) AddField ¶
AddField appends a field and returns the embed, so calls can be chained. Text is shortened to Discord's limits, an empty name or value is filled with an invisible character, and fields past Discord's 25 are dropped.
func (*Embed) SetColor ¶ added in v0.2.0
SetColor sets the coloured bar, as 0xRRGGBB, and returns the embed.
func (*Embed) SetDescription ¶ added in v0.2.0
SetDescription sets the main text and returns the embed.
func (*Embed) SetThumbnail ¶
SetThumbnail sets the corner thumbnail and returns the embed.
func (*Embed) SetTimestamp ¶ added in v0.2.0
SetTimestamp shows t in the footer, in each reader's time zone.
type EmbedAuthor ¶
type EmbedAuthor struct {
Name string `json:"name"` // max 256
URL string `json:"url,omitempty"`
IconURL string `json:"icon_url,omitempty"`
}
EmbedAuthor is the small line above the title.
type EmbedField ¶
type EmbedField struct {
Name string `json:"name"` // max 256
Value string `json:"value"` // max 1024
Inline bool `json:"inline,omitzero"`
}
EmbedField is one name/value pair in an embed's body.
type EmbedFooter ¶
type EmbedFooter struct {
}
EmbedFooter is the small line at the bottom of an embed.
type EmbedMedia ¶
type EmbedMedia struct {
URL string `json:"url"`
ProxyURL string `json:"proxy_url,omitempty"`
Height int `json:"height,omitzero"`
Width int `json:"width,omitzero"`
}
EmbedMedia is an image, thumbnail or video attached to an embed. Only URL matters when sending; Discord fills in the rest.
type EmbedProvider ¶
EmbedProvider names the source of an auto-generated embed.
type Emoji ¶
type Emoji struct {
ID Snowflake `json:"id"`
Name string `json:"name"`
Animated bool `json:"animated"`
}
Emoji is either a Unicode emoji (ID zero, Name holds the character) or a custom guild emoji (ID set).
type Entitlement ¶
type Entitlement struct {
ID Snowflake `json:"id"`
SKUID Snowflake `json:"sku_id"`
ApplicationID Snowflake `json:"application_id"`
UserID Snowflake `json:"user_id"`
GuildID Snowflake `json:"guild_id"`
Type EntitlementType `json:"type"`
Deleted bool `json:"deleted"`
StartsAt *time.Time `json:"starts_at"`
EndsAt *time.Time `json:"ends_at"`
Consumed bool `json:"consumed"`
SubscriptionID Snowflake `json:"subscription_id"`
GifterUserID Snowflake `json:"gifter_user_id"`
ParentID Snowflake `json:"parent_id"`
FulfilledAt *time.Time `json:"fulfilled_at"`
FulfillmentStatus int `json:"fulfillment_status"`
}
Entitlement is a user's or guild's access to a premium SKU.
type EntitlementCreate ¶
type EntitlementCreate struct {
Entitlement
// contains filtered or unexported fields
}
EntitlementCreate fires when someone buys or is granted a SKU.
type EntitlementDelete ¶
type EntitlementDelete struct {
Entitlement
// contains filtered or unexported fields
}
EntitlementDelete fires when an entitlement is revoked. Note that an expiry is an update rather than a delete.
type EntitlementType ¶
type EntitlementType int
EntitlementType says how a user came to hold an entitlement.
const ( EntitlementPurchase EntitlementType = 1 EntitlementPremiumSubscription EntitlementType = 2 EntitlementDeveloperGift EntitlementType = 3 EntitlementTestModePurchase EntitlementType = 4 EntitlementFreePurchase EntitlementType = 5 EntitlementUserGift EntitlementType = 6 EntitlementPremiumPurchase EntitlementType = 7 EntitlementApplicationSubscription EntitlementType = 8 )
type EntitlementUpdate ¶
type EntitlementUpdate struct {
Entitlement
// contains filtered or unexported fields
}
EntitlementUpdate fires when an entitlement changes, such as a renewal.
type EntitlementsQuery ¶
type EntitlementsQuery struct {
UserID Snowflake
SKUIDs []Snowflake
Before Snowflake
After Snowflake
Limit int // 1-100
GuildID Snowflake
ExcludeEnded bool
// IncludeDeleted overrides Discord's default of excluding deleted grants.
IncludeDeleted bool
}
EntitlementsQuery narrows a list of entitlements.
type EntryPointHandlerType ¶
type EntryPointHandlerType int
const ( EntryPointAppHandler EntryPointHandlerType = iota + 1 EntryPointDiscordLaunchActivity )
type Event ¶
type Event interface {
// contains filtered or unexported methods
}
Event is implemented by every gateway event type. The method is unexported, so the set of events is closed to this package - which is what lets On resolve a handler to a Discord event name with no configuration.
type EventWaiter ¶ added in v0.2.0
type EventWaiter[E Event] struct { // contains filtered or unexported fields }
EventWaiter owns a one-event subscription. Wait consumes the result once; Close and context cancellation remove the subscription. It does not retain a growing event history.
func Watch ¶ added in v0.2.0
Watch subscribes immediately to the next matching event. Register before sending a prompt, then Wait outside a synchronous gateway handler. Match should be quick and side-effect free, and check user/channel IDs for private workflows. A nil predicate accepts any event of E.
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
reply := starlings.Watch[starlings.MessageCreate](ctx, bot, func(m *starlings.MessageCreate) bool {
return m.ChannelID == channelID && m.Author != nil && m.Author.ID == userID
})
defer reply.Close()
// Send the prompt now, after the subscription exists.
message, err := reply.Wait()
func (*EventWaiter[E]) Close ¶ added in v0.2.0
func (w *EventWaiter[E]) Close()
Close cancels an unfinished wait and removes its listener.
func (*EventWaiter[E]) Wait ¶ added in v0.2.0
func (w *EventWaiter[E]) Wait() (*E, error)
Wait waits for one matching event or cancellation. Call it once per waiter.
type ExternalAuthType ¶
type ExternalAuthType string
ExternalAuthType identifies the game account provider behind a provisional user.
const ( ExternalAuthOIDC ExternalAuthType = "OIDC" ExternalAuthEpicAccessToken ExternalAuthType = "EPIC_ONLINE_SERVICES_ACCESS_TOKEN" ExternalAuthEpicIDToken ExternalAuthType = "EPIC_ONLINE_SERVICES_ID_TOKEN" ExternalAuthSteamSessionTicket ExternalAuthType = "STEAM_SESSION_TICKET" ExternalAuthUnityIDToken ExternalAuthType = "UNITY_SERVICES_ID_TOKEN" ExternalAuthDiscordBotAccessToken ExternalAuthType = "DISCORD_BOT_ISSUED_ACCESS_TOKEN" ExternalAuthAppleIDToken ExternalAuthType = "APPLE_ID_TOKEN" ExternalAuthPlayStationNetworkIDToken ExternalAuthType = "PLAYSTATION_NETWORK_ID_TOKEN" )
type FatalError ¶
FatalError wraps a gateway failure that retrying cannot fix: a rejected token, or intents the bot has not been granted. RunContext returns one of these instead of reconnecting forever.
func (*FatalError) Error ¶
func (e *FatalError) Error() string
type FieldError ¶
type FieldError struct {
Path string // dotted path, e.g. "embeds.0.description"
Code string
Message string
}
FieldError is a single validation failure against one field of the request.
type File ¶
type File struct {
Name string
Description string
ContentType string // guessed from the name when empty
Data io.Reader
// contains filtered or unexported fields
}
File is an attachment to upload.
Name is what Discord shows and must include an extension for previews to work. Description becomes the image's alt text.
func FileFromBytes ¶
FileFromBytes attaches data already in memory.
func FileFromPath ¶
FileFromPath prepares a file from disk without loading it into memory. The caller closes nothing; Starlings opens it while constructing the upload.
type ForumReaction ¶
type ForumReaction struct {
EmojiID Snowflake `json:"emoji_id"`
EmojiName string `json:"emoji_name"`
}
ForumReaction is the emoji shown as a forum channel's default reaction.
type ForumTag ¶
type ForumTag struct {
ID Snowflake `json:"id"`
Name string `json:"name"`
Moderated bool `json:"moderated"`
EmojiID Snowflake `json:"emoji_id"`
EmojiName string `json:"emoji_name"`
}
ForumTag is a selectable tag on a forum or media channel.
type GatewayCloseError ¶ added in v0.2.0
GatewayCloseError reports that Discord closed a gateway connection. The client reconnects on its own, and the Disconnect event carries the code and reason. A fatal code is returned from RunContext as a *FatalError instead.
func (*GatewayCloseError) Error ¶ added in v0.2.0
func (e *GatewayCloseError) Error() string
type GatewayInfo ¶
type GatewayInfo struct {
URL string `json:"url"`
Shards int `json:"shards"`
SessionStartLimit struct {
Total int `json:"total"`
Remaining int `json:"remaining"`
ResetAfter int `json:"reset_after"`
MaxConcurrency int `json:"max_concurrency"`
} `json:"session_start_limit"`
}
GatewayInfo is what Discord recommends for connecting: the websocket URL, how many shards to use, and how many sessions are left today.
type Guard ¶
type Guard struct {
// contains filtered or unexported fields
}
Guard is a small in-process profiler for manual and automatic implementations. It stores fixed-size histograms, never request payloads.
func (*Guard) Measure ¶
func (g *Guard) Measure(feature string, implementation GuardImplementation, fn func() error) error
Measure profiles one implementation without executing it twice. Use this for side-effecting work such as REST calls and message sends.
func (*Guard) Observe ¶
func (g *Guard) Observe(feature string, implementation GuardImplementation, duration time.Duration, err error)
Observe records a measurement made by application code.
func (*Guard) Report ¶
func (g *Guard) Report() GuardReport
Report returns stable, feature-sorted metrics and recommendations.
type GuardAdvice ¶
GuardAdvice compares the observed implementations for one feature.
type GuardFinding ¶ added in v0.2.0
GuardFinding is an evidence-backed performance or memory recommendation.
type GuardImplementation ¶
type GuardImplementation string
GuardImplementation identifies the implementation a profile sample used.
const ( GuardAutomatic GuardImplementation = "automatic" GuardManual GuardImplementation = "manual" GuardApplication GuardImplementation = "application" )
type GuardMetric ¶
type GuardMetric struct {
Feature string
Implementation GuardImplementation
Calls uint64
Errors uint64
Total time.Duration
Average time.Duration
Minimum time.Duration
Maximum time.Duration
P50 time.Duration
P95 time.Duration
}
GuardMetric is one immutable row in a Guard report.
type GuardOption ¶
type GuardOption func(*Guard)
GuardOption tunes Starlings Guard.
func WithGuardMaxFeatures ¶
func WithGuardMaxFeatures(maximum int) GuardOption
WithGuardMaxFeatures bounds distinct labels retained by Guard. Additional labels are combined under "other". The default is 256.
func WithGuardWarmup ¶ added in v0.2.0
func WithGuardWarmup(warmup time.Duration) GuardOption
WithGuardWarmup delays cache-rightsizing advice until Guard has observed a representative workload. Timing and correctness metrics are still recorded immediately. The default is 30 seconds; zero is useful in tests.
type GuardReport ¶
type GuardReport struct {
Metrics []GuardMetric
Advice []GuardAdvice
Findings []GuardFinding
Runtime GuardRuntime
DroppedSamples uint64
}
GuardReport is a race-safe point-in-time profile snapshot.
func (GuardReport) String ¶
func (r GuardReport) String() string
String formats a compact report suitable for logs and development output.
type GuardRuntime ¶ added in v0.2.0
GuardRuntime is a cheap process snapshot taken when Report is called.
type Guild ¶
type Guild struct {
ID Snowflake `json:"id"`
Name string `json:"name"`
Icon string `json:"icon"`
Splash string `json:"splash"`
OwnerID Snowflake `json:"owner_id"`
Permissions Permissions `json:"permissions,string"`
AFKChannelID Snowflake `json:"afk_channel_id"`
AFKTimeout int `json:"afk_timeout"`
VerificationLevel int `json:"verification_level"`
DefaultMessageNotifications int `json:"default_message_notifications"`
ExplicitContentFilter int `json:"explicit_content_filter"`
Roles []Role `json:"roles"`
Emojis []GuildEmoji `json:"emojis"`
Stickers []Sticker `json:"stickers"`
Features []string `json:"features"`
MFALevel int `json:"mfa_level"`
SystemChannelID Snowflake `json:"system_channel_id"`
RulesChannelID Snowflake `json:"rules_channel_id"`
Description string `json:"description"`
Banner string `json:"banner"`
PremiumTier int `json:"premium_tier"`
PremiumSubscriptionCount int `json:"premium_subscription_count"`
PreferredLocale string `json:"preferred_locale"`
NSFWLevel int `json:"nsfw_level"`
// Gateway-only, present on GUILD_CREATE.
JoinedAt time.Time `json:"joined_at"`
Large bool `json:"large"`
MemberCount int `json:"member_count"`
VoiceStates []VoiceState `json:"voice_states"`
Members []Member `json:"members"`
Channels []Channel `json:"channels"`
Threads []Channel `json:"threads"`
Presences []PresenceUpdate `json:"presences"`
StageInstances []StageInstance `json:"stage_instances"`
GuildScheduledEvents []ScheduledEvent `json:"guild_scheduled_events"`
SoundboardSounds []SoundboardSound `json:"soundboard_sounds"`
// contains filtered or unexported fields
}
Guild is a Discord server.
On the GUILD_CREATE that arrives right after connecting, the gateway fills in Channels, Members and the other collections below. Guilds fetched over REST carry only the guild's own fields.
func (*Guild) Member ¶ added in v0.2.0
Member returns a member from the cache, or from Discord when it is not cached.
func (*Guild) Role ¶
Role returns the role with the given ID, or nil. Only useful on a guild that came with its roles populated.
type GuildAuditLogEntryCreate ¶
type GuildAuditLogEntryCreate struct {
AuditLogEntry
GuildID Snowflake `json:"guild_id"`
// contains filtered or unexported fields
}
GuildAuditLogEntryCreate fires on any logged administrative action, which makes it the cheapest way to watch moderation without polling the audit log.
type GuildBanAdd ¶
type GuildBanAdd struct {
GuildID Snowflake `json:"guild_id"`
User *User `json:"user"`
// contains filtered or unexported fields
}
GuildBanAdd fires when a user is banned. Needs the GuildModeration intent.
type GuildBanRemove ¶
type GuildBanRemove struct {
GuildID Snowflake `json:"guild_id"`
User *User `json:"user"`
// contains filtered or unexported fields
}
GuildBanRemove fires when a user is unbanned.
type GuildCommandPermissions ¶
type GuildCommandPermissions struct {
ID Snowflake `json:"id"`
ApplicationID Snowflake `json:"application_id"`
GuildID Snowflake `json:"guild_id"`
Permissions []CommandPermission `json:"permissions"`
}
GuildCommandPermissions is the override set for one command in one guild.
type GuildCreate ¶
type GuildCreate struct {
Guild
// contains filtered or unexported fields
}
GuildCreate fires on connect for every guild the bot is in, and again whenever it joins a new one.
type GuildDelete ¶
type GuildDelete struct {
ID Snowflake `json:"id"`
BeforeDelete *Guild `json:"-"`
// contains filtered or unexported fields
}
GuildDelete fires when the bot leaves a guild, or the guild goes offline. Unavailable distinguishes the two.
type GuildEmoji ¶
type GuildEmoji struct {
ID Snowflake `json:"id"`
Name string `json:"name"`
Roles []Snowflake `json:"roles"` // if set, only these roles may use it
User *User `json:"user"` // who uploaded it
RequireColons bool `json:"require_colons"`
Managed bool `json:"managed"`
Animated bool `json:"animated"`
Available bool `json:"available"` // false when lost to a boost downgrade
}
GuildEmoji is a custom emoji uploaded to a guild. It extends the minimal Emoji sent on reactions with authorship and role restrictions.
type GuildEmojisUpdate ¶
type GuildEmojisUpdate struct {
GuildID Snowflake `json:"guild_id"`
Emojis []GuildEmoji `json:"emojis"`
BeforeUpdate []GuildEmoji `json:"-"`
// contains filtered or unexported fields
}
GuildEmojisUpdate fires when a guild's emoji change. It sends the whole new set rather than a delta.
type GuildIntegrationsUpdate ¶
type GuildIntegrationsUpdate struct {
GuildID Snowflake `json:"guild_id"`
// contains filtered or unexported fields
}
GuildIntegrationsUpdate fires when a guild's integrations change.
type GuildJoinRequest ¶
type GuildJoinRequest struct {
ID Snowflake `json:"id"`
UserID Snowflake `json:"user_id"`
GuildID Snowflake `json:"guild_id"`
Status string `json:"status"`
CreatedAt string `json:"created_at"`
RejectionReason string `json:"rejection_reason,omitzero"`
User *User `json:"user"`
}
GuildJoinRequest is someone waiting to be approved into a guild that has membership screening with approval enabled.
type GuildMemberAdd ¶
type GuildMemberAdd struct {
Member
GuildID Snowflake `json:"guild_id"`
// contains filtered or unexported fields
}
GuildMemberAdd fires when someone joins a guild. Needs the privileged GuildMembers intent.
type GuildMemberRemove ¶
type GuildMemberRemove struct {
GuildID Snowflake `json:"guild_id"`
User *User `json:"user"`
BeforeDelete *Member `json:"-"`
// contains filtered or unexported fields
}
GuildMemberRemove fires when someone leaves or is removed from a guild.
type GuildMemberUpdate ¶
type GuildMemberUpdate struct {
GuildID Snowflake `json:"guild_id"`
User *User `json:"user"`
Nick string `json:"nick"`
Avatar string `json:"avatar"`
Roles []Snowflake `json:"roles"`
JoinedAt *time.Time `json:"joined_at"`
PremiumSince *time.Time `json:"premium_since"`
Deaf *bool `json:"deaf"`
Mute *bool `json:"mute"`
Pending bool `json:"pending"`
Flags int `json:"flags"`
CommunicationDisabledUntil *time.Time `json:"communication_disabled_until"`
BeforeUpdate *Member `json:"-"`
// contains filtered or unexported fields
}
GuildMemberUpdate fires when a member's roles, nickname or timeout change.
Discord sends the member's complete current state, so a null field means the value was removed: CommunicationDisabledUntil is nil once a timeout is lifted, and Avatar is empty once a guild avatar is reset.
type GuildMembersChunk ¶
type GuildMembersChunk struct {
GuildID Snowflake `json:"guild_id"`
Members []Member `json:"members"`
ChunkIndex int `json:"chunk_index"`
ChunkCount int `json:"chunk_count"`
NotFound []Snowflake `json:"not_found"`
Presences []PresenceUpdate `json:"presences"`
Nonce string `json:"nonce"`
// contains filtered or unexported fields
}
GuildMembersChunk answers a Request Guild Members call. Large member lists arrive across several chunks; ChunkIndex and ChunkCount say where this one sits.
type GuildOnboarding ¶
type GuildOnboarding struct {
GuildID Snowflake `json:"guild_id"`
Prompts []OnboardingPrompt `json:"prompts"`
DefaultChannelIDs []Snowflake `json:"default_channel_ids"`
Enabled bool `json:"enabled"`
Mode int `json:"mode"`
}
GuildOnboarding is the new-member onboarding flow.
type GuildParams ¶
type GuildParams struct {
Name *string `json:"name,omitzero"`
VerificationLevel *int `json:"verification_level,omitzero"`
DefaultMessageNotifications *int `json:"default_message_notifications,omitzero"`
ExplicitContentFilter *int `json:"explicit_content_filter,omitzero"`
AFKChannelID *Snowflake `json:"afk_channel_id,omitzero"`
AFKTimeout *int `json:"afk_timeout,omitzero"`
Icon *string `json:"icon,omitzero"` // data URI
OwnerID *Snowflake `json:"owner_id,omitzero"`
Splash *string `json:"splash,omitzero"`
Banner *string `json:"banner,omitzero"`
SystemChannelID *Snowflake `json:"system_channel_id,omitzero"`
RulesChannelID *Snowflake `json:"rules_channel_id,omitzero"`
PublicUpdatesChannelID *Snowflake `json:"public_updates_channel_id,omitzero"`
PreferredLocale *string `json:"preferred_locale,omitzero"`
Features *[]string `json:"features,omitzero"`
Description *string `json:"description,omitzero"`
PremiumProgressBarEnabled *bool `json:"premium_progress_bar_enabled,omitzero"`
}
GuildParams are the settable fields of a guild.
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 []GuildEmoji `json:"emojis"`
Features []string `json:"features"`
ApproximateMemberCount int `json:"approximate_member_count"`
ApproximatePresenceCount int `json:"approximate_presence_count"`
Description string `json:"description"`
}
GuildPreview is the public summary of a discoverable guild, readable without being a member.
type GuildProductPurchase ¶
type GuildRoleCreate ¶
type GuildRoleCreate struct {
GuildID Snowflake `json:"guild_id"`
Role *Role `json:"role"`
// contains filtered or unexported fields
}
GuildRoleCreate fires when a role is added.
type GuildRoleDelete ¶
type GuildRoleDelete struct {
GuildID Snowflake `json:"guild_id"`
RoleID Snowflake `json:"role_id"`
BeforeDelete *Role `json:"-"`
// contains filtered or unexported fields
}
GuildRoleDelete fires when a role is removed.
type GuildRoleUpdate ¶
type GuildRoleUpdate struct {
GuildID Snowflake `json:"guild_id"`
Role *Role `json:"role"`
BeforeUpdate *Role `json:"-"`
// contains filtered or unexported fields
}
GuildRoleUpdate fires when a role changes.
type GuildScheduledEventCreate ¶
type GuildScheduledEventCreate struct {
ScheduledEvent
// contains filtered or unexported fields
}
GuildScheduledEventCreate fires when an event is scheduled.
type GuildScheduledEventDelete ¶
type GuildScheduledEventDelete struct {
ScheduledEvent
// contains filtered or unexported fields
}
GuildScheduledEventDelete fires when an event is cancelled.
type GuildScheduledEventUpdate ¶
type GuildScheduledEventUpdate struct {
ScheduledEvent
// contains filtered or unexported fields
}
GuildScheduledEventUpdate fires when an event changes, including when it starts and ends - watch Status for that.
type GuildScheduledEventUserAdd ¶
type GuildScheduledEventUserAdd struct {
GuildScheduledEventID Snowflake `json:"guild_scheduled_event_id"`
UserID Snowflake `json:"user_id"`
GuildID Snowflake `json:"guild_id"`
// contains filtered or unexported fields
}
GuildScheduledEventUserAdd fires when someone marks themselves interested.
type GuildScheduledEventUserRemove ¶
type GuildScheduledEventUserRemove struct {
GuildScheduledEventID Snowflake `json:"guild_scheduled_event_id"`
UserID Snowflake `json:"user_id"`
GuildID Snowflake `json:"guild_id"`
// contains filtered or unexported fields
}
GuildScheduledEventUserRemove fires when someone withdraws interest.
type GuildSoundboardSoundCreate ¶
type GuildSoundboardSoundCreate struct {
SoundboardSound
// contains filtered or unexported fields
}
GuildSoundboardSoundCreate fires when a sound is uploaded.
type GuildSoundboardSoundDelete ¶
type GuildSoundboardSoundDelete struct {
SoundID Snowflake `json:"sound_id"`
GuildID Snowflake `json:"guild_id"`
// contains filtered or unexported fields
}
GuildSoundboardSoundDelete fires when a sound is removed.
type GuildSoundboardSoundUpdate ¶
type GuildSoundboardSoundUpdate struct {
SoundboardSound
// contains filtered or unexported fields
}
GuildSoundboardSoundUpdate fires when a sound is edited.
type GuildSoundboardSoundsUpdate ¶
type GuildSoundboardSoundsUpdate struct {
GuildID Snowflake `json:"guild_id"`
SoundboardSounds []SoundboardSound `json:"soundboard_sounds"`
// contains filtered or unexported fields
}
GuildSoundboardSoundsUpdate fires with the guild's whole sound list after a bulk change.
type GuildStickersUpdate ¶
type GuildStickersUpdate struct {
GuildID Snowflake `json:"guild_id"`
Stickers []Sticker `json:"stickers"`
BeforeUpdate []Sticker `json:"-"`
// contains filtered or unexported fields
}
GuildStickersUpdate fires when a guild's stickers change.
type GuildTemplate ¶
type GuildTemplate struct {
Code string `json:"code"`
Name string `json:"name"`
Description string `json:"description"`
UsageCount int `json:"usage_count"`
CreatorID Snowflake `json:"creator_id"`
Creator *User `json:"creator"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
SourceGuildID Snowflake `json:"source_guild_id"`
SerializedSourceGuild *Guild `json:"serialized_source_guild"`
IsDirty bool `json:"is_dirty"` // source guild changed since the snapshot
}
GuildTemplate is a snapshot of a guild's channels, roles and settings that can be used to create new guilds.
type GuildUpdate ¶
type GuildUpdate struct {
Guild
BeforeUpdate *Guild `json:"-"`
// contains filtered or unexported fields
}
GuildUpdate fires when a guild's settings change.
type GuildWidgetJSON ¶
type GuildWidgetJSON struct {
ID Snowflake `json:"id"`
Name string `json:"name"`
InstantInvite string `json:"instant_invite"`
Channels []Channel `json:"channels"`
Members []User `json:"members"`
PresenceCount int `json:"presence_count"`
}
GuildWidgetJSON is the public widget payload, readable without a token when the widget is enabled.
type GuildWidgetSettings ¶
type GuildWidgetSettings struct {
Enabled bool `json:"enabled"`
ChannelID Snowflake `json:"channel_id"`
}
GuildWidgetSettings controls the embeddable server widget.
type HandlerFunc ¶ added in v0.2.0
type HandlerFunc func(*InteractionCreate) error
HandlerFunc is an interaction handler that reports failure by returning an error. See UserError for how errors are shown.
type IdentityProfile ¶
type IdentityProfile struct {
Username string `json:"username,omitzero"`
Metadata map[string]any `json:"metadata,omitzero"`
Data *ProfileData `json:"data,omitzero"`
}
IdentityProfile is a player's record for one application.
Metadata is game-defined and never read by Discord; it is storage the application gets for free alongside the stats.
type Integration ¶
type Integration struct {
ID Snowflake `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
Enabled bool `json:"enabled"`
User *User `json:"user"`
Account struct {
ID string `json:"id"`
Name string `json:"name"`
} `json:"account"`
}
Integration is a connection between a guild and an external service.
type IntegrationCreate ¶
type IntegrationCreate struct {
Integration
GuildID Snowflake `json:"guild_id"`
// contains filtered or unexported fields
}
IntegrationCreate fires when an integration is added to a guild.
type IntegrationDelete ¶
type IntegrationDelete struct {
ID Snowflake `json:"id"`
GuildID Snowflake `json:"guild_id"`
ApplicationID Snowflake `json:"application_id"`
// contains filtered or unexported fields
}
IntegrationDelete fires when an integration is removed.
type IntegrationUpdate ¶
type IntegrationUpdate struct {
Integration
GuildID Snowflake `json:"guild_id"`
// contains filtered or unexported fields
}
IntegrationUpdate fires when an integration changes.
type Intent ¶
type Intent uint64
Intent is a bitmask telling the gateway which families of events a bot wants to receive. Discord requires you to ask for what you need: an event you have no intent for is simply never sent.
Combine them with |, and pass the result to Config.Intents:
IntentGuilds | IntentGuildMessages | IntentMessageContent
const ( IntentGuilds Intent = 1 << iota IntentGuildMembers IntentGuildModeration IntentGuildExpressions IntentGuildIntegrations IntentGuildWebhooks IntentGuildInvites IntentGuildVoiceStates IntentGuildPresences IntentGuildMessages IntentGuildMessageReactions IntentGuildMessageTyping IntentDirectMessages IntentDirectMessageReactions IntentDirectMessageTyping IntentMessageContent IntentGuildScheduledEvents IntentAutoModerationConfiguration IntentAutoModerationExecution IntentGuildMessagePolls IntentDirectMessagePolls )
const IntentsNone Intent = 0
IntentsNone receives only events that need no intent at all, such as interactions from slash commands.
type Interaction ¶
type Interaction struct {
ID Snowflake `json:"id"`
ApplicationID Snowflake `json:"application_id"`
Type InteractionType `json:"type"`
Data InteractionData `json:"data"`
Guild *Guild `json:"guild"`
GuildID Snowflake `json:"guild_id"`
ChannelID Snowflake `json:"channel_id"`
Channel *Channel `json:"channel"`
Member *Member `json:"member"` // set in guilds
User *User `json:"user"` // set in DMs
Token string `json:"token"` // valid for 15 minutes
Version int `json:"version"`
Message *Message `json:"message"` // set for component interactions
AppPermissions Permissions `json:"app_permissions,string"`
Locale string `json:"locale"`
GuildLocale string `json:"guild_locale"`
Context InteractionContextType `json:"context"`
AuthorizingIntegrationOwners map[string]Snowflake `json:"authorizing_integration_owners"`
Entitlements []Entitlement `json:"entitlements"`
AttachmentSizeLimit int `json:"attachment_size_limit"`
}
Interaction is a user action Discord is asking the bot to respond to: a slash command, a button press, an autocomplete request or a modal submit.
Discord expects a reply within three seconds. If the work takes longer, call Defer first, then EditResponse or Followup when the answer is ready.
func (*Interaction) AuthorizingOwner ¶
func (i *Interaction) AuthorizingOwner(kind ApplicationIntegrationType) (Snowflake, bool)
AuthorizingOwner returns the user or guild that installed the app for this interaction. The bool is false when Discord did not supply that owner type.
func (*Interaction) Invoker ¶
func (i *Interaction) Invoker() *User
Invoker returns the user behind the interaction, whether it came from a guild or a DM.
type InteractionContextType ¶
type InteractionContextType int
InteractionContextType is where a command may be used.
const ( InteractionContextGuild InteractionContextType = iota InteractionContextBotDM InteractionContextPrivateChannel )
type InteractionCreate ¶
type InteractionCreate struct {
Interaction
// contains filtered or unexported fields
}
InteractionCreate fires when someone uses a slash command, presses a button or submits a modal. Discord expects a response within three seconds.
func (*InteractionCreate) Answered ¶ added in v0.2.0
func (i *InteractionCreate) Answered() bool
Answered reports whether the initial response has been sent or is being sent. After that, use EditResponse or Followup.
func (*InteractionCreate) AttachmentOption ¶ added in v0.2.0
func (i *InteractionCreate) AttachmentOption(name string) *Attachment
AttachmentOption resolves a selected attachment without another request.
func (*InteractionCreate) Autocomplete ¶
func (i *InteractionCreate) Autocomplete(choices ...CommandChoice) error
Autocomplete answers an autocomplete interaction with up to 25 suggestions.
func (*InteractionCreate) Bool ¶ added in v0.2.0
func (i *InteractionCreate) Bool(name string) bool
Bool returns a named boolean option, or false when it is absent.
func (*InteractionCreate) ChannelOption ¶
func (i *InteractionCreate) ChannelOption(name string) *Channel
ChannelOption resolves a channel option.
func (*InteractionCreate) Client ¶
func (e *InteractionCreate) Client() *Client
Client returns the client that received the event.
func (*InteractionCreate) Defer ¶
func (i *InteractionCreate) Defer(ephemeral bool) error
Defer acknowledges the interaction and shows "thinking...", giving you fifteen minutes to send the real answer with Followup.
Call this immediately if the handler does anything slow - an HTTP request, a database query - because missing the three-second deadline shows the user a permanent "application did not respond".
func (*InteractionCreate) DeferUpdate ¶ added in v0.2.0
func (i *InteractionCreate) DeferUpdate() error
DeferUpdate acknowledges a component without displaying a new thinking message. EditResponse can update the component's original message later.
func (*InteractionCreate) Deferred ¶ added in v0.2.0
func (i *InteractionCreate) Deferred() bool
Deferred reports whether the initial response was Defer or DeferUpdate, so the visible result still has to be sent with EditResponse or Followup.
func (*InteractionCreate) DeleteFollowup ¶
func (i *InteractionCreate) DeleteFollowup(ctx context.Context, messageID Snowflake) error
DeleteFollowup removes one follow-up response.
func (*InteractionCreate) DeleteResponse ¶
func (i *InteractionCreate) DeleteResponse(ctx context.Context) error
DeleteResponse removes the initial response.
func (*InteractionCreate) EditFollowup ¶
func (i *InteractionCreate) EditFollowup(ctx context.Context, messageID Snowflake, data InteractionResponseData) (*Message, error)
EditFollowup rewrites one follow-up response.
func (*InteractionCreate) EditFollowupFiles ¶
func (i *InteractionCreate) EditFollowupFiles(ctx context.Context, messageID Snowflake, data InteractionResponseData, files ...File) (*Message, error)
EditFollowupFiles rewrites one follow-up response and uploads files.
func (*InteractionCreate) EditResponse ¶
func (i *InteractionCreate) EditResponse(ctx context.Context, data InteractionResponseData) (*Message, error)
EditResponse rewrites the initial response, which is the other way to finish a deferred interaction.
func (*InteractionCreate) EditResponseFiles ¶
func (i *InteractionCreate) EditResponseFiles(ctx context.Context, data InteractionResponseData, files ...File) (*Message, error)
EditResponseFiles edits the original interaction response and uploads files.
func (*InteractionCreate) Float ¶ added in v0.2.0
func (i *InteractionCreate) Float(name string) float64
Float returns a named number option, or 0 when it is absent.
func (*InteractionCreate) Focused ¶ added in v0.2.0
func (i *InteractionCreate) Focused() *InteractionOption
Focused returns the option the user is typing in an autocomplete interaction, searching subcommands too, or nil.
func (*InteractionCreate) Followup ¶
func (i *InteractionCreate) Followup(ctx context.Context, data InteractionResponseData) (*Message, error)
Followup sends an additional message after the initial response. It is how you answer once Defer has bought you time.
func (*InteractionCreate) FollowupFiles ¶
func (i *InteractionCreate) FollowupFiles(ctx context.Context, data InteractionResponseData, files ...File) (*Message, error)
FollowupFiles sends an interaction follow-up with attachments.
func (*InteractionCreate) FollowupMessage ¶
func (i *InteractionCreate) FollowupMessage(ctx context.Context, messageID Snowflake) (*Message, error)
FollowupMessage fetches one follow-up response.
func (*InteractionCreate) Int ¶ added in v0.2.0
func (i *InteractionCreate) Int(name string) int64
Int returns a named integer option, or 0 when it is absent.
func (*InteractionCreate) MemberOption ¶ added in v0.2.0
func (i *InteractionCreate) MemberOption(name string) *Member
MemberOption resolves a selected member and joins its user data. Discord sends these separately. No REST request or cache is needed.
func (*InteractionCreate) Modal ¶
func (i *InteractionCreate) Modal(customID, title string, components ...Component) error
Modal opens a form. The custom ID comes back on the modal-submit interaction, which is how you match a submission to what opened it.
func (*InteractionCreate) OptionID ¶ added in v0.2.0
func (i *InteractionCreate) OptionID(name string) Snowflake
OptionID returns a named snowflake option, or zero when it is absent.
func (*InteractionCreate) Param ¶ added in v0.2.0
func (i *InteractionCreate) Param(name string) string
Param returns a parameter captured by a custom-ID route such as "ticket:close:{id}". Values come from the component, which any user can alter, so validate them like any other input.
func (*InteractionCreate) ParamID ¶ added in v0.2.0
func (i *InteractionCreate) ParamID(name string) Snowflake
ParamID returns a route parameter as a snowflake, or zero.
func (*InteractionCreate) ParamInt ¶ added in v0.2.0
func (i *InteractionCreate) ParamInt(name string) int64
ParamInt returns a route parameter as an integer, or zero.
func (*InteractionCreate) Reply ¶
func (i *InteractionCreate) Reply(content string) error
Reply answers with a message, visible to everyone in the channel.
func (*InteractionCreate) ReplyComplex ¶
func (i *InteractionCreate) ReplyComplex(data InteractionResponseData) error
ReplyComplex answers with embeds, components or flags.
func (*InteractionCreate) ReplyContext ¶ added in v0.2.0
func (i *InteractionCreate) ReplyContext(ctx context.Context, content string) error
ReplyContext is Reply with an application-owned deadline or cancellation.
func (*InteractionCreate) ReplyEmbed ¶ added in v0.2.0
func (i *InteractionCreate) ReplyEmbed(e *Embed) error
ReplyEmbed answers with one embed, visible to everyone in the channel.
func (*InteractionCreate) ReplyEmbedEphemeral ¶ added in v0.2.0
func (i *InteractionCreate) ReplyEmbedEphemeral(e *Embed) error
ReplyEmbedEphemeral answers with one embed only the user can see.
func (*InteractionCreate) ReplyEphemeral ¶
func (i *InteractionCreate) ReplyEphemeral(content string) error
ReplyEphemeral answers with a message only the invoking user can see, which is the polite default for errors and for anything noisy.
func (*InteractionCreate) ReplyEphemeralContext ¶ added in v0.2.0
func (i *InteractionCreate) ReplyEphemeralContext(ctx context.Context, content string) error
ReplyEphemeralContext sends a private reply using the supplied context.
func (*InteractionCreate) ReplyFiles ¶
func (i *InteractionCreate) ReplyFiles(data InteractionResponseData, files ...File) error
ReplyFiles answers an interaction with a message and attachments.
func (*InteractionCreate) Respond ¶
func (i *InteractionCreate) Respond(ctx context.Context, resp InteractionResponse) error
Respond sends the initial answer to an interaction.
Discord gives you **three seconds**. If the work takes longer, call Defer first, which shows "thinking..." and buys fifteen minutes for Followup.
If Starlings already deferred the interaction because the handler was slow (see WithAutoDefer), a message or update is delivered by editing the deferred response instead, so the handler does not need to know.
func (*InteractionCreate) RespondFiles ¶
func (i *InteractionCreate) RespondFiles(ctx context.Context, resp InteractionResponse, files ...File) error
RespondFiles sends the initial interaction response with file attachments.
func (*InteractionCreate) Response ¶
func (i *InteractionCreate) Response(ctx context.Context) (*Message, error)
Response fetches the initial interaction response.
func (*InteractionCreate) RoleOption ¶
func (i *InteractionCreate) RoleOption(name string) *Role
RoleOption resolves a role option.
func (*InteractionCreate) String ¶ added in v0.2.0
func (i *InteractionCreate) String(name string) string
String returns a named string option, or "" when it is absent. It is the short form of i.Data.Option(name).String().
func (*InteractionCreate) TextValue ¶ added in v0.2.0
func (i *InteractionCreate) TextValue(customID string) string
TextValue reads a submitted modal text input, including inputs inside labels. Missing inputs and non-text components return an empty string.
func (*InteractionCreate) UpdateMessage ¶
func (i *InteractionCreate) UpdateMessage(data InteractionResponseData) error
UpdateMessage edits the message a button or select menu belongs to, instead of posting a new one. Only valid for component interactions.
func (*InteractionCreate) UpdateMessageFiles ¶
func (i *InteractionCreate) UpdateMessageFiles(data InteractionResponseData, files ...File) error
UpdateMessageFiles edits a component's message and uploads attachments.
func (*InteractionCreate) UserOption ¶
func (i *InteractionCreate) UserOption(name string) *User
UserOption resolves a user option to the full user object, which Discord sends alongside the interaction so no extra request is needed.
type InteractionData ¶
type InteractionData struct {
// Application commands.
ID Snowflake `json:"id"`
Name string `json:"name"`
Type int `json:"type"`
Resolved *ResolvedData `json:"resolved"`
Options []InteractionOption `json:"options"`
TargetID Snowflake `json:"target_id"` // user/message context menu commands
GuildID Snowflake `json:"guild_id"`
// Message components and modals.
CustomID string `json:"custom_id"`
ComponentType ComponentType `json:"component_type"`
Values []string `json:"values"` // select menu choices
Components []Component `json:"components"` // modal submissions
}
InteractionData is the payload of an interaction. Which fields are set depends on Interaction.Type.
func (*InteractionData) Component ¶
func (d *InteractionData) Component(customID string) *Component
Component returns a submitted modal component by custom ID, walking through labels and action rows so handlers do not need to know the layout shape.
func (InteractionData) ComponentID ¶
func (d InteractionData) ComponentID() int
ComponentID returns the numeric component id used by Components V2. ID is also the application-command snowflake because Discord uses the same JSON field for both interaction variants.
func (*InteractionData) Option ¶
func (d *InteractionData) Option(name string) *InteractionOption
Option returns the named command option, or nil. Subcommands are searched too, so a handler need not care whether the command is nested.
type InteractionOption ¶
type InteractionOption struct {
Name string `json:"name"`
Type OptionType `json:"type"`
Value jsontext.Value `json:"value"`
Options []InteractionOption `json:"options"` // set for subcommands and groups
Focused bool `json:"focused"` // autocomplete: the option being typed
}
InteractionOption is one argument supplied to a slash command. Value holds the raw JSON, which the typed accessors below interpret.
func (*InteractionOption) Bool ¶
func (o *InteractionOption) Bool() bool
Bool returns the option's boolean value, or false.
func (*InteractionOption) Float ¶
func (o *InteractionOption) Float() float64
Float returns the option's number value, or 0.
func (*InteractionOption) Int ¶
func (o *InteractionOption) Int() int64
Int returns the option's integer value, or 0.
func (*InteractionOption) Snowflake ¶
func (o *InteractionOption) Snowflake() Snowflake
Snowflake returns the option's ID value for user, channel, role and mentionable options, or zero.
func (*InteractionOption) String ¶
func (o *InteractionOption) String() string
String returns the option's text value, or "" if it is absent or a different type.
type InteractionResponse ¶
type InteractionResponse struct {
Type CallbackType `json:"type"`
Data *InteractionResponseData `json:"data,omitzero"`
}
InteractionResponse is the body of an interaction callback.
type InteractionResponseData ¶
type InteractionResponseData struct {
Content string `json:"content,omitzero"`
TTS bool `json:"tts,omitzero"`
Embeds []Embed `json:"embeds,omitzero"`
Components []Component `json:"components,omitzero"`
AllowedMentions *AllowedMentions `json:"allowed_mentions,omitzero"`
Flags MessageFlags `json:"flags,omitzero"`
Poll *Poll `json:"poll,omitzero"`
Attachments []Attachment `json:"attachments,omitzero"`
// Autocomplete only. Max 25.
Choices []CommandChoice `json:"choices,omitzero"`
// Modal only.
CustomID string `json:"custom_id,omitzero"`
Title string `json:"title,omitzero"`
}
InteractionResponseData carries the message, autocomplete choices or modal that answers an interaction. Which fields matter depends on the callback type.
type InteractionType ¶
type InteractionType int
InteractionType says what triggered an interaction.
const ( InteractionPing InteractionType = iota + 1 InteractionApplicationCommand InteractionMessageComponent // a button press or select menu choice InteractionCommandAutocomplete // the user is still typing an option InteractionModalSubmit )
type Invite ¶
type Invite struct {
Code string `json:"code"`
Guild *Guild `json:"guild"`
Channel *Channel `json:"channel"`
Inviter *User `json:"inviter"`
TargetType int `json:"target_type"`
TargetUser *User `json:"target_user"`
ApproximatePresenceCount int `json:"approximate_presence_count"`
ApproximateMemberCount int `json:"approximate_member_count"`
ExpiresAt *string `json:"expires_at"`
Uses int `json:"uses"`
MaxUses int `json:"max_uses"`
MaxAge int `json:"max_age"`
Temporary bool `json:"temporary"`
CreatedAt string `json:"created_at"`
GuildID Snowflake `json:"guild_id"`
}
Invite is a link that lets people join a guild.
type InviteCreate ¶
type InviteCreate struct {
ChannelID Snowflake `json:"channel_id"`
Code string `json:"code"`
CreatedAt time.Time `json:"created_at"`
GuildID Snowflake `json:"guild_id"`
Inviter *User `json:"inviter"`
MaxAge int `json:"max_age"`
MaxUses int `json:"max_uses"`
Temporary bool `json:"temporary"`
Uses int `json:"uses"`
TargetType int `json:"target_type"`
TargetUser *User `json:"target_user"`
// contains filtered or unexported fields
}
InviteCreate fires when an invite is made. Needs the GuildInvites intent.
type InviteDelete ¶
type InviteDelete struct {
ChannelID Snowflake `json:"channel_id"`
GuildID Snowflake `json:"guild_id"`
Code string `json:"code"`
// contains filtered or unexported fields
}
InviteDelete fires when an invite is revoked or expires.
type InviteParams ¶
type InviteParams struct {
MaxAge *int `json:"max_age,omitzero"` // seconds, 0 = never expires
MaxUses *int `json:"max_uses,omitzero"` // 0 = unlimited
Temporary *bool `json:"temporary,omitzero"`
Unique *bool `json:"unique,omitzero"` // never reuse a similar existing invite
}
InviteParams configures a new invite. Zero values mean Discord's defaults: 24 hours, unlimited uses.
type InviteTargetUser ¶
type InviteTargetUser struct {
UserID Snowflake `json:"user_id"`
User *User `json:"user,omitzero"`
}
InviteTargetUser is someone explicitly allowed to use a targeted invite.
type InviteTargetUsersJob ¶
type InviteTargetUsersJob struct {
JobID string `json:"job_id"`
Status string `json:"status"`
Progress int `json:"progress,omitzero"`
}
InviteTargetUsersJob is the handle for a bulk allow-list change, which Discord processes asynchronously.
type Lobby ¶
type Lobby struct {
ID Snowflake `json:"id"`
ApplicationID Snowflake `json:"application_id"`
Metadata map[string]string `json:"metadata"`
Members []LobbyMember `json:"members"`
LinkedChannel *Channel `json:"linked_channel"`
Flags LobbyFlags `json:"flags"`
OverrideEventWebhooksURL string `json:"override_event_webhooks_url"`
}
Lobby is an application-owned group of users that can message each other.
type LobbyCreate ¶
type LobbyCreate struct {
Metadata map[string]string
Members []LobbyMemberInput
IdleTimeoutSeconds int
Flags LobbyFlags
OverrideEventWebhooksURL string
}
LobbyCreate configures a server-managed lobby.
type LobbyEdit ¶
type LobbyEdit struct {
Metadata *map[string]string
Members *[]LobbyMemberInput
IdleTimeoutSeconds *int
Flags *LobbyFlags
OverrideEventWebhooksURL *string
ClearMetadata bool
ClearOverrideEventWebhooksURL bool
}
LobbyEdit changes only the non-zero fields. Pointer collections let an empty value mean "replace with empty". ClearMetadata and ClearOverrideEventWebhooksURL explicitly send JSON null.
type LobbyFlags ¶
type LobbyFlags uint32
LobbyFlags controls application-level lobby behavior. Discord currently reserves the values, so Starlings keeps this typed without inventing names.
type LobbyJoin ¶
type LobbyJoin struct {
Secret string
LobbyMetadata map[string]string
MemberMetadata map[string]string
IdleTimeoutSeconds int
Flags LobbyFlags
}
LobbyJoin configures the user-authenticated create-or-join operation.
type LobbyMember ¶
type LobbyMember struct {
ID Snowflake `json:"id"`
Metadata map[string]string `json:"metadata"`
Flags LobbyMemberFlags `json:"flags"`
AdditionalName string `json:"additional_name"`
}
LobbyMember is one user's application-specific identity inside a lobby.
func (LobbyMember) CanLinkChannel ¶
func (m LobbyMember) CanLinkChannel() bool
CanLinkChannel reports whether the member may link a guild text channel.
type LobbyMemberFlags ¶
type LobbyMemberFlags int
LobbyMemberFlags controls what a member may do in a lobby.
const LobbyMemberCanLinkChannel LobbyMemberFlags = 1 << 0
type LobbyMemberInput ¶
type LobbyMemberInput struct {
ID Snowflake
Metadata map[string]string
Flags LobbyMemberFlags
AdditionalName string
ClearAdditionalName bool
Remove bool // only used by BulkUpdateLobbyMembers
}
LobbyMemberInput adds or updates a lobby member. Set ClearAdditionalName to explicitly send null; leaving both fields zero preserves the existing name.
type LobbyMessage ¶
type LobbyMessage struct {
ID Snowflake `json:"id"`
Type MessageType `json:"type"`
Content string `json:"content"`
LobbyID Snowflake `json:"lobby_id"`
ChannelID Snowflake `json:"channel_id"`
Author *User `json:"author"`
LobbyMember *MessageLobbyMember `json:"lobby_member"`
Metadata map[string]string `json:"metadata"`
ModerationMetadata map[string]string `json:"moderation_metadata"`
Flags MessageFlags `json:"flags"`
ApplicationID Snowflake `json:"application_id"`
}
LobbyMessage is a message sent within a Social SDK lobby.
type LobbyMessageData ¶
type LobbyMessageData struct {
Content string `json:"content,omitzero"`
Embeds []Embed `json:"embeds,omitzero"`
AllowedMentions *AllowedMentions `json:"allowed_mentions,omitzero"`
StickerIDs []Snowflake `json:"sticker_ids,omitzero"`
Components []Component `json:"components,omitzero"`
Flags MessageFlags `json:"flags,omitzero"`
Attachments []Attachment `json:"attachments,omitzero"`
Poll *Poll `json:"poll,omitzero"`
MessageRef *MessageRef `json:"message_reference,omitzero"`
Nonce any `json:"nonce,omitzero"`
EnforceNonce bool `json:"enforce_nonce,omitzero"`
TTS bool `json:"tts,omitzero"`
Metadata map[string]string `json:"metadata,omitzero"`
}
LobbyMessageData is everything Discord accepts when sending a lobby message. Content alone is enough for ordinary chat.
type Media ¶
type Media struct {
URL string `json:"url"`
}
Media is an image referenced by URL.
Discord's unfurler fetches the URL from its own servers, not from the viewer's client, so it has to be reachable from the public internet - localhost and LAN addresses never load.
type MediaGalleryItem ¶
type MediaGalleryItem struct {
Media UnfurledMedia `json:"media"`
Description string `json:"description,omitempty"`
Spoiler bool `json:"spoiler,omitzero"`
}
MediaGalleryItem is one image or video in a media gallery.
func GalleryItem ¶
func GalleryItem(url, description string) MediaGalleryItem
GalleryItem builds one media gallery entry.
type Member ¶
type Member struct {
User *User `json:"user"`
Nick string `json:"nick"`
Avatar string `json:"avatar"` // per-guild avatar hash
Roles []Snowflake `json:"roles"`
JoinedAt time.Time `json:"joined_at"`
PremiumSince *time.Time `json:"premium_since"`
Deaf bool `json:"deaf"`
Mute bool `json:"mute"`
Flags int `json:"flags"`
Pending bool `json:"pending"`
Permissions Permissions `json:"permissions,string"`
CommunicationDisabledUntil *time.Time `json:"communication_disabled_until"`
// contains filtered or unexported fields
}
Member is a user as seen inside one guild, carrying the nickname, roles and join date that only make sense in that guild's context.
User is nil on a few gateway payloads where Discord already sent the user alongside the member, so check it before dereferencing.
func (*Member) AvatarURL ¶ added in v0.2.0
AvatarURL returns this member's guild-specific avatar. When the member has not set one it falls back to the user's normal (or default) avatar. An empty string means the payload did not include enough user information.
func (*Member) Ban ¶ added in v0.2.0
Ban bans the member. deleteHistory removes their messages from that far back, up to seven days; zero keeps them.
func (*Member) CanModerate ¶ added in v0.2.0
CanModerate reports whether this member may moderate target, using the cached role hierarchy. See State.CanModerate.
func (*Member) ClearTimeout ¶ added in v0.2.0
ClearTimeout lifts the member's timeout.
func (*Member) DisplayName ¶
DisplayName returns the nickname if the member has one, otherwise the underlying user's name.
func (*Member) GuildID ¶ added in v0.2.0
GuildID returns the guild the member belongs to, when Starlings knows it.
func (*Member) RemoveRole ¶ added in v0.2.0
RemoveRole takes a role from the member.
func (*Member) SendComplex ¶ added in v0.2.0
SendComplex sends the member a direct message with embeds or components.
func (*Member) SetNick ¶ added in v0.2.0
SetNick changes the member's nickname. An empty nick removes it.
type MemberRequest ¶
type MemberRequest struct {
GuildID Snowflake `json:"guild_id"`
Query *string `json:"query,omitzero"`
Limit int `json:"-"`
Presences bool `json:"presences,omitzero"`
UserIDs []Snowflake `json:"user_ids,omitzero"`
Nonce string `json:"nonce,omitzero"`
}
MemberRequest selects members to fetch through the gateway. Set Query to "" and Limit to 0 for the full member list, or set UserIDs for exact users.
func (MemberRequest) MarshalJSON ¶ added in v0.2.0
func (r MemberRequest) MarshalJSON() ([]byte, error)
MarshalJSON preserves Discord's distinction between an absent limit and limit 0. Query-based requests require the field even when it is zero (zero means every matching member); user-ID requests must omit it.
type MembersQuery ¶
type MembersQuery struct {
Limit int // 1-1000, default 1
After Snowflake // members with a higher ID than this
}
MembersQuery pages through a guild's member list. Discord returns members in ascending user-ID order, so paging means passing the last ID back as After.
type Mentionable ¶ added in v0.2.0
type Mentionable interface {
Mention() string
}
Mentionable is anything that can be mentioned in message text.
type Message ¶
type Message struct {
ID Snowflake `json:"id"`
ChannelID Snowflake `json:"channel_id"`
GuildID Snowflake `json:"guild_id"`
Author *User `json:"author"`
Member *Member `json:"member"` // the author's guild-specific data, guilds only
Content string `json:"content"`
Timestamp time.Time `json:"timestamp"`
EditedTimestamp *time.Time `json:"edited_timestamp"`
TTS bool `json:"tts"`
MentionEveryone bool `json:"mention_everyone"`
Mentions []User `json:"mentions"`
MentionRoles []Snowflake `json:"mention_roles"`
MentionChannels []ChannelMention `json:"mention_channels"`
Attachments []Attachment `json:"attachments"`
Embeds []Embed `json:"embeds"`
Reactions []Reaction `json:"reactions"`
Pinned bool `json:"pinned"`
WebhookID Snowflake `json:"webhook_id"`
Type MessageType `json:"type"`
Flags MessageFlags `json:"flags"`
ReferencedMsg *Message `json:"referenced_message"`
MessageRef *MessageRef `json:"message_reference"`
Components []Component `json:"components"`
Activity *MessageActivity `json:"activity"`
Application *MessageApplication `json:"application"`
ApplicationID Snowflake `json:"application_id"`
Interaction *MessageInteraction `json:"interaction"` // deprecated by Discord; kept for old messages
InteractionMeta *MessageInteractionMetadata `json:"interaction_metadata"`
Thread *Channel `json:"thread"`
StickerItems []StickerItem `json:"sticker_items"`
Position int `json:"position"`
RoleSubscription *RoleSubscriptionData `json:"role_subscription_data"`
Resolved *ResolvedData `json:"resolved"`
Poll *Poll `json:"poll"`
Call *MessageCallInfo `json:"call"`
Snapshots []MessageSnapshot `json:"message_snapshots"`
Nonce any `json:"nonce"`
Stickers []Sticker `json:"stickers"` // legacy full sticker objects
PurchaseNotification *PurchaseNotification `json:"purchase_notification"`
LobbyMember *MessageLobbyMember `json:"lobby_member"`
// contains filtered or unexported fields
}
Message is a single post in a channel.
func (*Message) React ¶ added in v0.2.0
React adds the bot's reaction. emoji is a Unicode emoji or name:id for a custom one.
func (*Message) ReplyComplex ¶ added in v0.2.0
ReplyComplex replies with embeds or components.
func (*Message) ReplyEmbed ¶ added in v0.2.0
ReplyEmbed replies to the message with one embed.
type MessageActivity ¶
type MessageActivity struct {
Type MessageActivityType `json:"type"`
PartyID string `json:"party_id,omitempty"`
}
type MessageActivityType ¶
type MessageActivityType int
const ( MessageActivityJoin MessageActivityType = 1 MessageActivitySpectate MessageActivityType = 2 MessageActivityListen MessageActivityType = 3 MessageActivityJoinRequest MessageActivityType = 5 )
type MessageApplication ¶
type MessageApplication struct {
ID Snowflake `json:"id"`
CoverImage string `json:"cover_image,omitempty"`
Description string `json:"description"`
Icon string `json:"icon,omitempty"`
Name string `json:"name"`
Bot *User `json:"bot"`
Flags int `json:"flags"`
FlagsNew string `json:"flags_new"`
PrimarySKUID Snowflake `json:"primary_sku_id"`
Type int `json:"type"`
}
type MessageCallInfo ¶
type MessageCreate ¶
type MessageCreate struct {
Message
// contains filtered or unexported fields
}
MessageCreate fires when a message is posted in a channel the bot can see.
Content is empty unless the bot has the privileged MessageContent intent, or the message mentions the bot, or it is a DM.
func (*MessageCreate) Client ¶
func (e *MessageCreate) Client() *Client
Client returns the client that received the event.
func (*MessageCreate) IsFromBot ¶
func (m *MessageCreate) IsFromBot() bool
IsFromBot reports whether the message was posted by any bot, including this one. Guarding handlers with it is the standard way to avoid loops.
func (*MessageCreate) IsFromSelf ¶
func (m *MessageCreate) IsFromSelf() bool
IsFromSelf reports whether this bot posted the message. Almost every message handler should start by returning early on it.
func (*MessageCreate) React ¶
func (m *MessageCreate) React(emoji string) error
React adds a reaction to the message.
func (*MessageCreate) Reply ¶
func (m *MessageCreate) Reply(content string) (*Message, error)
Reply answers the message that triggered the event, as a Discord reply.
It uses the background context; for control over cancellation use Client.Reply directly.
func (*MessageCreate) ReplyComplex ¶
func (m *MessageCreate) ReplyComplex(data SendData) (*Message, error)
ReplyComplex answers with embeds or components. The reply reference is filled in for you if you leave it unset.
func (*MessageCreate) ReplyFiles ¶
func (m *MessageCreate) ReplyFiles(data SendData, files ...File) (*Message, error)
ReplyFiles answers a message with attachments.
type MessageDelete ¶
type MessageDelete struct {
ID Snowflake `json:"id"`
ChannelID Snowflake `json:"channel_id"`
GuildID Snowflake `json:"guild_id"`
BeforeDelete *Message `json:"-"`
// contains filtered or unexported fields
}
MessageDelete fires when a single message is deleted. Only the IDs are sent - the content is gone.
type MessageDeleteBulk ¶
type MessageDeleteBulk struct {
IDs []Snowflake `json:"ids"`
ChannelID Snowflake `json:"channel_id"`
GuildID Snowflake `json:"guild_id"`
BeforeDelete []Message `json:"-"`
// contains filtered or unexported fields
}
MessageDeleteBulk fires when messages are purged together.
type MessageFlags ¶
type MessageFlags int
MessageFlags is a bitmask of per-message options.
const ( MessageFlagCrossposted MessageFlags = 1 << iota MessageFlagIsCrosspost MessageFlagSuppressEmbeds MessageFlagSourceMessageDeleted MessageFlagUrgent MessageFlagHasThread MessageFlagEphemeral // only the invoking user can see it MessageFlagLoading // the "thinking..." state of a deferred interaction MessageFlagFailedToMentionSomeRolesInThread MessageFlagSuppressNotifications MessageFlagIsVoiceMessage MessageFlagIsComponentsV2 )
type MessageInteraction ¶
type MessageInteraction struct {
ID Snowflake `json:"id"`
Type InteractionType `json:"type"`
Name string `json:"name"`
User *User `json:"user"`
Member *Member `json:"member"`
}
type MessageInteractionMetadata ¶
type MessageInteractionMetadata struct {
ID Snowflake `json:"id"`
Type InteractionType `json:"type"`
User *User `json:"user"`
AuthorizingIntegrationOwners map[string]Snowflake `json:"authorizing_integration_owners"`
OriginalResponseMessageID Snowflake `json:"original_response_message_id"`
InteractedMessageID Snowflake `json:"interacted_message_id"`
TargetMessageID Snowflake `json:"target_message_id"`
TargetUser *User `json:"target_user"`
TriggeringInteractionMetadata *MessageInteractionMetadata `json:"triggering_interaction_metadata"`
}
type MessageLobbyMember ¶
type MessageLobbyMember struct {
AdditionalName string `json:"additional_name"`
}
type MessagePin ¶
MessagePin is one pinned message with the time it was pinned.
type MessagePins ¶
type MessagePins struct {
Items []MessagePin `json:"items"`
HasMore bool `json:"has_more"`
}
MessagePins is the newer paginated pins API, which supersedes the older /channels/{id}/pins endpoint and returns pin timestamps.
type MessagePollVoteAdd ¶
type MessagePollVoteAdd struct {
UserID Snowflake `json:"user_id"`
ChannelID Snowflake `json:"channel_id"`
MessageID Snowflake `json:"message_id"`
GuildID Snowflake `json:"guild_id"`
AnswerID int `json:"answer_id"`
// contains filtered or unexported fields
}
MessagePollVoteAdd fires when someone votes in a poll.
type MessagePollVoteRemove ¶
type MessagePollVoteRemove struct {
UserID Snowflake `json:"user_id"`
ChannelID Snowflake `json:"channel_id"`
MessageID Snowflake `json:"message_id"`
GuildID Snowflake `json:"guild_id"`
AnswerID int `json:"answer_id"`
// contains filtered or unexported fields
}
MessagePollVoteRemove fires when someone retracts a poll vote.
type MessageReactionAdd ¶
type MessageReactionAdd struct {
UserID Snowflake `json:"user_id"`
ChannelID Snowflake `json:"channel_id"`
MessageID Snowflake `json:"message_id"`
GuildID Snowflake `json:"guild_id"`
Member *Member `json:"member"`
Emoji Emoji `json:"emoji"`
BeforeUpdate *Message `json:"-"`
// contains filtered or unexported fields
}
MessageReactionAdd fires when someone reacts to a message.
type MessageReactionRemove ¶
type MessageReactionRemove struct {
UserID Snowflake `json:"user_id"`
ChannelID Snowflake `json:"channel_id"`
MessageID Snowflake `json:"message_id"`
GuildID Snowflake `json:"guild_id"`
Emoji Emoji `json:"emoji"`
BeforeUpdate *Message `json:"-"`
// contains filtered or unexported fields
}
MessageReactionRemove fires when someone takes a reaction back.
type MessageReactionRemoveAll ¶
type MessageReactionRemoveAll struct {
ChannelID Snowflake `json:"channel_id"`
MessageID Snowflake `json:"message_id"`
GuildID Snowflake `json:"guild_id"`
BeforeUpdate *Message `json:"-"`
// contains filtered or unexported fields
}
MessageReactionRemoveAll fires when every reaction is cleared from a message.
type MessageReactionRemoveEmoji ¶
type MessageReactionRemoveEmoji struct {
ChannelID Snowflake `json:"channel_id"`
GuildID Snowflake `json:"guild_id"`
MessageID Snowflake `json:"message_id"`
Emoji Emoji `json:"emoji"`
BeforeUpdate *Message `json:"-"`
// contains filtered or unexported fields
}
MessageReactionRemoveEmoji fires when every reaction of one emoji is cleared from a message.
type MessageRef ¶
type MessageRef struct {
Type MessageReferenceType `json:"type,omitzero"`
MessageID Snowflake `json:"message_id"`
ChannelID Snowflake `json:"channel_id,omitzero"`
GuildID Snowflake `json:"guild_id,omitzero"`
// FailIfNotExists makes sending fail when the referenced message is gone.
// Discord's default is true; the pointer lets you send an explicit false.
FailIfNotExists *bool `json:"fail_if_not_exists,omitempty"`
}
MessageRef points at another message, used for replies and forwards.
type MessageReferenceType ¶
type MessageReferenceType int
MessageReferenceType distinguishes a reply from a forwarded-message snapshot.
const ( MessageReferenceDefault MessageReferenceType = iota MessageReferenceForward )
type MessageSearchResult ¶
type MessageSearchResult struct {
TotalResults int `json:"total_results"`
Messages [][]Message `json:"messages"`
}
MessageSearchResult is a page of search hits. Messages is a list of groups because Discord returns each hit with its surrounding context.
type MessageSnapshot ¶
type MessageSnapshot struct {
Message *Message `json:"message"`
}
type MessageType ¶
type MessageType int
MessageType marks how a message came to exist. Ordinary user and bot posts are MessageDefault or MessageReply; the rest are system notices such as join messages and pins.
const ( MessageDefault MessageType = 0 MessageRecipientAdd MessageType = 1 MessageRecipientRemove MessageType = 2 MessageCall MessageType = 3 MessageChannelNameChange MessageType = 4 MessageChannelIconChange MessageType = 5 MessageChannelPinnedMessage MessageType = 6 MessageUserJoin MessageType = 7 MessageGuildBoost MessageType = 8 MessageGuildBoostTier1 MessageType = 9 MessageGuildBoostTier2 MessageType = 10 MessageGuildBoostTier3 MessageType = 11 MessageChannelFollowAdd MessageType = 12 MessageGuildDiscoveryDisqualified MessageType = 14 MessageGuildDiscoveryRequalified MessageType = 15 MessageGuildDiscoveryGracePeriodInitialWarning MessageType = 16 MessageGuildDiscoveryGracePeriodFinalWarning MessageType = 17 MessageThreadCreated MessageType = 18 MessageReply MessageType = 19 MessageChatInputCommand MessageType = 20 MessageThreadStarterMessage MessageType = 21 MessageGuildInviteReminder MessageType = 22 MessageContextMenuCommand MessageType = 23 MessageAutoModerationAction MessageType = 24 MessageRoleSubscriptionPurchase MessageType = 25 MessageInteractionPremiumUpsell MessageType = 26 MessageStageStart MessageType = 27 MessageStageEnd MessageType = 28 MessageStageSpeaker MessageType = 29 MessageStageTopic MessageType = 30 MessageGuildApplicationPremiumSubscription MessageType = 31 MessagePrivateChannelIntegrationAdded MessageType = 32 MessagePollResult MessageType = 36 )
type MessageUpdate ¶
type MessageUpdate struct {
Message
BeforeUpdate *Message `json:"-"`
// contains filtered or unexported fields
}
MessageUpdate fires when a message is edited. Discord sends a partial message, so fields the edit did not touch may be zero.
type MessagesQuery ¶
type MessagesQuery struct {
Limit int // 1-100, default 50
Before Snowflake // messages older than this ID
After Snowflake // messages newer than this ID
Around Snowflake // messages either side of this ID
}
MessagesQuery narrows a channel history request. Leave the anchors zero for the most recent messages.
type MetadataType ¶
type MetadataType int
MetadataType is the comparison a guild applies to one role-connection metadata value when deciding whether to grant a linked role.
The type matters for role rules, not for display: the profile card shows whatever value you push regardless of which comparison is declared.
const ( MetadataIntegerLessThanOrEqual MetadataType = iota + 1 MetadataIntegerGreaterThanOrEqual MetadataIntegerEqual MetadataIntegerNotEqual MetadataDateTimeLessThanOrEqual // value is an ISO8601 string MetadataDateTimeGreaterThanOrEqual // value is an ISO8601 string MetadataBooleanEqual // value is "1" or "0" MetadataBooleanNotEqual )
type ModerationDenial ¶ added in v0.2.0
type ModerationDenial uint8
ModerationDenial is the reason CanModerate refused.
const ( DenyTargetIsSelf ModerationDenial = iota + 1 DenyTargetIsOwner DenyTargetIsBot DenyActorTooLow DenyBotTooLow DenyActorTimedOut )
func (ModerationDenial) String ¶ added in v0.2.0
func (d ModerationDenial) String() string
type ModerationError ¶ added in v0.2.0
type ModerationError struct {
Reason ModerationDenial
}
ModerationError explains why one member cannot act on another. Its message is written for the person who ran the command, so it can be shown as is.
func (*ModerationError) Error ¶ added in v0.2.0
func (e *ModerationError) Error() string
func (*ModerationError) UserMessage ¶ added in v0.2.0
func (e *ModerationError) UserMessage() string
UserMessage returns the denial as shown to the user.
type ModifyMember ¶
type ModifyMember struct {
Nick *string `json:"nick,omitzero"`
Roles *[]Snowflake `json:"roles,omitzero"`
Mute *bool `json:"mute,omitzero"`
Deaf *bool `json:"deaf,omitzero"`
// ChannelID moves the member between voice channels. A pointer to zero
// disconnects them.
ChannelID *Snowflake `json:"channel_id,omitzero"`
// CommunicationDisabledUntil times a member out, up to 28 days ahead.
// A pointer to nil clears an existing timeout.
CommunicationDisabledUntil **time.Time `json:"communication_disabled_until,omitzero"`
Flags *int `json:"flags,omitzero"`
}
ModifyMember is the set of member fields a bot may change. Every field is optional: a nil pointer leaves that attribute alone, which is why these are pointers rather than plain values.
type NewMemberWelcome ¶
type NewMemberWelcome struct {
GuildID Snowflake `json:"guild_id"`
Description string `json:"description"`
NewMemberActions []struct {
ChannelID Snowflake `json:"channel_id"`
ActionType int `json:"action_type"`
Title string `json:"title"`
Description string `json:"description"`
EmojiID Snowflake `json:"emoji_id,omitzero"`
EmojiName string `json:"emoji_name,omitzero"`
} `json:"new_member_actions"`
}
NewMemberWelcome is the "start here" panel shown to people who just joined.
type NewSoundboardSound ¶
type NewSoundboardSound struct {
Name string `json:"name"`
// Sound is a data URI of an MP3 or OGG clip, at most 5.2 seconds long and
// 512 KiB.
Sound string `json:"sound"`
Volume *float64 `json:"volume,omitzero"`
EmojiID Snowflake `json:"emoji_id,omitzero"`
EmojiName string `json:"emoji_name,omitzero"`
}
NewSoundboardSound is the payload for uploading a sound.
type OAuth2Authorization ¶
type OAuth2Authorization struct {
Application *CurrentApplication `json:"application"`
Scopes []string `json:"scopes"`
Expires string `json:"expires"`
User *User `json:"user"`
}
OAuth2Authorization describes the token used to make a request: which application it belongs to, what scopes it carries and when it expires.
type OnboardingOption ¶
type OnboardingOption struct {
ID Snowflake `json:"id"`
ChannelIDs []Snowflake `json:"channel_ids"`
RoleIDs []Snowflake `json:"role_ids"`
Emoji *Emoji `json:"emoji,omitzero"`
Title string `json:"title"`
Description string `json:"description"`
}
OnboardingOption is one answer to an onboarding prompt.
type OnboardingPrompt ¶
type OnboardingPrompt struct {
ID Snowflake `json:"id"`
Type int `json:"type"`
Options []OnboardingOption `json:"options"`
Title string `json:"title"`
SingleSelect bool `json:"single_select"`
Required bool `json:"required"`
InOnboarding bool `json:"in_onboarding"`
}
OnboardingPrompt is one question asked during onboarding.
type Opcode ¶
type Opcode int
Opcode identifies what a gateway frame is for. The payload's meaning depends entirely on it.
const ( OpDispatch Opcode = 0 // server -> client: an event, named by "t" OpHeartbeat Opcode = 1 // both ways: keep-alive OpIdentify Opcode = 2 // client -> server: open a new session OpPresenceUpdate Opcode = 3 // client -> server: change status OpVoiceStateUpdate Opcode = 4 // client -> server: join or leave a voice channel OpResume Opcode = 6 // client -> server: resume a dropped session OpReconnect Opcode = 7 // server -> client: reconnect and resume OpRequestGuildMembers Opcode = 8 // client -> server: ask for a guild's member list OpInvalidSession Opcode = 9 // server -> client: session is dead OpHello Opcode = 10 // server -> client: first frame, carries the heartbeat interval OpHeartbeatACK Opcode = 11 // server -> client: heartbeat received OpRequestSoundboardSounds Opcode = 31 // client -> server: fetch soundboard sounds OpRequestChannelInfo Opcode = 43 // client -> server: fetch ephemeral channel data )
type OpenIDUserInfo ¶
type OpenIDUserInfo struct {
Sub string `json:"sub"`
Username string `json:"username"`
Avatar string `json:"avatar"`
Email string `json:"email,omitzero"`
Verified bool `json:"email_verified,omitzero"`
}
OpenIDUserInfo is the OpenID Connect profile for a bearer token carrying the openid scope.
type Option ¶
type Option func(*Client)
Option configures a Client. Pass them to New.
func Explicit ¶ added in v0.2.0
func Explicit() Option
Explicit turns off everything Starlings does on its own, so the client does only what you configure, the way DiscordGo behaves:
- no token from DISCORD_TOKEN or .env; use WithToken
- no intents chosen from handlers; use WithIntents (none means zero)
- no automatic deferral of slow interaction handlers
- no automatic command publishing
- no recovery from handler panics
- no return of startup memory to the operating system
Options after Explicit can turn single behaviours back on:
starlings.New(starlings.Explicit(), starlings.WithToken(t), starlings.WithAutoDefer(2*time.Second))
func WithAsyncEvents ¶
WithAsyncEvents runs application event handlers in their own goroutines. Internal cache maintenance remains ordered. Synchronous dispatch is the default because it is deterministic and naturally applies backpressure.
func WithAutoDefer ¶ added in v0.2.0
WithAutoDefer sets how long a slash command, button, select, or modal handler may run before Starlings acknowledges the interaction for it. Fast handlers answer normally in one request. A slow handler's later Reply or UpdateMessage edits the deferred response instead. This helps meet Discord's deadline but cannot guarantee delivery during an outage or blocked dispatch. The default is 2.2 seconds; zero turns it off.
It applies to interactions received over the gateway. Interactions served by InteractionHandler must answer before the handler returns.
func WithAutoSharding ¶
WithAutoSharding controls whether Run uses Discord's recommended shard count. It is enabled by default. WithShard selects one manual shard and disables automatic management.
func WithAutoSync ¶ added in v0.2.0
WithAutoSync controls automatic command publishing. When it is on, the default, Run publishes the registered slash commands after connecting, but only when they differ from what Discord already has. Commands go to the guild in DISCORD_GUILD_ID when it is set, where changes appear at once, and to every guild otherwise. Turn it off to call SyncCommands yourself.
func WithCommandSync ¶ added in v0.2.0
WithCommandSync publishes commands automatically after the first READY. Use a guild ID while developing for immediate updates, or zero for global commands. Without this option, SyncCommands remains fully manual.
func WithGatewayCompression ¶
WithGatewayCompression controls Discord's transport compression. It is on by default because large READY and GUILD_CREATE events shrink dramatically. Disable it when inspecting raw gateway traffic with a proxy.
func WithGlobalRateLimit ¶ added in v0.2.0
WithGlobalRateLimit sets how many requests per second the client sends before Discord's global limit would apply. The default is Discord's 50. Raise it only if Discord granted the bot a higher limit; zero disables local pacing and relies on 429 responses alone.
func WithGuard ¶
func WithGuard(options ...GuardOption) Option
WithGuard enables Starlings Guard for this client.
func WithHTTPClient ¶
WithHTTPClient supplies the http.Client used for REST calls. The default is tuned for Discord's API; replace it if you need a proxy or custom transport.
func WithIdentity ¶
func WithIdentity(id ClientIdentity) Option
WithIdentity overrides what the client tells Discord it is: the browser and device strings in the identify payload, and the REST User-Agent.
func WithIntents ¶
WithIntents sets which families of events the gateway should send. Without it the bot receives only events that need no intent, such as interactions.
func WithLogger ¶
WithLogger replaces the default logger. Pass one writing to io.Discard to silence starlings entirely.
func WithMemberChunking ¶ added in v0.2.0
WithMemberChunking asks Discord for the full member list of every guild whose GUILD_CREATE did not include all members. Discord only sends members up front for small guilds, so without it State.Members is incomplete in larger ones.
It needs the privileged IntentGuildMembers. Requests go through the gateway's command limit, so a bot in many guilds fills its cache over a few minutes instead of being disconnected.
func WithMemoryTrim ¶ added in v0.2.0
WithMemoryTrim controls whether the client returns memory to the operating system once the startup burst is over. Connecting delivers every guild and member list at once; the Go runtime keeps the memory that burst needed unless it is asked to give it back. With trimming on, the default, the client does that once, after guild and member events have been quiet for two seconds. It costs one garbage collection.
func WithPacing ¶
WithPacing sets the minimum interval between any two REST requests the client makes - a global gate in front of the rate limiter, applied one request at a time. The default is zero, meaning as fast as Discord's rate limits allow.
Set it when you would rather be gentle than quick: a bulk backfill, a migration script, or any job whose throughput you do not care about but whose 429s you do.
func WithPanicRecovery ¶ added in v0.2.0
WithPanicRecovery controls what happens when an event or command handler panics. With recovery on, the default, the panic is logged with its stack and the bot keeps running. Off, the panic stops the process, as it would in plain Go.
func WithPrefix ¶
WithPrefix sets the character (or word) that triggers commands registered with Command. The default is DefaultPrefix, "!".
func WithRequestTimeout ¶ added in v0.2.0
WithRequestTimeout bounds REST calls whose context has no deadline, including time spent waiting for rate limits. The default is one minute; zero leaves such calls unbounded. A deadline on the context always wins.
func WithShard ¶
WithShard tells Discord this connection handles one slice of the bot's guilds. Required once a bot is in more than around 2,500 guilds.
func WithStarlog ¶
WithStarlog installs Starlog as the client's logger and attaches live bot metrics. RunContext automatically starts and restores the TUI.
func WithStateCache ¶
func WithStateCache(config StateConfig) Option
WithStateCache replaces the default cache configuration.
func WithStateMode ¶
WithStateMode switches between automatic and manual event application while preserving the rest of the cache configuration.
func WithStatus ¶
WithStatus sets the status and activity shown for the bot as soon as it connects.
func WithTaskConcurrency ¶ added in v0.2.0
WithTaskConcurrency caps in-flight SlashTask handlers across all shards. The default is 32. Busy requests receive an ephemeral reply instead of entering an unbounded queue. A nonpositive limit is a programming error.
type OptionType ¶
type OptionType int
OptionType is the declared type of a slash command option.
const ( OptionSubCommand OptionType = iota + 1 OptionSubCommandGroup OptionString OptionInteger OptionBoolean OptionUser OptionChannel OptionRole OptionMentionable OptionNumber OptionAttachment )
type Overwrite ¶
type Overwrite struct {
ID Snowflake `json:"id"`
Type int `json:"type"` // 0 = role, 1 = member
Allow Permissions `json:"allow,string"`
Deny Permissions `json:"deny,string"`
}
Overwrite is a per-channel permission adjustment for one role or member. Deny is applied before Allow.
type Page ¶ added in v0.2.0
type Page struct {
Content string
Embed *Embed
// Pages is the total number of pages, used to disable the arrows.
Pages int
// Extra holds additional components, placed below the arrows.
Extra []Component
}
Page is one page of a paged view.
type PageFunc ¶ added in v0.2.0
type PageFunc func(i *InteractionCreate, page int, arg string) (Page, error)
PageFunc renders page (from zero) of a paged view. arg is the value given to Pager.Show, carried in the buttons' custom IDs.
type Pager ¶ added in v0.2.0
type Pager struct {
// contains filtered or unexported fields
}
Pager is a paged view with previous and next buttons. It keeps no state: the page, owner, and argument travel in the buttons' custom IDs, so pages keep working after the bot restarts. Only the person who opened the view can turn its pages.
type Permissions ¶
type Permissions uint64
Permissions is a bitmask of what an account may do. Discord sends it as a decimal string because the mask has outgrown 53 bits, so struct fields that hold one need the ",string" JSON tag option.
const ( PermissionCreateInstantInvite Permissions = 1 << iota PermissionKickMembers PermissionBanMembers PermissionAdministrator PermissionManageChannels PermissionManageGuild PermissionAddReactions PermissionViewAuditLog PermissionPrioritySpeaker PermissionStream PermissionViewChannel PermissionSendMessages PermissionSendTTSMessages PermissionManageMessages PermissionEmbedLinks PermissionAttachFiles PermissionReadMessageHistory PermissionMentionEveryone PermissionUseExternalEmojis PermissionViewGuildInsights PermissionConnect PermissionSpeak PermissionMuteMembers PermissionDeafenMembers PermissionMoveMembers PermissionUseVAD PermissionChangeNickname PermissionManageNicknames PermissionManageRoles PermissionManageWebhooks PermissionManageGuildExpressions PermissionUseApplicationCommands PermissionRequestToSpeak PermissionManageEvents PermissionManageThreads PermissionCreatePublicThreads PermissionCreatePrivateThreads PermissionUseExternalStickers PermissionSendMessagesInThreads PermissionUseEmbeddedActivities PermissionModerateMembers PermissionViewCreatorMonetizationAnalytics PermissionUseSoundboard PermissionCreateGuildExpressions PermissionCreateEvents PermissionUseExternalSounds PermissionSendVoiceMessages PermissionSetVoiceChannelStatus PermissionSendPolls PermissionUseExternalApps PermissionPinMessages PermissionBypassSlowmode )
func (Permissions) Add ¶
func (p Permissions) Add(other Permissions) Permissions
Add returns p with the given permissions granted.
func (Permissions) Has ¶
func (p Permissions) Has(other Permissions) bool
Has reports whether every permission in other is granted by p. Administrator short-circuits the check, matching how Discord evaluates it.
func (Permissions) HumanString ¶ added in v0.2.0
func (p Permissions) HumanString() string
HumanString returns known permission names joined for logs and user-facing diagnostics. Zero is rendered as "None". String remains the decimal wire form Discord expects.
func (Permissions) Missing ¶ added in v0.2.0
func (p Permissions) Missing(required Permissions) Permissions
Missing returns the permissions required contains but p does not. An administrator is never missing a permission.
func (Permissions) Names ¶ added in v0.2.0
func (p Permissions) Names() []string
Names returns stable Go-style names for every known bit in p, in bit order. Unknown future bits are preserved by appending their decimal value.
func (Permissions) Remove ¶
func (p Permissions) Remove(other Permissions) Permissions
Remove returns p with the given permissions revoked.
func (Permissions) String ¶
func (p Permissions) String() string
String renders the bitmask as the decimal string Discord expects in request bodies. The mask has outgrown 53 bits, so it never travels as a number.
type Poll ¶
type Poll struct {
Question PollMedia `json:"question"`
Answers []PollAnswer `json:"answers"`
Expiry *time.Time `json:"expiry,omitempty"`
AllowMultiselect bool `json:"allow_multiselect,omitzero"`
LayoutType PollLayoutType `json:"layout_type"`
Results *PollResults `json:"results,omitempty"`
Duration int `json:"duration,omitzero"`
}
Poll is accepted when sending and fully populated when receiving. Duration is the requested number of hours; Expiry and Results are response fields.
type PollAnswer ¶
type PollAnswerCount ¶
type PollResults ¶
type PollResults struct {
Finalized bool `json:"is_finalized"`
AnswerCounts []PollAnswerCount `json:"answer_counts"`
}
type PollVotersQuery ¶
PollVotersQuery pages through the people who picked one poll answer.
type Presence ¶
type Presence struct {
Since *int64 `json:"since"`
Activities []Activity `json:"activities"`
Status Status `json:"status"`
AFK bool `json:"afk"`
}
Presence is the status shown for the bot. Since is a Unix timestamp in milliseconds and only matters for an idle status.
type PresenceUpdate ¶
type PresenceUpdate struct {
User *User `json:"user"`
GuildID Snowflake `json:"guild_id"`
Status string `json:"status"` // online, idle, dnd, offline
Activities []Activity `json:"activities"`
ClientStatus struct {
Desktop string `json:"desktop"`
Mobile string `json:"mobile"`
Web string `json:"web"`
} `json:"client_status"`
BeforeUpdate *PresenceUpdate `json:"-"`
// contains filtered or unexported fields
}
PresenceUpdate fires when someone's status or activity changes. It needs the privileged GuildPresences intent, and on a large guild it is the noisiest event Discord sends - which is precisely the case Starlings' skip path is built for.
type PresencesReplace ¶
type PresencesReplace []PresenceUpdate
PresencesReplace is the legacy full presence snapshot event. Discord's current bot gateway sends incremental PresenceUpdate events, but older gateway versions and compatible implementations may still send this event.
type PrimaryProfileData ¶
type PrimaryProfileData struct {
Season string `json:"season,omitzero"`
RankName string `json:"rank_name,omitzero"`
RankImage *Media `json:"rank_image,omitzero"`
HighestRank string `json:"highest_rank,omitzero"`
HighestRankImage *Media `json:"highest_rank_image,omitzero"`
FeaturedPlayedCharacter string `json:"featured_played_character,omitzero"`
FeaturedPlayedCharacterImage *Media `json:"featured_played_character_image,omitzero"`
PlaytimeHours float64 `json:"playtime_hours,omitzero"` // decimals allowed
TotalWins int `json:"total_wins,omitzero"`
CurrentPeriodWins int `json:"current_period_wins,omitzero"`
TotalGames int `json:"total_games,omitzero"`
CurrentPeriodGames int `json:"current_period_games,omitzero"`
TotalKills int `json:"total_kills,omitzero"`
CurrentPeriodKills int `json:"current_period_kills,omitzero"`
TotalAssists int `json:"total_assists,omitzero"`
CurrentPeriodAssists int `json:"current_period_assists,omitzero"`
TotalDeaths int `json:"total_deaths,omitzero"`
CurrentPeriodDeaths int `json:"current_period_deaths,omitzero"`
}
PrimaryProfileData is Discord's set of pre-defined stats, meant to be generic across games. Every field is optional; populate the ones that suit the game and leave the rest zero.
type ProfileData ¶
type ProfileData struct {
Primary *PrimaryProfileData `json:"primary,omitzero"`
Dynamic []DynamicField `json:"dynamic,omitzero"`
}
ProfileData holds the stats themselves.
type ProvisionalCredentials ¶
type ProvisionalCredentials struct {
ClientID Snowflake `json:"client_id"`
ClientSecret string `json:"client_secret,omitzero"`
ExternalAuthToken string `json:"external_auth_token"`
ExternalAuthType ExternalAuthType `json:"external_auth_type"`
}
ProvisionalCredentials authenticates an external game identity. Keep ClientSecret on a trusted server; public clients should use Discord's native SDK helper instead.
type ProvisionalToken ¶
type ProvisionalToken struct {
TokenType string `json:"token_type"`
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
Scope string `json:"scope"`
IDToken string `json:"id_token"`
RefreshToken string `json:"refresh_token"`
Scopes []string `json:"scopes"`
ExpiresAtS *int64 `json:"expires_at_s"`
}
ProvisionalToken is a short-lived sdk.social_layer OAuth2 token.
type PurchaseNotification ¶
type PurchaseNotification struct {
Type int `json:"type"`
GuildProductPurchase *GuildProductPurchase `json:"guild_product_purchase"`
}
type PurgeOptions ¶ added in v0.2.0
type PurgeOptions struct {
// Count is how many matching messages to delete.
Count int
// Match selects messages; nil matches every message.
Match func(*Message) bool
// MaxScan caps how many messages are read while looking for matches.
// Zero means 100, or 500 when Match is set.
MaxScan int
// MaxOld caps how many messages older than 14 days are deleted one at a
// time, since Discord's bulk delete refuses them. Zero means 20; a
// negative value skips them.
MaxOld int
// Reason is recorded in the audit log.
Reason string
}
PurgeOptions chooses which recent messages Purge deletes.
type PurgeResult ¶ added in v0.2.0
type PurgeResult struct {
Scanned int // messages read
Matched int // messages that matched, up to Count
Deleted int // messages deleted, in bulk and one at a time
OldDeleted int // of Deleted, older than 14 days
OldSkipped int // older messages left because of MaxOld
}
PurgeResult reports what Purge did.
type RESTRequest ¶
type RESTRequest struct {
Method string
Path string
Route string
Body any
RawBody []byte
Files []File
Reason string
Auth string
NoAuth bool
Base string
Headers http.Header
ContentType string
}
RESTRequest is the unrestricted REST escape hatch. Route should be the stable rate-limit bucket key; when empty Starlings uses "METHOD path".
type RateLimit ¶
type RateLimit struct {
Method string `json:"method"`
Path string `json:"path"`
Route string `json:"route"`
RetryAfterSeconds float64 `json:"retry_after"`
Global bool `json:"global"`
// contains filtered or unexported fields
}
RateLimit fires whenever Discord returns an HTTP 429. Starlings still waits and retries automatically; this event exists for metrics and alerting.
type RateLimitError ¶ added in v0.2.0
RateLimitError is returned instead of waiting when a request made with a FailFast context would have to wait for a rate limit.
func (*RateLimitError) Error ¶ added in v0.2.0
func (e *RateLimitError) Error() string
type RateLimitWait ¶ added in v0.2.0
type RateLimitWait struct {
Method string `json:"method"`
Route string `json:"route"`
WaitSeconds float64 `json:"wait_seconds"`
// contains filtered or unexported fields
}
RateLimitWait fires when a REST request waited for a rate-limit bucket that Starlings already knew was empty. Unlike RateLimit, nothing was rejected; it shows where the bot spends time waiting on Discord.
func (*RateLimitWait) Client ¶ added in v0.2.0
func (e *RateLimitWait) Client() *Client
Client returns the client that received the event.
func (RateLimitWait) Wait ¶ added in v0.2.0
func (r RateLimitWait) Wait() time.Duration
Wait returns WaitSeconds as a Go duration.
type RateLimited ¶
type RateLimited struct {
Opcode Opcode `json:"opcode"`
RetryAfter float64 `json:"retry_after"`
Meta struct {
GuildID Snowflake `json:"guild_id"`
Nonce string `json:"nonce"`
} `json:"meta"`
// contains filtered or unexported fields
}
RateLimited fires when Discord rejects a gateway request, currently member chunk requests. RetryAfter is in seconds.
type RawEvent ¶
RawEvent exposes the untouched data object from any gateway dispatch. Data is owned by the event and remains valid after the handler returns.
type Reaction ¶
type Reaction struct {
Count int `json:"count"`
CountDetails ReactionCountDetails `json:"count_details"`
Me bool `json:"me"` // whether the current bot reacted
MeBurst bool `json:"me_burst"`
Emoji Emoji `json:"emoji"`
BurstColors []string `json:"burst_colors"`
}
Reaction is the aggregate count of one emoji on a message.
type ReactionCountDetails ¶
type ReactionsQuery ¶
type ReactionsQuery struct {
After Snowflake
Limit int // 1-100
Type int // 0 normal, 1 burst ("super") reactions
}
ReactionsQuery pages through the users who reacted with one emoji.
type Ready ¶
type Ready struct {
Version int `json:"v"`
User *User `json:"user"`
Guilds []Guild `json:"guilds"` // unavailable stubs; GuildCreate follows for each
SessionID string `json:"session_id"`
ResumeGatewayURL string `json:"resume_gateway_url"`
Application *AppInfo `json:"application"`
Shard [2]int `json:"shard"`
// contains filtered or unexported fields
}
Ready fires once the gateway has accepted the connection and sent the initial state. It is the signal that the bot is online.
type ResolvedData ¶
type ResolvedData struct {
Users map[Snowflake]*User `json:"users"`
Members map[Snowflake]*Member `json:"members"`
Roles map[Snowflake]*Role `json:"roles"`
Channels map[Snowflake]*Channel `json:"channels"`
Messages map[Snowflake]*Message `json:"messages"`
Attachments map[Snowflake]*Attachment `json:"attachments"`
}
ResolvedData holds the full objects for IDs referenced by command options, so a command taking a user option does not need a second API call to learn anything about them.
type Response ¶ added in v0.2.0
type Response struct {
// contains filtered or unexported fields
}
Response is a handler result that says how it should be sent.
func Ephemeral ¶ added in v0.2.0
Ephemeral returns a reply only the user can see. content is a string or an *Embed.
type Resumed ¶
type Resumed struct {
// contains filtered or unexported fields
}
Resumed fires when a dropped connection has been resumed and any events missed in the gap have been replayed.
type Role ¶
type Role struct {
ID Snowflake `json:"id"`
Name string `json:"name"`
Color int `json:"color"`
Hoist bool `json:"hoist"` // shown separately in the member list
Icon string `json:"icon"`
Position int `json:"position"`
Permissions Permissions `json:"permissions,string"`
Managed bool `json:"managed"` // created by an integration, not editable
Mentionable bool `json:"mentionable"`
// contains filtered or unexported fields
}
Role is a set of permissions that can be assigned to members of a guild.
type RoleConnection ¶
type RoleConnection struct {
PlatformName string `json:"platform_name,omitzero"` // the card's title, max 50
PlatformUsername string `json:"platform_username,omitzero"` // the line under it, max 100
Metadata map[string]string `json:"metadata,omitzero"`
}
RoleConnection is the card shown on a user's profile for one application: a platform name, an optional username line, and the values for the metadata keys the application registered.
Metadata values are always strings on the wire, even the numeric ones.
type RoleConnectionMetadata ¶
type RoleConnectionMetadata struct {
Key string `json:"key"` // a-z, 0-9 and _ only, max 50
Name string `json:"name"` // max 100, shown on the card
NameLocalizations map[string]string `json:"name_localizations,omitzero"`
Description string `json:"description"` // max 200
DescriptionLocalizations map[string]string `json:"description_localizations,omitzero"`
Type MetadataType `json:"type"`
}
RoleConnectionMetadata declares one field an application can publish about a user. Registering these is what makes the fields appear on the connection card on a user's profile, and what guilds build linked-role rules from.
Key is the identifier used when pushing values; Name and Description are what people see.
type RoleParams ¶
type RoleParams struct {
Name *string `json:"name,omitzero"`
Permissions *Permissions `json:"permissions,string,omitzero"`
Color *int `json:"color,omitzero"` // 0xRRGGBB, 0 means "no colour"
Hoist *bool `json:"hoist,omitzero"` // list separately in the sidebar
Icon *string `json:"icon,omitzero"` // image data URI
UnicodeEmoji *string `json:"unicode_emoji,omitzero"`
Mentionable *bool `json:"mentionable,omitzero"`
}
RoleParams are the fields settable when creating or editing a role. All are optional; omitted ones take Discord's defaults on create, and are left alone on edit.
type RolePosition ¶
RolePosition is one entry of a reordering request.
type RoleSubscriptionData ¶
type SKU ¶
type SKU struct {
ID Snowflake `json:"id"`
Type SKUType `json:"type"`
ApplicationID Snowflake `json:"application_id"`
Name string `json:"name"`
Slug string `json:"slug"`
Flags SKUFlags `json:"flags"`
}
SKU is a premium offering belonging to an application.
type SKUFlags ¶
type SKUFlags int
SKUFlags describes availability and who receives a SKU's benefits.
type ScheduledEvent ¶
type ScheduledEvent struct {
ID Snowflake `json:"id"`
GuildID Snowflake `json:"guild_id"`
ChannelID Snowflake `json:"channel_id,omitzero"`
CreatorID Snowflake `json:"creator_id,omitzero"`
Name string `json:"name"`
Description string `json:"description,omitzero"`
ScheduledStartTime time.Time `json:"scheduled_start_time"`
ScheduledEndTime *time.Time `json:"scheduled_end_time,omitzero"`
PrivacyLevel int `json:"privacy_level"` // always 2, guild-only
Status int `json:"status,omitzero"`
EntityType int `json:"entity_type"`
EntityID Snowflake `json:"entity_id,omitzero"`
EntityMetadata *ScheduledEventMetadata `json:"entity_metadata,omitzero"`
Creator *User `json:"creator,omitzero"`
UserCount int `json:"user_count,omitzero"`
Image string `json:"image,omitzero"`
}
ScheduledEvent is a planned guild event.
type ScheduledEventException ¶
type ScheduledEventException struct {
EventExceptionID Snowflake `json:"event_exception_id"`
EventID Snowflake `json:"event_id"`
GuildID Snowflake `json:"guild_id"`
IsCanceled bool `json:"is_canceled"`
ScheduledStartTime *time.Time `json:"scheduled_start_time,omitzero"`
ScheduledEndTime *time.Time `json:"scheduled_end_time,omitzero"`
}
ScheduledEventException is a single occurrence of a recurring event that has been moved or cancelled.
type ScheduledEventMetadata ¶ added in v0.2.0
type ScheduledEventMetadata = struct {
Location string `json:"location"`
}
ScheduledEventMetadata holds the location of an external scheduled event. It is an alias, so code written against the earlier anonymous struct still compiles.
type ScheduledEventUpdate ¶ added in v0.2.0
type ScheduledEventUpdate struct {
ChannelID *Snowflake `json:"channel_id,omitzero"`
Name string `json:"name,omitzero"`
Description *string `json:"description,omitzero"`
ScheduledStartTime *time.Time `json:"scheduled_start_time,omitzero"`
ScheduledEndTime *time.Time `json:"scheduled_end_time,omitzero"`
PrivacyLevel int `json:"privacy_level,omitzero"`
Status int `json:"status,omitzero"`
EntityType int `json:"entity_type,omitzero"`
EntityMetadata *ScheduledEventMetadata `json:"entity_metadata,omitzero"`
Image *string `json:"image,omitzero"`
ClearChannel bool `json:"-"`
ClearScheduledEnd bool `json:"-"`
ClearEntityMetadata bool `json:"-"`
}
ScheduledEventUpdate is a partial scheduled-event PATCH. Zero values are omitted, so changing one field never accidentally sends empty required create fields. Clear flags encode JSON null for Discord's nullable fields.
func (ScheduledEventUpdate) MarshalJSON ¶ added in v0.2.0
func (u ScheduledEventUpdate) MarshalJSON() ([]byte, error)
type ScheduledEventUser ¶
type ScheduledEventUser struct {
GuildScheduledEventID Snowflake `json:"guild_scheduled_event_id"`
User *User `json:"user"`
Member *Member `json:"member"`
}
ScheduledEventUser is someone subscribed to an event.
type SelectDefaultValue ¶
SelectDefaultValue preselects an entity in an auto-populated select menu. Type is "user", "role", or "channel".
type SelectOption ¶
type SelectOption struct {
Label string `json:"label"`
Value string `json:"value"`
Description string `json:"description,omitempty"`
Emoji *Emoji `json:"emoji,omitempty"`
Default bool `json:"default,omitzero"`
}
SelectOption is one choice in a string select menu.
type SendData ¶
type SendData struct {
Content string `json:"content,omitzero"`
TTS bool `json:"tts,omitzero"`
Embeds []Embed `json:"embeds,omitzero"`
Components []Component `json:"components,omitzero"`
MessageRef *MessageRef `json:"message_reference,omitzero"`
AllowedMentions *AllowedMentions `json:"allowed_mentions,omitzero"`
Flags MessageFlags `json:"flags,omitzero"`
StickerIDs []Snowflake `json:"sticker_ids,omitzero"`
Poll *Poll `json:"poll,omitzero"`
Nonce any `json:"nonce,omitzero"`
EnforceNonce bool `json:"enforce_nonce,omitzero"`
}
SendData is everything a message can carry. Most calls need only Content, so prefer Client.Send and the Reply helpers; reach for this when you need embeds, components or a reply reference.
func ComponentsMessage ¶
ComponentsMessage creates a Components V2 message with Discord's required flag already set.
type Sendable ¶ added in v0.2.0
type Sendable interface {
Send(content string) (*Message, error)
SendComplex(data SendData) (*Message, error)
}
Sendable is anything a message can be sent to: a channel, a thread, or a user or member (by direct message).
type SeparatorSpacing ¶
type SeparatorSpacing int
SeparatorSpacing controls the vertical space around a separator.
const ( SeparatorSpacingSmall SeparatorSpacing = iota + 1 SeparatorSpacingLarge )
type ShardStatus ¶
type ShardStatus struct {
ID int
Count int
Connected bool
// Ready reports that this connection has received READY or RESUMED and
// is delivering events. It becomes false again when the connection drops.
Ready bool
Latency time.Duration
Sequence int64
Resumable bool
}
ShardStatus is a concurrency-safe snapshot of one gateway connection.
type SharedClientTheme ¶
type SharedClientTheme struct {
}
type SlashFunc ¶
type SlashFunc func(i *InteractionCreate)
SlashFunc handles one slash command invocation.
type SlashRoute ¶ added in v0.2.0
type SlashRoute struct {
// contains filtered or unexported fields
}
SlashRoute is the optional fluent configuration returned by Slash and SlashCommand. Ignoring it is fine; keeping it makes common command policy readable without expanding back into a full ApplicationCommand literal.
func (*SlashRoute) Autocomplete ¶ added in v0.2.0
func (r *SlashRoute) Autocomplete(fn SlashFunc) *SlashRoute
Autocomplete registers the command's autocomplete handler separately from its execution handler. This separation prevents command side effects from running while a user is merely typing an option.
func (*SlashRoute) BotNeeds ¶ added in v0.2.0
func (r *SlashRoute) BotNeeds(permissions Permissions) *SlashRoute
BotNeeds checks, before the handler runs, that the bot has every supplied permission in the channel where the command was used. Without them the user gets a private message naming what is missing, instead of a failed request halfway through the handler.
func (*SlashRoute) Contexts ¶ added in v0.2.0
func (r *SlashRoute) Contexts(contexts ...InteractionContextType) *SlashRoute
Contexts selects where Discord offers the command.
func (*SlashRoute) Ephemeral ¶ added in v0.2.0
func (r *SlashRoute) Ephemeral() *SlashRoute
Ephemeral makes SlashTask's deferred response private to the invoker. Manual Slash handlers choose visibility on their own response methods.
func (*SlashRoute) GuildOnly ¶ added in v0.2.0
func (r *SlashRoute) GuildOnly() *SlashRoute
GuildOnly is shorthand for Contexts(InteractionContextGuild).
func (*SlashRoute) InstallTypes ¶ added in v0.2.0
func (r *SlashRoute) InstallTypes(types ...ApplicationIntegrationType) *SlashRoute
InstallTypes selects whether a command belongs to guild installs, user installs, or both.
func (*SlashRoute) NoAutoDefer ¶ added in v0.2.0
func (r *SlashRoute) NoAutoDefer() *SlashRoute
NoAutoDefer turns automatic deferral off for one command, for a handler that may open a modal after slow work. A modal must be the first response.
func (*SlashRoute) Permissions ¶ added in v0.2.0
func (r *SlashRoute) Permissions(permissions Permissions) *SlashRoute
Permissions limits the command to members with every supplied permission. Discord performs the visibility check before Starlings receives the command.
func (*SlashRoute) Require ¶ added in v0.2.0
func (r *SlashRoute) Require(permissions Permissions) *SlashRoute
Require limits the command to members with every supplied permission. It sets Discord's default member permissions, and also checks the permissions Discord reports with each use, because server admins can override the default. Members without them get a private message naming what is missing. Uses without guild membership are denied as well; there are no guild permissions to establish in a DM.
func (*SlashRoute) Run ¶ added in v0.2.0
func (r *SlashRoute) Run(fn HandlerFunc) *SlashRoute
Run sets an error-returning handler for the command, replacing the one given to Slash:
bot.Slash("kick", "Kick a member", nil).Require(starlings.PermissionKickMembers).
Run(func(i *starlings.InteractionCreate) error { ... })
func (*SlashRoute) Timeout ¶ added in v0.2.0
func (r *SlashRoute) Timeout(timeout time.Duration) *SlashRoute
Timeout selects the deadline passed to SlashTask. It must be positive and less than the interaction token's fifteen-minute lifetime.
type Snowflake ¶
type Snowflake uint64
Snowflake is a Discord object ID. Discord generates these as 64-bit integers but sends them over the wire as decimal strings, because JavaScript cannot represent them exactly as numbers. Snowflake keeps the integer form in memory and handles the string conversion at the JSON boundary.
func MustID ¶
MustID converts a Discord ID literal into a Snowflake, panicking if it is not a valid ID.
It is meant for IDs written into the source - a channel you always post to, your own guild - where a typo is a bug to fix rather than a condition to handle:
var logChannel = starlings.MustID("123456789012345678")
For an ID that arrives at runtime, from a config file or a command argument, use ParseSnowflake and check the error.
func ParseSnowflake ¶
ParseSnowflake converts a decimal ID string into a Snowflake.
func (Snowflake) IsZero ¶
IsZero reports whether the snowflake is unset. Discord never issues an ID of zero, so it doubles as the "absent" value.
func (Snowflake) MarshalJSON ¶
MarshalJSON encodes the snowflake as a JSON string, matching Discord's wire format. A zero snowflake encodes as null so that omitted IDs round-trip.
func (Snowflake) MarshalJSONTo ¶
MarshalJSONTo is the encoding/json/v2 fast path: it writes straight into the encoder's buffer instead of allocating an intermediate []byte the way MarshalJSON must.
func (Snowflake) MarshalText ¶ added in v0.2.0
MarshalText returns the decimal form, so snowflakes work as map keys in JSON and in text formats such as CSV.
func (*Snowflake) Scan ¶ added in v0.2.0
Scan reads a snowflake stored as text, an integer, or NULL.
func (Snowflake) String ¶
String returns the decimal form Discord's API expects in URLs and payloads.
func (Snowflake) Time ¶
Time returns when Discord created the object. The top 42 bits of a snowflake are a millisecond timestamp, so this needs no API call.
func (*Snowflake) UnmarshalJSON ¶
UnmarshalJSON accepts the string form Discord sends, and tolerates both null and a bare JSON number.
func (*Snowflake) UnmarshalJSONFrom ¶
UnmarshalJSONFrom is the encoding/json/v2 fast path. It reads one token rather than being handed a copied []byte, so decoding an ID allocates nothing.
func (*Snowflake) UnmarshalText ¶ added in v0.2.0
UnmarshalText parses the decimal form. Empty text is zero.
type SocialClient ¶
type SocialClient struct {
// contains filtered or unexported fields
}
SocialClient performs operations as a user authorized with the sdk.social_layer OAuth2 scope. It shares the parent client's HTTP transport and rate limiter but never its bot authorization header.
func (*SocialClient) CreateOrJoinLobby ¶
CreateOrJoinLobby joins the OAuth user to the lobby identified by Secret, creating it when necessary.
func (*SocialClient) LeaveLobby ¶
func (s *SocialClient) LeaveLobby(ctx context.Context, lobbyID Snowflake) error
LeaveLobby removes the OAuth user from a lobby.
func (*SocialClient) LinkLobbyChannel ¶
func (s *SocialClient) LinkLobbyChannel(ctx context.Context, lobbyID, channelID Snowflake) (*Lobby, error)
LinkLobbyChannel links a guild text channel to a lobby.
func (*SocialClient) LobbyInvite ¶
LobbyInvite creates a one-use invite to the linked channel for the OAuth user.
func (*SocialClient) LobbyMessages ¶
func (s *SocialClient) LobbyMessages(ctx context.Context, lobbyID Snowflake, limit int) ([]LobbyMessage, error)
LobbyMessages returns the newest messages, up to 200.
func (*SocialClient) SendLobbyMessage ¶
func (s *SocialClient) SendLobbyMessage(ctx context.Context, lobbyID Snowflake, content string) (*LobbyMessage, error)
SendLobbyMessage sends plain text as the OAuth user.
func (*SocialClient) SendLobbyMessageComplex ¶
func (s *SocialClient) SendLobbyMessageComplex(ctx context.Context, lobbyID Snowflake, data LobbyMessageData) (*LobbyMessage, error)
SendLobbyMessageComplex sends a rich Social SDK lobby message.
func (*SocialClient) UnlinkLobbyChannel ¶
UnlinkLobbyChannel removes the lobby's current channel link.
type SoundboardSound ¶
type SoundboardSound struct {
SoundID Snowflake `json:"sound_id"`
Name string `json:"name"`
Volume float64 `json:"volume"` // 0 to 1
EmojiID Snowflake `json:"emoji_id,omitzero"`
EmojiName string `json:"emoji_name,omitzero"`
GuildID Snowflake `json:"guild_id,omitzero"`
Available bool `json:"available"` // false when lost to a boost downgrade
User *User `json:"user,omitzero"`
}
SoundboardSound is a clip that can be played into a voice channel.
Playing one needs no voice connection: Discord mixes it server-side when you call SendSoundboardSound, so a bot can be a soundboard without implementing any of the voice protocol.
func (*SoundboardSound) Emoji ¶
func (s *SoundboardSound) Emoji() string
Emoji renders the sound's icon for display, preferring a custom emoji and falling back to the unicode one. Returns "" when the sound has neither.
type SoundboardSounds ¶
type SoundboardSounds struct {
GuildID Snowflake `json:"guild_id"`
SoundboardSounds []SoundboardSound `json:"soundboard_sounds"`
// contains filtered or unexported fields
}
SoundboardSounds answers a Request Soundboard Sounds call.
type StageInstance ¶
type StageInstance struct {
ID Snowflake `json:"id,omitzero"`
GuildID Snowflake `json:"guild_id,omitzero"`
ChannelID Snowflake `json:"channel_id"`
Topic string `json:"topic"`
PrivacyLevel int `json:"privacy_level,omitzero"` // 2 = guild only
GuildScheduledEventID Snowflake `json:"guild_scheduled_event_id,omitzero"`
}
StageInstance is a live stage channel event.
type StageInstanceCreate ¶
type StageInstanceCreate struct {
StageInstance
// contains filtered or unexported fields
}
StageInstanceCreate fires when a stage channel goes live.
type StageInstanceDelete ¶
type StageInstanceDelete struct {
StageInstance
// contains filtered or unexported fields
}
StageInstanceDelete fires when a stage ends.
type StageInstanceUpdate ¶
type StageInstanceUpdate struct {
StageInstance
// contains filtered or unexported fields
}
StageInstanceUpdate fires when a live stage changes.
type StarPetVariant ¶
type StarPetVariant uint8
StarPetVariant selects one of Starlog's built-in colour personalities.
const ( StarPetNova StarPetVariant = iota StarPetComet StarPetNebula )
type Starlog ¶
type Starlog struct {
// contains filtered or unexported fields
}
Starlog is both a structured logger and an optional fullscreen terminal dashboard. It is safe for concurrent handlers and subprocess writers.
func NewStarlog ¶
func NewStarlog(name string, options ...StarlogOption) *Starlog
NewStarlog creates the optional terminal logger. The TUI, colour, bounded history, and animated Star Pet are enabled by default; all have independent options.
func (*Starlog) AddSink ¶
func (s *Starlog) AddSink(sink *StarlogSink) (remove func())
AddSink attaches an independent styled output and returns a removal function. Removing a sink never closes its writer.
func (*Starlog) Build ¶
Build records compiler, downloader, or subprocess progress with the pet's build reaction while keeping the semantic log level at Info.
func (*Starlog) BuildWriter ¶
func (s *Starlog) BuildWriter(source string) io.WriteCloser
BuildWriter is a subprocess writer that keeps the Star Pet in its animated build/jump state while output is arriving.
func (*Starlog) Close ¶
Close stops the dashboard and restores the terminal. It never closes the configured output writer.
func (*Starlog) Errors ¶
func (s *Starlog) Errors(output io.Writer, options ...StarlogSinkOption) *StarlogSink
Errors is the short path for a red, illustrated error-only destination.
func (*Starlog) FollowLogs ¶
func (s *Starlog) FollowLogs()
FollowLogs returns the dashboard viewport to the newest output.
func (*Starlog) FollowPlayback ¶
func (s *Starlog) FollowPlayback(source StarlogPlaybackSource)
FollowPlayback changes the real player shown in the dashboard. Passing nil removes the strip. VoiceConnection.Play attaches compatible providers automatically when the connection belongs to a client using Starlog.
func (*Starlog) Logger ¶
Logger returns the standard slog facade used by Starlings and application code.
func (*Starlog) Metrics ¶
func (s *Starlog) Metrics() StarlogMetrics
Metrics returns the latest dashboard counters without starting the TUI.
func (*Starlog) Scroll ¶
Scroll moves the dashboard log viewport. Positive values move toward older output and negative values move back toward the live tail.
func (*Starlog) ScrollOffset ¶
ScrollOffset reports how many rendered rows the viewport is behind live.
func (*Starlog) Snapshot ¶
func (s *Starlog) Snapshot() []StarlogEntry
Snapshot returns deep copies of the newest retained entries.
func (*Starlog) Start ¶
Start activates the fullscreen dashboard when possible. It is safe to call even when RunContext will also start it.
func (*Starlog) Styled ¶
func (s *Starlog) Styled(output io.Writer, color int, options ...StarlogSinkOption) *StarlogSink
Styled is the short path for an all-level, single-colour destination.
func (*Starlog) Warnings ¶
func (s *Starlog) Warnings(output io.Writer, options ...StarlogSinkOption) *StarlogSink
Warnings is the short path for a gold, illustrated warning-and-error destination.
type StarlogColorPolicy ¶
type StarlogColorPolicy uint8
StarlogColorPolicy controls whether a styled sink emits ANSI colour. Auto keeps ordinary files escape-free, Always is useful for ANSI-aware log viewers, and Never retains Starlog's Unicode layout without colour codes.
const ( StarlogColorAuto StarlogColorPolicy = iota StarlogColorAlways StarlogColorNever )
type StarlogEntry ¶
type StarlogEntry struct {
Time time.Time
Level slog.Level
Message string
Fields []StarlogField
Shard int
Mood StarlogMood
}
StarlogEntry is one immutable item in the bounded in-memory log history.
type StarlogField ¶
StarlogField is one structured slog attribute after formatting.
type StarlogFrame ¶
type StarlogFrame []string
StarlogFrame is one code-native animation frame. Artwork can be replaced later without changing the logger or its public API.
type StarlogMediaReader ¶ added in v0.2.0
type StarlogMediaReader interface {
ReadPlayback() (StarlogPlayback, error)
Close()
}
StarlogMediaReader reads the operating system's current media session. The sysmedia package provides readers for Windows and Linux.
type StarlogMetrics ¶
type StarlogMetrics struct {
Uptime time.Duration
CPUPercent float64
HeapBytes uint64
Goroutines int
LogsPerSecond float64
TotalLogs uint64
DebugLogs uint64
InfoLogs uint64
WarnLogs uint64
ErrorLogs uint64
Shards []ShardStatus
LogsByShard map[int]uint64
}
StarlogMetrics is the dashboard's current runtime snapshot.
type StarlogMood ¶
type StarlogMood uint8
StarlogMood selects a pet frame. Build is separate from Info so command and compiler output can have its own reaction without pretending to be a warning.
const ( StarlogCalm StarlogMood = iota StarlogBuild StarlogWarn StarlogError )
type StarlogOption ¶
type StarlogOption func(*Starlog)
StarlogOption changes the optional logger without affecting Client options.
func StarlogColor ¶
func StarlogColor(enabled bool) StarlogOption
StarlogColor controls ANSI colours. Non-terminal outputs are always plain.
func StarlogDashboard ¶
func StarlogDashboard() StarlogOption
StarlogDashboard explicitly selects the full live terminal application. It is the default, but naming it can make shared configuration clearer.
func StarlogHistory ¶
func StarlogHistory(entries int) StarlogOption
StarlogHistory changes the bounded record count shown by Snapshot and TUI.
func StarlogMediaSource ¶ added in v0.2.0
func StarlogMediaSource(open func() (StarlogMediaReader, error)) StarlogOption
StarlogMediaSource shows the operating system's media session in the now-playing strip when no attached Discord voice or file source is active. open runs when the dashboard starts, on an OS thread reserved for the reader, and Starlog polls the reader once a second. Most bots use sysmedia.Option instead of calling this directly.
func StarlogNoPets ¶
func StarlogNoPets() StarlogOption
StarlogNoPets removes mascot art while keeping every dashboard and logging feature. It is equivalent to StarlogWithPets() but reads better in config.
func StarlogOutput ¶
func StarlogOutput(w io.Writer) StarlogOption
StarlogOutput sends terminal output somewhere other than os.Stdout.
func StarlogRefresh ¶
func StarlogRefresh(period time.Duration) StarlogOption
StarlogRefresh changes the dashboard redraw period.
func StarlogStreamArt ¶
func StarlogStreamArt(enabled bool) StarlogOption
StarlogStreamArt controls whether warning, error, and build records show a compact pet frame when the fullscreen dashboard is disabled.
func StarlogStreaming ¶
func StarlogStreaming() StarlogOption
StarlogStreaming selects styled records without the fullscreen application.
func StarlogTUI ¶
func StarlogTUI(enabled bool) StarlogOption
StarlogTUI controls the fullscreen dashboard. It falls back to streaming output when the destination is not an interactive terminal.
func StarlogWithPet ¶
func StarlogWithPet(pet StarlogPet) StarlogOption
StarlogWithPet selects one mascot. Pass an empty StarlogPet to disable pets.
func StarlogWithPets ¶
func StarlogWithPets(pets ...StarlogPet) StarlogOption
StarlogWithPets installs a small dashboard crew. The first pet also supplies reaction art for streaming output and styled sinks.
func StarlogWithPlayback ¶
func StarlogWithPlayback(source StarlogPlaybackSource) StarlogOption
StarlogWithPlayback attaches a real player to the optional now-playing strip.
type StarlogPet ¶
type StarlogPet struct {
Name string
Variant string
Color int // ANSI 256-colour foreground; zero uses the dashboard accent.
FrameDelay time.Duration
Picture *StarlogSpriteSheet
Calm []StarlogFrame
Build []StarlogFrame
Warn []StarlogFrame
Error []StarlogFrame
}
StarlogPet is an original terminal-native Star Pet. Every mood is an animation, so pets can blink, bounce, jump, celebrate builds, and react to warnings. Frames can have any height; Starlog clips them to the dashboard.
func NewStarPet ¶
func NewStarPet(variant StarPetVariant) StarlogPet
NewStarPet returns one of Starlog's animated mascots. Import the starpets package to draw them with the bundled pixel art; otherwise they use terminal characters.
type StarlogPlayback ¶
type StarlogPlayback struct {
Provider string
Title string
Artist string
Position time.Duration
Duration time.Duration
Playing bool
}
StarlogPlayback is one immutable snapshot for the optional now-playing strip.
type StarlogPlaybackSource ¶
type StarlogPlaybackSource interface {
StarlogPlayback() StarlogPlayback
}
StarlogPlaybackSource supplies live player state. FFmpegOpusProvider implements it, and custom players only need this one snapshot method.
type StarlogSink ¶
type StarlogSink struct {
// contains filtered or unexported fields
}
StarlogSink writes a filtered, styled copy of Starlog records. A sink never owns or closes its output, so the caller remains in control of files and pipes. It is safe to use from concurrent event handlers.
func NewStarlogSink ¶
func NewStarlogSink(output io.Writer, options ...StarlogSinkOption) *StarlogSink
NewStarlogSink creates a reusable styled destination. By default it accepts every level, uses cyan, includes reaction art for non-calm records, and only emits ANSI when output is an interactive terminal.
type StarlogSinkOption ¶
type StarlogSinkOption func(*StarlogSink)
StarlogSinkOption customises one independent styled output.
func StarlogSinkArt ¶
func StarlogSinkArt(enabled bool) StarlogSinkOption
StarlogSinkArt controls the compact Star Pet reaction beside styled records.
func StarlogSinkColor ¶
func StarlogSinkColor(color int) StarlogSinkOption
StarlogSinkColor selects an ANSI 256-colour foreground.
func StarlogSinkColorPolicy ¶
func StarlogSinkColorPolicy(policy StarlogColorPolicy) StarlogSinkOption
StarlogSinkColorPolicy selects automatic, forced, or disabled ANSI colour.
func StarlogSinkLevels ¶
func StarlogSinkLevels(minimum, maximum slog.Level) StarlogSinkOption
StarlogSinkLevels limits a sink to an inclusive level range.
func StarlogSinkMinLevel ¶
func StarlogSinkMinLevel(level slog.Level) StarlogSinkOption
StarlogSinkMinLevel accepts a level and everything more severe.
func StarlogSinkPet ¶
func StarlogSinkPet(pet StarlogPet) StarlogSinkOption
StarlogSinkPet changes the sink's pet independently from the full dashboard.
type StarlogSpriteSheet ¶
type StarlogSpriteSheet struct {
PNG []byte
Columns int
Rows int
Width int // preferred terminal width in cells
Calm []int
Build []int
Warn []int
Error []int
// contains filtered or unexported fields
}
StarlogSpriteSheet describes pictured Star Pet animation frames. PNG remains portable and embeddable; Starlog decodes it once and renders it directly to true-colour terminal cells without an external image process.
func NewStarlogSpriteSheet ¶
func NewStarlogSpriteSheet(png []byte, columns, rows, width int) *StarlogSpriteSheet
NewStarlogSpriteSheet creates a custom pictured-pet sheet. Frames are numbered left-to-right, top-to-bottom. The byte slice is copied.
type State ¶
type State struct {
// contains filtered or unexported fields
}
State is Starlings' concurrency-safe in-memory view of Discord. Returned objects are snapshots: callers may mutate them safely.
func (*State) Apply ¶
Apply mutates the cache for one gateway event. Automatic mode calls this before user handlers; manual mode lets applications choose exactly when.
func (*State) BasePermissions ¶
func (s *State) BasePermissions(guildID, userID Snowflake) (value Permissions, err error)
BasePermissions calculates a member's guild-wide permissions before channel overwrites. Guild owners and administrators receive every permission.
func (*State) CanModerate ¶ added in v0.2.0
CanModerate reports whether actor may kick, ban, time out, or change the roles of target, and whether the bot can carry it out. It applies Discord's role hierarchy: the owner outranks everyone, and otherwise a member's highest role must be strictly above the target's. It does not check the specific permission; combine it with BasePermissions or Permissions for that.
A refusal is a *ModerationError. ErrGuildNotCached and ErrMemberNotCached mean the cache cannot answer, not that the action is refused.
func (*State) ChannelPermissions ¶
func (s *State) ChannelPermissions(channelID, userID Snowflake) (value Permissions, err error)
ChannelPermissions is the short form when the channel is cached; it derives the guild ID automatically.
func (*State) Config ¶
func (s *State) Config() StateConfig
Config returns a copy of the active cache configuration.
func (*State) Emojis ¶
func (s *State) Emojis(guildID Snowflake) (out []GuildEmoji)
func (*State) GuildInfo ¶ added in v0.2.0
GuildInfo returns a snapshot of the guild's own fields without its resource collections. Use it for a name, owner, icon, or Discord's reported member count. Guild returns the full composed snapshot when you need the resources.
func (*State) MemberCount ¶ added in v0.2.0
MemberCount returns the number of cached members without cloning or sorting them. Zero can mean an empty, disabled, or not-yet-populated cache. For the total reported by Discord, read MemberCount from the returned GuildInfo.
func (*State) MessageColor ¶
MessageColor returns the cached author's display colour.
func (*State) MessagePermissions ¶
func (s *State) MessagePermissions(message *Message) (Permissions, error)
MessagePermissions is the convenient form for a cached message author.
func (*State) Permissions ¶
func (s *State) Permissions(guildID, channelID, userID Snowflake) (value Permissions, err error)
Permissions calculates a member's effective permissions in a channel, including @everyone, aggregate role, and member-specific overwrites.
func (*State) Presence ¶
func (s *State) Presence(guildID, userID Snowflake) (value PresenceUpdate, ok bool)
func (*State) Presences ¶
func (s *State) Presences(guildID Snowflake) []PresenceUpdate
func (*State) Stats ¶
func (s *State) Stats() StateStats
func (*State) ThreadMember ¶
func (s *State) ThreadMember(threadID, userID Snowflake) (value ThreadMember, ok bool)
func (*State) ThreadMembers ¶
func (s *State) ThreadMembers(threadID Snowflake) (out []ThreadMember)
func (*State) UserColor ¶
UserColor returns the member's display colour from their highest coloured role. Zero means Discord's default text colour.
func (*State) VoiceState ¶
func (s *State) VoiceState(guildID, userID Snowflake) (value VoiceState, ok bool)
func (*State) VoiceStates ¶
func (s *State) VoiceStates(guildID Snowflake) (out []VoiceState)
type StateConfig ¶
type StateConfig struct {
Mode StateMode
Guilds bool
Channels bool
Members bool
Users bool
Roles bool
Emojis bool
Stickers bool
ThreadMembers bool
VoiceStates bool
Presences bool
MaxMessagesPerChannel int
}
StateConfig controls which gateway resources Starlings retains.
Start with DefaultStateConfig and turn off resources a bot does not need. A zero MaxMessagesPerChannel disables the message cache.
func DefaultStateConfig ¶
func DefaultStateConfig() StateConfig
DefaultStateConfig returns Starlings' complete zero-configuration cache.
func MinimalStateConfig ¶ added in v0.2.0
func MinimalStateConfig() StateConfig
MinimalStateConfig disables resource retention while leaving automatic mode selected. Use it for stateless interaction bots, workers, and prefix bots that only react to the event currently being handled.
type StateStats ¶
type StateStats struct {
Guilds, Channels, Members, Users int
Roles, Emojis, Stickers, ThreadMembers int
VoiceStates, Presences, Messages, MessageChannels int
}
StateStats is a cheap count-only snapshot of cache occupancy.
type Sticker ¶
type Sticker struct {
ID Snowflake `json:"id"`
PackID Snowflake `json:"pack_id"`
Name string `json:"name"`
Description string `json:"description"`
Tags string `json:"tags"` // comma-separated autocomplete hints
Type int `json:"type"`
FormatType int `json:"format_type"`
Available bool `json:"available"`
GuildID Snowflake `json:"guild_id"`
User *User `json:"user"`
SortValue int `json:"sort_value"`
}
Sticker is an image or animation that can be sent in a message.
type StickerItem ¶
type StickerPack ¶
type StickerPack struct {
ID Snowflake `json:"id"`
Stickers []Sticker `json:"stickers"`
Name string `json:"name"`
SKUID Snowflake `json:"sku_id"`
CoverStickerID Snowflake `json:"cover_sticker_id"`
Description string `json:"description"`
BannerAssetID Snowflake `json:"banner_asset_id"`
}
StickerPack is a set of stickers Discord ships.
type Subscription ¶
type Subscription struct {
ID Snowflake `json:"id"`
UserID Snowflake `json:"user_id"`
SKUIDs []Snowflake `json:"sku_ids"`
EntitlementIDs []Snowflake `json:"entitlement_ids"`
RenewalSKUIDs []Snowflake `json:"renewal_sku_ids"`
CurrentPeriodStart time.Time `json:"current_period_start"`
CurrentPeriodEnd time.Time `json:"current_period_end"`
Status SubscriptionStatus `json:"status"`
CanceledAt *time.Time `json:"canceled_at"`
Country string `json:"country"`
}
Subscription is a recurring purchase of one or more SKUs.
type SubscriptionCreate ¶
type SubscriptionCreate struct {
Subscription
// contains filtered or unexported fields
}
SubscriptionCreate fires when an application subscription starts.
type SubscriptionDelete ¶
type SubscriptionDelete struct {
Subscription
// contains filtered or unexported fields
}
SubscriptionDelete fires when a subscription ends.
type SubscriptionStatus ¶
type SubscriptionStatus int
SubscriptionStatus is the billing lifecycle state. Grant perks from entitlements, not this value: billing retries can make the period and status temporarily appear inconsistent.
const ( SubscriptionActive SubscriptionStatus = 0 SubscriptionInactive SubscriptionStatus = 1 SubscriptionEnding SubscriptionStatus = 2 )
type SubscriptionUpdate ¶
type SubscriptionUpdate struct {
Subscription
// contains filtered or unexported fields
}
SubscriptionUpdate fires when a subscription renews or changes state.
type SubscriptionsQuery ¶
SubscriptionsQuery pages through a SKU's subscriptions.
type TaskFunc ¶ added in v0.2.0
type TaskFunc func(context.Context, *InteractionCreate) (string, error)
TaskFunc does bounded background work for a slash command. Starlings sends the acknowledgement before calling it and edits the original response with its result. Return an error to log it and show a generic failure message. Use Slash for manual response ownership, modals, files, or multiple replies.
type TextInputStyle ¶
type TextInputStyle int
TextInputStyle controls whether a text input is one line or a paragraph.
const ( TextInputShort TextInputStyle = iota + 1 TextInputParagraph )
type ThreadCreate ¶
type ThreadCreate struct {
Channel
NewlyCreated bool `json:"newly_created"`
// contains filtered or unexported fields
}
ThreadCreate fires when a thread is created, and when the bot is added to an existing one. NewlyCreated distinguishes the two.
type ThreadDelete ¶
type ThreadDelete struct {
ID Snowflake `json:"id"`
GuildID Snowflake `json:"guild_id"`
ParentID Snowflake `json:"parent_id"`
Type ChannelType `json:"type"`
BeforeDelete *Channel `json:"-"`
// contains filtered or unexported fields
}
ThreadDelete fires when a thread is deleted.
type ThreadListSync ¶
type ThreadListSync struct {
GuildID Snowflake `json:"guild_id"`
ChannelIDs []Snowflake `json:"channel_ids"`
Threads []Channel `json:"threads"`
Members []ThreadMember `json:"members"`
// contains filtered or unexported fields
}
ThreadListSync fires when the bot gains access to a channel, listing the active threads it can now see.
type ThreadMember ¶
type ThreadMember struct {
ID Snowflake `json:"id"` // the thread
UserID Snowflake `json:"user_id"`
JoinTimestamp time.Time `json:"join_timestamp"`
Flags int `json:"flags"`
Member *Member `json:"member"`
}
ThreadMember records that a user is following a thread.
type ThreadMemberUpdate ¶
type ThreadMemberUpdate struct {
ThreadMember
GuildID Snowflake `json:"guild_id"`
BeforeUpdate *ThreadMember `json:"-"`
// contains filtered or unexported fields
}
ThreadMemberUpdate fires when the bot's own thread membership changes.
type ThreadMembersUpdate ¶
type ThreadMembersUpdate struct {
ID Snowflake `json:"id"`
GuildID Snowflake `json:"guild_id"`
MemberCount int `json:"member_count"`
AddedMembers []ThreadMember `json:"added_members"`
RemovedMemberIDs []Snowflake `json:"removed_member_ids"`
BeforeUpdate []ThreadMember `json:"-"`
// contains filtered or unexported fields
}
ThreadMembersUpdate fires when people join or leave a thread. The added and removed lists are only populated with the GuildMembers intent.
type ThreadMeta ¶
type ThreadMeta struct {
Archived bool `json:"archived"`
AutoArchiveDuration int `json:"auto_archive_duration"` // minutes
ArchiveTimestamp time.Time `json:"archive_timestamp"`
Locked bool `json:"locked"`
Invitable bool `json:"invitable"`
CreateTimestamp *time.Time `json:"create_timestamp"`
}
ThreadMeta holds the fields that only exist on threads.
type ThreadParams ¶
type ThreadParams struct {
Name string `json:"name"`
AutoArchiveDuration int `json:"auto_archive_duration,omitzero"`
Type ChannelType `json:"type,omitzero"`
Invitable *bool `json:"invitable,omitzero"`
RateLimitPerUser *int `json:"rate_limit_per_user,omitzero"`
}
ThreadParams configures a new thread.
type ThreadSearchResult ¶
type ThreadSearchResult struct {
Threads []Channel `json:"threads"`
Members []ThreadMember `json:"members"`
HasMore bool `json:"has_more"`
TotalResults int `json:"total_results"`
}
ThreadSearchResult is a page of forum or media channel threads.
type ThreadUpdate ¶
type ThreadUpdate struct {
Channel
BeforeUpdate *Channel `json:"-"`
// contains filtered or unexported fields
}
ThreadUpdate fires when a thread's settings change. It does not fire for the last-message timestamp moving.
type TypingStart ¶
type TypingStart struct {
ChannelID Snowflake `json:"channel_id"`
GuildID Snowflake `json:"guild_id"`
UserID Snowflake `json:"user_id"`
Timestamp int64 `json:"timestamp"` // unix seconds
Member *Member `json:"member"`
// contains filtered or unexported fields
}
TypingStart fires when a user starts typing in a channel.
type UnfurledMedia ¶
type UnfurledMedia struct {
ID Snowflake `json:"id,omitzero"`
URL string `json:"url"`
ProxyURL string `json:"proxy_url,omitempty"`
Height *int `json:"height,omitempty"`
Width *int `json:"width,omitempty"`
ContentType string `json:"content_type,omitempty"`
AttachmentID Snowflake `json:"attachment_id,omitzero"`
Placeholder string `json:"placeholder,omitempty"`
PlaceholderVersion int `json:"placeholder_version,omitzero"`
Flags int `json:"flags,omitzero"`
}
UnfurledMedia is media Discord fetches and renders inside a Components V2 layout. For uploads, URL uses the attachment://filename form.
type User ¶
type User struct {
ID Snowflake `json:"id"`
Username string `json:"username"`
Discriminator string `json:"discriminator"` // "0" for accounts migrated to unique usernames
GlobalName string `json:"global_name"` // display name, may be empty
Avatar string `json:"avatar"` // image hash, empty if using a default avatar
Bot bool `json:"bot"`
System bool `json:"system"`
MFAEnabled bool `json:"mfa_enabled"`
Banner string `json:"banner"`
AccentColor int `json:"accent_color"`
Locale string `json:"locale"`
Verified bool `json:"verified"`
Email string `json:"email"`
Flags int `json:"flags"`
PremiumType int `json:"premium_type"`
PublicFlags int `json:"public_flags"`
// contains filtered or unexported fields
}
User is a Discord account: a person or a bot.
func (*User) AvatarURL ¶
AvatarURL returns a CDN link to the user's avatar, or to the default avatar Discord assigns when they have not set one. Pass a size that is a power of two between 16 and 4096; zero uses Discord's default.
func (*User) Send ¶ added in v0.2.0
Send sends a direct message. The DM channel is looked up once and reused.
func (*User) SendComplex ¶ added in v0.2.0
SendComplex sends a direct message with embeds, components, or other fields.
type UserError ¶ added in v0.2.0
type UserError struct {
Message string
}
UserError is an error whose message is meant for the person who used the command. When an error-returning handler returns one, Starlings shows the message to that person privately. Every other error is logged and replaced with a generic message, so internal details never reach Discord.
func (*UserError) UserMessage ¶ added in v0.2.0
UserMessage returns the text shown to the user.
type UserUpdate ¶
type UserUpdate struct {
User
BeforeUpdate *User `json:"-"`
// contains filtered or unexported fields
}
UserUpdate fires when the bot's own user changes.
type VoiceChannelEffectSend ¶
type VoiceChannelEffectSend struct {
ChannelID Snowflake `json:"channel_id"`
GuildID Snowflake `json:"guild_id"`
UserID Snowflake `json:"user_id"`
Emoji *Emoji `json:"emoji"`
AnimationType int `json:"animation_type"`
AnimationID int `json:"animation_id"`
SoundID Snowflake `json:"sound_id"`
SoundVolume float64 `json:"sound_volume"`
// contains filtered or unexported fields
}
VoiceChannelEffectSend fires when someone sends a reaction effect in a voice channel.
type VoiceChannelStartTimeUpdate ¶
type VoiceChannelStartTimeUpdate struct {
ID Snowflake `json:"id"`
GuildID Snowflake `json:"guild_id"`
VoiceStartTime *int64 `json:"voice_start_time"`
BeforeUpdate *Channel `json:"-"`
// contains filtered or unexported fields
}
VoiceChannelStartTimeUpdate fires when a voice session starts or ends.
type VoiceChannelStatusUpdate ¶
type VoiceChannelStatusUpdate struct {
ID Snowflake `json:"id"`
GuildID Snowflake `json:"guild_id"`
Status *string `json:"status"`
BeforeUpdate *Channel `json:"-"`
// contains filtered or unexported fields
}
VoiceChannelStatusUpdate fires when a voice channel's visible status changes.
type VoiceRegion ¶
type VoiceRegion struct {
ID string `json:"id"`
Name string `json:"name"`
Optimal bool `json:"optimal"`
Deprecated bool `json:"deprecated"`
Custom bool `json:"custom"`
}
VoiceRegion is a server region available for voice channels.
type VoiceServerUpdate ¶
type VoiceServerUpdate struct {
Token string `json:"token"`
GuildID Snowflake `json:"guild_id"`
Endpoint string `json:"endpoint"`
// contains filtered or unexported fields
}
VoiceServerUpdate carries the endpoint and token used by ConnectVoice.
type VoiceState ¶
type VoiceState struct {
GuildID Snowflake `json:"guild_id"`
ChannelID Snowflake `json:"channel_id"` // zero when the member has disconnected
UserID Snowflake `json:"user_id"`
Member *Member `json:"member"`
SessionID string `json:"session_id"`
Deaf bool `json:"deaf"`
Mute bool `json:"mute"`
SelfDeaf bool `json:"self_deaf"`
SelfMute bool `json:"self_mute"`
SelfStream bool `json:"self_stream"`
SelfVideo bool `json:"self_video"`
Suppress bool `json:"suppress"`
}
VoiceState is a member's current voice connection within a guild.
type VoiceStateUpdate ¶
type VoiceStateUpdate struct {
VoiceState
BeforeUpdate *VoiceState `json:"-"`
// contains filtered or unexported fields
}
VoiceStateUpdate fires when someone joins, leaves or moves between voice channels, or mutes themselves. It needs the GuildVoiceStates intent, which is not privileged.
ChannelID is zero when the user has disconnected.
type Webhook ¶
type Webhook struct {
ID Snowflake `json:"id"`
Type WebhookType `json:"type"`
GuildID Snowflake `json:"guild_id"`
ChannelID Snowflake `json:"channel_id"`
User *User `json:"user"` // who created it
Name string `json:"name"`
Avatar string `json:"avatar"`
Token string `json:"token"`
ApplicationID Snowflake `json:"application_id"`
URL string `json:"url"`
}
Webhook posts into a channel without a bot user. Its token is as sensitive as a bot token: anyone holding it can post as the webhook.
type WebhookMessage ¶
type WebhookMessage struct {
Content string `json:"content,omitzero"`
Username string `json:"username,omitzero"`
AvatarURL string `json:"avatar_url,omitzero"`
TTS bool `json:"tts,omitzero"`
Embeds []Embed `json:"embeds,omitzero"`
Components []Component `json:"components,omitzero"`
AllowedMentions *AllowedMentions `json:"allowed_mentions,omitzero"`
Flags MessageFlags `json:"flags,omitzero"`
ThreadName string `json:"thread_name,omitzero"`
Poll *Poll `json:"poll,omitzero"`
AppliedTags []Snowflake `json:"applied_tags,omitzero"`
}
WebhookMessage is what a webhook posts. Username and AvatarURL override the webhook's configured identity for this message only.
type WebhookParams ¶
type WebhookParams struct {
Name *string `json:"name,omitzero"`
Avatar *string `json:"avatar,omitzero"` // image data URI
ChannelID *Snowflake `json:"channel_id,omitzero"`
}
WebhookParams are the settable fields of a webhook.
type WebhookType ¶
type WebhookType int
WebhookType distinguishes the kinds of webhook Discord issues.
const ( // WebhookIncoming posts messages into a channel via a token URL. WebhookIncoming WebhookType = iota + 1 // WebhookChannelFollower is created by following an announcement channel. WebhookChannelFollower // WebhookApplication backs interaction responses and follow-ups. WebhookApplication )
type WebhooksUpdate ¶
type WebhooksUpdate struct {
GuildID Snowflake `json:"guild_id"`
ChannelID Snowflake `json:"channel_id"`
// contains filtered or unexported fields
}
WebhooksUpdate fires when a channel's webhooks change. Like ChannelPinsUpdate it carries no detail, only the fact of the change.
type WelcomeScreen ¶
type WelcomeScreen struct {
Description string `json:"description"`
WelcomeChannels []WelcomeScreenChannel `json:"welcome_channels"`
}
WelcomeScreen is the panel new members see when joining a community guild.
type WelcomeScreenChannel ¶
type WelcomeScreenChannel struct {
ChannelID Snowflake `json:"channel_id"`
Description string `json:"description"`
EmojiID Snowflake `json:"emoji_id"`
EmojiName string `json:"emoji_name"`
}
WelcomeScreenChannel is one suggested channel on the welcome screen.
type WidgetAsset ¶
type WidgetAsset struct {
Key string `json:"key"`
AssetID Snowflake `json:"asset_id"`
AssetType string `json:"asset_type"`
Visibility string `json:"visibility"` // "public" or the image renders as a skeleton
Metadata struct {
Width int `json:"width"`
Height int `json:"height"`
ContentType string `json:"content_type"`
IsAnimated bool `json:"is_animated"`
} `json:"metadata"`
}
WidgetAsset is an image uploaded to the application, as reported back alongside a config.
type WidgetComponent ¶
type WidgetComponent struct {
Fields map[string]WidgetField `json:"fields"`
}
WidgetComponent is one slot in a layout - a stat, a tile, the title.
type WidgetConfig ¶
type WidgetConfig struct {
ConfigID string `json:"config_id,omitzero"`
ApplicationID Snowflake `json:"application_id,omitzero"`
DisplayName string `json:"display_name,omitzero"`
Status string `json:"status,omitzero"` // "published" once live
Surfaces map[string]WidgetSurface `json:"surfaces,omitzero"`
ResolvedAssets []WidgetAsset `json:"resolved_assets,omitzero"`
}
WidgetConfig is one widget's appearance. Surfaces are keyed "widget_top", "widget_bottom", "add_widget_preview", "mini_profile" and "activity_accessory"; the first three are required before publishing.
type WidgetField ¶
type WidgetField struct {
ValueType string `json:"value_type"`
PresentationType string `json:"presentation_type"`
Value string `json:"value"`
}
WidgetField is one displayed value.
func AssetField ¶
func AssetField(assetKey string) WidgetField
AssetField references an image uploaded to the developer portal by its key.
func DataField ¶
func DataField(key, presentation string) WidgetField
DataField reads a key from the player's identity profile.
func LiteralField ¶
func LiteralField(text string) WidgetField
LiteralField is a fixed string, the same for every player.
type WidgetStat ¶
type WidgetStat struct {
Key string // profile data key, e.g. "total_wins"
Label string // the caption under it
Presentation string // PresentText, PresentNumber or PresentDuration
}
WidgetStat is one entry of a stats grid.
type WidgetSurface ¶
type WidgetSurface struct {
Layout string `json:"layout"`
Components map[string]WidgetComponent `json:"components"`
}
WidgetSurface is one region of the widget: a layout plus its components.
func CollectionSurface ¶
func CollectionSurface(keyPrefix string) WidgetSurface
CollectionSurface builds a widget_bottom_collection surface - four tiles, each an image with a name and a description, all read from profile data.
keyPrefix is combined with the tile number, so a prefix of "item" reads item_1_image, item_1_name, item_1_desc and so on.
func StatsSurface ¶
func StatsSurface(stats ...WidgetStat) WidgetSurface
StatsSurface builds a widget_bottom_stats surface from up to six stats, each a profile key rendered with the given presentation and a fixed label.
Source Files
¶
- activity.go
- appcommand.go
- application_management.go
- autodefer.go
- automod.go
- cdn.go
- channel.go
- channeladmin.go
- chunking.go
- client.go
- command.go
- component.go
- dispatch.go
- doc.go
- embed.go
- emoji.go
- endpoints.go
- errors.go
- events.go
- events_resources.go
- extension.go
- gateway.go
- gateway_compression.go
- gateway_control.go
- gateway_predial.go
- gateway_send.go
- guard.go
- guild.go
- guild_settings.go
- guildadmin.go
- handler.go
- handlers.go
- history.go
- identity.go
- intentcheck.go
- intents.go
- interaction.go
- interaction_http.go
- interaction_routes.go
- interactionresponse.go
- member.go
- message.go
- message_admin.go
- misc.go
- moderation.go
- monetisation.go
- objects.go
- opcode.go
- permissions.go
- purge.go
- rest.go
- rest_limit.go
- role.go
- roleconnection.go
- routes.go
- run.go
- sharding.go
- slash.go
- slash_task.go
- slashargs.go
- snowflake.go
- social.go
- soundboard.go
- starlog.go
- starlog_media.go
- starlog_render.go
- starlog_sink.go
- starlog_terminal_other.go
- starpet_picture.go
- state.go
- state_access.go
- state_apply.go
- state_clone.go
- state_permissions.go
- thread.go
- trim.go
- typename.go
- upload.go
- user.go
- useradmin.go
- util.go
- values.go
- wait.go
- webhook.go
- widgetconfig.go
Directories
¶
| Path | Synopsis |
|---|---|
|
benchmarks
|
|
|
arena/adapters/go_discordgo
command
|
|
|
arena/adapters/starlings
command
|
|
|
arena/cmd/report
command
|
|
|
examples
|
|
|
firstbot
command
Command firstbot is the smallest useful Starlings bot.
|
Command firstbot is the smallest useful Starlings bot. |
|
guard
command
|
|
|
interactions
command
|
|
|
kitty
command
Command kitty runs a live smoke test against Discord and posts the results in a channel named dev-chat.
|
Command kitty runs a live smoke test against Discord and posts the results in a channel named dev-chat. |
|
ping
command
Command ping is the smallest Starlings bot: a /ping slash command.
|
Command ping is the smallest Starlings bot: a /ping slash command. |
|
slashbot
command
Command slashbot demonstrates the short API without a resource cache.
|
Command slashbot demonstrates the short API without a resource cache. |
|
soundboard
command
Command soundboard is a Discord soundboard bot built on starlings.
|
Command soundboard is a Discord soundboard bot built on starlings. |
|
starlog
command
|
|
|
starlogdemo
command
|
|
|
voice
command
Command voice joins an occupied voice channel and plays a local file.
|
Command voice joins an occupied voice channel and plays a local file. |
|
widget
command
Command widget drives Discord's Game Stats Widget API with starlings.
|
Command widget drives Discord's Game Stats Widget API with starlings. |
|
internal
|
|
|
apidoc
command
Command apidoc regenerates the reference files in starlings/docs from Discord's official OpenAPI description, and measures how much of that surface starlings actually implements.
|
Command apidoc regenerates the reference files in starlings/docs from Discord's official OpenAPI description, and measures how much of that surface starlings actually implements. |
|
Package stardb provides small, optional persistence adapters for Starlings bots.
|
Package stardb provides small, optional persistence adapters for Starlings bots. |
|
Package starpets adds Starlings' bundled pixel art to Starlog's pets.
|
Package starpets adds Starlings' bundled pixel art to Starlog's pets. |
|
Package sysmedia shows the operating system's current media session in Starlog's now-playing strip.
|
Package sysmedia shows the operating system's current media session in Starlog's now-playing strip. |
|
Command arena-generate-fixtures creates the immutable payloads consumed by every language adapter.
|
Command arena-generate-fixtures creates the immutable payloads consumed by every language adapter. |
|
Package voice connects Starlings bots to Discord voice channels.
|
Package voice connects Starlings bots to Discord voice channels. |