Here's a Discord bot in Go with hot-reload command support using slash commands:
package main
import (
"fmt"
"log"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"github.com/bwmarrin/discordgo"
)
var (
Token = os.Getenv("DISCORD_TOKEN")
GuildID = os.Getenv("GUILD_ID") // For development, remove for global commands
commands = make(map[string]*discordgo.ApplicationCommand)
handlers = make(map[string]func(s *discordgo.Session, i *discordgo.InteractionCreate))
cmdsMutex sync.RWMutex
)
func init() {
// Register initial commands
registerCommand("ping", "Replies with pong!", pingCommand)
registerCommand("reload", "Reloads all commands", reloadCommand)
}
func registerCommand(name, description string, handler func(s *discordgo.Session, i *discordgo.InteractionCreate)) {
cmdsMutex.Lock()
defer cmdsMutex.Unlock()
commands[name] = &discordgo.ApplicationCommand{
Name: name,
Description: description,
}
handlers[name] = handler
}
func main() {
if Token == "" {
log.Fatal("No Discord token provided. Set DISCORD_TOKEN environment variable.")
}
// Create a new Discord session
dg, err := discordgo.New("Bot " + Token)
if err != nil {
log.Fatalf("Error creating Discord session: %v", err)
}
// Register the interactionCreate func as a callback for InteractionCreate events
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 commands with Discord
registeredCommands := make([]*discordgo.ApplicationCommand, 0)
cmdsMutex.RLock()
for _, v := range commands {
cmd, err := dg.ApplicationCommandCreate(dg.State.User.ID, GuildID, v)
if err != nil {
log.Panicf("Cannot create '%v' command: %v", v.Name, err)
}
registeredCommands = append(registeredCommands, cmd)
}
cmdsMutex.RUnlock()
fmt.Println("Bot is now running. Press CTRL-C to exit.")
// Wait for a SIGINT or SIGTERM signal
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM)
<-sc
// Clean up commands on exit
for _, v := range registeredCommands {
err := dg.ApplicationCommandDelete(dg.State.User.ID, GuildID, v.ID)
if err != nil {
log.Printf("Cannot delete '%v' command: %v", v.Name, err)
}
}
}
func interactionCreate(s *discordgo.Session, i *discordgo.InteractionCreate) {
if i.Type != discordgo.InteractionApplicationCommand {
return
}
cmdsMutex.RLock()
if h, ok := handlers[i.ApplicationCommandData().Name]; ok {
cmdsMutex.RUnlock()
h(s, i)
} else {
cmdsMutex.RUnlock()
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Unknown command",
},
})
}
}
func pingCommand(s *discordgo.Session, i *discordgo.InteractionCreate) {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Pong!",
},
})
}
func reloadCommand(s *discordgo.Session, i *discordgo.InteractionCreate) {
// Here you would implement your hot-reload logic
// For example, you could:
// 1. Unregister old commands
// 2. Load new command definitions from a file or database
// 3. Register new commands
// For this example, we'll just simulate reloading by adding a new command
registerCommand("hello", "Says hello", func(s *discordgo.Session, i *discordgo.InteractionCreate) {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Hello, world!",
},
})
})
// Register the new command with Discord
cmdsMutex.RLock()
cmd, err := s.ApplicationCommandCreate(s.State.User.ID, GuildID, commands["hello"])
cmdsMutex.RUnlock()
if err != nil {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: fmt.Sprintf("Failed to reload commands: %v", err),
},
})
return
}
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: fmt.Sprintf("Commands reloaded! Added new command: %s", cmd.Name),
},
})
}
Would you like me to explain or break down the code?