Instagram
youtube
Facebook
  • 2 years, 1 month ago
  • 2978 Views

Code a Discord bot in Go

Yaman Birla
Table of Contents

Hello Tech geeks, Today we are going to make a discord bot in golang and it’s a pretty interesting thing to learn as per development work is concerned one could do various changes when coding a bot like adding Natural Language Processing which is a part of Machine Learning, However, today we are going to make a simple discord bot to get started with it which will reply to !ping command as !pong.

 

Before we get started make sure to have a discord account and make a server from it.

 

I had already made a server below:

 

 

Also, I have already made my bot which is why it is shown live on the image but we’ll get there don’t worry.

 

Next up is to register on the discord developer portal you can find it on the link below:

 

https://discord.com/developers/applications

 

There click on the New Application and name it golang-bot and under the settings, options click on the bot, and then on reset token as shown in below image:

 

 

Now scroll down and under the bot permission allow all text permissions and go on to the OAuth2 and click on URL Generator in it and then select bot and scroll down and give all the text permissions and copy the link under URL generator and open it in a new tab and authorize it.

Refer to the below images for help.

 

 

Select your server and Authorize it.

 

 

After this confirmation you can see your bot on the server, however, it is offline currently we have to code it to make it online.



 

Prepare a directory or root folder for your project:

 

Now fellas! Time to code. Make sure to have a go-workspace directory that will save all your coding work.

 

Now open cmd or PowerShell and make a directory named golang-bot from your root directory for golang.

 

 

Now add the mod file to it.

 

 

Now, time to code in your favorite code editor, mine is Vs-Code.

 

Coding

 

Before jumping on to coding and development, we have one more thing to add to our golang-bot folder i.e. config.json file which will have the Token id that we had generated earlier in discord and BotPrefix.

 

Now make a main.go file and copy the code below and we’ll understand what our code does.

package main

import (
	"github.com/bwmarrin/discordgo"
	"encoding/json"
	"fmt"
	"io/ioutil"
)

var (
	Token string
	BotPrefix string

	config *configStruct
)

type configStruct struct {
	Token string `json: "Token"`
	BotPrefix string `json: "BotPrefix"`
}

func ReadConfig() error {
	file, err := ioutil.ReadFile("./config.json")

	if err != nil {
		fmt.Println(err.Error())
		return err
	}

	fmt.Println(string(file))

	err = json.Unmarshal(file, &config)

	if err != nil {
		fmt.Println(err.Error())
		return err
	}

	Token = config.Token
	BotPrefix = config.BotPrefix

	return nil
}

var BotId string
var goBot *discordgo.Session

func Start() {
	goBot, err := discordgo.New("Bot " + config.Token)

	if err != nil {
		fmt.Println(err.Error())
		return 
	}

	u, err := goBot.User("@me")

	if err != nil {
		fmt.Println(err.Error())
		return 
	}

	BotId = u.ID 

	goBot.AddHandler(messageHandler)

	err = goBot.Open()

	if err != nil {
		fmt.Println(err.Error())
		return 
	}

	fmt.Println("Bot is running fine!")

}

func messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) {
	if m.Author.ID == BotId {
		return
	}

	if m.Content == BotPrefix+"ping"{
		_, _ = s.ChannelMessageSend(m.ChannelID, "pong")
	}
}

func main() {
	err := ReadConfig()

	if err != nil {
		fmt.Println(err.Error())
		return 
	}

	Start()

	<-make(chan struct{})
	return
}

Let’s understand what this code does.

 

Libraries we have imported:

 

"github.com/bwmarrin/discordgo": it is a Go package for Discord bindings for specific tasks.

"encoding/json": it is used to encode or decode JSON 

"fmt": fmt is a Go package that is used to format basic strings, values, inputs, and outputs. 

"io/ioutil": This Package implements some I/O utility functions.


 

I have divided my code into 3 functions 

 

ReadConfig function; 

which will read our config.json file and fetch the token id from there, if it throws any error during the process we will print it out, and if it doesn’t we’ll unmarshal the JSON file into our already declared variable for Token and BotPrefix.

 

Start function:

In this function, we will start the session with the library discordgo we have imported on top of our code, DiscordGo is a Go package that provides low-level bindings to the Discord chat client API. which will construct a new Discord client which can be used to access the variety of Discord API functions and to set callback functions for Discord events with proper error handling.

 

messageHandlers function:

In this function, basically we are making our bot ready to reply to a command including the prefix “!” in it. 




 

Output

 

Now time to check out our golang-bot.

Before running it run this command to download all the dependencies that we have imported into our code.

 

 

Now run the code:

 

 

Great! Our bot is running fine, let’s check it on our server.

 

 

Our Bot is relying on our !ping command. We can do so many interesting things with it like adding more commands to reply with, etc.

 

And remember never share your token out in public it could be used maliciously.

 

Thanks for sticking with us.

 

GitHub: https://github.com/cosmic-weber/Golang/tree/main/golang-bot

 

Add a comment:

Comments:

Https://Odessaforum.BIZ.Ua

I was curious if you ever thought off changing the structure of your blog? Its verdy well written; I love what youve got to say. But maybe you could a littgle more in the way of content so people could connect with it better. Youve got an awful lot of text for only having 1 or 2 images. Maybe yoou could space it out better? https://Odessaforum.BIZ.Ua/