seagatewholesale.com

Creating a Sticky Message Bot with Golang: A Practical Guide

Written on

Chapter 1: Introduction to the Sticky Message Bot

In the previous installment of this series, we covered the following topics:

  • Setting up Golang on your machine
  • Creating your project
  • Installing necessary libraries (including the DiscordGo wrapper)
  • Establishing a new bot session
  • Reading and responding to basic messages via the bot

If you haven’t had the chance to read it yet, you can find it here:

Building a Golang Discord Bot- Part 1: Setup

Learn Go development through a real-world project

Here, we will delve into several key concepts:

  • Sending messages to a specified channel and verifying if a message was delivered to that channel
  • Retrieving and saving messages in a text file using the os library, along with appropriate error handling
  • Sending and removing specific messages based on certain events
  • Ultimately, integrating all these features to create a Sticky bot for a specific channel on our server

Excited? Let’s jump right in! :)

What is a Sticky Message?

Imagine a message from our bot positioned at the bottom of a channel in our server. Now, let’s create a new message and dispatch it:

Example of a message in a Discord channel

When a sticky bot is active in a channel, this is what occurs:

Sticky message behavior in action

Upon sending a message, two things happen:

  1. The bot removes the previous “sticky” message.
  2. The bot sends the new message to the channel, ensuring it remains at the bottom for easy visibility.

This encapsulates the essence of a sticky bot’s functionality.

Let’s send another message:

Another message sent in Discord

Here’s what happens after dispatching the above message:

Result after sending a new sticky message

Pretty neat, right? Now that we grasp the purpose and application of the bot, let’s get started on its development!

Components of a Sticky Bot

When the bot sends a new message while removing the previous one to avoid duplication, it’s essential to track the messages that it has sent. To accomplish this, we will create a global variable:

var persistentMessageID string

Since we want our bot to operate “sticky” only in a specific channel, the first step is to obtain the channel ID from our Discord server and incorporate it into our messageCreate function. We can introduce a new block in the function as follows:

if m.ChannelID == "yourChannelId" {

Before we dive into writing this conditional block, we need to create a new file in the project directory named lastTextSentDetails.txt. This file will be used to store the ID of the last sent sticky message, ensuring persistence across different bot sessions. Consequently, even if the bot is stopped, the file will contain the ID of the last sticky message, which can then be used to delete the previous message when the bot sends a new one.

For our initial attempt, let’s take the last sent sticky message’s ID and place it into the text file. It should look something like this:

Text file for storing message IDs

Now, let’s finalize our conditional block.

Reading from and Writing to Files in Go

Our first task is to read the last message ID from the file and delete that message. Let’s implement that:

if m.ChannelID == "yourChannelId" {

if persistentMessageID == "" {

// Read the last message ID from the file and delete it

data, err_readfile := os.ReadFile("lastTextSentDetails.txt")

if err_readfile != nil {

fmt.Println("Error reading file: ", err_readfile)

} else {

persistentMessageID = string(data)

}

}

If the global variable persistentMessageID is an empty string, we read from the file and store the ID in that variable.

Next, we proceed to delete the previous message:

// Delete the last message

err := s.ChannelMessageDelete("yourChannelId", persistentMessageID)

if err != nil {

fmt.Println("Error deleting previous sticky message: ", err)

}

Now that we’ve handled the deletion, let’s move on to the writing and sending part.

First, we send a new sticky message to the channel:

// Send a new message to the bottom

message, err := s.ChannelMessageSend(m.ChannelID, "Here is a nice little sticky message.")

if err != nil {

fmt.Println("Error sending sticky message: ", err)

}

Next, we save the ID of the new message in our global variable:

// Store the ID of the new message in the persistent variable

persistentMessageID = message.ID

Finally, we write this new message’s ID to the file:

// Write persistentMessageID to the file

err = os.WriteFile("lastTextSentDetails.txt", []byte(persistentMessageID), 0644)

if err != nil {

fmt.Println("Error writing to file: ", err)

}

In the os.WriteFile() function, the 0644 code ensures that we overwrite the existing string in the file instead of appending to it. For appending, we would first need to open the file using the OpenFile() function and then use the flag os.O_APPEND.

And there you have it! We’ve successfully built a functional Sticky Bot!

Testing the Sticky Bot

Let’s see it in action! First, stop the bot and restart it. Observe how the ID in the lastTextSentDetails.txt file changes. Now, send a new message:

Sending a new sticky message

This message transforms into:

Result after the sticky message is sent

As we can see, our bot operates as intended!

Conclusion

In this tutorial, we explored how to create a Sticky Bot that helps "pin" a message to the bottom of a channel. We learned various concepts, including file reading and writing, along with some basic error handling, and gained deeper insight into the workings of the DiscordGo library.

If you wish to explore further on your own, you can read about file handling in Golang from here.

To check out the current bot code, you can find the repository here. :)

If you found this tutorial helpful, be sure to subscribe for more articles from me:

Read every story from Yash Prakash (and thousands of other writers on Medium). Your membership fee directly supports…

A few more articles from me that you may find interesting:

Golang Development Utilities You Should Know

How to easily make use of simple yet meaningful development tools in your Go projects

The Easy Python Auto-code Formatting Guide

Set them up just once and write and auto-format your code upon commits — hassle-free with these tools.

26 GitHub Repositories To Inspire Your Next Data Science Project

Start the new year with this inspired list of interesting code with libraries, roadmaps, and projects to bookmark

How to make a STICKY MESSAGE for your discord bot!

[How To] Building a Simple Discord Bot using DiscordGo

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Unraveling Malaria's 5,500-Year Journey Through Trade and Conflict

Explore how ancient DNA reveals the influence of trade and conflict on malaria's global spread over 5,500 years.

A Global Challenge: The Urgent Quest for a Covid-19 Vaccine

An overview of the global race for a Covid-19 vaccine, examining development efforts and distribution challenges.

Achieve Your Summer Body: Treadmill Secrets to Burn Calories

Discover effective treadmill techniques to burn calories and achieve your ideal summer body with minimal effort.