How to Build a Fitness Suggestion Discord Bot with Python

In this article, we will show you what a Discord Bot is and how to go about building one with Python.

Muhammed Ali
Python in Plain English

--

Photo by Samuel Girven on Unsplash

Are you trying to figure out how to build a Discord Bot with Python?

Do you know what a Discord Bot is and how to build it with Python?

If you’re asking yourself these questions, you’ve come to the right place. In this article, we’ll show you what a Discord Bot is and how to go about building one with Python.

Discord Bots can help automate the process of engaging with your community on your Discord server. You can use Discord bots to welcome new members to the server, regulate communication between members, ban people who refuse to follow the rules, automate responses to reoccurring questions, and so on. The Discord Bot you will be building will send fitness tips to people on the Discord server when a particular message is sent. Members of the server can create, delete and view a list of workout tips.

We will use Replit for this tutorial so you don’t need to install anything.

If you didn’t know already, Replit is an online IDE, so all you have to do is open the website on your web browser. This is good because you don’t need to start installing anything on your local machine.

Prerequisites

To follow this article, you should have a good understanding of Python and be familiar with Discord.

Building a Discord Bot

The first thing you need to do is create a Discord server that the bot will run on. To do that, go to https://discord.com/ and log in or register if you don’t have an account already.

After the authentication process, you should see something like the image below. Next, click the “+” button on the left-hand side and fill in the necessary information to create a new Discord server.

Next, create a Discord Bot account to access Discord API. To do this, go to the Discord developer portal.

On the Discord developer portal page, click the “New Application” button on the top right corner, then fill in the “Name” field and submit. Since you are building a bot that displays fitness tips, the name of the bot could be “Fitness tips bot”.
Once that’s done, you should see something like this:

Next, go to the “Bot” tab under Settings and click the “Add Bot” button. Doing this will create your bot.

Now, create a link that will be used to invite the bot to your Discord server. To create the link, go to the “OAuth2” tab and select the “SCOPES” and the “BOT PERMISSIONS”.

The scope and permissions that should be ticked are:
SCOPES: bot
BOT PERMISSION: View Channels, Send Messages, Public Threads, Private Threads, Manage Messages, Manage Threads, Embed Links, Attach Files, Read Message History, Mention Everyone, Add Reactions, and Use Slash Commands.

Then, copy the URL provided in the “SCOPES” section. This is the URL that will be used to connect the bot to the server.

Open the URL on the browser, then select the server you want to connect the bot to it and submit all the redirects.

Now go to Discord and click on the server you attached the bot to. You should see that your bot has been added to the server.

The bot is offline because you haven’t written the code for the bot yet so let’s get right into it.

As mentioned earlier, Replit will be used for the development of this bot.

The first thing you have to do before using Replit is creating a Replit account, or log in if you already have an account.

You will be redirected to the replit home page. Click on the “+” button to create a new Repl for your bot. The Repl will contain the files for your bot.

Next, select Python as the language since that is what we are working with and create a name for your file then click on the “Create repl” button.

Developing the Bot

First, let’s start with the necessary imports.

# main.pyimport discord # Here you are importing the Discord library for Python
import random # used to display random tips from the list of fitness tips
from replit import db # replit database that will be used to store the fitness tips
client = discord.Client() # This represents a client connection that connects to Discord itself

After importing all that, we are now ready to start writing some code.

First, create a list of words that will trigger the action of the bot. Since you are building a fitness tips bot, some trigger words could be “workout”, “fitness tip”, “tip”, etc.

Add them to a Python list:

trigger_words = [“fitness”, “fitness tip”,]# This is a list of tips that we will be working with before adding new tips to the Replit databasestarter_tips  = [
"Make sure you drink water",
"Make sure you're eating healthy",
"Good posture is essential for a great workout"
]

Next, we are going to create the event decorator from the client. The event will enable the bot to initiate an action with respect to the message. The library, Discord.py, is built asynchronously so it makes use of callbacks.

@client.eventasync def on_message(message):  """With this, if the trigger word is coming from the bot it will     be ignored"""  if message.author == client.user:    return  options = starter_tips  """this loops through the trigger words and compares it with the message"""  if any(word in message.content for word in trigger_words):    """If a trigger_word is found in the message a random fitness tip will be sent. Remember you  imported Random module earlier"""    await message.channel.send(random.choice(options))

To add and delete tips from the database, two functions will be created.

Directly after the starter_tips list, paste the code below. The functions add_tip() and delete_tip() will be used to add tips and delete tips respectively as you can see in the code snippet below.

def add_tip(fitness_tip):  if "tips" in db.keys(): # db.keys() returns to a list of keys in the database    tips = db["tips"] # Get the value of the key in the database    tips.append(fitness_tip)    db["tips"] = tips # this adds the fitness tip to the database  else:    db["tips"] = [fitness_tip]def delete_tip(index): 
#index will be the number position of the tip to be deleted
tips = db["tips"] if len(tips) > index: del tips[index] db["tips"] = tips

Now you are going to use these functions in the event of your bot.

@client.eventasync def on_message(message):if message.author == client.user:  returnoptions = starter_tipsif "tips" in db.keys():  options = options + list(db["tips"])if any(word in message.content for word in trigger_words):  await message.channel.send(random.choice(options))if message.content.startswith("#new"):  """ Here you are just telling the bot that if there if there is “#new ” in the message add anything after it in the database as a new tip"""  fitness_tip = message.content.split("#new ",1)[1]  add_tips(fitness_tip)  await message.channel.send("New fitness tip added.") # This is     displayed if a tip is saved.

Next, add an if statement to handle deleting of tips.

if message.content.startswith("#del"):""" Here you are just telling the bot that if there is “#del” and a number next to it in the message, the bot should delete the tip attached to that particular number beside #del"""  tips = []if "tips" in db.keys():  index = int(message.content.split("#del",1)[1])  delete_tip(index)  tips = db["tips"]await message.channel.send("A tip has been deleted")

The last if statement will handle listing all the tips that are available.

if message.content.startswith("#list"):  """DIsplays the list of tips in the database when you send #list"""  tips = []  if "tips" in db.keys():    tips = list(db["tips"])  await message.channel.send(tips)

Now you’ll need the Discord Bot token. The token uniquely identifies your bot.

To get the secret key, go to the discord developer portal, click on the bot you just created, and go to the “Bot” tab.

Next, click on the “Copy” button you see there.

After the token is copied, go to the end of your code and paste the code below:

client.run(“paste_your_bot_token_here”)

Testing the Bot

To test the bot, first, run your code by clicking the “Run” button above your code. On another tab in your browser, go to your Discord server.

In the image below you’ll see that I triggered the bot by sending a “fitness tip”. Then by using “#new” before the message, I was able to add tips. Also, you can see that the “#list” is working as expected. The “0” in “#del0” in the image below represents the id of the tip you want to delete.

As you can see, all the functionalities are working as they should be. Try it out!

Conclusion

In this article, you were able to build a Discord Bot that is able to send fitness tips to members of the Discord server when a particular message is sent. Members of the server can create, delete, and view a list of workout tips on the Discord server. As for the bot token, that should be hidden if you are planning to deploy it or make it public.

Congratulations on going through this process successfully. From now on, you will start building a Discord Bot for your Discord servers. The code is on Drive for your convenience.

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter and LinkedIn. Check out our Community Discord and join our Talent Collective.

--

--

Technical Writer with experience in building awesome stuff with Django, Python, JavaScript, React, Kubernetes, etc. || Cloud-Native enthusiast.