How to create a Python Discord bot
Your own Discord server can be a lot of work, which is why bots that take care of administrative functions are popular. You can easily design your own bot using the Python library discord.py and applying basic Python knowledge.
Step by step to your own Python Discord bot
Before you begin programming your bot, you should create a Discord bot. You can create your own application with Discord and once you’ve done so, nothing will stand in the way of your Discord bot. The code you need for your Discord bot depends on the tasks you wish to automate. The bot presented in this tutorial is intended to add roles within a Discord server.
Step 1: install discord.py
To create your bot, the Python library discord.py is an essential tool. Before getting started, you must install it on your system using pip, as is customary with Python. On Windows, the appropriate terminal command for installation is:
py -3 -m pip install -U discord.py
pythonStep 2: create Python document
Create a new Python document to code your bot. You can use various code editors for your Python file or an integrated development environment (IDE) such as Pycharm.
Step 3: connect to Discord
First, import the Discord library into your Python document. Set the bot token you received when registering your Discord bot on the Discord developer site. To do this, replace the placeholder with your custom bot token:
import discord
TOKEN = token_placeholder
pythonYou need the library to interact with the Discord API. In order to connect to Discord, you’ll need an instance of the so-called client object. Use the following code to create this:
client = discord.Client()
pythonStep 4: Verify that the connection was successfully established
To ensure that your bot is properly connected to the Discord server, include an asynchronous method in your Python file. This is achieved by responding to the on_ready
event, which is defined in the discord.py API. To enable your function to serve as an event handler, use the @client.event
decorator in Python.
@client.event
async def on_ready():
print(f'{client.user} is connected to the following server:\n')
for server in client.guilds:
print(f'{server.name}(id: {server.id})')
pythonAsynchronous functions are frequently employed in Discord bot programming. This ensures that the function runs on a dedicated thread separate from the main thread, allowing for parallel execution of bot tasks without blocking the main thread.
Step 5: add functionalities to your bot
To implement bot functionality in discord.py, the on_message
event is utilized. This event is triggered whenever your Discord bot receives a message. To handle this event, your method should first determine the message sender and then execute the desired functionality, such as adding roles.
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!add_role'):
# Find role name
role_name = message.content.split(' ')[1]
# search corresponding Discord role
role = discord.utils.get(message.guild.roles, name=role_name)
# Check if the role exists
if role is None:
await message.channel.send(f'Role "{role_name}" does not exist)
return
# Role assignment
await message.author.add_roles(role)
await message.channel.send(f'Role "{role_name}" was added to {message.author}')
Initially, the function checks whether the received message is sent by the Discord bot itself. If that’s true, the function is exited using the return
statement.
The next step involves a closer examination of the message content. If the message begins with the string !add_role
, the bot recognizes it as a command. This indicates that server users must initiate requests to the Discord bot with the !add_role
string. Although any string can be utilized as a command, it is preferable to use strings that are not commonly used in natural language.
The bot determines the desired role name from a correctly interpreted command using the Python function split()
. Subsequently, it locates the relevant role on your server. You can do this by leveraging the message
object, which contains a variety of information about your server in the message.guild
field.
If the role doesn’t exist and consequently has a value of “None”, an error message is generated and the function is terminated using the return
statement. If the role does exist, it’s assigned as needed. For this, we utilize the add_roles
function from the discord.py library, which is also defined within the message
object.
Your Discord bot has the capacity to carry out any tasks you set for it. You could design bots that execute functions akin to the well-known chat and moderation bot, MEE6, or even code your own Discord Music Bots. We’ve illustrated this using a basic example that beginners can easily follow.