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.
-
Initialize a new Go module in your project directory.
go mod init discord-bot -
Install a popular Discord library like
discordgointo your module.go get github.com/bwmarrin/discordgo -
Create a
main.gofile 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`
-
Replace
YOUR_BOT_TOKENinmain.gowith your actual bot token from the Discord Developer Portal.sed -i 's/YOUR_BOT_TOKEN/your_actual_token_here/g' main.go -
Run the bot to connect to Discord and listen for commands.
go run main.go