Building Discord Bots with Python
8 min read
I have only just started using Discord. This site Hashnode that I have fallen in love with so much has a Discord channel that I joined. Even though I am not the most chatty person in the world, I find it comforting that I have a place to go to ask questions or get advice.
From there I explored Discord some and found a home in the "The Codin' Nerds" Where I like to answer questions on Linux. I had noticed that they use a lot of bots and I was curious about them. I have written bots and AI chatbots for our old Minecraft server and I really enjoyed my time working on them.
Out of curiosity, I wanted to know what was involved in writing one for my own server.
So I created a server and searched for a quick tutorial in python. I found How to Make a Discord Bot in Python From the Real Python website.
It turns out to be a lot simpler than I thought using the Discord module in python.
In this tutorial, I will show you how to build a jokes bot to render a joke upon request.
Discords Developer Portal
If you are already on Discord and have your own server/guild then start here, otherwise use the Real Python link above to catch up on what Discord is and how to create a user account.
Create a user account for the developer portal. If you need to create a new account, then click on the Register button below Login and enter your account information.
Verify your email account after in order to move on.
Once you’re finished, you’ll be redirected to the Developer Portal home page, where you’ll create your application.
Create a New Application by clicking on the blueish New Application gui button in the upper right-hand corner.
You will be prompted with a new pop up window asking for you to name your new application.
I named it jokeBot for this tutorial.
Click on the Create gui button to move on to the General Information page.
On the left and side is a list of settings. Click on the Bot Setting to bring up the bot information.
Then on the right, click the gui button 'Add Bot'
You will see another pop up that says:
Add a bot to this app
adding a bot user gives your app visible life in Discord. However, this action is irrevocable! Choose wisely.
Click on yes do it!
Once you confirm that you want to add the bot to your application, you’ll see the new bot user in the portal:
Adding The JokeBot To Your Server
This tool generates an authorization URL that hits Discord’s OAuth2 API and authorizes API access using your application’s credentials. You will grant your bot rights to access to Discords APIs using your account OAuth credentials.
To do this, scroll down and select bot from the SCOPES options and Administrator from BOT PERMISSIONS:
As you can see under SCOPES, Discord has generated your bots authorization URL with the selected scope and permissions.
I selected the Administrator as the permissions because I was wide open on what I wanted my bot to accomplish. If using in a production environment you should restrict permissions.
Select copy beside the generated URL and paste it into an open browser window.
Select your server from the dropdown option and click the gui continue button. Then confirm the connection bu clicking Authorize (You may get a reCaptcha option)
You should be rewarded with a window:
Close the window but do not close the browser. You will want to return to the Discord Developer page to grab the Token.
Go to the server you attached it to and verify that your bot has been added. At this point, your bot has a greyed-out look to it as it is currently offline.
Create Your JokeBot In Python
Now for the fun part. Open your Linux terminal and install discord.py with pip.
(I am on RHEL8 using python3 but discord will install with just pip)
sudo pip3 install -U discord.py
Connect your bot to your server.
I have written my app in 3 separate scripts. They are small and simple but will give you a good idea on how to expand your bot and scale up. The 3 files are:
- jokes.txt = This is the file where I keep my jokes in. It is easy enough to add to by adding one joke to a line.
- pylogic.py = This is the heavy lifter of the set. It performs the logic and grabs a random line from the jokes.txt file.
- jokebot.py = This is the app that houses the TOKEN, connects the bot, calls the logic from the pylogic.py file.
Lets create the jokes.txt file first. I have a couple of jokes for you to copy and paste into a text file. Make sure you name it
When I heard that oxygen and magnesium hooked up I was like Omg! Two goldfish are in a tank. One looks at the other and asks, "You know how to drive this thing?" As a scarecrow, people say I am outstanding in my field. But hay, it is in my jeans. Why aren't Koalas actual bears? They don't meet the Koalafications. I bought the worlds worst thesaurus yesterday. Not only is it terrible, it is terrible. What do Alexander the Great and Winnie the Pooh have in common? Same middle name. What did the left eye say to the right eye? Between you and me, something smells. Why can't you tease egg whites? They can't take a yolk. Einsteins' mum: Are you happy? Einstein: Relatively. I bought some shoes from a drug dealer. I don't know what he laced them with but I've been tripping all day. It's a disgrace that gingerbread men are forced to live in houses made of their own flesh. A man said to me: "I'm going to attack you with the neck of a guitar: I said: "Is that a fret?" What's the difference between ignorance and apathy? I don't know and I don't care. This sentence contains exactly threee erors.
Remember to have each joke on the same line. Not to say it can not expand mutiple lines just make your character return at the end of each joke.
I work in VIM so it may just be easier for me.
The next file is our
pylogic.py file. If you are familiar with python then this will be easy to read.
import random def readjoke(): with open('jokes.txt', 'r') as r: l=r.readlines() random_joke = random.choice(l) return random_joke
- Import the random module so we can pick from a random option every time the function is called.
- Create a function called
readjoke(). It then opens the
jokes.txtas read only and saves all the lines in the file to memory.
random.choice()chooses one line from the memory and saves that as
random_jokeis what will be passed to
The jokebot is the connection app somewhat like a flask or django app.
from pylogic import readjoke import discord from discord.ext import commands TOKEN = ('NzU4MzYxOTM3MTM4MDI0NTMw.X2t1lw.qoudMz7XtQPL4mooyVK_znz_DvM') bot = commands.Bot(command_prefix='#') async def jokes(ctx): await ctx.send(readjoke()) bot.run(TOKEN)
- The import commands import our pylogic file. Specifically the readjoke function from the pylogic.py file. It also imports the discord module.
from discord.ext import commandsis the actual function working here. More on that down the script.
TOKENwill need to be gathered from the discord bot page. You will need to get it by copying the string.
bot = commands.Bot(command_prefix='#')sets the command prefix. You can set it to anything you like, here I choose a hash #. If you do not choose one then your bot could respond after any chat message and even respond to itself which would end up in a loop that never stops.
async def jokes(ctx):listens for the command (#) to respond by calling the function readjoke()
Now look at your server and verify your bot is available.
Hopefully this will get a bot working for you in a dev environment. In most cases, you would set the token as a environment variable but inthis case it is trying out new logic ideas. Also instead of having to add jokes in a json style format you can just add your joke to the joke.txt without having to restart the jokebot.py app. It has been fun to work with and I would like to expand it to grab online data. My kids want to take it and build their own RPG game. I have to say they are a lot more creative than I am.
I hope you enjoyed this post.
Did you find this article valuable?
Support Dallas Spohn by becoming a sponsor. Any amount is appreciated!