AMZ DIGICOM

Digital Communication

AMZ DIGICOM

Digital Communication

Create a Discord bot in Python: detailed tutorial

PARTAGEZ

Having your own Discord server can sometimes mean a lot of effort, which is why bots that handle administrative functions are popular. Such a bot can be easily created using the discord.py Python library and basic Python knowledge.

Create your own Discord bot in Python step by step

Before you can start programming your bot, you need to create a Discord bot. To do this, you can create your own application under Discord. Nothing will stand in the way of your Discord bot! The code you need for your Discord bot depends on the tasks that will need to be automated. In these instructions, the bot presented must add roles in a Discord server.

Step 1: Install discord.py

When creating your bot, you primarily use the Python library discord.py, which is why you then need to install it on your system. As always in Python, the installation is run under pip. On Windows, the required terminal command is:

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

python

Step 2: Create a Python Document

Create a new Python document in which you code your bot. For your Python file you can use various code editors or a integrated development environment (IDE)like Pycharm.

Step 3: Connect to Discord

Then import the Discord library into your Python document and enter the bot token you received while recording your Discord bot on the Discord developer’s website. To do this, replace the placeholder with your individual bot token:

import discord
TOKEN = paramètre_fictif_jeton

python

The library must interact with the Discord API. In order to connect to Discord, an instance of the client object is also required. Use the following code to create it:

client = discord.Client()

python

Step 4: check the correct connection

The next step is to integrate a asynchronous method in your Python document, which checks whether your bot’s connection to the Discord server worked correctly. To do this, react to the “on_ready” event defined in the discord.py API. To make your function act as an event handler, use the Python function decorator “@client.event”.

@client.event
async def on_ready():
    print(f'{client.user} est connecté au serveur suivant :\n')
    for server in client.guilds:
        print(f'{server.name}(id: {server.id})')

python

When programming the Discord bot, asynchronous functions are often used. This has the effect that the function is executed in a dedicated thread decoupled from the main thread. This way, the main thread is not blocked and bot tasks can be executed in parallel.

Step 5: Add functionality to your bot

The discord.py API defines an event that helps you execute your bot’s functionality, the“on_message” event. This event will then always be triggered when your Discord bot receives a message. A method that processes this event must then check which sender the message came from, then execute the desired functionality, role addition in our case.

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('!add_role'):
        # Déterminer le nom des rôles
        role_name = message.content.split(' ')[1]

        # Trouver le rôle Discord correspondant
        role = discord.utils.get(message.guild.roles, name=role_name)

        # Vérifier que le rôle existe
        if role is None:
            await message.channel.send(f'Le rôle "{role_name}" n’existe pas.)
            return

        # Assignation du rôle
        await message.author.add_roles(role)
        await message.channel.send(f'Le rôle "{role_name}" a été ajouté à {message.author}.')

python

The function then checks if the received message comes from the Discord bot itself. If so, the function is exited with the “return” instruction.

Secondly, the message content is analyzed thoroughly. If it begins with the character string “!add_role”, the bot interprets it as a command. This means that server users must start requests to the Discord bot with the string “!add_role”. You can of course use any string as a command. However, make sure that it is a character string that does not appear in natural linguistic usage.

Using the Python “split()” function, the name of the desired role is then extracted from a message interpreted as a correct command by the bot. In a new step, the corresponding role is searched on your server. To do this, you can exploit the “message” object which contains various information about your server under the “message.guild” point.

If the role does not exist and therefore returns the value « None », an error message is generated and the function is exited with the « return » instruction. If the role exists, it is assigned accordingly. The “add_roles” function present in the discord.py library is then used. It is also defined by the “message” object.

Your Discord bot can of course perform any action. So you can create bots that support similar tasks, like the popular MEE6 chat and moderation bot, or write your own music bot in Discord. We have opted for an easy example that beginners can also understand.

Télécharger notre livre blanc

Comment construire une stratégie de marketing digital ?

Le guide indispensable pour promouvoir votre marque en ligne

En savoir plus

Souhaitez vous Booster votre Business?

écrivez-nous et restez en contact