Creating a Discord Bot in Python

Meredith Quintana
Strategio
Published in
5 min readAug 11, 2022

Introduction

For years, I’ve been communicating with my friends on a social messaging platform called Discord. Discord has many bots available for servers to utilize. These bots can do anything from playing music in voice channels to allowing users to choose roles based on emoji reactions.

Note: You may be familiar with Discord’s more work/business-oriented counterpart Slack. Discord is catered more towards gamers and more recently a wide variety of communities since the pandemic started and more people started to go online to socialize.

I always thought it would be fun to make a Discord bot of my own! Since I’ve been revisiting Python, I thought it would be a great opportunity to learn more about the discord.py library and use it to make my bot.

I wanted to make a bot based on Kazuha from the video game Genshin Impact. My goal today is to make the Kazuha bot send random quotes and pictures of him through custom Discord commands. Feel free to follow along with another character/person of your choice.

Prerequisites

  • Make sure you have downloaded the latest version of Python and have your chosen IDE set up and ready.
  • Since we’re using the discord.py library, make sure it’s downloaded.
  • We will use the dotenv, os, and random libraries, so make sure those are also downloaded!

Making a Bot

We need to create a bot account first to connect to it and make it do something! There are many tutorials about this, and you can find one on the official discord.py documentation.

Once you’ve made the bot, invite it to a server to test out!

Writing the Code for the Bot

Getting & Setting Token

After making an official bot and having it join a server you’ve made, you should get the token generated on the bot page. It’s not pictured here for security purposes, but you can get a new token by pressing the “Reset Token” button.

The discord Bot API page shows my current Kazuha settings and where to get the token.

We will put that token into a .env file (where environment variables are stored) so that our token isn’t directly in the code. Here’s an example of mine:

The .env file where I put the token.

Next, we’re going to be setting up the token and our imports in the code as follows:

import osimport randomimport discord.ext as commandsfrom dotenv import load_dotenv
load_dotenv()
token = os.getenv('DISCORD_TOKEN')
client = commands.Bot(command_prefix=".")

We’re importing commands from discord.py because we will make some custom commands.

The load_dotenv() function loads the .env files in the directory and os.getenv('DISCORD_TOKEN') gets the token we put in the .env file earlier.

The line initiating the client variable makes a bot client through the discord.py API and indicates that commands will be prefixed with a singular “.”.

Simple Response

Just to test if the bot is connected and ready, here’s code to check once the client is up and running.

@client.event
async def on_ready():
print("Logged in as a bot {0.user}".format(client))client.run(token)

This is an event provided by the Discord API, and once the client is initialized (with the client.run(token) line) it will trigger the on_ready() function.

Here’s mine, all set up and running!

Kazuha bot logged in, indicated by the statement on the command line.

Setting Up Quotes

I first wanted to make a command that made the Kazuha bot give a quote from him in response.

To start, I made the function with the wrapper @client.command() and named it _quote. The ctx argument must always be in any bot command you define.

Inside of the wrapper, I had a list of aliases for the bot command. This means the commands .quote, .q, and .wind will be recognized in the server and return the randomized quote.

I then gathered a list of quotes (not showing all of them here, but will be putting them in a .txt file in the future to not clump up the code) and put them in a list of strings called kazu_quotes.

Finally, we’re going to send a message as the bot. We do this by using the ctx argument and using ctx’s send() method. I sent a random quote from the kazu_quotes list. Here’s the code altogether:

@client.command(aliases=['quote', 'q', 'wind'])
async def _quote(ctx):
# from this link: https://genshin-impact.fandom.com/wiki/Kaedehara_Kazuha/Voice-Overs kazu_quotes = ["Come driving rain or winds that churn, I shall return, by blade alone, armed, if barefoot, to my home... I am Kaedehara Kazuha, a wanderer who roams the land. Since we are both travelers, let us journey together for a time.",
... (shortened the quotes so you don't have to see it all)
"The wind has ceased... The world is silent, so now is the best time to rest well. See you tomorrow."] await ctx.send(str(random.choice(kazu_quotes)))

Here’s the quote feature in action!

The .quote command in action.

Sending Pictures

I’m going to be setting up pictures in a very similar manner. The significant difference in the following code snippet is that the list of quotes is instead of image links (found through Discord’s built-in GIF search).

@client.command()async def pic(ctx):pic_list = ["https://tenor.com/view/kazuha-genshin-impact-kazuha-drinking-genshin-impact-kazuha-gif-25917615",..."https://tenor.com/view/kazuha-gif-25902775"]await ctx.send(str(random.choice(pic_list)))

Here’s the bot in action with the new .pic command!

The .pic command in action.

With that done, we’ve successfully made a Discord bot with the discord.py API!

Things I’m Planning to Add in the Future

This is only the beginning of my journey in making a bot. I have a lot of ideas and functions I’d love to try and code into it. Here are a few I’m thinking of already:

  • Set up a custom help command with helpful guidance.
  • Set up custom status messages on the bot.
  • A way to play music or specific music clips in voice channels.
  • Changing and removing roles with emoji messages.
  • An 8Ball command to answer random questions.

More Resources

This was a brief introduction to the world of making bots on Discord. Here’s a great video series that helps explain more parts of the discord.py library and making your bots!

Here’s another tutorial with more setup involved if this one was confusing.

Let me know if you had any questions. Thanks for reading!

--

--