Go SDK reference
Every exported declaration of `github.com/mnema-xyz/bot-sdk-go`, with its doc comment. Generated from bot-sdk-go v0.4.0 (e1f8a97ac406).
Functions
ActionRow
ActionRow returns an action row with the given children: up to 5 buttons, exactly one select menu, or (in a modal) one text input.
func ActionRow(children ...ComponentBuilder) Component
AddBotLink
AddBotLink returns the link that opens the server's confirm screen for the
manifest:
func AddBotLink(serverURL string, m Manifest) (string, error)
DangerButton
DangerButton returns a danger (red) button.
func DangerButton(customID, label string) Button
FormatPermissions
FormatPermissions returns a decimal string bitfield combining the given permissions.
func FormatPermissions(perms ...Permission) string
HasPermission
HasPermission reports whether a decimal permission bitfield string includes the permission. Administrator grants all permissions.
func HasPermission(rawPermissions string, p Permission) bool
IsFatalClose
IsFatalClose reports whether a close code stops Run.
func IsFatalClose(code int) bool
LinkButton
LinkButton returns a button that opens url (http or https).
func LinkButton(url, label string) Button
New
New returns a client for the bot. It does not connect; Run does.
func New(o Options) (*Client, error)
NewModal
NewModal returns a modal with one row per text input.
func NewModal(customID, title string, inputs ...TextInput) Modal
NewREST
NewREST returns a REST client for o.BaseURL and o.Token; the gateway fields of Options are ignored. New builds one for every Client.
func NewREST(o Options) (*REST, error)
PrimaryButton
PrimaryButton returns a primary button.
func PrimaryButton(customID, label string) Button
SecondaryButton
SecondaryButton returns a secondary button.
func SecondaryButton(customID, label string) Button
SuccessButton
SuccessButton returns a success (green) button.
func SuccessButton(customID, label string) Button
ValidateComponents
ValidateComponents checks the components of a message: at most 5 action rows and 25 components, each row valid, and custom IDs unique.
func ValidateComponents(rows []Component) error
Types
Activity
Activity is what the bot is doing ("Playing chess"). A custom activity (type 4) shows State, or Name when State is empty. The server cuts the text to 64 characters.
type Activity struct {
Name string `json:"name"`
Type ActivityType `json:"type"`
State string `json:"state,omitempty"`
}
ActivityType
ActivityType is the kind of a bot's activity.
type ActivityType int
AllowedMentions
AllowedMentions limits whom a message notifies: Parse may contain "everyone" and "roles"; Users and Roles list ids.
type AllowedMentions struct {
Parse []string `json:"parse,omitempty"`
Users []string `json:"users,omitempty"`
Roles []string `json:"roles,omitempty"`
}
Attachment
Attachment is a file of a message; REST.DownloadAttachment(ID) reads it. Filename, ContentType and Size carry the same values as OriginalFilename, MimeType and SizeBytes, under the names doc/bots.md documents first.
type Attachment struct {
ID string `json:"id"`
URL string `json:"url"`
Filename string `json:"filename,omitempty"`
ContentType string `json:"content_type,omitempty"`
Size int64 `json:"size,omitempty"`
OriginalFilename string `json:"original_filename"`
MimeType string `json:"mime_type"`
SizeBytes int64 `json:"size_bytes"`
IsDeleted bool `json:"is_deleted"`
}
Button
Button is a button. Interactive styles carry a CustomID; ButtonLink carries a URL instead. Emoji is an optional Unicode emoji.
type Button struct {
Style ButtonStyle
Label string
CustomID string
URL string
Emoji string
Disabled bool
}
Button.Component
Component returns the button's JSON form. A zero Style means primary, or link when only a URL is set.
func (b Button) Component() Component
Button.Validate
Validate checks the button against the server's limits.
func (b Button) Validate() error { return b.Component().Validate() }
ButtonStyle
ButtonStyle is the style of a button.
type ButtonStyle int
Category
Category groups channels.
type Category struct {
ID string `json:"id"`
Name string `json:"name"`
SortOrder int `json:"sort_order"`
CreatedAt time.Time `json:"created_at"`
Channels []Channel `json:"channels"`
}
Channel
Channel is a channel the bot can view.
type Channel struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
Topic string `json:"topic"`
CategoryID *string `json:"category_id"`
Number int `json:"number"`
SortOrder int `json:"sort_order"`
SlowModeSeconds int `json:"slow_mode_seconds"`
Slug string `json:"slug,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
ChannelHierarchy
ChannelHierarchy is the answer of GET /channels: the channels the bot can view, grouped by category.
type ChannelHierarchy struct {
Categories []Category `json:"categories"`
Uncategorized []Channel `json:"uncategorized"`
}
ChannelHierarchy.All
All returns every channel of the hierarchy, categorised ones first.
func (h *ChannelHierarchy) All() []Channel
ChannelSelect
ChannelSelect is a select menu of text, forum and announcement channels.
type ChannelSelect selectMenu
ChannelSelect.Component
Component returns the select's JSON form.
func (s ChannelSelect) Component() Component { return selectMenu(s).component(ComponentChannelSelect) }
ChannelSelect.Validate
Validate checks the select against the server's limits.
func (s ChannelSelect) Validate() error { return s.Component().Validate() }
ChannelsUpdate
ChannelsUpdate is the CHANNELS_UPDATE dispatch: the channel layout or the bot's access changed; fetch REST.Channels again.
type ChannelsUpdate struct{}
Client
Client is a bot: the REST client and a gateway session that delivers events to the registered handlers. Register handlers before Run.
type Client struct {
// REST is the REST client of the bot.
REST *REST
}
Client.OnChannelsUpdate
OnChannelsUpdate registers a handler for CHANNELS_UPDATE (GUILDS).
func (c *Client) OnChannelsUpdate(h func(context.Context, *ChannelsUpdate))
Client.OnDispatch
OnDispatch registers a handler for every dispatch, with its name and raw data, including events this SDK does not know yet.
func (c *Client) OnDispatch(h func(ctx context.Context, name string, data json.RawMessage))
Client.OnInteraction
OnInteraction registers a handler for INTERACTION_CREATE (no intent needed). The interaction's Reply and other methods use c.REST.
func (c *Client) OnInteraction(h func(context.Context, *Interaction))
Client.OnMemberAdd
OnMemberAdd registers a handler for GUILD_MEMBER_ADD (GUILD_MEMBERS).
func (c *Client) OnMemberAdd(h func(context.Context, *MemberAdd)) { add(c, &c.handlers.memberAdd, h) }
Client.OnMessageCreate
OnMessageCreate registers a handler for MESSAGE_CREATE (GUILD_MESSAGES).
func (c *Client) OnMessageCreate(h func(context.Context, *Message))
Client.OnMessageDelete
OnMessageDelete registers a handler for MESSAGE_DELETE (GUILD_MESSAGES).
func (c *Client) OnMessageDelete(h func(context.Context, *MessageDelete))
Client.OnMessageUpdate
OnMessageUpdate registers a handler for MESSAGE_UPDATE (GUILD_MESSAGES).
func (c *Client) OnMessageUpdate(h func(context.Context, *Message))
Client.OnReactionsUpdate
OnReactionsUpdate registers a handler for MESSAGE_REACTIONS_UPDATE (GUILD_MESSAGE_REACTIONS).
func (c *Client) OnReactionsUpdate(h func(context.Context, *ReactionsUpdate))
Client.OnReady
OnReady registers a handler for READY (also after a new session).
func (c *Client) OnReady(h func(context.Context, *Ready)) { add(c, &c.handlers.ready, h) }
Client.OnResumed
OnResumed registers a handler for RESUMED: a dropped session continued.
func (c *Client) OnResumed(h func(context.Context)) { add(c, &c.handlers.resumed, h) }
Client.Run
Run connects to the gateway and delivers events to the handlers until ctx ends (it then returns nil) or the gateway closes with a fatal code (4004, 4013, 4014: it returns a *CloseError). Dropped connections are resumed with the session ID and the last sequence number; when the session cannot be resumed the client identifies again. Reconnects wait with exponential backoff and jitter between 1 and 60 seconds, longer after 4008. A REST answer of 401 or 403 to GET /gateway is returned as a *RESTError. Run waits for running handlers before it returns.
func (c *Client) Run(ctx context.Context) error
Client.SetPresence
SetPresence sets the bot's status and activity (gateway op 3). While no connection is live it is kept and sent with the next IDENTIFY or after the next RESUME. The server applies at most 5 updates per 60 seconds and drops further ones without an error.
func (c *Client) SetPresence(ctx context.Context, p Presence) error
CloseError
CloseError is returned by Run when the gateway closed with a fatal code (4004, 4013, 4014): the token or the intents must change before the bot can connect again.
type CloseError struct {
Code int
Reason string
}
CloseError.Error
func (e *CloseError) Error() string
Command
Command is a registered slash command.
type Command struct {
ID string `json:"id"`
BotID string `json:"bot_id"`
Name string `json:"name"`
Description string `json:"description"`
Options []CommandOption `json:"options"`
Disabled bool `json:"disabled"`
DefaultMemberPermissions *string `json:"default_member_permissions,omitempty"`
}
CommandInput
CommandInput is a command to register.
type CommandInput struct {
Name string `json:"name"`
Description string `json:"description"`
Options []CommandOption `json:"options"`
DefaultMemberPermissions any `json:"default_member_permissions,omitempty"`
}
CommandInput.MarshalJSON
MarshalJSON serializes CommandInput, converting integer or Permission bit values of DefaultMemberPermissions to a decimal string as expected by the REST API.
func (c CommandInput) MarshalJSON() ([]byte, error)
CommandOption
CommandOption is one option of a command. Required options come first; Choices (text options only) restrict the values.
type CommandOption struct {
Name string `json:"name"`
Description string `json:"description"`
Type OptionType `json:"type"`
Required bool `json:"required"`
Choices []string `json:"choices,omitempty"`
}
Component
Component is one element of a message's components or of a modal, in the bot API's JSON: an action row, a button, a select menu or a text input. Which fields apply depends on Type. The builders (ActionRow, Button, StringSelect, ...) fill it; Validate checks the documented limits.
type Component struct {
Type ComponentType `json:"type"`
Components []Component `json:"components,omitempty"`
CustomID string `json:"custom_id,omitempty"`
Style int `json:"style,omitempty"`
Label string `json:"label,omitempty"`
Emoji *Emoji `json:"emoji,omitempty"`
URL string `json:"url,omitempty"`
Disabled bool `json:"disabled,omitempty"`
Options []SelectOption `json:"options,omitempty"`
Placeholder string `json:"placeholder,omitempty"`
MinValues *int `json:"min_values,omitempty"`
MaxValues *int `json:"max_values,omitempty"`
MinLength *int `json:"min_length,omitempty"`
MaxLength *int `json:"max_length,omitempty"`
Required *bool `json:"required,omitempty"`
Value string `json:"value,omitempty"`
}
Component.Component
Component returns c itself, so a Component can be passed where a builder is expected.
func (c Component) Component() Component { return c }
Component.Validate
Validate checks one component against the documented limits. An action row is checked as a row of a message (buttons or one select).
func (c Component) Validate() error
ComponentBuilder
ComponentBuilder is anything that becomes a Component: the builder types below and Component itself.
type ComponentBuilder interface {
Component() Component
}
ComponentType
ComponentType is the type of a message component (the bot API's numbers).
type ComponentType int
DownloadedAttachment
DownloadedAttachment is an attachment being downloaded. The caller must close Body.
type DownloadedAttachment struct {
// ContentType is the server's Content-Type, application/octet-stream if
// none was sent.
ContentType string
// Size is the announced Content-Length, -1 when unknown.
Size int64
// Filename is the name from Content-Disposition, empty when none.
Filename string
// Body streams the file; with MaxBytes set, a read past the limit fails
// with a *MaxBytesError.
Body io.ReadCloser
}
DownloadOptions
DownloadOptions bound an attachment download.
type DownloadOptions struct {
// MaxBytes refuses a larger file: before the body when the server
// announces a larger Content-Length, else while reading. 0 means no
// limit.
MaxBytes int64
// Timeout ends the request, reading the body included. 0 leaves it to
// the context and the HTTP client.
Timeout time.Duration
}
Edit
Edit changes a response or the message a component is on (EditReply, Update). Nil fields stay as they are; an empty Components slice removes the components. It has no Ephemeral: the first response (Reply or DeferReply) decides whether an answer is ephemeral, and the server refuses flags on an edit.
type Edit struct {
Content *string `json:"content,omitempty"`
Embeds *[]Embed `json:"embeds,omitempty"`
Components *[]Component `json:"components,omitempty"`
// AllowedMentions narrows whom the new text notifies, as on a post.
AllowedMentions *AllowedMentions `json:"allowed_mentions,omitempty"`
}
Embed
Embed is a rich embed of a message.
type Embed struct {
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
URL string `json:"url,omitempty"`
Color int `json:"color,omitempty"`
Timestamp string `json:"timestamp,omitempty"`
Author *EmbedAuthor `json:"author,omitempty"`
Footer *EmbedFooter `json:"footer,omitempty"`
Image *EmbedMedia `json:"image,omitempty"`
Thumbnail *EmbedMedia `json:"thumbnail,omitempty"`
Fields []EmbedField `json:"fields,omitempty"`
}
EmbedAuthor
EmbedAuthor is the author line of an embed.
type EmbedAuthor struct {
Name string `json:"name"`
URL string `json:"url,omitempty"`
}
EmbedField
EmbedField is one name/value field of an embed.
type EmbedField struct {
Name string `json:"name"`
Value string `json:"value"`
Inline bool `json:"inline,omitempty"`
}
EmbedFooter
EmbedFooter is the footer of an embed.
type EmbedFooter struct {
Text string `json:"text"`
}
EmbedMedia
EmbedMedia is the image or thumbnail of an embed.
type EmbedMedia struct {
URL string `json:"url"`
}
Emoji
Emoji is the Unicode emoji of a button or select option.
type Emoji struct {
Name string `json:"name"`
}
Forward
Forward marks a forwarded message; its content is the forwarder's comment.
type Forward struct {
Forwarded bool `json:"forwarded"`
}
GatewayInfo
GatewayInfo is the answer of GET /gateway.
type GatewayInfo struct {
URL string `json:"url"`
HeartbeatInterval int `json:"heartbeat_interval"`
MaxConnections int `json:"max_connections"`
}
Intents
Intents choose the event classes of a gateway session (bit flags).
type Intents int64
Intents.Names
Names returns the manifest names of the intents ("GUILDS", ...).
func (i Intents) Names() []string
Interaction
Interaction is an INTERACTION_CREATE dispatch: a member ran a command (type 2), used a component (type 3) or submitted a modal (type 5). Answer it within 15 minutes with Reply, DeferReply, Update, DeferUpdate or ShowModal; then EditReply, DeleteReply and FollowUp work for the same 15 minutes.
type Interaction struct {
ID string `json:"id"`
Token string `json:"token"`
Type InteractionType `json:"type"`
ChannelID string `json:"channel_id"`
ApplicationID string `json:"application_id"`
Member *InteractionMember `json:"member,omitempty"`
// User is the member who caused the interaction (Member.User). The server
// sends it with every interaction; one without it is not delivered.
User User `json:"-"`
// Message is the message the component is on (type 3, and type 5 when
// the modal came from a component).
Message *Message `json:"message,omitempty"`
Data InteractionData `json:"data"`
}
Interaction.CommandName
CommandName is the name of the command that ran ("" for other types).
func (i *Interaction) CommandName() string
Interaction.CustomID
CustomID is the custom ID of the component used, or of the modal submitted.
func (i *Interaction) CustomID() string { return i.Data.CustomID }
Interaction.DeferReply
DeferReply acknowledges now (callback 5); the answer follows with EditReply or FollowUp. With ephemeral the answer is shown to the member only.
func (i *Interaction) DeferReply(ctx context.Context, ephemeral bool) error
Interaction.DeferUpdate
DeferUpdate acknowledges a click without changing anything yet (callback 6).
func (i *Interaction) DeferUpdate(ctx context.Context) error
Interaction.DeleteReply
DeleteReply deletes the original response.
func (i *Interaction) DeleteReply(ctx context.Context) error
Interaction.EditReply
EditReply edits the original response, or posts it after DeferReply. The message is nil for an ephemeral note (the server answers 204).
func (i *Interaction) EditReply(ctx context.Context, e Edit) (*Message, error)
Interaction.Field
Field returns the submitted value of a modal's text input ("" when absent).
func (i *Interaction) Field(customID string) string
Interaction.FollowUp
FollowUp sends a further message (up to 5 responses in total). The message is nil for an ephemeral one.
func (i *Interaction) FollowUp(ctx context.Context, resp Response) (*Message, error)
Interaction.HasPermission
HasPermission reports whether the invoking member holds the given permission.
func (i *Interaction) HasPermission(p Permission) bool
Interaction.IsButton
IsButton reports a button click.
func (i *Interaction) IsButton() bool
Interaction.IsCommand
IsCommand reports a slash command.
func (i *Interaction) IsCommand() bool { return i.Type == InteractionCommand }
Interaction.IsComponent
IsComponent reports a click or a select.
func (i *Interaction) IsComponent() bool { return i.Type == InteractionComponent }
Interaction.IsModalSubmit
IsModalSubmit reports a submitted modal.
func (i *Interaction) IsModalSubmit() bool { return i.Type == InteractionModalSubmit }
Interaction.IsSelect
IsSelect reports a pick in any select menu.
func (i *Interaction) IsSelect() bool
Interaction.Option
Option returns the command option of that name, or nil. The getters of the result are safe on nil: i.Option("text").String().
func (i *Interaction) Option(name string) *InteractionOption
Interaction.Reply
Reply posts the response message (callback 4).
func (i *Interaction) Reply(ctx context.Context, r Response) error
Interaction.ShowModal
ShowModal opens a modal (callback 9); a modal submit cannot open another.
func (i *Interaction) ShowModal(ctx context.Context, m Modal) error
Interaction.UnmarshalJSON
UnmarshalJSON decodes the interaction and fills User from Member.
func (i *Interaction) UnmarshalJSON(b []byte) error
Interaction.Update
Update changes the message the component is on (callback 7).
func (i *Interaction) Update(ctx context.Context, e Edit) error
Interaction.Values
Values are the values picked in a select.
func (i *Interaction) Values() []string { return i.Data.Values }
InteractionData
InteractionData is the data of an interaction; which fields are set depends on the type.
type InteractionData struct {
// ID and Name identify the command (type 2); Options are its values.
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Options []InteractionOption `json:"options,omitempty"`
// CustomID is the component's (type 3) or the modal's (type 5).
CustomID string `json:"custom_id,omitempty"`
ComponentType ComponentType `json:"component_type,omitempty"`
// Values are the picked values of a select.
Values []string `json:"values,omitempty"`
// Resolved describes the picks of user, role and channel selects.
Resolved *Resolved `json:"resolved,omitempty"`
// Components are the submitted rows of a modal (type 5).
Components []Component `json:"components,omitempty"`
}
InteractionMember
InteractionMember is the member who caused an interaction, with their permissions in the channel.
type InteractionMember struct {
User User `json:"user"`
Permissions string `json:"permissions,omitempty"`
}
InteractionMember.HasPermission
HasPermission reports whether the member holds the given permission in the channel where the interaction occurred. Administrator grants all permissions.
func (m *InteractionMember) HasPermission(p Permission) bool
InteractionOption
InteractionOption is one option value of a command.
type InteractionOption struct {
Name string `json:"name"`
Type OptionType `json:"type"`
Value json.RawMessage `json:"value"`
}
InteractionOption.Bool
Bool returns a boolean option (false when missing or of another type).
func (o *InteractionOption) Bool() bool
InteractionOption.Int
Int returns an integer option (0 when missing or of another type).
func (o *InteractionOption) Int() int64
InteractionOption.String
String returns a text, user or channel option ("" when missing or of another type). It is safe on a nil option.
func (o *InteractionOption) String() string
InteractionType
InteractionType is the type of an interaction.
type InteractionType int
Manifest
Manifest describes a bot so that an admin can add it from an add link or by pasting it (doc/bots.md, Adding a bot from a manifest).
type Manifest struct {
// ManifestVersion must be 1; AddBotLink sets it when it is 0.
ManifestVersion int `json:"manifest_version"`
// Name is 1 to 24 characters.
Name string `json:"name"`
// Description is up to 200 characters.
Description string `json:"description,omitempty"`
// Homepage is an https URL of up to 512 characters.
Homepage string `json:"homepage,omitempty"`
// Avatar is a data: URL of a PNG, JPEG or WebP image of at most 256 KB.
Avatar string `json:"avatar,omitempty"`
// Intents are names such as "GUILDS"; Intents.Names() gives them.
Intents []string `json:"intents,omitempty"`
// Permissions are channel permissions: view_channel, send_messages,
// attach_files, add_reactions, manage_messages, mention_everyone.
Permissions []string `json:"permissions,omitempty"`
// Commands are registered as with SetCommands (at most 50).
Commands []CommandInput `json:"commands,omitempty"`
}
Manifest.Validate
Validate checks the manifest against the server's rules.
func (m Manifest) Validate() error
MaxBytesError
MaxBytesError reports an attachment larger than DownloadOptions.MaxBytes.
type MaxBytesError struct {
MaxBytes int64
// Bytes is the announced or the read size so far, at least MaxBytes+1.
Bytes int64
}
MaxBytesError.Error
func (e *MaxBytesError) Error() string
Member
Member is a member as GET /members lists them.
type Member = User
MemberAdd
MemberAdd is the GUILD_MEMBER_ADD dispatch.
type MemberAdd = User
Message
Message is a message as the REST API and the gateway carry it.
type Message struct {
ID string `json:"id"`
ChannelID string `json:"channel_id"`
UserID string `json:"user_id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
AvatarURL string `json:"avatar_url,omitempty"`
IsBot bool `json:"is_bot,omitempty"`
IsWebhook bool `json:"is_webhook,omitempty"`
Content string `json:"content"`
Embeds []Embed `json:"embeds,omitempty"`
Components []Component `json:"components,omitempty"`
Attachments []Attachment `json:"attachments,omitempty"`
Reactions []Reaction `json:"reactions,omitempty"`
Mentions []string `json:"mentions,omitempty"`
MentionRole []string `json:"mention_roles,omitempty"`
Number int64 `json:"number"`
ParentID string `json:"parent_id,omitempty"`
ReplyToID string `json:"reply_to_id,omitempty"`
ReplyCount int `json:"reply_count"`
IsEdited bool `json:"is_edited"`
IsPinned bool `json:"is_pinned"`
Nonce string `json:"nonce,omitempty"`
Flags int `json:"flags,omitempty"`
Forward *Forward `json:"forward,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
// ExpiresAt is when the server deletes the message, the end of its
// lifetime; nil on a message without one.
ExpiresAt *time.Time `json:"expires_at,omitempty"`
}
Message.MentionsUser
MentionsUser reports whether the message mentions the user with the given id (for a bot: Ready.User.ID).
func (m *Message) MentionsUser(id string) bool
MessageCreate
MessageCreate is the body of a new message. A message needs content, embeds or components.
type MessageCreate struct {
Content string `json:"content,omitempty"`
Embeds []Embed `json:"embeds,omitempty"`
Components []Component `json:"components,omitempty"`
AllowedMentions *AllowedMentions `json:"allowed_mentions,omitempty"`
MessageReference *MessageReference `json:"message_reference,omitempty"`
// ParentID makes the message a reply in the thread of that message.
ParentID string `json:"parent_id,omitempty"`
// LifetimeSeconds makes the server delete the message that long after it
// is stored, as for a member: 60 to 2592000 and at most the community's
// ceiling (doc/timed-messages.md). 0 sends none. Refused with 400 when
// lifetimes are off or out of bounds.
LifetimeSeconds int `json:"lifetime_seconds,omitempty"`
}
MessageDelete
MessageDelete is the MESSAGE_DELETE dispatch.
type MessageDelete struct {
ID string `json:"id"`
ChannelID string `json:"channel_id"`
ParentID string `json:"parent_id,omitempty"`
}
MessageEdit
MessageEdit changes a bot's own message. Nil fields stay as they are; Components set to an empty slice removes the components.
type MessageEdit struct {
Content *string `json:"content,omitempty"`
Components *[]Component `json:"components,omitempty"`
// AllowedMentions is whom the new text notifies, as on a post; an edit
// with it counts as a post for the channel's limit.
AllowedMentions *AllowedMentions `json:"allowed_mentions,omitempty"`
}
MessageQuery
MessageQuery pages through a channel's messages: at most one of Before, After and Around (message ids); Limit is 1 to 100 (0 means the server's default of 50).
type MessageQuery struct {
Limit int
Before string
After string
Around string
}
MessageReference
MessageReference makes a message a reply to another one.
type MessageReference struct {
MessageID string `json:"message_id"`
}
Modal
Modal is a form opened with Interaction.ShowModal: a title and 1 to 5 rows of one text input each. Rows may be given as TextInputs (each becomes a row) through NewModal, or as action rows directly.
type Modal struct {
CustomID string `json:"custom_id"`
Title string `json:"title"`
Components []Component `json:"components"`
}
Modal.Validate
Validate checks the modal: title 1 to 45 characters, a custom ID, and 1 to 5 rows of exactly one text input each, with unique custom IDs.
func (m Modal) Validate() error
Options
Options configure a Client (and NewREST).
type Options struct {
// BaseURL is the server's address, e.g. https://talk.example.org.
BaseURL string
// Token is the bot token (mnb_...).
Token string
// Intents are the event classes the gateway session asks for.
Intents Intents
// Presence is the status and activity to identify with (optional).
Presence *Presence
// Logger receives the SDK's logs; nil means slog.Default().
Logger *slog.Logger
// HTTPClient sends the REST requests; nil means a client with a 60 s
// timeout that does not follow redirects (a redirect fails the call with
// a *RESTError). A client passed here keeps its own redirect policy.
HTTPClient *http.Client
// MaxRetries bounds how often a request answered with 429 is sent again
// (0 means 3, a negative value none).
MaxRetries int
// GatewayURL overrides the address GET /gateway answers (optional).
GatewayURL string
// HandlerConcurrency bounds how many dispatches are handled at once
// (0 means 64).
HandlerConcurrency int
}
OptionType
OptionType is the type of a command option.
type OptionType int
Permission
Permission is a permission bit of Mnema Talk's permission catalogue (GET /api/permissions).
Mnema's permission bits have their own values: bit constants from other chat libraries do not match them. Use these constants, compute bits from the catalogue or pass permission keys.
type Permission uint64
Permission.Has
Has reports whether the permission set contains the given permission bit.
func (p Permission) Has(other Permission) bool
Permission.String
String returns the decimal bitfield string of the permission.
func (p Permission) String() string
Presence
Presence is the bot's status and optional activity.
type Presence struct {
// Status is online, idle, dnd or invisible (offline is an alias of
// invisible).
Status string
Activity *Activity
}
Presence.Validate
Validate checks the status and the activity type.
func (p Presence) Validate() error
Reaction
Reaction is the summary of one emoji on a message.
type Reaction struct {
Emoji string `json:"emoji"`
Count int `json:"count"`
Users []string `json:"users"`
}
ReactionsUpdate
ReactionsUpdate is the MESSAGE_REACTIONS_UPDATE dispatch: the new summary.
type ReactionsUpdate struct {
MessageID string `json:"message_id"`
ChannelID string `json:"channel_id"`
Reactions []Reaction `json:"reactions"`
}
Ready
Ready is the READY dispatch: the session started.
type Ready struct {
V int `json:"v"`
User Self `json:"user"`
SessionID string `json:"session_id"`
Intents Intents `json:"intents"`
ResumeGatewayURL string `json:"resume_gateway_url"`
HeartbeatInterval int `json:"heartbeat_interval"`
}
Resolved
Resolved holds what user, role and channel selects picked, keyed by id.
type Resolved struct {
Users map[string]User `json:"users,omitempty"`
Roles map[string]ResolvedRole `json:"roles,omitempty"`
Channels map[string]ResolvedChannel `json:"channels,omitempty"`
}
ResolvedChannel
ResolvedChannel is a channel picked in a channel select.
type ResolvedChannel struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
}
ResolvedRole
ResolvedRole is a role picked in a role select.
type ResolvedRole struct {
ID string `json:"id"`
Name string `json:"name"`
Color int `json:"color"`
}
Response
Response is a message sent in answer to an interaction (Reply, FollowUp).
type Response struct {
Content string
Embeds []Embed
Components []Component
// Ephemeral shows the response to the member only (flags 64).
Ephemeral bool
// AllowedMentions narrows whom the message notifies, as on a post; nil
// notifies the members it names, never @all, @here or a role.
AllowedMentions *AllowedMentions
}
REST
REST is the client of the bot REST API. It keeps within the server's rate limits (50 requests per second, 5 messages per 5 seconds per channel), waits out 429 answers (retry_after, Retry-After) with bounded retries, and stops waiting when the context ends. It is safe for concurrent use.
type REST struct {
}
REST.AddReaction
AddReaction reacts to a message with a Unicode emoji or a custom emoji token (<:name:id>).
func (r *REST) AddReaction(ctx context.Context, channelID, messageID, emoji string) error
REST.Channels
Channels returns the channels the bot can view, with their categories.
func (r *REST) Channels(ctx context.Context) (*ChannelHierarchy, error)
REST.Commands
Commands lists the bot's commands.
func (r *REST) Commands(ctx context.Context) ([]Command, error)
REST.CreateCommand
CreateCommand adds a command, or updates the one of the same name.
func (r *REST) CreateCommand(ctx context.Context, cmd CommandInput) (*Command, error)
REST.CreateMessage
CreateMessage posts a message. Components are validated first.
func (r *REST) CreateMessage(ctx context.Context, channelID string, m MessageCreate) (*Message, error)
REST.DeleteCommand
DeleteCommand removes a command.
func (r *REST) DeleteCommand(ctx context.Context, commandID string) error
REST.DeleteMessage
DeleteMessage deletes a message (the bot's own, or others' with Manage messages).
func (r *REST) DeleteMessage(ctx context.Context, channelID, messageID string) error
REST.DownloadAttachment
DownloadAttachment streams the attachment with this id (GET /media/{id}, doc/bots.md "Downloading attachments"). The server answers 404 for a file the bot cannot view, which gives an error matching ErrNotFound. Redirects are not followed, a 429 is waited out like any request, and opts bound the size and the time.
func (r *REST) DownloadAttachment(ctx context.Context, id string, opts DownloadOptions) (*DownloadedAttachment, error)
REST.EditMessage
EditMessage changes one of the bot's own messages.
func (r *REST) EditMessage(ctx context.Context, channelID, messageID string, e MessageEdit) (*Message, error)
REST.Gateway
Gateway returns the gateway's address.
func (r *REST) Gateway(ctx context.Context) (*GatewayInfo, error)
REST.Me
Me returns the bot account.
func (r *REST) Me(ctx context.Context) (*Self, error)
REST.Member
Member returns one member.
func (r *REST) Member(ctx context.Context, userID string) (*Member, error)
REST.Members
Members lists the members who share a channel with the bot (needs the GUILD_MEMBERS intent allowed).
func (r *REST) Members(ctx context.Context) ([]Member, error)
REST.Message
Message returns one message.
func (r *REST) Message(ctx context.Context, channelID, messageID string) (*Message, error)
REST.Messages
Messages returns a page of a channel's messages.
func (r *REST) Messages(ctx context.Context, channelID string, q MessageQuery) ([]Message, error)
REST.RemoveReaction
RemoveReaction takes the bot's reaction back.
func (r *REST) RemoveReaction(ctx context.Context, channelID, messageID, emoji string) error
REST.SetCommands
SetCommands replaces all of the bot's commands (a bulk overwrite).
func (r *REST) SetCommands(ctx context.Context, cmds []CommandInput) ([]Command, error)
REST.Upload
Upload posts a file, with an optional caption.
func (r *REST) Upload(ctx context.Context, channelID string, u Upload) (*Message, error)
RESTError
RESTError is a non-2xx answer of the REST API ({message, code}). A 429 that persisted beyond the retries also carries RetryAfter and Global.
type RESTError struct {
// Status is the HTTP status.
Status int
// Code is the JSON error code (0 for plain HTTP errors).
Code int
// Message is the server's text.
Message string
// RetryAfter is how long the server asked to wait (429 only).
RetryAfter time.Duration
// Global reports that the bot's overall limit was hit (429 only).
Global bool
}
RESTError.Error
func (e *RESTError) Error() string
RESTError.Is
Is makes errors.Is(err, ErrNotFound) true for a 404.
func (e *RESTError) Is(target error) bool
RoleSelect
RoleSelect is a select menu of roles (not @everyone, not the managed bot roles).
type RoleSelect selectMenu
RoleSelect.Component
Component returns the select's JSON form.
func (s RoleSelect) Component() Component { return selectMenu(s).component(ComponentRoleSelect) }
RoleSelect.Validate
Validate checks the select against the server's limits.
func (s RoleSelect) Validate() error { return s.Component().Validate() }
SelectOption
SelectOption is one choice of a string select.
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,omitempty"`
}
Self
Self is the bot account, the answer of GET /users/@me.
type Self struct {
ID string `json:"id"`
BotID string `json:"bot_id"`
// Username is the bot's name as members see it (its display name).
Username string `json:"username"`
// Handle is the account's unique name, the one members mention
// (for example @mnemo). Servers before 3.1 do
// not send it (empty): recognise a mention of the bot by its ID in
// Message.Mentions instead.
Handle string `json:"handle,omitempty"`
Bot bool `json:"bot"`
AvatarURL string `json:"avatar_url,omitempty"`
AllowedIntents Intents `json:"allowed_intents"`
}
StringSelect
StringSelect is a select menu of fixed options. MinValues and MaxValues default to 1 when nil.
type StringSelect struct {
CustomID string
Placeholder string
Options []SelectOption
MinValues *int
MaxValues *int
Disabled bool
}
StringSelect.Component
Component returns the select's JSON form.
func (s StringSelect) Component() Component
StringSelect.Validate
Validate checks the select against the server's limits.
func (s StringSelect) Validate() error { return s.Component().Validate() }
TextInput
TextInput is a text field of a modal. Required defaults to true when nil. A zero Style means short.
type TextInput struct {
CustomID string
Label string
Style TextInputStyle
MinLength *int
MaxLength *int
Required *bool
Value string
Placeholder string
}
TextInput.Component
Component returns the text input's JSON form.
func (t TextInput) Component() Component
TextInput.Validate
Validate checks the text input against the server's limits.
func (t TextInput) Validate() error { return t.Component().Validate() }
TextInputStyle
TextInputStyle is the style of a modal's text input.
type TextInputStyle int
Upload
Upload is a file to post. Reader is read completely before the request (so a rate-limited upload can be sent again). Content is an optional caption.
type Upload struct {
Name string
Reader io.Reader
Content string
AllowedMentions *AllowedMentions
ParentID string
ReplyToID string
}
User
User is a member as events and interactions show them.
type User struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
AvatarURL string `json:"avatar_url,omitempty"`
Bot bool `json:"bot,omitempty"`
}
UserSelect
UserSelect is a select menu of members.
type UserSelect selectMenu
UserSelect.Component
Component returns the select's JSON form.
func (s UserSelect) Component() Component { return selectMenu(s).component(ComponentUserSelect) }
UserSelect.Validate
Validate checks the select against the server's limits.
func (s UserSelect) Validate() error { return s.Component().Validate() }
Constants and variables
The component types the server offers.
const (
ComponentActionRow ComponentType = 1
ComponentButton ComponentType = 2
ComponentStringSelect ComponentType = 3
ComponentTextInput ComponentType = 4
ComponentUserSelect ComponentType = 5
ComponentRoleSelect ComponentType = 6
ComponentChannelSelect ComponentType = 8
)
The button styles; ButtonLink carries a URL instead of a custom ID.
const (
ButtonPrimary ButtonStyle = 1
ButtonSecondary ButtonStyle = 2
ButtonSuccess ButtonStyle = 3
ButtonDanger ButtonStyle = 4
ButtonLink ButtonStyle = 5
)
The text input styles.
const (
TextInputShort TextInputStyle = 1
TextInputParagraph TextInputStyle = 2
)
Limits of components and modals (doc/bots.md, Message components, Modals).
const (
MaxActionRows = 5
MaxComponents = 25
MaxButtonsPerRow = 5
MaxCustomIDLength = 100
MaxButtonLabelLength = 80
MaxSelectOptions = 25
MaxOptionTextLength = 100
MaxPlaceholderLength = 150
MaxSelectValues = 25
MaxModalTitleLength = 45
MaxModalRows = 5
MaxInputLabelLength = 45
MaxInputTextLength = 4000
MaxInputPlaceholder = 100
)
ErrInvalidComponent is wrapped by every validation error of components and modals.
var ErrInvalidComponent = errors.New("mnema: invalid component")
JSON error codes the bot API answers (doc/bots.md, REST API).
const (
CodeUnknownChannel = 10003
CodeUnknownMessage = 10008
CodeUnknownUser = 10013
CodeUnknownInteraction = 10062
CodeMissingPermissions = 50013
CodeEmptyMessage = 50006
CodeInvalidFormBody = 50035
CodeTooLarge = 40005
)
Close codes of the bot gateway (doc/bots.md, Close codes).
const (
CloseSessionTakenOver = 4000
CloseUnknownOpcode = 4001
CloseDecodeError = 4002
CloseNotAuthenticated = 4003
CloseAuthFailed = 4004
CloseAlreadyIdentified = 4005
CloseRateLimited = 4008
CloseSessionTimedOut = 4009
CloseInvalidIntents = 4013
CloseDisallowedIntents = 4014
closeHeartbeatNotAcked = 4900
closeCodeFrameTooLarge = 1009
closeCodeReadsTooSlowly = 1013
)
ErrAlreadyRunning is returned by Run while another Run of the same client is active.
var ErrAlreadyRunning = errors.New("mnema: the client is already running")
ErrFrameTooLarge is returned for an outgoing gateway frame above 4096 bytes.
var ErrFrameTooLarge = errors.New("mnema: gateway frame larger than 4096 bytes")
MaxGatewayFrame is the largest frame the client reads from the gateway.
const MaxGatewayFrame = 4 << 20
The interaction types.
const (
InteractionCommand InteractionType = 2
InteractionComponent InteractionType = 3
InteractionModalSubmit InteractionType = 5
)
FlagEphemeral shows a response to the member who caused the interaction only; it is never stored.
const FlagEphemeral = 64
ErrAlreadyAnswered is returned when an interaction gets a second first answer; use EditReply or FollowUp instead.
var ErrAlreadyAnswered = errors.New("mnema: this interaction was already answered; use EditReply or FollowUp")
ErrNotFromComponent is returned by Update and DeferUpdate on an interaction that did not come from a component.
var ErrNotFromComponent = errors.New("mnema: only for a component interaction or a modal submit opened from one")
ErrInvalidManifest is wrapped by every manifest validation error.
var ErrInvalidManifest = errors.New("mnema: invalid manifest")
const (
// PermissionAdministrator grants every permission below (Owner powers stay
// with the Owner) and ignores channel overwrites.
PermissionAdministrator Permission = 1 << iota
// PermissionViewChannel lets a member see a channel (or Talk) and read its history.
PermissionViewChannel
PermissionSendMessages
PermissionAttachFiles
PermissionAddReactions
PermissionManageMessages
PermissionMentionEveryone
PermissionConnect
PermissionSpeak
PermissionVideo
PermissionDisconnectMembers
PermissionManageChannels
PermissionManageRoles
PermissionCreateInvites
PermissionManageWebhooks
PermissionManageMembers
PermissionManageBots
PermissionViewAuditLog Permission = 1 << 17
PermissionTimeoutMembers Permission = 1 << 18
PermissionBanMembers Permission = 1 << 19
PermissionManageEmoji Permission = 1 << 20
PermissionManageReports Permission = 1 << 21
PermissionSendDirectMessages Permission = 1 << 22
PermissionKickMembers Permission = 1 << 23
PermissionManageStage Permission = 1 << 24
PermissionManageEvents Permission = 1 << 25
PermissionBypassNewMemberLimits Permission = 1 << 26
PermissionEditWiki Permission = 1 << 27
PermissionManageWiki Permission = 1 << 28
PermissionViewWiki Permission = 1 << 29
PermissionCreateMemberInvites Permission = 1 << 30
)
The activity types the server accepts (streaming, 1, is refused).
const (
ActivityPlaying ActivityType = 0
ActivityListening ActivityType = 2
ActivityWatching ActivityType = 3
ActivityCustom ActivityType = 4
ActivityCompeting ActivityType = 5
)
The statuses of a bot.
const (
StatusOnline = "online"
StatusIdle = "idle"
StatusDND = "dnd"
StatusInvisible = "invisible"
)
BasePath is the path of the bot REST API.
const BasePath = "/api/bot/v1"
MaxRetryAfter is the longest 429 wait the client takes on its own.
const MaxRetryAfter = 60 * time.Second
ErrNotFound matches (with errors.Is) a REST answer of 404: an unknown or inaccessible attachment, message, channel or member.
var ErrNotFound = errors.New("mnema: not found")
The option types.
const (
OptionString OptionType = 3
OptionInteger OptionType = 4
OptionBoolean OptionType = 5
OptionUser OptionType = 6
OptionChannel OptionType = 7
)
The intents the gateway knows.
const (
IntentGuilds Intents = 1 << 0
IntentGuildMembers Intents = 1 << 1
IntentGuildMessages Intents = 1 << 9
IntentGuildMessageReactions Intents = 1 << 10
)
Version returns the SDK's module version as the Go toolchain recorded it (a tag such as v0.1.0 or a pseudo-version), or "devel" when it is unknown, for example in a build from a work tree.
var Version = sync.OnceValue(func() string {