Your own Discord server can be a lot of work, which is why bots that take care of ad­min­is­trat­ive 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 pro­gram­ming your bot, you should create a Discord bot. You can create your own ap­plic­a­tion 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 ap­pro­pri­ate terminal command for in­stall­a­tion is:

py -3 -m pip install -U discord.py
python

Step 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 in­teg­rated de­vel­op­ment en­vir­on­ment (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 re­gis­ter­ing your Discord bot on the Discord developer site. To do this, replace the place­hold­er with your custom bot token:

import discord
TOKEN = token_placeholder
python

You 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()
python

Step 4: Verify that the con­nec­tion was suc­cess­fully es­tab­lished

To ensure that your bot is properly connected to the Discord server, include an asyn­chron­ous method in your Python file. This is achieved by re­spond­ing 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})')
python
Note

Asyn­chron­ous functions are fre­quently employed in Discord bot pro­gram­ming. 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 func­tion­al­it­ies to your bot

To implement bot func­tion­al­ity in discord.py, the on_message event is utilised. 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 func­tion­al­ity, 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 ex­am­in­a­tion of the message content. If the message begins with the string !add_role, the bot re­cog­nises 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 utilised as a command, it is prefer­able to use strings that are not commonly used in natural language.

The bot de­term­ines the desired role name from a correctly in­ter­preted command using the Python function split(). Sub­sequently, it locates the relevant role on your server. You can do this by lever­aging the message object, which contains a variety of in­form­a­tion about your server in the message.guild field.

If the role doesn’t exist and con­sequently has a value of ‘None’, an error message is generated and the function is ter­min­ated using the return statement. If the role does exist, it’s assigned as needed. For this, we utilise the add_roles function from the discord.py library, which is also defined within the message object.

Note

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 mod­er­a­tion bot, MEE6, or even code your own Discord Music Bots. We’ve il­lus­trated this using a basic example that beginners can easily follow.

Go to Main Menu