Skip to content
The Chat Archive
o3-mini· OpenAI LMArena Human Preference 140K

make a discord bot using go with hot-reload command support, mainly using slash command

  1. User

    make a discord bot using go with hot-reload command support, mainly using slash command

  2. Assistant

    Below is an example of a Discord bot written in Go that uses the discordgo library to register slash commands and includes a “hot-reload” command that lets you update the registered slash commands on the fly (without restarting the bot). In this example the bot registers two slash commands in a specific guild:

    • /ping – replies with “Pong!”
    • /reload – deletes and re-registers the commands (a “hot reload”) that you can use to change the commands without stopping the bot

    You can later extend this idea (or combine it with a file watcher such as fsnotify) to trigger reloads when the command definitions change on disk.

    Note: For development it’s recommended to register your commands as guild commands rather than global “application commands” because guild commands update almost instantly.

    Prerequisites

    1. Go installed (version 1.16+ recommended)
    2. Set up a Discord bot application and have its token ready.
    3. Create a test/guild server and have its ID handy to use in testing commands.

    Example Code

    Create a file (for example, main.go) with the following content:

    package main
    
    import (
    	"fmt"
    	"log"
    	"os"
    	"os/signal"
    	"syscall"
    
    	"github.com/bwmarrin/discordgo"
    )
    
    // Replace these with your values (or load them from environment variables).
    var (
    	BotToken = os.Getenv("DISCORD_BOT_TOKEN") // Your bot token as environment variable.
    	GuildID  = os.Getenv("GUILD_ID")          // Guild ID for testing commands.
    )
    
    // Define our commands.
    var commands = []*discordgo.ApplicationCommand{
    	{
    		Name:        "ping",
    		Description: "Replies with Pong!",
    	},
    	{
    		Name:        "reload",
    		Description: "Hot-reloads the bot commands.",
    	},
    }
    
    // For storing the command IDs so we can delete them later.
    var registeredCommands = make(map[string]*discordgo.ApplicationCommand)
    
    func main() {
    	// Check if required environment variables are provided.
    	if BotToken == "" || GuildID == "" {
    		log.Fatalf("Missing environment variables. Please set DISCORD_BOT_TOKEN and GUILD_ID.")
    	}
    
    	// Create a new Discord session.
    	dg, err := discordgo.New("Bot " + BotToken)
    	if err != nil {
    		log.Fatalf("Error creating Discord session: %v", err)
    	}
    
    	// Add handlers.
    	dg.AddHandler(interactionCreate)
    
    	// Open a websocket connection to Discord.
    	err = dg.Open()
    	if err != nil {
    		log.Fatalf("Error opening connection: %v", err)
    	}
    	defer dg.Close()
    
    	// Register the initial slash commands.
    	err = registerCommands(dg)
    	if err != nil {
    		log.Fatalf("Cannot register commands: %v", err)
    	}
    
    	log.Println("Bot is now running. Press CTRL-C to exit.")
    
    	// Wait here until CTRL-C or other term signal is received.
    	stop := make(chan os.Signal, 1)
    	signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
    	<-stop
    
    	// Optional: clean up by unregistering commands when shutting down.
    	err = unregisterCommands(dg)
    	if err != nil {
    		log.Printf("Failed to unregister commands: %v", err)
    	}
    }
    
    // registerCommands registers (or re-registers) the slash commands.
    func registerCommands(s *discordgo.Session) error {
    	log.Println("Registering slash commands...")
    	for _, cmd := range commands {
    		registeredCmd, err := s.ApplicationCommandCreate(s.State.User.ID, GuildID, cmd)
    		if err != nil {
    			return fmt.Errorf("cannot create '%v' command: %w", cmd.Name, err)
    		}
    		registeredCommands[cmd.Name] = registeredCmd
    		log.Printf("Registered command: %s (ID: %s)", cmd.Name, registeredCmd.ID)
    	}
    	return nil
    }
    
    // unregisterCommands removes all commands we registered.
    func unregisterCommands(s *discordgo.Session) error {
    	log.Println("Unregistering slash commands...")
    	for _, cmd := range registeredCommands {
    		err := s.ApplicationCommandDelete(s.State.User.ID, GuildID, cmd.ID)
    		if err != nil {
    			log.Printf("Cannot delete '%v' command: %v", cmd.Name, err)
    		} else {
    			log.Printf("Unregistered command: %s", cmd.Name)
    		}
    	}
    	return nil
    }
    
    // interactionCreate is called whenever an interaction is created (like a slash command)
    func interactionCreate(s *discordgo.Session, i *discordgo.InteractionCreate) {
    	// We only care about application command interactions.
    	if i.Type != discordgo.InteractionApplicationCommand {
    		return
    	}
    
    	// Dispatch based on the command name.
    	switch i.ApplicationCommandData().Name {
    	case "ping":
    		handlePing(s, i)
    	case "reload":
    		handleReload(s, i)
    	default:
    		log.Printf("Unknown command: %s", i.ApplicationCommandData().Name)
    	}
    }
    
    // handlePing replies "Pong!" to the user.
    func handlePing(s *discordgo.Session, i *discordgo.InteractionCreate) {
    	err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
    		Type: discordgo.InteractionResponseChannelMessageWithSource,
    		Data: &discordgo.InteractionResponseData{
    			Content: "Pong!",
    		},
    	})
    	if err != nil {
    		log.Printf("Error sending ping response: %v", err)
    	}
    }
    
    // handleReload performs a hot-reload of the bot commands.
    func handleReload(s *discordgo.Session, i *discordgo.InteractionCreate) {
    	// First, acknowledge the command.
    	err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
    		Type: discordgo.InteractionResponseDeferredChannelMessageWithSource,
    	})
    	if err != nil {
    		log.Printf("Error acknowledging reload command: %v", err)
    		return
    	}
    
    	// First, unregister existing commands.
    	err = unregisterCommands(s)
    	if err != nil {
    		log.Printf("Error unregistering commands: %v", err)
    	}
    
    	// Clear our local map.
    	registeredCommands = make(map[string]*discordgo.ApplicationCommand)
    
    	// Here, you might update the commands slice (for example, by re-reading a configuration file).
    	// For this example, we simply re-register the same commands.
    	err = registerCommands(s)
    	if err != nil {
    		log.Printf("Error re-registering commands: %v", err)
    		// Edit the follow-up message to indicate an error.
    		_, errEdit := s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{
    			Content: func(s string) *string { return &s }("Failed to reload commands."),
    		})
    		if errEdit != nil {
    			log.Printf("Error editing reload response: %v", errEdit)
    		}
    		return
    	}
    
    	// Inform the user that commands were reloaded.
    	_, err = s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{
    		Content: func(s string) *string { return &s }("Commands reloaded successfully!"),
    	})
    	if err != nil {
    		log.Printf("Error editing reload response: %v", err)
    	}
    }
    

    How It Works

    1. Initialization:
      The bot reads the Discord token (DISCORD_BOT_TOKEN) and a test guild ID (GUILD_ID) from environment variables. We initialize a new Discord session using these credentials.

    2. Registering Commands:
      In the registerCommands function, we create our slash commands in the specified guild. The commands are stored in a local map (registeredCommands) for later reference.

    3. Handling Slash Commands:
      The interactionCreate function dispatches incoming interactions:

      • /ping replies immediately with “Pong!”
      • /reload calls handleReload which:
        • Acknowledges the command.
        • Deletes the existing commands.
        • (Optionally) reloads updated definitions (in this example, we simply re-register the same commands).
        • Replies to the user informing that the commands were reloaded.
    4. Clean Shutdown:
      The bot waits for an OS termination signal (like CTRL‑C) and then unregisters all commands before exiting.

    Running the Bot

    1. Set up your environment variables. For example, in your shell:

      export DISCORD_BOT_TOKEN="your_bot_token_here"
      export GUILD_ID="your_test_guild_id_here"
      
    2. Build and run the bot:

      go run main.go
      
    3. In your Discord server (with ID matching GUILD_ID), you should see the commands appear almost instantly. Try running /ping and /reload to see the bot’s responses.

    Extending Hot-Reload

    For a more advanced hot-reload, you could integrate a file watcher like fsnotify that monitors a configuration file containing command definitions. When changes are detected, you would call the unregisterCommands and registerCommands functions accordingly.

    This example gives you a starting point for a Discord bot in Go that supports dynamic slash command reloading. Enjoy coding your bot!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.