How to Build a Discord Bot in Go

Web
Initialize a Go module, install a Discord library, write a handler for messages, and run the program to create a Discord bot.

You build a Discord bot in Go by initializing a module, installing a Discord library, and writing a main program that connects to the Discord API and handles events.

  1. Initialize a new Go module in your project directory. go mod init discord-bot

  2. Install a popular Discord library like discordgo into your module. go get github.com/bwmarrin/discordgo

  3. Create a main.go file that sets up the Discord session, registers an event handler for messages, and starts the connection. `cat > main.go << 'EOF' package main

import ( "github.com/bwmarrin/discordgo" )

func main() { dg, err := discordgo.New("Bot " + "YOUR_BOT_TOKEN") if err != nil { panic(err) } dg.AddHandler(handleMessage) dg.Open() defer dg.Close() select {} }

func handleMessage(s *discordgo.Session, m *discordgo.MessageCreate) { if m.Author.ID == s.State.User.ID { return } if m.Content == "ping" { s.ChannelMessageSend(m.ChannelID, "pong") } } EOF`

  1. Replace YOUR_BOT_TOKEN in main.go with your actual bot token from the Discord Developer Portal. sed -i 's/YOUR_BOT_TOKEN/your_actual_token_here/g' main.go

  2. Run the bot to connect to Discord and listen for commands. go run main.go