Go is a popular language for creating Discord bots due to its versatility and ease of use. This guide will walk you through setting up a simple Discord bot in Go, including how to set up commands and use it on your Discord server.
Requirements
- A Discord account
- A text editor such as Visual Studio Code
- Go programming language
- Discord Go SDK
Setting Up
-
Create a new project folder and open it in your text editor.
-
Make sure the Go programming language is installed on your computer and the
GOPATH
is configured correctly. -
Install the Discord Go SDK by running the command
go get github.com/bwmarrin/discordgo
. -
Create a file called
main.go
within your project folder and add the following code to it:package main import ( "fmt" "os" "github.com/bwmarrin/discordgo" ) func main() { // Create a new Discord session discord, err := discordgo.New("BOT_TOKEN") if err != nil { fmt.Println(err.Error()) return } // Open a websocket connection to Discord err = discord.Open() if err != nil { fmt.Println(err.Error()) return } // Wait here until CTRL-C or other term signal is received fmt.Println("Bot is now running. Press CTRL-C to exit.") <-make(chan struct{}) return }
-
Replace
BOT_TOKEN
with your bot’s token.
Adding Commands
-
To add commands to the bot, you’ll need to use the
AddHandler()
method. This method takes a callback function as an argument, which will be called when the command is invoked. -
For example, let’s add a command to print out a greeting:
discord.AddHandler(func(s *discordgo.Session, m *discordgo.MessageCreate) { // Ignore all messages created by the bot itself if m.Author.ID == s.State.User.ID { return } // If the message is "hello" if m.Content == "hello" { // Send a message to the channel _, _ = s.ChannelMessageSend(m.ChannelID, "Hello!") } })
-
Add any other commands you would like to the bot using this method.
Deployment
-
When you are finished creating your bot, you can deploy it to your Discord server.
-
To do this, first add the bot to your server using the OAuth2 URL Generator.
-
Once the bot is added to your server, you can start it by running the
go run main.go
command in the terminal.
Conclusion
Creating a Discord Bot in Go is a simple and straightforward process. With the help of this guide, you should now have a basic understanding of how to set up a simple Discord bot, including adding commands and deploying it to your server.