Building a simple Discord bot using Go
This article offers tutorials on how to build a Discord `Hello World` bot using Golang.
We will be using DiscordGo to build our very first bot, DiscordGo is a Go package that provides low level bindings to the Discord chat client API. DiscordGo has nearly complete support for all of the Discord API endpoints, WebSocket interface, and voice interface.
GitHub repository: https://github.com/bwmarrin/discordgo
First, you need to create a application by logging into your Discord developer portal.
Discord Setup Steps:
1. Redirect to : https://discord.com/developers/applications
2. Click on New Application
button and provide any name to your application. Note: The application is not the bot
3. On the left menu, select Bot
and then click on Add Bot
button.
4. Uncheck the public bot check box
.
5. Click the Reset Token
button, to generate a Token ID.
6. Go to URL Generator under OAuth2 on the left, and provide scope as Bot
, and permissions such as Receive Message
, Send Message
, Send Message in Thread
.
7. Copy the URL
generated at the bottom, after the permission are set.
8. Go to that URL
and add the bot to any of your server, after all these steps you should be having a Token ID
and Bot(offline)
in your server.
Lets now build a Hello world bot using Golang, so for that create a project with two files, main.go
and bot.go
Open the terminal and intialize a module,
go mod init example.com/hello_world_bot
The go.mod
file that got generated defines the module’s module path, which is also the import path used for the root directory, and its dependency requirements, which are the other modules needed for a successful build.
Next, add the DiscordGo dependency using the following command,
go get github.com/bwmarrin/discordgo
In main.go
,
package main
import bot "example.com/hello_world_bot/Bot"
func main() {
bot.BotToken = "DISCORD TOKEN ID"
bot.Run() // call the run function of bot/bot.go
}
In bot/bot.go
,
package bot
import (
"fmt"
"log"
"os"
"os/signal"
"strings"
"github.com/bwmarrin/discordgo"
)
var BotToken string
func checkNilErr(e error) {
if e != nil {
log.Fatal("Error message")
}
}
func Run() {
// create a session
discord, err := discordgo.New("Bot " + BotToken)
checkNilErr(err)
// add a event handler
discord.AddHandler(newMessage)
// open session
discord.Open()
defer discord.Close() // close session, after function termination
// keep bot running untill there is NO os interruption (ctrl + C)
fmt.Println("Bot running....")
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
<-c
}
func newMessage(discord *discordgo.Session, message *discordgo.MessageCreate) {
/* prevent bot responding to its own message
this is achived by looking into the message author id
if message.author.id is same as bot.author.id then just return
*/
if message.Author.ID == discord.State.User.ID {
return
}
// respond to user message if it contains `!help` or `!bye`
switch {
case strings.Contains(message.Content, "!help"):
discord.ChannelMessageSend(message.ChannelID, "Hello World😃")
case strings.Contains(message.Content, "!bye"):
discord.ChannelMessageSend(message.ChannelID, "Good Bye👋")
// add more cases if required
}
}
I have added few comments for better understanding, but most of the functions and lines are self explanatory.
Finally its time to run the bot, for that use the following command,
go run main.go
We can also first build the project and then run the executable file using following command,
go build
.\hello_world_bot.exe
When you run the project, the bot turns toonline state
on discord. Just type !help
or !bye
and the bot should respond without error.
Output:
That’s pretty much all for the Hello World Discord bot. Here is a more better example of Discord Weather Bot.
It’s also recommended to use environment variable rather than exposing the TOKEN ID
’s. Have a look at the .envfile
implementation in the above example.
The article’s main goal was to show how straightforward it is to develop a simple Discord bot. I sincerely apologise if the article had any inaccuracies. If you found it helpful, kindly give it an upvote.