### Build the Autocomplete Example Source: https://github.com/bwmarrin/discordgo/blob/master/examples/autocomplete/README.md Compile the autocomplete example using the Go build command. Ensure your Go environment is set up and DiscordGo is installed. ```sh go build ``` -------------------------------- ### Compile and Install DiscordGo Source: https://github.com/bwmarrin/discordgo/blob/master/docs/GettingStarted.md After downloading, navigate to the package directory and run 'go install' to compile and install the DiscordGo libraries. This step is recommended for editor autocompletion. ```sh cd $GOPATH/src/github.com/bwmarrin/discordgo go install ``` -------------------------------- ### Run DiscordGo Component Example Source: https://github.com/bwmarrin/discordgo/blob/master/examples/components/README.md Execute the compiled components example with your bot token, application ID, and test guild ID. Replace placeholders with your actual credentials. ```sh ./components -app YOUR_APPLICATION_ID -guild YOUR_TESTING_GUILD -token YOUR_BOT_TOKEN ``` -------------------------------- ### Run DiscordGo Voice Receive Example Source: https://github.com/bwmarrin/discordgo/blob/master/examples/voice_receive/README.md Execute the voice receive example using the bot token, guild ID, and voice channel ID as command-line flags. ```sh ./voice_receive -t MY_TOKEN -g 1234123412341234 -c 5678567856785678 ``` -------------------------------- ### Run DiscordGo Threads Example Source: https://github.com/bwmarrin/discordgo/blob/master/examples/threads/README.md Execute the compiled threads example by providing your bot token. This starts the bot and enables thread management functionalities. ```sh ./threads -token YOUR_BOT_TOKEN ``` -------------------------------- ### Install Missing Go Packages Source: https://github.com/bwmarrin/discordgo/wiki/Troubleshooting If you encounter a "cannot find package" error during build, use `go get` to download the required package. ```sh go get golang.org/x/crypto/nacl/secretbox ``` -------------------------------- ### Install DiscordGo Package Source: https://github.com/bwmarrin/discordgo/blob/master/docs/GettingStarted.md Use 'go get' to download the latest tagged release of the DiscordGo package to your GOPATH/src folder. This command fetches the package source code. ```sh go get github.com/bwmarrin/discordgo ``` -------------------------------- ### Run Custom Proxy Server (nirn-proxy Example) Source: https://github.com/bwmarrin/discordgo/wiki/How-to-use-a-proxy-(like-nirn‐proxy) This example shows how to run a custom proxy server, nirn-proxy, using Docker. Your bot will then route its traffic through this proxy. ```shell docker run -p 8080:8080 ghcr.io/germanoeich/nirn-proxy:main & ``` -------------------------------- ### Run the Scheduled Events Example Source: https://github.com/bwmarrin/discordgo/blob/master/examples/scheduled_events/README.md Execute the scheduled events example bot with your specific guild, token, and voice channel IDs. Replace placeholders with your actual values. ```sh ./scheduled_events -guild YOUR_TESTING_GUILD -token YOUR_BOT_TOKEN -voice YOUR_TESTING_CHANNEL ``` -------------------------------- ### Autocomplete Example Usage Source: https://github.com/bwmarrin/discordgo/blob/master/examples/autocomplete/README.md Run the compiled autocomplete example with necessary flags. The `-guild` flag is optional for global command registration. ```sh ./autocomplete -guild YOUR_TESTING_GUILD -token YOUR_BOT_TOKEN ``` -------------------------------- ### Run DiscordGo Modals Example Source: https://github.com/bwmarrin/discordgo/blob/master/examples/modals/README.md Execute the compiled modals example with necessary application, guild, results channel, and bot token parameters. The cleanup of commands defaults to true. ```sh ./modals -app YOUR_APPLICATION_ID -guild YOUR_TESTING_GUILD -results YOUR_TESTING_CHANNEL -token YOUR_BOT_TOKEN ``` -------------------------------- ### Context Menu Example Usage Source: https://github.com/bwmarrin/discordgo/blob/master/examples/context_menus/README.md Run the compiled context menu example with the required application ID, test guild ID, and bot token. The cleanup flag is true by default. ```sh ./context_menus -app YOUR_APPLICATION_ID -guild YOUR_TESTING_GUILD -token YOUR_BOT_TOKEN ``` -------------------------------- ### Run DiscordGo Slash Commands Example Source: https://github.com/bwmarrin/discordgo/blob/master/examples/slash_commands/README.md Run the compiled example bot, specifying a test guild ID and bot token. If no guild ID is passed, commands are registered globally. ```sh ./slash_commands -guild YOUR_TESTING_GUILD -token YOUR_BOT_TOKEN ``` -------------------------------- ### Scheduled Events Example Usage Source: https://github.com/bwmarrin/discordgo/blob/master/examples/scheduled_events/README.md View the command-line arguments for the scheduled events example. This includes options for guild ID, bot token, and voice channel ID. ```sh Usage of scheduled_events: -guild string Test guild ID -token string Bot token -voice string Test voice channel ID ``` -------------------------------- ### Run DiscordGo Stage Instance Example Source: https://github.com/bwmarrin/discordgo/blob/master/examples/stage_instance/README.md Execute the compiled stage_instance bot with necessary parameters: guild ID, stage channel ID, and bot token. Replace placeholders with your actual values. ```sh ./stage_instance -guild YOUR_TESTING_GUILD -stage STAGE_CHANNEL_ID -token YOUR_BOT_TOKEN ``` -------------------------------- ### Manage Monetization SKUs and Entitlements Source: https://context7.com/bwmarrin/discordgo/llms.txt Provides examples for listing available SKUs, retrieving user entitlements with filters, testing entitlement creation (development only), and consuming a one-time purchase entitlement. ```go // List all SKUs skus, err := s.SKUs("appID") // List entitlements with filters entitlements, err := s.Entitlements("appID", &discordgo.EntitlementFilterOptions{ UserID: "userID", ExcludeEnded: true, Limit: 100, }) for _, e := range entitlements { fmt.Printf("User %s has entitlement to SKU %s\n", e.UserID, e.SKUID) } // Test entitlement (development only) err = s.EntitlementTestCreate("appID", &discordgo.EntitlementTest{ SkuID: "skuID", OwnerID: "userID", OwnerType: discordgo.EntitlementOwnerTypeUser, }) // Consume a one-time purchase err = s.EntitlementConsume("appID", "entitlementID") ``` -------------------------------- ### Start Ping Pong Bot Source: https://github.com/bwmarrin/discordgo/blob/master/examples/pingpong/README.md Execute the compiled bot with your Discord bot token. The bot will indicate when it is running. ```sh ./pingpong -t YOUR_BOT_TOKEN Bot is now running. Press CTRL-C to exit. ``` -------------------------------- ### Start a Thread from a Message Source: https://context7.com/bwmarrin/discordgo/llms.txt Initiates a new thread based on an existing message. Configurable with name, auto-archive duration, invitable status, and rate limits. ```go // Start a thread from an existing message thread, err := s.MessageThreadStartComplex("channelID", "messageID", &discordgo.ThreadStart{ Name: "Discussion: PR #42", AutoArchiveDuration: 1440, // archive after 24 hours of inactivity Invitable: false, RateLimitPerUser: 5, }) ``` -------------------------------- ### Set Discord Avatar from Local File Source: https://github.com/bwmarrin/discordgo/blob/master/examples/avatar/README.md Use the avatar example to set your Discord account's avatar from a local image file. Provide your bot token and the local file name. ```sh ./avatar -t TOKEN -f avatar.png ``` -------------------------------- ### Start a Private Thread Source: https://context7.com/bwmarrin/discordgo/llms.txt Creates a new private thread without a parent message. Requires channel ID, thread name, channel type, and auto-archive duration. ```go // Start a standalone private thread (no parent message) privateThread, err := s.ThreadStart( "channelID", "Dev Chat", discordgo.ChannelTypeGuildPrivateThread, 60, ) ``` -------------------------------- ### Autocomplete Command Line Flags Source: https://github.com/bwmarrin/discordgo/blob/master/examples/autocomplete/README.md View the available command-line flags for the autocomplete example. These control bot behavior like guild testing and command removal. ```text Usage of autocomplete: -guild string Test guild ID. If not passed - bot registers commands globally -rmcmd Whether to remove all commands after shutting down (default true) -token string Bot access token ``` -------------------------------- ### Autocomplete - InteractionApplicationCommandAutocomplete Source: https://context7.com/bwmarrin/discordgo/llms.txt Provides dynamic suggestions as users type slash command option values. This example shows how to create a slash command with an autocomplete option and handle the autocomplete requests. ```APIDOC ## Autocomplete — `InteractionApplicationCommandAutocomplete` Provides dynamic suggestions as users type slash command option values. ```go cmd := &discordgo.ApplicationCommand{ Name: "search", Description: "Search items", Options: []*discordgo.ApplicationCommandOption{{ Type: discordgo.ApplicationCommandOptionString, Name: "query", Description: "Search query", Required: true, Autocomplete: true, }}, } s.ApplicationCommandCreate(s.State.User.ID, "guildID", cmd) s.AddHandler(func(s *discordgo.Session, i *discordgo.InteractionCreate) { if i.Type != discordgo.InteractionApplicationCommandAutocomplete { return } data := i.ApplicationCommandData() var choices []*discordgo.ApplicationCommandOptionChoice if opt := data.GetOption("query"); opt != nil && opt.Focused { // Build suggestions based on opt.StringValue() prefix := opt.StringValue() for _, item := range []string{"apple", "apricot", "avocado", "banana"} { if strings.HasPrefix(item, prefix) { choices = append(choices, &discordgo.ApplicationCommandOptionChoice{ Name: item, Value: item, }) } } } s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ Type: discordgo.InteractionApplicationCommandAutocompleteResult, Data: &discordgo.InteractionResponseData{Choices: choices}, }) }) ``` ``` -------------------------------- ### Modals - InteractionResponseModal Source: https://context7.com/bwmarrin/discordgo/llms.txt Presents a pop-up form to collect multi-field input from users. This example demonstrates how to respond to a slash command with a modal and how to handle the submitted modal data. ```APIDOC ## Modals — `InteractionResponseModal` Presents a pop-up form to collect multi-field input from users. ```go s.AddHandler(func(s *discordgo.Session, i *discordgo.InteractionCreate) { switch i.Type { case discordgo.InteractionApplicationCommand: if i.ApplicationCommandData().Name == "feedback" { required := true s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ Type: discordgo.InteractionResponseModal, Data: &discordgo.InteractionResponseData{ CustomID: "feedback_modal_" + i.Member.User.ID, Title: "Submit Feedback", Components: []discordgo.MessageComponent{ discordgo.ActionsRow{Components: []discordgo.MessageComponent{ discordgo.TextInput{ CustomID: "subject", Label: "Subject", Style: discordgo.TextInputShort, Required: &required, MaxLength: 100, Placeholder: "Brief summary", }, }}, discordgo.ActionsRow{Components: []discordgo.MessageComponent{ discordgo.TextInput{ CustomID: "body", Label: "Details", Style: discordgo.TextInputParagraph, Required: &required, MaxLength: 2000, }, }}, }, }, }) } case discordgo.InteractionModalSubmit: data := i.ModalSubmitData() if !strings.HasPrefix(data.CustomID, "feedback_modal") { return } subject := data.Components[0].(*discordgo.ActionsRow).Components[0].(*discordgo.TextInput).Value body := data.Components[1].(*discordgo.ActionsRow).Components[0].(*discordgo.TextInput).Value s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ Type: discordgo.InteractionResponseChannelMessageWithSource, Data: &discordgo.InteractionResponseData{ Content: fmt.Sprintf("Received feedback:\n**%%s**\n%%s", subject, body), Flags: discordgo.MessageFlagsEphemeral, }, }) } }) ``` ``` -------------------------------- ### DiscordGo Avatar CLI Usage Source: https://github.com/bwmarrin/discordgo/blob/master/examples/avatar/README.md View the command-line usage for the avatar example. This shows the available flags for specifying the bot token, local avatar file, or avatar image URL. ```sh ./avatar --help Usage of ./avatar: -f string Avatar File Name -t string Bot Token -u string URL to the avatar image ``` -------------------------------- ### Run the Airhorn Bot Source: https://github.com/bwmarrin/discordgo/blob/master/examples/airhorn/README.md Run the compiled airhorn bot, providing your bot token via the -t flag. This starts the bot listening for commands. ```sh ./airhorn -t YOUR_BOT_TOKEN ``` -------------------------------- ### Set Discord Avatar from URL Source: https://github.com/bwmarrin/discordgo/blob/master/examples/avatar/README.md Use the avatar example to set your Discord account's avatar from a remote image URL. Provide your bot token and the URL of the image. ```sh ./avatar -t TOKEN -u https://raw.githubusercontent.com/bwmarrin/discordgo/master/docs/img/discordgo.svg ``` -------------------------------- ### Manage Scheduled Events Source: https://context7.com/bwmarrin/discordgo/llms.txt Creates and manages guild scheduled events. Includes creating events, listing events with user counts, getting RSVPed users, and canceling events. ```go startTime := time.Now().Add(24 * time.Hour) endTime := startTime.Add(2 * time.Hour) event, err := s.GuildScheduledEventCreate("guildID", &discordgo.GuildScheduledEventParams{ Name: "Community Game Night", Description: "Join us for some Minecraft!", ScheduledStartTime: &startTime, ScheduledEndTime: &endTime, EntityType: discordgo.GuildScheduledEventEntityTypeVoice, ChannelID: "voiceChannelID", Status: discordgo.GuildScheduledEventStatusScheduled, }) ``` ```go // List events (including user counts) events, err := s.GuildScheduledEvents("guildID", true /*withUserCount*/) for _, e := range events { fmt.Printf("%s — %d interested\n", e.Name, e.UserCount) } ``` ```go // Get RSVPed users users, err := s.GuildScheduledEventUsers("guildID", event.ID, 100, true, "", "") ``` ```go // Cancel event err = s.GuildScheduledEventDelete("guildID", event.ID) ``` -------------------------------- ### Create DCA Sound Files Source: https://github.com/bwmarrin/discordgo/blob/master/examples/airhorn/README.md Convert audio files (like MP3) into DCA format using ffmpeg and the dca CLI. DCA files are optimized for Discord playback. Ensure FFmpeg and DCA are installed. ```sh ffmpeg -i test.mp3 -f s16le -ar 48000 -ac 2 pipe:1 | dca > test.dca ``` -------------------------------- ### Get Snowflake Creation Time Source: https://github.com/bwmarrin/discordgo/wiki/FAQ Calculates the creation time of a Discord snowflake ID. This is useful for determining when a user, channel, or guild was created. ```go func CreationTime(ID string) (t time.Time, err error) { i, err := strconv.ParseInt(ID, 10, 64) if err != nil { return } timestamp := (i >> 22) + 1420070400000 t = time.Unix(timestamp/1000, 0) return } ``` -------------------------------- ### Run the Echo Bot Source: https://github.com/bwmarrin/discordgo/blob/master/examples/echo/README.md Execute the compiled bot with your Discord application and guild IDs, and your bot token. Replace placeholders with your actual credentials. ```sh ./echo -guild YOUR_TESTING_GUILD -app YOUR_TESTING_APP -token YOUR_BOT_TOKEN ``` -------------------------------- ### Register Application Command with Options Source: https://github.com/bwmarrin/discordgo/wiki/FAQ Define a slash command with string options and predefined choices. Ensure the option type and choices are correctly configured. ```golang command := &discordgo.ApplicationCommand{ Name: "command-name", Type: discordgo.ChatApplicationCommand, Description: "Slash commands are amazing", Options: []*discordgo.ApplicationCommandOption { { Name: "rick-astley", Description: "The singer", Type: discordgo.ApplicationCommandOptionString, // Commands might have choices, think of them like of enum values Choices: []*discordgo.ApplicationCommandOptionChoice { { Name: "never-gonna-give-you-up", Value: "never gonna run around and desert you", }, { Name: "never-gonna-make-you-cry", Value: "never gonna tell a lie and hurt you", }, }, }, }, } ``` -------------------------------- ### Create a Slash Command Application Command Source: https://github.com/bwmarrin/discordgo/wiki/FAQ Defines a basic slash command with a name, type, and description. This is the first step in registering application commands. ```go command := &discordgo.ApplicationCommand{ Name: "command-name", Type: discordgo.ChatApplicationCommand, Description: "Slash commands are amazing", } ``` -------------------------------- ### Import DiscordGo Package Source: https://github.com/bwmarrin/discordgo/blob/master/README.md Import the DiscordGo package into your Go project to begin using its functionalities. ```go import "github.com/bwmarrin/discordgo" ``` -------------------------------- ### Configure Sharding Source: https://context7.com/bwmarrin/discordgo/llms.txt Splits gateway load across multiple processes for large bots. Query recommended shard count from Discord. ```go totalShards := 4 for id := 0; id < totalShards; id++ { go func(shardID int) { dg, _ := discordgo.New("Bot " + token) dg.ShardID = shardID dg.ShardCount = totalShards dg.Identify.Intents = discordgo.IntentsAllWithoutPrivileged dg.AddHandler(func(s *discordgo.Session, m *discordgo.MessageCreate) { fmt.Printf("[shard %d] message: %s\n", shardID, m.Content) }) if err := dg.Open(); err != nil { log.Printf("shard %d failed: %v", shardID, err) } }(id) } ``` ```go // Query recommended shard count from Discord gwBot, err := dg.GatewayBot() fmt.Printf("Recommended shards: %d\n", gwBot.Shards) ``` -------------------------------- ### Get Guild from Message Source: https://github.com/bwmarrin/discordgo/wiki/FAQ Retrieves the Guild object associated with a message. It first attempts to fetch from the session's state and falls back to the REST API if necessary. ```go // Attempt to get the guild from the state, // If there is an error, fall back to the restapi. guild, err := session.State.Guild(message.GuildID) if err != nil { guild, err = session.Guild(message.GuildID) if err != nil { return } } ``` -------------------------------- ### Run the Ping Pong Bot Source: https://github.com/bwmarrin/discordgo/blob/master/examples/dm_pingpong/README.md Execute the compiled bot, providing your bot token as a command-line argument. The bot will then be active and ready to respond. ```sh ./dm_pingpong -t YOUR_BOT_TOKEN Bot is now running. Press CTRL-C to exit. ``` -------------------------------- ### Interaction Signature Verification - VerifyInteraction Source: https://context7.com/bwmarrin/discordgo/llms.txt Verifies the Ed25519 signature on incoming HTTP interaction requests, which is required for outbound webhook bots. This example shows how to integrate the verification into an HTTP handler. ```APIDOC ## Interaction Signature Verification — `VerifyInteraction` Verifies the Ed25519 signature on incoming HTTP interaction requests (required for outbound webhook bots). ```go import ( "crypto/ed25519" "encoding/hex" "net/http" "github.com/bwmarrin/discordgo" ) func interactionHandler(w http.ResponseWriter, r *http.Request) { publicKeyHex := os.Getenv("DISCORD_PUBLIC_KEY") pubKeyBytes, _ := hex.DecodeString(publicKeyHex) pubKey := ed25519.PublicKey(pubKeyBytes) if !discordgo.VerifyInteraction(r, pubKey) { http.Error(w, "Unauthorized", http.StatusUnauthorized) return } // Parse and handle interaction JSON from r.Body... } http.HandleFunc("/interactions", interactionHandler) http.ListenAndServe(":8080", nil) ``` ``` -------------------------------- ### Manage WebSocket Connection Lifecycle Source: https://context7.com/bwmarrin/discordgo/llms.txt Demonstrates opening the WebSocket connection, checking heartbeat latency, requesting guild members, and gracefully closing the connection with or without a specific code. `DataReady` indicates the initial handshake is complete. ```go // Open connection (blocks until READY or error) err := dg.Open() // Check heartbeat round-trip time latency := dg.HeartbeatLatency() fmt.Printf("Gateway latency: %v\n", latency) // DataReady is true once the first heartbeat ACK is received fmt.Println("Data ready:", dg.DataReady) // Request guild member list over gateway (triggers GuildMembersChunk events) err = dg.RequestGuildMembers("guildID", "", 0, "nonce123", false) // Close gracefully (sends close frame, emits Disconnect event) err = dg.Close() // Close with a specific close code err = dg.CloseWithCode(websocket.CloseGoingAway) ``` -------------------------------- ### Register Application Command with Subcommands Source: https://github.com/bwmarrin/discordgo/wiki/FAQ Structure a slash command to include subcommands and subcommand groups. Commands with subcommands cannot have other options and must be executed with a subcommand. ```golang command := &discordgo.ApplicationCommand{ Name: "command-name", Type: discordgo.ChatApplicationCommand, Description: "This is command description", Options: []*discordgo.ApplicationCommandOption { { Name: "subcommand", Type: discordgo.ApplicationCommandOptionSubCommand, Description: "This is subcommand description", }, { Name: "subcommand-group", Type: discordgo.ApplicationCommandOptionSubCommandGroup, Description: "This is subcommand group description", Options: []*discordgo.ApplicationCommandOption { { Name: "subcommand", Type: discordgo.ApplicationCommandOptionSubCommand, Description: "This is subcommand description", }, }, }, }, } ``` -------------------------------- ### Create a Webhook Source: https://context7.com/bwmarrin/discordgo/llms.txt Creates a new webhook in a specified channel. Requires channel ID and a name for the webhook. An optional avatar can be provided. ```go // Create a webhook in a channel wh, err := s.WebhookCreate("channelID", "Notifier", "") ``` -------------------------------- ### Implement Autocomplete for Slash Commands in discordgo Source: https://context7.com/bwmarrin/discordgo/llms.txt Use this to provide dynamic suggestions as users type slash command option values. Ensure the command is registered with `Autocomplete: true` for the relevant option. ```go cmd := &discordgo.ApplicationCommand{ Name: "search", Description: "Search items", Options: []*discordgo.ApplicationCommandOption{{ Type: discordgo.ApplicationCommandOptionString, Name: "query", Description: "Search query", Required: true, Autocomplete: true, }}, } s.ApplicationCommandCreate(s.State.User.ID, "guildID", cmd) s.AddHandler(func(s *discordgo.Session, i *discordgo.InteractionCreate) { if i.Type != discordgo.InteractionApplicationCommandAutocomplete { return } data := i.ApplicationCommandData() var choices []*discordgo.ApplicationCommandOptionChoice if opt := data.GetOption("query"); opt != nil && opt.Focused { // Build suggestions based on opt.StringValue() prefix := opt.StringValue() for _, item := range []string{"apple", "apricot", "avocado", "banana"} { if strings.HasPrefix(item, prefix) { choices = append(choices, &discordgo.ApplicationCommandOptionChoice{ Name: item, Value: item, }) } } } s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ Type: discordgo.InteractionApplicationCommandAutocompleteResult, Data: &discordgo.InteractionResponseData{Choices: choices}, }) }) ``` -------------------------------- ### Subscribe to Speaking Events Source: https://context7.com/bwmarrin/discordgo/llms.txt Adds a handler to receive notifications when users start or stop speaking in a voice channel. The handler receives the `VoiceSpeakingUpdate` struct containing the user ID and speaking status. ```go // Subscribe to speaking-start/stop events vc.AddHandler(func(vc *discordgo.VoiceConnection, vsu *discordgo.VoiceSpeakingUpdate) { fmt.Printf("User %s is speaking: %v\n", vsu.UserID, vsu.Speaking) }) ``` -------------------------------- ### Create New Discord Client Source: https://github.com/bwmarrin/discordgo/blob/master/README.md Construct a new Discord client using your authentication token. This client is used to access Discord API functions and set up event callbacks. ```go discord, err := discordgo.New("Bot " + "authentication token") ``` -------------------------------- ### Define Context Menu Command Source: https://github.com/bwmarrin/discordgo/wiki/FAQ Create a context menu command for user or message interactions. These commands can have spaces and capitalized letters in their names. ```golang command := discordgo.ApplicationCommand { Name: "User scope command", // Context menu commands might contain spaces and capitalized letters. Type: discordgo.UserApplicationCommand, // Or discordgo.MessageApplicationCommand for message context menu. } ``` -------------------------------- ### Handle Modals with discordgo Source: https://context7.com/bwmarrin/discordgo/llms.txt Use this to present a pop-up form to collect multi-field input from users. It handles both the initial modal presentation and the subsequent submission. ```go s.AddHandler(func(s *discordgo.Session, i *discordgo.InteractionCreate) { switch i.Type { case discordgo.InteractionApplicationCommand: if i.ApplicationCommandData().Name == "feedback" { required := true s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ Type: discordgo.InteractionResponseModal, Data: &discordgo.InteractionResponseData{ CustomID: "feedback_modal_" + i.Member.User.ID, Title: "Submit Feedback", Components: []discordgo.MessageComponent{ discordgo.ActionsRow{Components: []discordgo.MessageComponent{ discordgo.TextInput{ CustomID: "subject", Label: "Subject", Style: discordgo.TextInputShort, Required: &required, MaxLength: 100, Placeholder: "Brief summary", }, }}, discordgo.ActionsRow{Components: []discordgo.MessageComponent{ discordgo.TextInput{ CustomID: "body", Label: "Details", Style: discordgo.TextInputParagraph, Required: &required, MaxLength: 2000, }, }}, }, }, }) } case discordgo.InteractionModalSubmit: data := i.ModalSubmitData() if !strings.HasPrefix(data.CustomID, "feedback_modal") { return } subject := data.Components[0].(*discordgo.ActionsRow).Components[0].(*discordgo.TextInput).Value body := data.Components[1].(*discordgo.ActionsRow).Components[0].(*discordgo.TextInput).Value s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ Type: discordgo.InteractionResponseChannelMessageWithSource, Data: &discordgo.InteractionResponseData{ Content: fmt.Sprintf("Received feedback:\n**%%s**\n%%s", subject, body), Flags: discordgo.MessageFlagsEphemeral, }, }) } }) ``` -------------------------------- ### Create, List, and Delete AutoMod Rules Source: https://context7.com/bwmarrin/discordgo/llms.txt Demonstrates creating a new AutoMod rule, listing all rules for a guild, and deleting a specific rule. Ensure the bot has the necessary permissions. ```go enabled := true rule, err := s.AutoModerationRuleCreate("guildID", &discordgo.AutoModerationRule{ Name: "Block slurs", EventType: discordgo.AutoModerationEventMessageSend, TriggerType: discordgo.AutoModerationTriggerKeyword, TriggerMetadata: &discordgo.AutoModerationTriggerMetadata{ KeywordFilter: []string{"badword1", "badword2"}, }, Enabled: &enabled, Actions: []discordgo.AutoModerationAction{ {Type: discordgo.AutoModerationRuleActionBlockMessage}, { Type: discordgo.AutoModerationRuleActionSendAlertMessage, Metadata: &discordgo.AutoModerationActionMetadata{ ChannelID: "modLogChannelID", }, }, }, }) // List all rules rules, err := s.AutoModerationRules("guildID") // Delete a rule err = s.AutoModerationRuleDelete("guildID", rule.ID) ``` -------------------------------- ### Run the Auto Moderation Bot Source: https://github.com/bwmarrin/discordgo/blob/master/examples/auto_moderation/README.md Execute the compiled auto-moderation bot with necessary parameters. Replace placeholders with your actual testing channel, guild, and bot token. ```sh ./auto_moderation -channel YOUR_TESTING_CHANNEL -guild YOUR_TESTING_GUILD -token YOUR_BOT_TOKEN ``` -------------------------------- ### Simplified Discordgo Embed Creation Source: https://github.com/bwmarrin/discordgo/wiki/FAQ Shows a simplified method for creating embeds using helper functions, reducing boilerplate code. This approach is inspired by discord.js. ```Go embed := NewEmbed(). SetTitle("I am an embed"). SetDescription("This is a discordgo embed"). AddField("I am a field", "I am a value"). AddField("I am a second field", "I am a value"). SetImage("https://cdn.discordapp.com/avatars/119249192806776836/cc32c5c3ee602e1fe252f9f595f9010e.jpg?size=2048"). SetThumbnail("https://cdn.discordapp.com/avatars/119249192806776836/cc32c5c3ee602e1fe252f9f595f9010e.jpg?size=2048"). SetColor(0x00ff00).MessageEmbed session.ChannelMessageSendEmbed(channelid, embed) ``` -------------------------------- ### Register and Handle Slash Commands Source: https://context7.com/bwmarrin/discordgo/llms.txt Register guild-scoped or global slash commands with ApplicationCommandCreate. Handle incoming interactions by checking the interaction type and command name, then responding using InteractionRespond. ApplicationCommandBulkOverwrite can register multiple commands at once, and ApplicationCommandDelete removes a command. ```go // Register a guild-scoped slash command (use "" for guildID = global) cmd, err := s.ApplicationCommandCreate(s.State.User.ID, "guildID", &discordgo.ApplicationCommand{ Name: "greet", Description: "Greet a user", Options: []*discordgo.ApplicationCommandOption{ { Type: discordgo.ApplicationCommandOptionUser, Name: "target", Description: "User to greet", Required: true, }, { Type: discordgo.ApplicationCommandOptionString, Name: "message", Description: "Custom greeting (optional)", Required: false, }, }, }) ``` ```go // Handle the interaction s.AddHandler(func(s *discordgo.Session, i *discordgo.InteractionCreate) { if i.Type != discordgo.InteractionApplicationCommand { return } data := i.ApplicationCommandData() if data.Name != "greet" { return } opts := make(map[string]*discordgo.ApplicationCommandInteractionDataOption) for _, o := range data.Options { opts[o.Name] = o } target := opts["target"].UserValue(s) greeting := "Hello" if msg, ok := opts["message"]; ok { greeting = msg.StringValue() } s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ Type: discordgo.InteractionResponseChannelMessageWithSource, Data: &discordgo.InteractionResponseData{ Content: fmt.Sprintf("%s, <@%s>!", greeting, target.ID), Flags: discordgo.MessageFlagsEphemeral, // visible only to invoker }, }) }) ``` ```go // Bulk-register/overwrite all commands at once s.ApplicationCommandBulkOverwrite(s.State.User.ID, "guildID", commands) ``` ```go // Delete a command err = s.ApplicationCommandDelete(s.State.User.ID, "guildID", cmd.ID) ``` -------------------------------- ### Join a Voice Channel Source: https://context7.com/bwmarrin/discordgo/llms.txt Connects the bot to a specified voice channel in a guild. Requires guild ID, voice channel ID, and flags for mute and deafen status. ```go // Join a voice channel vc, err := s.ChannelVoiceJoin("guildID", "voiceChannelID", false /*mute*/, false /*deaf*/) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Set HTTP/HTTPS Proxy Environment Variables Source: https://github.com/bwmarrin/discordgo/wiki/How-to-use-a-proxy-(like-nirn‐proxy) For real HTTP/HTTPS proxies, set the standard environment variables. The Go client will automatically use these settings. ```shell export HTTP_PROXY="http://your.proxy.server:port" export HTTPS_PROXY="http://your.proxy.server:port" ``` -------------------------------- ### Create Discord Session Source: https://context7.com/bwmarrin/discordgo/llms.txt Creates a new Discord session with automatic configuration for rate limiting, state caching, and reconnection. Restrict gateway intents to only what is needed and open the WebSocket connection. The session should be closed when no longer needed. ```go package main import ( "fmt" "os" "os/signal" "syscall" "github.com/bwmarrin/discordgo" ) func main() { // Create session — auto-configures rate limiter, state cache, reconnect logic dg, err := discordgo.New("Bot " + os.Getenv("DISCORD_TOKEN")) if err != nil { fmt.Println("error creating session:", err) return } // Restrict gateway intents to only what is needed dg.Identify.Intents = discordgo.IntentsGuildMessages | discordgo.IntentsGuilds // Open WebSocket connection to Discord gateway if err = dg.Open(); err != nil { fmt.Println("error opening connection:", err) return } defer dg.Close() fmt.Println("Bot running. CTRL-C to exit.") sc := make(chan os.Signal, 1) signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt) <-sc } ``` -------------------------------- ### Create a Forum Post Source: https://context7.com/bwmarrin/discordgo/llms.txt Creates a new post within a forum channel. Requires forum channel ID, post title, auto-archive duration, and initial message content. ```go // Create a forum post forumPost, err := s.ForumThreadStart( "forumChannelID", "Bug Report: Login fails", 10080, // auto-archive in 7 days "Steps to reproduce: ...", ) ``` -------------------------------- ### Session Creation - New Source: https://context7.com/bwmarrin/discordgo/llms.txt Creates a new Discord session with automatic configuration for rate limiting, state caching, and reconnection logic. Bot tokens should be prefixed with "Bot " and OAuth2 bearer tokens with "Bearer ". ```APIDOC ## Session Creation — `New` Creates a new Discord session. Bot tokens must be prefixed with `"Bot "`, OAuth2 bearer tokens with `"Bearer "`. ```go package main import ( "fmt" "os" "os/signal" "syscall" "github.com/bwmarrin/discordgo" ) func main() { // Create session — auto-configures rate limiter, state cache, reconnect logic dg, err := discordgo.New("Bot " + os.Getenv("DISCORD_TOKEN")) if err != nil { fmt.Println("error creating session:", err) return } // Restrict gateway intents to only what is needed dg.Identify.Intents = discordgo.IntentsGuildMessages | discordgo.IntentsGuilds // Open WebSocket connection to Discord gateway if err = dg.Open(); err != nil { fmt.Println("error opening connection:", err) return } defer dg.Close() fmt.Println("Bot running. CTRL-C to exit.") sc := make(chan os.Signal, 1) signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt) <-sc } ``` ``` -------------------------------- ### Send Message with Buttons and Select Menu Source: https://context7.com/bwmarrin/discordgo/llms.txt Use this to send a message that includes interactive buttons and a select menu. Ensure the necessary components are correctly structured within ActionsRows. ```go // Send a message with buttons and a select menu s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ Type: discordgo.InteractionResponseChannelMessageWithSource, Data: &discordgo.InteractionResponseData{ Content: "Choose an action:", Components: []discordgo.MessageComponent{ discordgo.ActionsRow{ Components: []discordgo.MessageComponent{ discordgo.Button{ Label: "Confirm", Style: discordgo.SuccessButton, CustomID: "confirm_action", }, discordgo.Button{ Label: "Cancel", Style: discordgo.DangerButton, CustomID: "cancel_action", }, discordgo.Button{ Label: "Docs", Style: discordgo.LinkButton, URL: "https://discord.com/developers/docs", }, }, }, discordgo.ActionsRow{ Components: []discordgo.MessageComponent{ discordgo.SelectMenu{ CustomID: "priority_select", Placeholder: "Set priority…", Options: []discordgo.SelectMenuOption{ {Label: "High", Value: "high", Emoji: &discordgo.ComponentEmoji{Name: "🔴"}}, {Label: "Medium", Value: "medium", Emoji: &discordgo.ComponentEmoji{Name: "🟡"}}, {Label: "Low", Value: "low", Emoji: &discordgo.ComponentEmoji{Name: "🟢"}}, }, }, }, }, }, }, }) // Handle component interactions s.AddHandler(func(s *discordgo.Session, i *discordgo.InteractionCreate) { if i.Type != discordgo.InteractionMessageComponent { return } data := i.MessageComponentData() switch data.CustomID { case "confirm_action": s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ Type: discordgo.InteractionResponseChannelMessageWithSource, Data: &discordgo.InteractionResponseData{Content: "Confirmed!", Flags: discordgo.MessageFlagsEphemeral}, }) case "priority_select": s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ Type: discordgo.InteractionResponseChannelMessageWithSource, Data: &discordgo.InteractionResponseData{ Content: "Priority set to: " + data.Values[0], Flags: discordgo.MessageFlagsEphemeral, }, }) } }) ``` -------------------------------- ### Create and Send a Discordgo Embed Message Source: https://github.com/bwmarrin/discordgo/wiki/FAQ Demonstrates how to create a complex embed message with fields, images, and timestamps using discordgo. This is useful for rich message formatting. ```Go embed := &discordgo.MessageEmbed{ Author: &discordgo.MessageEmbedAuthor{}, Color: 0x00ff00, // Green Description: "This is a discordgo embed", Fields: []*discordgo.MessageEmbedField{ &discordgo.MessageEmbedField{ Name: "I am a field", Value: "I am a value", Inline: true, }, &discordgo.MessageEmbedField{ Name: "I am a second field", Value: "I am a value", Inline: true, }, }, Image: &discordgo.MessageEmbedImage{ URL: "https://cdn.discordapp.com/avatars/119249192806776836/cc32c5c3ee602e1fe252f9f595f9010e.jpg?size=2048", }, Thumbnail: &discordgo.MessageEmbedThumbnail{ URL: "https://cdn.discordapp.com/avatars/119249192806776836/cc32c5c3ee602e1fe252f9f595f9010e.jpg?size=2048", }, Timestamp: time.Now().Format(time.RFC3339), // Discord wants ISO8601; RFC3339 is an extension of ISO8601 and should be completely compatible. Title: "I am an Embed", } session.ChannelMessageSendEmbed(channelid, embed) ``` -------------------------------- ### Join and Leave Threads Source: https://context7.com/bwmarrin/discordgo/llms.txt Allows a user to join or leave an existing thread. Requires the thread's ID. ```go // Join / leave a thread err = s.ThreadJoin(thread.ID) err = s.ThreadLeave(thread.ID) ``` -------------------------------- ### Ping Pong Bot Usage Help Source: https://github.com/bwmarrin/discordgo/blob/master/examples/pingpong/README.md View the command-line arguments for the ping pong bot. Use the -t flag to specify your bot token. ```sh ./pingpong --help Usage of ./pingpong: -t string Bot Token ``` -------------------------------- ### Fetch and Manage Discord Guilds Source: https://context7.com/bwmarrin/discordgo/llms.txt Fetches and manages Discord guilds (servers). Use GuildCreate for bots in fewer than 10 guilds. GuildEdit requires a GuildParams struct and can include an audit log reason. ```go // Fetch a guild guild, err := s.Guild("guildID") fmt.Println(guild.Name, guild.MemberCount) ``` ```go // Fetch with approximate member counts guild, err = s.GuildWithCounts("guildID") ``` ```go // Create a new guild (bot-owned; limited to bots in <10 guilds) newGuild, err := s.GuildCreate("My New Server") ``` ```go // Edit guild settings verif := discordgo.VerificationLevelHigh guild, err = s.GuildEdit("guildID", &discordgo.GuildParams{ Name: "Updated Name", VerificationLevel: &verif, }, discordgo.WithAuditLogReason("Rebranding")) ``` ```go // Audit log — last 50 member-ban events auditLog, err := s.GuildAuditLog("guildID", "", "", discordgo.AuditLogActionMemberBanAdd, 50) for _, entry := range auditLog.AuditLogEntries { fmt.Printf("Action %d by %s\n", entry.ActionType, entry.UserID) } ``` ```go // Leave a guild err = s.GuildLeave("guildID") ``` -------------------------------- ### Control DiscordGo Log Level and Debug Output Source: https://context7.com/bwmarrin/discordgo/llms.txt Shows how to set the library's internal log verbosity and enable/disable the dumping of raw HTTP request/response bodies for debugging. A custom logger can also be integrated. ```go import "github.com/bwmarrin/discordgo" dg.LogLevel = discordgo.LogDebug // LogError, LogWarning, LogInformational, LogDebug dg.Debug = true // additionally dump raw HTTP request/response bodies // Custom log handler (integrates with structured loggers) discordgo.Logger = func(msgL, caller int, format string, a ...interface{}) { if msgL <= discordgo.LogWarning { log.Printf("[discordgo] "+format, a...) } } ``` -------------------------------- ### Create and Manage Guild Roles Source: https://context7.com/bwmarrin/discordgo/llms.txt Creates and manages guild roles. GuildRoleCreate allows specifying name, color, hoisting, and permissions. GuildRoleEdit updates an existing role. GuildRoleMemberCounts provides member counts per role. ```go // List all roles roles, err := s.GuildRoles("guildID") ``` ```go // Create a role with color and hoisting color := 0x1abc9c hoist := true role, err := s.GuildRoleCreate("guildID", &discordgo.RoleParams{ Name: "Moderator", Color: &color, Hoist: &hoist, Permissions: discordgo.PermissionKickMembers | discordgo.PermissionBanMembers, }) ``` ```go // Edit a role newName := "Senior Moderator" updatedRole, err := s.GuildRoleEdit("guildID", role.ID, &discordgo.RoleParams{ Name: newName, }) ``` ```go // Reorder roles s.GuildRoleReorder("guildID", roles) ``` ```go // Member counts per role (excludes @everyone) counts, err := s.GuildRoleMemberCounts("guildID") fmt.Println("Mods:", counts[role.ID]) ``` ```go // Delete err = s.GuildRoleDelete("guildID", role.ID) ``` -------------------------------- ### Execute a Webhook Source: https://context7.com/bwmarrin/discordgo/llms.txt Executes a webhook to send a message. Supports waiting for the message to be sent, setting content, username, embeds, and other parameters. Requires webhook ID and token. ```go // Execute the webhook (wait=true returns the sent message) msg, err := s.WebhookExecute(wh.ID, wh.Token, true, &discordgo.WebhookParams{ Content: "Deployment finished successfully ✅", Username: "CI Bot", Embeds: []*discordgo.MessageEmbed{{ // Embeds are optional Title: "Build #128", Description: "All tests passed", Color: 0x00cc44, }}, }) ``` -------------------------------- ### Enable All Gateway Intents in Discordgo Source: https://github.com/bwmarrin/discordgo/wiki/FAQ To enable all intents, including privileged ones, set Identify.Intents to discordgo.MakeIntent(discordgo.IntentsAll) before calling Open. This requires enabling privileged intents in the Discord Developer Portal. ```go session.Identify.Intents = discordgo.MakeIntent(discordgo.IntentsAll) ``` -------------------------------- ### Join User's Voice Channel in Discordgo Source: https://github.com/bwmarrin/discordgo/wiki/FAQ Joins the session to the same voice channel as a specified user. Requires finding the user's voice state first. ```go // joinUserVoiceChannel joins a session to the same channel as another user. func joinUserVoiceChannel(session *discordgo.Session, userID string) (*discordgo.VoiceConnection, error) { // Find a user's current voice channel vs, err := findUserVoiceState(session, userID) if err != nil { return nil, err } // Join the user's channel and start unmuted and deafened. return session.ChannelVoiceJoin(vs.GuildID, vs.ChannelID, false, true) } ``` -------------------------------- ### Logging Source: https://context7.com/bwmarrin/discordgo/llms.txt Controls library-internal log verbosity and allows custom log handlers. ```APIDOC ## Session.LogLevel ### Description Sets the verbosity level for library-internal logs. ### Method `Session.LogLevel` ### Parameters - **level** (discordgo.LogLevel) - Required - The desired log level (e.g., `discordgo.LogDebug`, `discordgo.LogError`). ### Example ```go dg.LogLevel = discordgo.LogDebug ``` ## Session.Debug ### Description Enables or disables the dumping of raw HTTP request/response bodies for debugging purposes. ### Method `Session.Debug` ### Parameters - **enabled** (bool) - Required - `true` to enable, `false` to disable. ### Example ```go dg.Debug = true ``` ## discordgo.Logger ### Description Assigns a custom log handler function to integrate with structured loggers. ### Method `discordgo.Logger` ### Parameters - **loggerFunc** (func(msgL, caller int, format string, a ...interface{})) - Required - The custom log handler function. ### Example ```go discordgo.Logger = func(msgL, caller int, format string, a ...interface{}) { if msgL <= discordgo.LogWarning { log.Printf("[discordgo] "+format, a...) } } ``` ```