=============== LIBRARY RULES =============== From library maintainers: - Always create a client with: bot := client.New(token, client.WithIntents(intents)) - You MUST declare gateway intents via client.WithIntents() before calling bot.Connect() - Always defer bot.Close() after a successful bot.Connect() - For interaction responses use bot.RespondWithMessage(), NOT bot.SendMessage() - bot.SendMessage() is for channel messages only, NOT for replying to interactions - For deferred responses call bot.DeferInteraction() then bot.UpdateInteractionMessage() - Snowflake IDs are constructed with types.Snowflake(uint64), not strings - Components V2 messages require the IsComponentsV2 flag via bot.SendMessageWithComponents() - MessageContent intent is PRIVILEGED — must be enabled in Discord Developer Portal for message content access in guilds with 100+ members - Use client.NewComponentBuilder() fluent API for building component layouts, call .Build() at the end - Select menus MUST be the only component in their ActionRow - Modals support max 5 top-level components (Labels wrapping inputs) - All REST and client methods require a context.Context as first argument - Rate limiting is handled automatically — do NOT implement your own rate limit logic ### Install Gophord Source: https://github.com/mvkweb/gophord/blob/main/docs/getting-started.md Installs the Gophord library using the Go module system. This is the first step to using Gophord in your project. ```bash go get github.com/Mvkweb/gophord ``` -------------------------------- ### Minimal Discord Bot Example in Go Source: https://github.com/mvkweb/gophord/blob/main/docs/getting-started.md A Go program demonstrating a minimal Discord bot using Gophord. It configures intents, registers event handlers for 'ready' and 'message create' events, connects to Discord, and gracefully shuts down on interrupt. Requires the DISCORD_BOT_TOKEN environment variable. ```go package main import ( "context" "log" "os" "os/signal" "github.com/Mvkweb/gophord/pkg/client" "github.com/Mvkweb/gophord/pkg/gateway" "github.com/Mvkweb/gophord/pkg/types" ) func main() { token := os.Getenv("DISCORD_BOT_TOKEN") if token == "" { log.Fatal("DISCORD_BOT_TOKEN is required") } // 1. Create client with intents // To read message content in a guild, the IntentMessageContent flag is required. bot := client.New(token, client.WithIntents(types.IntentGuilds|types.IntentGuildMessages|types.IntentMessageContent), client.WithMobileStatus(true), // Appear as mobile client ) // 2. Register event handlers bot.OnReady(func(event *gateway.ReadyEvent) { log.Printf("Logged in as %s#%s", event.User.Username, event.User.Discriminator) }) bot.OnMessageCreate(func(event *gateway.MessageCreateEvent) { // Ignore messages from other bots if event.Author.Bot { return } if event.Content == "!ping" { // bot.SendMessage is for sending normal channel messages. // If replying to an Interaction, use bot.RespondWithMessage instead. bot.SendMessage(context.Background(), event.ChannelID, "Pong!") } }) // 3. Connect to Discord ctx, cancel := context.WithCancel(context.Background()) defer cancel() if err := bot.Connect(ctx); err != nil { log.Fatal(err) } // 4. Wait for interrupt stop := make(chan os.Signal, 1) signal.Notify(stop, os.Interrupt) <-stop // 5. Clean up connection bot.Close() } ``` -------------------------------- ### Create and Connect Gophord Client (Go) Source: https://github.com/mvkweb/gophord/blob/main/docs/session.md Demonstrates the basic usage of creating a Gophord client with specified intents and options, connecting to Discord, and deferring the closure of the connection. It highlights the primary entry point for bot interactions. ```go package main import ( "context" "log" "github.com/Mvkweb/gophord/pkg/client" "github.com/Mvkweb/gophord/pkg/types" ) func main() { token := "YOUR_BOT_TOKEN_HERE" ctx := context.Background() // Create the client bot := client.New(token, client.WithIntents(types.IntentsDefault | types.IntentMessageContent), client.WithMobileStatus(false), ) // Register handlers before connecting // bot.OnReady(...) // Connect to Discord if err := bot.Connect(ctx); err != nil { log.Fatalf("Failed to connect: %v", err) } // Always defer closing the connection defer bot.Close() // Access underlying REST client directly if needed: // user, err := bot.REST.GetCurrentUser(ctx) } ``` -------------------------------- ### Initialize and consume raw gateway events in Go Source: https://github.com/mvkweb/gophord/blob/main/docs/gateway.md Demonstrates how to instantiate a gateway client, establish a connection, and process incoming events and errors using Go channels. This approach requires manual parsing of raw event payloads into specific event structures. ```go package main import ( "context" "log" "github.com/Mvkweb/gophord/pkg/gateway" "github.com/Mvkweb/gophord/pkg/types" ) func runGateway(token string) { gw := gateway.New(token, gateway.WithIntents(types.IntentsDefault), gateway.WithMobileStatus(false), ) if err := gw.Connect(context.Background()); err != nil { log.Fatal(err) } defer gw.Close() for { select { case event := <-gw.Events(): parsed, err := gateway.ParseEvent(event.Type, event.Data) if err != nil { log.Printf("Parse error: %v", err) continue } switch e := parsed.(type) { case *gateway.ReadyEvent: log.Printf("Ready! Session: %s", e.SessionID) case *gateway.MessageCreateEvent: log.Printf("Message from %s: %s", e.Author.Username, e.Content) } case err := <-gw.Errors(): log.Printf("Gateway error: %v", err) } } } ``` -------------------------------- ### Create and display a modal form in Go Source: https://github.com/mvkweb/gophord/blob/main/docs/modals.md Demonstrates using the ComponentBuilder to construct a modal with text inputs and select menus, then triggering it via the bot client. ```go func showFeedbackModal(ctx context.Context, bot *client.Client, interaction *types.Interaction) { components := client.NewComponentBuilder(). AddLabel(client.NewLabel("Your Name", "Enter your name", client.NewTextInput("name_input", "", 1, client.WithRequired(true), client.WithPlaceholder("John Doe"), ), )). AddLabel(client.NewLabel("Feedback", "Share your thoughts", client.NewTextInput("feedback_input", "", 2, client.WithPlaceholder("Tell us what you think..."), client.WithMinLength(10), client.WithMaxLength(500), ), )). AddLabel(client.NewLabel("Rating", "How would you rate us?", client.NewStringSelect("rating_select", types.SelectOption{Label: "⭐⭐⭐⭐⭐ Excellent", Value: "5"}, types.SelectOption{Label: "⭐ Terrible", Value: "1"}, ), )). Build() err := bot.ShowModal(ctx, interaction, "Feedback Form", "feedback_modal", components) if err != nil { log.Printf("Failed to show modal: %v", err) } } ``` -------------------------------- ### Gateway Client Instantiation and Lifecycle Source: https://github.com/mvkweb/gophord/blob/main/docs/gateway.md Details on how to create, configure, connect, and close a raw gateway client. ```APIDOC ## Gateway Client Instantiation & Lifecycle ### Description This section covers the core methods for managing the gateway client's lifecycle, including creation, configuration, connection, and disconnection. ### Methods #### `New` - **Method**: `New` - **Signature**: `func New(token string, opts ...ClientOption) *Client` - **Description**: Creates a new gateway client instance. #### `WithIntents` - **Method**: `WithIntents` - **Signature**: `func WithIntents(intents types.IntentFlags) ClientOption` - **Description**: Configures the event intents for the gateway connection. #### `WithMobileStatus` - **Method**: `WithMobileStatus` - **Signature**: `func WithMobileStatus(enabled bool) ClientOption` - **Description**: Enables or disables mimicking Discord Android for a phone status icon. #### `Connect` - **Method**: `Connect` - **Signature**: `func (c *Client) Connect(ctx context.Context) error` - **Description**: Establishes the WebSocket connection to Discord. #### `Close` - **Method**: `Close` - **Signature**: `func (c *Client) Close() error` - **Description**: Closes the WebSocket connection gracefully. ``` -------------------------------- ### Constructing Button Components with ComponentBuilder Source: https://github.com/mvkweb/gophord/blob/main/docs/buttons.md Demonstrates how to use the client.ComponentBuilder to create complex button layouts. It shows the implementation of various button styles and the use of ActionRows to group components. ```go func sendButtonsDemo(ctx context.Context, bot *client.Client, channelID types.Snowflake) { components := client.NewComponentBuilder(). AddTextDisplay("# Button Styles Demo"). AddSeparator(true, types.SeparatorSpacingSmall). AddActionRow( client.NewPrimaryButton("btn_primary", "Primary"), client.NewSecondaryButton("btn_secondary", "Secondary"), client.NewSuccessButton("btn_success", "Success"), client.NewDangerButton("btn_danger", "Danger"), ). AddActionRow( client.NewLinkButton("https://github.com/Mvkweb/gophord", "GitHub"), &types.Button{ Style: types.ButtonStylePrimary, CustomID: "btn_emoji", Label: "With Emoji", Emoji: &types.PartialEmoji{Name: "🚀"}, }, &types.Button{ Style: types.ButtonStyleSecondary, CustomID: "btn_disabled", Label: "Disabled", Disabled: true, }, ). Build() _, err := bot.SendMessageWithComponents(ctx, channelID, components) if err != nil { log.Printf("Failed to send buttons: %v", err) } } ``` -------------------------------- ### Create and Send Discord Select Menus (Go) Source: https://github.com/mvkweb/gophord/blob/main/docs/select-menus.md Demonstrates how to create and send different types of select menus (String, User, Channel) within an ActionRow using Gophord's ComponentBuilder. It shows how to configure placeholders and channel types for ChannelSelect. ```go package main import ( "context" "log" "github.com/Mvkweb/gophord/pkg/client" "github.com/Mvkweb/gophord/pkg/types" ) func sendSelectsDemo(ctx context.Context, bot *client.Client, channelID types.Snowflake) { components := client.NewComponentBuilder(). // 1. String Select - Custom options AddActionRow(&types.StringSelect{ CustomID: "language_select", Placeholder: "Choose your favorite language", Options: []types.SelectOption{ {Label: "Go", Value: "go", Description: "Simple and efficient", Emoji: &types.PartialEmoji{Name: "🐹"}}, {Label: "Rust", Value: "rust", Description: "Memory safety", Emoji: &types.PartialEmoji{Name: "🦀"}}, }, }). // 2. User Select - Auto-populated with server members AddActionRow(&types.UserSelect{ CustomID: "user_select", Placeholder: "Select a user", }). // 3. Channel Select - Filtered to text channels only AddActionRow(&types.ChannelSelect{ CustomID: "channel_select", Placeholder: "Select a text channel", ChannelTypes: []types.ChannelType{types.ChannelTypeGuildText}, }). Build() _, err := bot.SendMessageWithComponents(ctx, channelID, components) if err != nil { log.Printf("Failed to send selects: %v", err) } } ``` -------------------------------- ### Create Section Components with Gophord Source: https://github.com/mvkweb/gophord/blob/main/docs/sections.md Demonstrates how to instantiate types.Section to create layouts with text and accessories. It covers both static thumbnail displays and interactive button components using the Gophord client. ```go package main import ( "context" "log" "github.com/Mvkweb/gophord/pkg/client" "github.com/Mvkweb/gophord/pkg/types" ) func sendSectionDemo(ctx context.Context, bot *client.Client, channelID types.Snowflake) { // Scenario A: A Product-style section with an image thumbnail productSection := &types.Section{ Components: []types.Component{ &types.TextDisplay{ Content: "**Gophord Pro** 🚀\nHigh-performance Discord API wrapper\n• Blazing fast JSON parsing\n• Native Components V2", }, }, Accessory: &types.Thumbnail{ Media: types.UnfurledMediaItem{URL: "https://picsum.photos/80/80?random=2"}, }, } // Scenario B: An interactive row with an action button buttonSection := &types.Section{ Components: []types.Component{ &types.TextDisplay{Content: "**With Button**\nThis section has an action button on the right."}, }, Accessory: &types.Button{ Style: types.ButtonStylePrimary, CustomID: "section_action", Label: "Action", }, } _, err := bot.SendMessageWithComponents(ctx, channelID, []types.Component{productSection, buttonSection}) if err != nil { log.Printf("Failed to send sections: %v", err) } } ``` -------------------------------- ### Implement a Container component in Go Source: https://github.com/mvkweb/gophord/blob/main/docs/containers.md Demonstrates how to instantiate a Container struct with an accent color and nested components. It uses the Gophord client to send the containerized message to a specified channel. ```go package main import ( "context" "log" "github.com/Mvkweb/gophord/pkg/client" "github.com/Mvkweb/gophord/pkg/types" ) func sendContainerDemo(ctx context.Context, bot *client.Client, channelID types.Snowflake) { // 1. Define an accent color (integer hex) successColor := 0x57F287 // Green // 2. Create the container container := &types.Container{ AccentColor: &successColor, Components: types.ComponentList{ &types.TextDisplay{Content: "✅ **Success!**\nOperation completed successfully!"}, &types.ActionRow{ Components: types.ComponentList{ client.NewPrimaryButton("container_confirm", "Okay"), }, }, }, } // 3. Send _, err := bot.SendMessageWithComponents(ctx, channelID, types.ComponentList{container}) if err != nil { log.Printf("Failed to send container: %v", err) } } ``` -------------------------------- ### Send Media Gallery with Go Source: https://github.com/mvkweb/gophord/blob/main/docs/media-galleries.md Demonstrates how to send a media gallery with multiple image items to a Discord channel using the Gophord client. Requires the 'context', 'log', and specific Gophord packages. It takes a context, a client instance, and a channel ID as input, and outputs a log message indicating success or failure. ```go package main import ( "context" "log" "github.com/Mvkweb/gophord/pkg/client" "github.com/Mvkweb/gophord/pkg/types" ) func sendGalleryDemo(ctx context.Context, bot *client.Client, channelID types.Snowflake) { // Add media gallery with multiple items gallery := &types.MediaGallery{ Items: []types.MediaGalleryItem{ { Media: types.UnfurledMediaItem{URL: "https://picsum.photos/400/300?random=1"}, Description: "Random landscape image 1", }, { Media: types.UnfurledMediaItem{URL: "https://picsum.photos/400/300?random=2"}, Description: "Random landscape image 2", }, { Media: types.UnfurledMediaItem{URL: "https://picsum.photos/400/300?random=3"}, Description: "Random landscape image 3", }, }, } _, err := bot.SendMessageWithComponents(ctx, channelID, types.ComponentList{gallery}) if err != nil { log.Printf("Failed to send gallery: %v", err) } } ``` -------------------------------- ### Handle Discord Select Menu Interactions (Go) Source: https://github.com/mvkweb/gophord/blob/main/docs/select-menus.md Illustrates how to process `MessageComponent` interactions triggered by user selections in a select menu. It shows how to identify the `CustomID` and access the selected `Values` from the interaction data. ```go func handleSelectInteraction(ctx context.Context, bot *client.Client, interaction *types.Interaction) { customID := interaction.Data.CustomID // Values is a []string. Even for user/role selects, it contains Snowflake IDs as strings. values := interaction.Data.Values switch customID { case "language_select": // Handle string choices bot.RespondWithMessage(ctx, interaction, "You chose: " + values[0]) case "user_select": // Handle user pick bot.RespondWithMessage(ctx, interaction, "You pinged <@!" + values[0] + ">") } } ``` -------------------------------- ### Register Typed Event Handlers in Go Source: https://github.com/mvkweb/gophord/blob/main/docs/events.md Demonstrates registering typed handlers for Discord gateway events like Ready, MessageCreate, and InteractionCreate using the high-level client.Client. This approach simplifies event handling by providing pre-defined functions for common events. It requires importing the client and gateway packages. ```go package main import ( "log" "github.com/Mvkweb/gophord/pkg/client" "github.com/Mvkweb/gophord/pkg/gateway" ) func registerHandlers(bot *client.Client) { // Fired when the bot initially connects and is ready bot.OnReady(func(event *gateway.ReadyEvent) { log.Printf("Ready! Session ID: %s", event.SessionID) }) // Fired when a message is created in a text channel bot.OnMessageCreate(func(event *gateway.MessageCreateEvent) { log.Printf("New message from %s: %s", event.Author.Username, event.Content) }) // Fired when an interaction (slash command, button, modal) is triggered bot.OnInteractionCreate(func(event *gateway.InteractionCreateEvent) { log.Printf("Interaction received of type %d", event.Type) }) // Fired for any event (useful for generic logic or unimplemented events) bot.On(gateway.EventGuildMemberAdd, func(data interface{}) { log.Printf("Raw event data: %v", data) }) } ``` -------------------------------- ### Configure Discord Bot Intents with Gophord Source: https://github.com/mvkweb/gophord/blob/main/docs/intents.md Demonstrates how to create a Gophord client with various intent configurations. It shows using default intents, custom combinations with bitwise OR, all non-privileged intents, and including privileged intents. Requires the Gophord client and types packages. ```go package main import ( "github.com/Mvkweb/gophord/pkg/client" "github.com/Mvkweb/gophord/pkg/types" ) func createBotWithIntents(token string) *client.Client { // 1. Sensible defaults (guilds, guild messages, reactions, DMs) bot := client.New(token, client.WithIntents(types.IntentsDefault)) // 2. Custom combination using bitwise OR (|) customIntents := types.IntentGuilds | types.IntentGuildMessages | types.IntentGuildMessageReactions | types.IntentMessageContent // NOTE: Privileged! botWithCustom := client.New(token, client.WithIntents(customIntents)) // 3. All non-privileged intents botAll := client.New(token, client.WithIntents(types.IntentsAll)) // 4. Including privileged intents botPrivileged := client.New(token, client.WithIntents(types.IntentsAll|types.IntentsPrivileged)) return botPrivileged } ``` -------------------------------- ### Customize Gophord Client Options (Go) Source: https://github.com/mvkweb/gophord/blob/main/docs/session.md Illustrates how to customize the Gophord client during creation using functional options. It specifically shows how to set required intents for receiving events and how to enable or disable the mobile status indicator. ```go bot := client.New(token, // It's required to pass intents to receive events client.WithIntents(types.IntentGuilds | types.IntentGuildMessages), // Setting to true shows a mobile phone icon next to the bot's status client.WithMobileStatus(true), ) ``` -------------------------------- ### Handle Slash Commands with Gophord Source: https://github.com/mvkweb/gophord/blob/main/docs/interactions.md Demonstrates how to register an interaction listener and switch between different slash command types using the Gophord client. It extracts command data and provides responses using helper methods. ```go package main import ( "log" "github.com/Mvkweb/gophord/pkg/client" "github.com/Mvkweb/gophord/pkg/gateway" "github.com/Mvkweb/gophord/pkg/types" ) func handleInteractions(bot *client.Client) { bot.OnInteractionCreate(func(e *gateway.InteractionCreateEvent) { i := e.Interaction if i.Type == types.InteractionTypeApplicationCommand { data := i.Data switch data.Name { case "ping": err := bot.RespondWithMessage(i.ID, i.Token, "Pong!") if err != nil { log.Printf("Error responding: %v", err) } case "echo": var echoText string if data.Options != nil && len(data.Options) > 0 { echoText = data.Options[0].Value.(string) } bot.RespondWithMessage(i.ID, i.Token, "Echo: "+echoText) } } }) } ``` -------------------------------- ### Register Guild Application Commands in Go Source: https://github.com/mvkweb/gophord/blob/main/docs/commands.md This Go code snippet demonstrates how to register application commands for a specific guild using the Gophord library's REST client. It defines command structures, including options, and uses `BulkOverwriteGuildApplicationCommands` for instant updates within a guild. Ensure you have a valid REST client and application/guild IDs. ```go package main import ( "log" "github.com/Mvkweb/gophord/pkg/rest" "github.com/Mvkweb/gophord/pkg/types" ) func registerCommands(restClient *rest.Client, appID, guildID string) { cmdType := types.ApplicationCommandTypeChatInput commands := []types.CreateApplicationCommandParams{ { Name: "ping", Description: "Responds with pong!", Type: &cmdType, }, { Name: "echo", Description: "Echoes your text", Type: &cmdType, Options: []types.ApplicationCommandOption{ { Type: types.ApplicationCommandOptionTypeString, Name: "text", Description: "The text to echo", Required: true, }, }, }, } // Bulk overwrite commands for a specific guild (instant update) // For global commands, pass an empty string "" for the guildID (takes up to an hour to propagate) registered, err := restClient.BulkOverwriteGuildApplicationCommands(appID, guildID, commands) if err != nil { log.Fatalf("Failed to register commands: %v", err) } log.Printf("Successfully registered %d commands", len(registered)) } ``` -------------------------------- ### Access Gophord Sub-Clients (Go) Source: https://github.com/mvkweb/gophord/blob/main/docs/session.md Shows how to access the underlying REST and Gateway sub-clients directly from the main Gophord client instance. This is useful for performing specific REST API calls or direct Gateway operations when higher-level abstractions are not sufficient. ```go // Direct REST API access bot.REST.GetGuild(ctx, guildID) // Direct Gateway access bot.Gateway.UpdatePresence(&presenceUpdate) ``` -------------------------------- ### POST /components/media-gallery Source: https://github.com/mvkweb/gophord/blob/main/docs/media-galleries.md This endpoint or component structure allows the creation of a media gallery to display multiple images in a responsive grid layout within a message. ```APIDOC ## POST /components/media-gallery ### Description Sends a media gallery component to a specified channel, displaying multiple images in a responsive grid layout. ### Method POST ### Endpoint /channels/{channelID}/messages ### Parameters #### Request Body - **Items** (Array) - Required - A list of media items to be displayed in the grid. ### Request Example { "Items": [ { "Media": { "URL": "https://picsum.photos/400/300?random=1" }, "Description": "Random landscape image 1" }, { "Media": { "URL": "https://picsum.photos/400/300?random=2" }, "Description": "Random landscape image 2" } ] } ### Response #### Success Response (200) - **id** (Snowflake) - The ID of the sent message. #### Response Example { "id": "123456789012345678" } ``` -------------------------------- ### Handling Button Interaction Events Source: https://github.com/mvkweb/gophord/blob/main/docs/buttons.md Shows how to process incoming interaction events when a user clicks a button. It uses the CustomID to identify the specific button clicked and respond accordingly. ```go func handleButtonClick(ctx context.Context, bot *client.Client, interaction *types.Interaction) { customID := interaction.Data.CustomID switch customID { case "btn_primary": bot.RespondWithMessage(ctx, interaction, "You clicked the Primary button!") case "btn_danger": bot.RespondWithMessage(ctx, interaction, "Danger zone! ⚠️") } } ``` -------------------------------- ### POST /interactions/respond Source: https://github.com/mvkweb/gophord/blob/main/docs/interactions.md Methods for sending responses to interactions. Responses must be sent within 3 seconds of the interaction event. ```APIDOC ## [POST] /interactions/respond ### Description Sends a response to a specific interaction using the interaction ID and token. Supports text, embeds, components, and raw payloads. ### Parameters #### Path Parameters - **id** (Snowflake) - Required - The unique ID of the interaction. - **token** (string) - Required - The continuation token for the interaction. #### Request Body - **content** (string) - Optional - The message content to display. - **embeds** (array) - Optional - List of embed objects. - **components** (array) - Optional - List of UI components. ### Response #### Success Response (200) - **status** (string) - Confirmation of delivery. ### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Process Raw Gateway Events in Go Source: https://github.com/mvkweb/gophord/blob/main/docs/events.md Illustrates how to process raw gateway events directly from the gateway.Client. This involves listening to the Events() channel, parsing the raw JSON payload using gateway.ParseEvent, and then using a type switch to handle different event types. This method is useful for advanced control or handling events not covered by typed handlers. It requires importing the gateway package. ```go package main import ( "log" "github.com/Mvkweb/gophord/pkg/gateway" ) func processRawEvents(gw *gateway.Client) { for { select { case event := <-gw.Events(): // Parse the raw JSON payload into a typed struct parsed, err := gateway.ParseEvent(event.Type, event.Data) if err != nil { log.Printf("Failed to parse event %s: %v", event.Type, err) continue } // Type switch on the parsed event switch e := parsed.(type) { case *gateway.ReadyEvent: log.Printf("Connected as %s", e.User.Username) case *gateway.MessageCreateEvent: log.Printf("Message: %s", e.Content) } case err := <-gw.Errors(): log.Printf("Gateway error: %v", err) } } } ``` -------------------------------- ### Bulk Overwrite Guild Application Commands Source: https://github.com/mvkweb/gophord/blob/main/docs/commands.md This endpoint allows you to bulk overwrite all commands for a specific guild. This provides an instant update for commands within that guild. For global commands, an empty guildID can be used, but propagation may take up to an hour. ```APIDOC ## POST /applications/{application.id}/guilds/{guild.id}/commands ### Description Bulk overwrite all commands for a specific guild. This provides an instant update for commands within that guild. For global commands, an empty guildID can be used, but propagation may take up to an hour. ### Method POST ### Endpoint `/applications/{application.id}/guilds/{guild.id}/commands` ### Parameters #### Path Parameters - **application.id** (string) - Required - The ID of the application whose commands you want to manage. - **guild.id** (string) - Required - The ID of the guild where commands will be registered. #### Query Parameters None #### Request Body - **commands** (array of `types.CreateApplicationCommandParams`) - Required - An array of command objects to register. - **name** (string) - Required - Name of the command, 1-32 characters. - **description** (string) - Required - Description of the command, 1-100 characters. - **type** (`types.ApplicationCommandType`) - Optional - Type of the command. Defaults to `ApplicationCommandTypeChatInput`. - **options** (array of `types.ApplicationCommandOption`) - Optional - The parameters for the command. - **type** (`types.ApplicationCommandOptionType`) - Required - The type of option. - **name** (string) - Required - Name of the option, 1-32 characters. - **description** (string) - Required - Description of the option, 1-100 characters. - **required** (boolean) - Optional - Whether the option is required. ### Request Example ```json { "commands": [ { "name": "ping", "description": "Responds with pong!", "type": 1 }, { "name": "echo", "description": "Echoes your text", "type": 1, "options": [ { "type": 3, "name": "text", "description": "The text to echo", "required": true } ] } ] } ``` ### Response #### Success Response (200) - **registered_commands** (array of `types.ApplicationCommand`) - A list of the registered commands. - **id** (string) - The ID of the command. - **application_id** (string) - The ID of the application this command belongs to. - **guild_id** (string) - The ID of the guild this command belongs to (if not global). - **name** (string) - The name of the command. - **description** (string) - The description of the command. - **type** (`types.ApplicationCommandType`) - The type of the command. - **options** (array of `types.ApplicationCommandOption`) - The parameters for the command. #### Response Example ```json [ { "id": "123456789012345678", "application_id": "987654321098765432", "guild_id": "112233445566778899", "name": "ping", "description": "Responds with pong!", "type": 1, "options": [] }, { "id": "123456789012345679", "application_id": "987654321098765432", "guild_id": "112233445566778899", "name": "echo", "description": "Echoes your text", "type": 1, "options": [ { "type": 3, "name": "text", "description": "The text to echo", "required": true } ] } ] ``` ``` -------------------------------- ### Updating Presence Source: https://github.com/mvkweb/gophord/blob/main/docs/gateway.md How to update the bot's status and activity through the gateway. ```APIDOC ## Updating Presence ### Description This section details how to send presence updates to Discord via the gateway client, allowing you to change the bot's status and activity. ### Method #### `UpdatePresence` - **Method**: `UpdatePresence` - **Signature**: `func (c *Client) UpdatePresence(presence *PresenceUpdate) error` - **Description**: Sends a presence update payload to Discord. ### Request Body Example ```json { "status": "online", "activities": [ { "name": "with the Discord API", "type": 0 } ], "afk": false } ``` ### Parameter Details - **status** (string) - Required - The new status ('online', 'idle', 'dnd', 'invisible'). - **activities** (array of objects) - Optional - The activities the bot is engaged in. - **name** (string) - Required - The name of the activity. - **type** (integer) - Required - The type of activity (0: Playing, 1: Streaming, 2: Listening, 3: Watching, 5: Competing). - **afk** (boolean) - Required - Whether the bot is AFK. ``` -------------------------------- ### Handle modal submission events in Go Source: https://github.com/mvkweb/gophord/blob/main/docs/modals.md Shows how to intercept the InteractionTypeModalSubmit event, iterate through the submitted components, and extract values from TextInputs and StringSelects. ```go func handleModalSubmit(ctx context.Context, bot *client.Client, interaction *types.Interaction) { if interaction.Data.CustomID != "feedback_modal" { return } var results []string for _, comp := range interaction.Data.Components { if label, ok := comp.(*types.Label); ok { switch inner := label.Component.(type) { case *types.TextInput: results = append(results, fmt.Sprintf("**%s**: %s", inner.CustomID, inner.Value)) case *types.StringSelect: results = append(results, fmt.Sprintf("**%s**: %s", inner.CustomID, strings.Join(inner.Values, ", "))) } } } response := "## Form Submitted!\n" + strings.Join(results, "\n") bot.RespondWithEphemeral(ctx, interaction, response) } ``` -------------------------------- ### Update bot presence via gateway Source: https://github.com/mvkweb/gophord/blob/main/docs/gateway.md Shows how to update the bot's status and activity using the UpdatePresence method. This allows developers to set the bot's current activity type and status string directly through the active gateway connection. ```go func updatePresence(gw *gateway.Client) { gw.UpdatePresence(&gateway.PresenceUpdate{ Status: "online", Activities: []gateway.Activity{ { Name: "with the Discord API", Type: 0, }, }, AFK: false, }) } ``` -------------------------------- ### Send Raw Interaction Responses Source: https://github.com/mvkweb/gophord/blob/main/docs/interactions.md Shows how to use the RespondRaw method to send complex interaction responses, such as ephemeral messages, by manually constructing the InteractionResponse struct. ```go func sendEphemeralMessage(bot *client.Client, i *types.Interaction) { bot.RespondRaw(i.ID, i.Token, &types.InteractionResponse{ Type: types.InteractionCallbackTypeChannelMessageWithSource, Data: &types.InteractionCallbackData{ Content: "This message is only visible to you!", Flags: 64, // EPHEMERAL flag }, }) } ``` -------------------------------- ### Send Message with Buttons using Go Source: https://github.com/mvkweb/gophord/blob/main/docs/components-v2.md Demonstrates how to create and send a message containing interactive buttons within an Action Row using the Gophord library. It requires a `rest.Client` and a `channelID`. The function constructs two buttons and places them inside an Action Row, then sends the message. ```go package main import ( "log" "github.com/Mvkweb/gophord/pkg/rest" "github.com/Mvkweb/gophord/pkg/types" ) func sendComponentsMessage(restClient *rest.Client, channelID string) { button1 := &types.Button{ Style: types.ButtonStylePrimary, Label: "Accept", CustomID: "btn_accept", } button2 := &types.Button{ Style: types.ButtonStyleDanger, Label: "Decline", CustomID: "btn_decline", } row := &types.ActionRow{ Components: types.ComponentList{button1, button2}, } _, err := restClient.CreateMessage(channelID, rest.CreateMessageParams{ Content: "Do you accept the terms?", Components: types.ComponentList{row}, }) if err != nil { log.Fatalf("Error: %v", err) } } ``` -------------------------------- ### Send Discord Messages via REST API Source: https://github.com/mvkweb/gophord/blob/main/docs/messages.md Demonstrates how to use the rest.Client to send simple text messages, reply to existing messages, and send silent messages with mention suppression. It utilizes the CreateMessageParams struct to configure message content and behavior. ```go package main import ( "log" "github.com/Mvkweb/gophord/pkg/rest" "github.com/Mvkweb/gophord/pkg/types" ) func sendMessages(restClient *rest.Client, channelID string) { // 1. Simple text message msg, err := restClient.CreateMessage(channelID, rest.CreateMessageParams{ Content: "Hello, Discord!", }) if err != nil { log.Fatalf("Error: %v", err) } log.Printf("Sent message %s", msg.ID) // 2. Message replying to another message _, err = restClient.CreateMessage(channelID, rest.CreateMessageParams{ Content: "This is a reply", MessageReference: &types.MessageReference{ MessageID: msg.ID, ChannelID: types.Snowflake(channelID), FailIfNotExists: true, }, }) // 3. Message with mentions disabled (silent) _, err = restClient.CreateMessage(channelID, rest.CreateMessageParams{ Content: "Testing silent mentions @everyone", Flags: 4096, // MessageFlagSuppressNotifications AllowedMentions: &types.AllowedMentions{ Parse: []string{}, // Empty array parses no mentions }, }) } ``` -------------------------------- ### OnInteractionCreate Event Source: https://github.com/mvkweb/gophord/blob/main/docs/interactions.md Handles incoming interaction payloads from the Discord Gateway, such as slash commands or component clicks. ```APIDOC ## [EVENT] OnInteractionCreate ### Description Triggered when a user interacts with an application command, component, or modal. Use this to route interaction logic based on the interaction type. ### Parameters - **e** (gateway.InteractionCreateEvent) - Required - The event object containing the interaction payload. ### Request Example ```go bot.OnInteractionCreate(func(e *gateway.InteractionCreateEvent) { // Handle interaction logic here }) ``` ``` -------------------------------- ### Parse Components from Message using Go Source: https://github.com/mvkweb/gophord/blob/main/docs/components-v2.md Illustrates how to parse and identify different types of interactive components (Buttons and Select Menus) within a received Discord message using Gophord. It iterates through the message's components, type-asserting them to `*types.ActionRow` and then to their specific types like `*types.Button` or `*types.StringSelect`. ```go func parseComponents(msg *types.Message) { for _, comp := range msg.Components { if row, ok := comp.(*types.ActionRow); ok { for _, inner := range row.Components { switch c := inner.(type) { case *types.Button: log.Printf("Found button: %s", c.CustomID) case *types.StringSelect: log.Printf("Found select: %s", c.CustomID) } } } } } ``` -------------------------------- ### Gateway Event and Error Channels Source: https://github.com/mvkweb/gophord/blob/main/docs/gateway.md Information on accessing raw events and errors from the gateway client. ```APIDOC ## Gateway Event and Error Channels ### Description This section describes how to access the channels that provide raw gateway events and potential errors. ### Methods #### `Events` - **Method**: `Events` - **Signature**: `func (c *Client) Events() <-chan *Event` - **Description**: Returns a read-only channel for receiving raw `gateway.Event` objects. #### `Errors` - **Method**: `Errors` - **Signature**: `func (c *Client) Errors() <-chan error` - **Description**: Returns a read-only channel for receiving gateway errors, such as missed heartbeats or disconnects. #### `ParseEvent` - **Method**: `ParseEvent` - **Signature**: `func ParseEvent(eventType string, data []byte) (interface{}, error)` - **Description**: Deserializes a generic event payload into a specific event struct (e.g., `*gateway.ReadyEvent`). ``` -------------------------------- ### Send Rich Embed Message with Gophord Source: https://github.com/mvkweb/gophord/blob/main/docs/embeds.md This Go code snippet demonstrates how to construct and send a rich embed message using the Gophord library. It utilizes the `types.Embed` struct and its sub-components to define the embed's content, appearance, and fields. The function requires a `rest.Client` and a `channelID` as input and logs any errors encountered during message sending. Dependencies include the `log` package and Gophord's `rest` and `types` packages. ```go package main import ( "log" "github.com/Mvkweb/gophord/pkg/rest" "github.com/Mvkweb/gophord/pkg/types" ) func sendEmbedMessage(restClient *rest.Client, channelID string) { embed := types.Embed{ Title: "Gophord Documentation", Description: "Learning how to build embeds with Gophord.", URL: "https://github.com/Mvkweb/gophord", Color: 0x00ADD8, // Go blue (hex) Author: &types.EmbedAuthor{ Name: "Gopher", IconURL: "https://go.dev/blog/go-brand/Go-Logo/PNG/Go-Logo_Blue.png", }, Thumbnail: &types.EmbedThumbnail{ URL: "https://go.dev/blog/go-brand/Go-Logo/PNG/Go-Logo_Blue.png", }, Fields: []types.EmbedField{ { Name: "Version", Value: "v1.0.0", Inline: true, }, { Name: "API", Value: "v10", Inline: true, }, { Name: "Performance", Value: "Uses bytedance/sonic for ultra-fast JSON parsing.", Inline: false, // Breaks to a new line }, }, Footer: &types.EmbedFooter{ Text: "Documentation Generated", }, Timestamp: "2023-10-27T12:00:00Z", // ISO8601 string } _, err := restClient.CreateMessage(channelID, rest.CreateMessageParams{ Content: "Here is an example embed:", Embeds: []types.Embed{embed}, }) if err != nil { log.Fatalf("Error sending embed: %v", err) } } ``` -------------------------------- ### Interaction Struct Definition Source: https://github.com/mvkweb/gophord/blob/main/docs/interactions.md Defines the structure of the Interaction object used within Gophord to represent incoming gateway events from Discord. ```go type Interaction struct { ID Snowflake ApplicationID Snowflake Type InteractionType Data *InteractionData GuildID *Snowflake ChannelID *Snowflake Member *GuildMember User *User Token string Version int Message *Message } ``` -------------------------------- ### POST /channels/{channel.id}/messages Source: https://github.com/mvkweb/gophord/blob/main/docs/messages.md Creates a new message in a specific Discord channel. ```APIDOC ## POST /channels/{channel.id}/messages ### Description Sends a new message to the specified channel using the REST client. ### Method POST ### Endpoint /channels/{channel.id}/messages ### Parameters #### Path Parameters - **channel.id** (string) - Required - The unique snowflake ID of the target channel. #### Request Body - **content** (string) - Optional - The message contents (up to 2000 characters). - **message_reference** (object) - Optional - Reference to another message for replies. - **allowed_mentions** (object) - Optional - Fine-grained control over allowed mentions. - **flags** (integer) - Optional - Message flags (e.g., 4096 for silent notifications). ### Request Example { "content": "Hello, Discord!", "message_reference": { "message_id": "123456789012345678" } } ### Response #### Success Response (200) - **id** (string) - The ID of the created message. - **content** (string) - The content of the message. #### Response Example { "id": "987654321098765432", "content": "Hello, Discord!" } ``` -------------------------------- ### POST /channels/{channel.id}/messages Source: https://github.com/mvkweb/gophord/blob/main/docs/embeds.md Sends a message containing one or more rich embeds to a specified channel. ```APIDOC ## POST /channels/{channel.id}/messages ### Description Sends a message to a specific channel. Embeds are passed as an array within the request body, allowing for rich content formatting. ### Method POST ### Endpoint /channels/{channel.id}/messages ### Parameters #### Path Parameters - **channel.id** (string) - Required - The unique identifier of the target channel. #### Request Body - **content** (string) - Optional - The text content of the message. - **embeds** (array) - Optional - A list of up to 10 embed objects. ### Request Example { "content": "Here is an example embed:", "embeds": [{ "title": "Gophord Documentation", "description": "Learning how to build embeds with Gophord.", "color": 1145752 }] } ### Response #### Success Response (200) - **id** (string) - The ID of the created message. - **channel_id** (string) - The ID of the channel where the message was sent. #### Response Example { "id": "123456789012345678", "channel_id": "876543210987654321", "content": "Here is an example embed:" } ``` -------------------------------- ### PATCH /channels/{channel.id}/messages/{message.id} Source: https://github.com/mvkweb/gophord/blob/main/docs/messages.md Edits the content of an existing message. ```APIDOC ## PATCH /channels/{channel.id}/messages/{message.id} ### Description Updates an existing message content or embeds. ### Method PATCH ### Endpoint /channels/{channel.id}/messages/{message.id} ### Parameters #### Path Parameters - **channel.id** (string) - Required - The channel ID. - **message.id** (string) - Required - The message ID to edit. ### Request Example { "content": "Updated message content" } ``` -------------------------------- ### DELETE /channels/{channel.id}/messages/{message.id} Source: https://github.com/mvkweb/gophord/blob/main/docs/messages.md Deletes an existing message from a channel. ```APIDOC ## DELETE /channels/{channel.id}/messages/{message.id} ### Description Deletes a message from the specified channel. ### Method DELETE ### Endpoint /channels/{channel.id}/messages/{message.id} ### Parameters #### Path Parameters - **channel.id** (string) - Required - The channel ID. - **message.id** (string) - Required - The message ID to delete. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.