How to build a Discord Bot with Python

How to build a Discord Bot with Python

Discord is a popular platform for communication among communities(of developers, web3 folks, etc), and friends. Several companies also use Discord to manage their relationship with users. It has served as a repository for managing communities over time. It includes all the features needed for close interaction among people in similar fields.

Why do we need Discord bots? As a result of the massive adoption of discord, different communities have faced the challenge of not being able to oversee all activities in a community with large and active members. The greatest advantage of creating bots is for proper coordination of some activities to mitigate the works of real moderators. Bots can be used to provide answers to previously asked questions by new members or even provide 24/7 support to satisfy the curiosity of users/members. Things like auto-reply and using commands to trigger an action are mostly powered by bots.

So do you have a Discord server? or do you manage a community that is growing bigger day by day and you need to add a bot to your server to ease your workload? In this article, I will be providing a step-by-step tutorial on how to get that done.

There are several ways to create a Discord bot but creating a Discord bot with Python is easier and can enhance your server's functionality and engagement. After this tutorial, you will be able to:

  • Integrate bots into your discord server

  • Get more familiar with Python scripts

Let's dive right into it! Before we proceed I believe you should have acquired a basic knowledge of Python programming and be familiar with Discord.

To better understand this tutorial:

  • Ensure you have a Discord account to create and manage your bot.

  • Install Python on your machine if you haven't already. You can download it from python.org.

  • Be familiar with some terminal commands

Setting Up Your Bot

To set up your bot:

  1. Visit the Discord Developer Portal

  2. After visiting the Developer Portal, click on "New Application" to create a new application.

  3. Give your application a name, and optionally set an avatar.

  4. In your application settings, navigate to the "Bot" tab.

  5. Click "Reset Token" to generate your bot's token.

  6. Copy this token and save it elsewhere on your PC. You can use a notepad.

  7. Scroll down and make sure you enable all the options under the Authorization flow, especially the "Privileged Gateway Intents"

Add Your Bot to a Server:

  1. Navigate to the "OAuth2" tab in your application settings.

  2. In the "OAuth2 URL Generator," select the "bot" scope and the permissions your bot needs. For this tutorial, I checked the "application.commands" box.

  3. Copy the generated link and paste it into another browser tab.

  4. Follow the instructions to add your bot to a server.

Congrats! you have added your bot to a server! Now you need to write some code to make your bot functional. You can use Vscode or any text editor of your choice and follow the next steps.

Make the bot functional

  1. Install Discord.py:

  2. Open your terminal and run pip install discord.py to install the Discord.py library.

  3. Open vs code or any text editor of your choice through the terminal or manually.

  4. Create a new Python file (e.g., bot.py) to write your bot's code/script.

Code Structure:

After installing the necessary dependencies you need to import the necessary modules:

import discord
from discord.ext import commands

Add intents to Initialize the bot :

# Define intents
intents = discord.Intents.default()
intents.messages = True  # Enable the message intent, as it's required for commands
intents.message_content = True

bot = commands.Bot(command_prefix='!', intents=intents)

An instance of discord.Intents.default() and the intent.messages is required for handling commands.

intents.message_content = True is necessary for the on_message event to work correctly, which is used by the command extension in discord.py.

Simple Command Example:

You can create a simple "hello" command:

@bot.command()
async def hello(ctx):
    await ctx.send('Hello!')

You can also create other commands to suit your server needs.

For example, to get the server info:

@bot.command()
async def info(ctx):
    server = ctx.guild
    embed = discord.Embed(title='Server Information', description=f'Server: {server.name}', color=discord.Color.blue())
    embed.add_field(name='Total Members', value=server.member_count, inline=True)
    embed.add_field(name='Server ID', value=server.id, inline=True)
    await ctx.send(embed=embed)

So when you use !hello or !info command in your server, It would trigger this Python script and generate a response.

Run Your Bot:

Add the following code at the end of your script:

bot.run('YOUR_BOT_TOKEN')

Replace 'YOUR_BOT_TOKEN' with the actual token you obtained from the Discord Developer Portal.

It is always advisable to store your bot tokens in a .env file for security purposes supposing you want to use this in a real-life project. To do that:

  1. Create a new file with the name .env

  2. In this file, create a variable named BOT_TOKEN

  3. Store your bot token on this variable this way, BOT_TOKEN = "your token"

  4. Open your terminal and run pip install python-dotenv (this installs a package that enables you to use your token from the environment variable)

  5. Import the necessary module:

     from dotenv import load_dotenv
     import os
    
  6. Load the bot token from the environment variable:

     # Load environment variables from .env file
     load_dotenv()
    
     # Get the bot token from the environment variable
     TOKEN = os.getenv('BOT_TOKEN')
    
  7. Replace 'YOUR_BOT_TOKEN' with the TOKEN variable instead of the actual token.

     bot.run('YOUR_BOT_TOKEN')
    

Now you have successfully stored your token in an environment variable.

Start Your Bot:

Run your script in the terminal to check if it's working:

python bot.py

You should get a successful connection response in the terminal like this:

Although it only works locally, this shows that your code works perfectly.

Hosting

After completing the steps subsequent steps, your discord bot will only run locally and you may want to make it available 24/7. There are many hosting services you can use below:

Visit any of these hosting platforms and follow their hosting guides to get your bot up and running on your Discord server.

Testing Your Hosted Bot

  • Make sure you add your bot to the server(If you skipped this process, kindly go back to the "Invite your bot to a server" section).

  • Use Your Command: Type !hello or !info in a text channel, and your bot should respond with 'Hello!' or your server information.

  • You can also add more commands to your bot apart from the two we used here.

Congratulations! You've successfully created a Discord bot using Python and you can now run your Discord community with ease. From here, you can explore more advanced features, such as event handling, multiple commands, and so on.