Skip to content

Creating a Discord Bot in Go

Posted on:December 8, 2022 at 02:10 PM

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

Setting Up

  1. Create a new project folder and open it in your text editor.

  2. Make sure the Go programming language is installed on your computer and the GOPATH is configured correctly.

  3. Install the Discord Go SDK by running the command go get github.com/bwmarrin/discordgo.

  4. 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
    }
  5. Replace BOT_TOKEN with your bot’s token.

Adding Commands

  1. 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.

  2. 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!")
        }
    })
  3. Add any other commands you would like to the bot using this method.

Deployment

  1. When you are finished creating your bot, you can deploy it to your Discord server.

  2. To do this, first add the bot to your server using the OAuth2 URL Generator.

  3. 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.