In recent years, Discord has become one of the most popular communication platforms, especially in the world of video games and online communities. And with millions of daily active users, it is no wonder that the demand for Discord bots has grown significantly.
Discord bots can perform a wide variety of tasks, from moderating servers to providing real-time feedback, improving user experience and automating repetitive processes.
If you are interested in learning how to create a Discord bot, you are in the right place. Below, we'll walk you step-by-step through programming a Discord bot with Python, one of the most accessible and versatile programming languages available today.
What is a Discord bot
This type of technology is nothing more than an automated application that interacts with users and performs tasks on a Discord server. These bots can execute specific commands, respond to messages, and perform administrative actions such as muting users or assigning roles. They are also valuable tools for maintaining organisation and improving server functionality.
Why use Python to create them
Python is an excellent choice for anyone wondering how to create a Discord bot for a number of reasons:
- Simplicity: Python is known for its clear and easy-to-read syntax, which makes it ideal for beginners and experienced developers.
- Documentation and community: There is a wealth of resources and an active community ready to help. The documentation for the Python libraries for Discord is extensive and detailed.
- Specialised libraries: There are libraries such as `discord.py` that are specifically designed to interact with the Official Discord API, The development process is greatly facilitated.
Initial configuration
Before you start developing a Discord bot in Python, it is crucial to properly set up your working environment. This process includes making sure you have all the necessary tools installed, creating a clean development environment, and registering your bot on the Discord Developer Portal. A well-configured initial setup not only makes development easier, but also prevents potential problems as you progress through the project.
Configuration of the development environment
As we said, before you start programming your Discord bot with Python, it is essential to properly prepare your development environment. Let's take a look at the necessary steps to set up your environment:
- Python installation: Make sure you have Python installed on your system. You can download the latest version from python.org. Follow the installation instructions according to your operating system (Windows, macOS or Linux).
- Configuration of the virtual environment: It is recommended to use a virtual environment to isolate your project's dependencies and avoid conflicts with other projects. To create a virtual environment, open your terminal or command line and run the following commands:
«`bash
python -m venv environment_name
«`
Then, activate the virtual environment:
- On Windows:
«`bash
environment_nameScriptsactivate
«`
- On macOS/Linux:
«`bash
source environment_name/bin/activate
«`
- Installation of dependencies: With the virtual environment enabled, install the `discord.py` library using pip:
«`bash
pip install discord.py
«`
- Code editor: Choose a code editor that you are comfortable with. Visual Studio Code, PyCharm and Sublime Text are popular choices. Install the necessary extensions to facilitate development, such as linters and debuggers for Python.
Register the bot on Discord and obtain the necessary API keys.
Now, for your Python Discord bot to be able to interact with the Discord servers, you need to register it and get the necessary API keys. Here's how to do it:
- Access the Discord Developer Portal: Go to Discord Developer Portal and log in with your Discord account.
- Create a new application: Click on «New Application» in the top right corner. Give your application a name and click on «Create».
- Configure the bot: From the menu on the left, select «Bot». Click «Add Bot» and confirm the action when prompted. Your Python Discord bot will be created and appear in the list of bots.
- Obtain the bot token: Under the «TOKEN» section, click «Copy» to copy the bot token. Keep this token in a safe place. It is crucial to authenticate your bot and allow it to interact with Discord.
- Assign permissions to the Discord bot in Python: In the «OAuth2» section, select «URL Generator». Under «OAuth2 URL Generator», select «bot» in the «Scopes» scope. In the «Bot Permissions» section, select the permissions your bot needs. For example, you can select «Send Messages», «Manage Roles», and «Read Message History». Copy the generated URL and paste it into your browser. Select the server where you want to add the bot and authorise the application.
- Configure bot intentions: In the «Bot» section, be sure to enable «Privileged Gateway Intents» if you plan to use functions that require them, such as detecting when members join or leave the server. Enable the required intents, such as «PRESENCE INTENT» and «SERVER MEMBERS INTENT».
Installation of required libraries
To create a Discord bot with Python, it is essential to have the right libraries to facilitate interaction with the Discord API and extend the capabilities of your bot. The main library we will use is `discord.py`, a powerful and easy-to-use tool that allows you to handle events, commands and many other Discord functions. In addition, there are other libraries that can be useful for specific tasks, such as making HTTP requests, manipulating images or managing databases. Let's see how to install and configure `discord.py`, as well as other tools that will help you create a more functional bot.
Install and configure Discord.py
To create a Discord bot with Python, we will use `discord.py`, a powerful library that makes it easy to interact with the Discord API. Here is the step-by-step to install and configure `discord.py`:
- Installation of discord.py: With your virtual environment activated, install `discord.py` using pip. Open your terminal and run the following command:
«`bash
pip install discord.py
«`
- Basic configuration: Create a new file for your bot, e.g. `bot.py`. Open this file in your favourite code editor. Import the necessary libraries and set up your bot instance:
«`python
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True # This is necessary to receive the content of the messages.
bot = commands.Bot(command_prefix=’!’, intents=intents)
@bot.event
async def on_ready():
print(f'{bot.user.name} is logged in.’)
@bot.command()
async def hello(ctx):
await ctx.send(‘Hello! How are you?’)
bot.run(‘YOUR_TOKEN_HERE’)
«`
- Run the bot: Replace `’YOUR_TOKEN_HERE’` with your bot token that you obtained from the Discord Developer Portal. Save the file and run the bot with the following command:
«`bash
python bot.py
«`
If everything is set up correctly, you will see a message in the console indicating that your bot is logged in. You can now test the `!hello` command on your Discord server to make sure the bot responds correctly.
Other tools to extend bot functionality
In addition to `discord.py`, there are several other libraries and tools that can help you extend the functionality of your Discord bot with Python. Here are some of the most useful ones:
- Requests: The `requests` library makes it easy to make HTTP requests. This is useful if your bot needs to interact with external APIs. Install it with pip:
«`bash
pip install requests
«`
- Example of use:
«`python
import requests
@bot.command()
async def gato(ctx):
response = requests.get(‘https://api.thecatapi.com/v1/images/search’)
data = response.json()
await ctx.send(data[0][‘url’])
«`
- BeautifulSoup: BeautifulSoup is excellent for scraping web data, allowing your bot to extract information from web pages. Install it with pip:
«`bash
pip install beautifulsoup4
«`
- Example of use:
«`python
from bs4 import BeautifulSoup
@bot.command()
async def news(ctx):
response = requests.get(‘https://example.com/news’)
soup = BeautifulSoup(response.text, ‘html.parser’)
headline = soup.find(‘h1’).text
await ctx.send(f'Latest news: {headline}’)
«`
- SQLAlchemy: If you need your bot to handle persistent data, `SQLAlchemy` is an excellent choice for interacting with SQL databases. Install it with pip:
«`bash
pip install sqlalchemy
«`
- Example of use:
«`python
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
engine = create_engine(‘sqlite:///bot.db’)
Base = declarative_base()
class User(Base):
__tablename__ = ‘users’ = 'users'.’
id = Column(Integer, primary_key=True)
name = Column(String)
points = Column(Integer, default=0)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
@bot.command()
async def points(ctx, points: int):
user = session.query(User).filter_by(name=ctx.author.name).first()
if not user:
user = User(name=ctx.author.name, points=points)
else:
user.points += points
session.add(user)
session.commit()
await ctx.send(f'{ctx.author.name} now has {user.points} points.’)
«`
- Pillow: Pillow is an image manipulation library that can be useful if your Python Discord bot needs to generate or edit images. Install it with pip:
«`bash
pip install pillow
«`
- Example of use:
«`python
from PIL import Image, ImageDraw, ImageFont
@bot.command()
async def image(ctx, text: str):
img = Image.new(‘RGB’, (200, 100), colour = (73, 109, 137))
d = ImageDraw.Draw(img)
font = ImageFont.load_default()
d.text((10,10), text, font=font, fill=(255, 255, 0))
img.save(‘image.png’)
await ctx.send(file=discord.File(‘image.png’))
«`
Writing bot code
With your development environment set up and the necessary libraries installed, it's time to tackle writing the code to answer the question how to create a Discord bot with Python.
This is the heart of bot development, where you define how the bot will behave, what commands it will respond to and how it will interact with users on your Discord server.
We will start with the basic structure of the code, making sure that the bot can connect and respond to simple commands.
Then, we'll delve into more complex event handling and commands to make your bot truly interactive and useful.
Are you ready to start programming?
Basic structure of the code
To start writing your Discord bot code in Python, it is important to understand the basic structure. Here's how to set up the skeleton of your bot:
- Imports and initial configuration: Import the necessary libraries and set up your bot instance.
«`python
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True # To receive message contents
bot = commands.Bot(command_prefix=’!’, intents=intents)
«`
- Event `on_ready`: This event is triggered when the bot successfully connects to Discord.
«`python
@bot.event
async def on_ready():
print(f'{bot.user.name} is logged in.’)
«`
- Basic commands: Define some basic commands to make sure the bot works properly.
«`python
@bot.command()
async def hello(ctx):
await ctx.send(‘Hello! How are you?’)
@bot.command()
async def adios(ctx):
await ctx.send(‘Goodbye! Have a nice day!’)
«`
- Execution of the bot: Finally, run the bot using the token you obtained from the Discord Developer Portal.
«`python
bot.run(‘YOUR_TOKEN_HERE’)
«`
Here is the complete code for the basic structure of your bot:
«`python
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix=’!’, intents=intents)
@bot.event
async def on_ready():
print(f'{bot.user.name} is logged in.’)
@bot.command()
async def hello(ctx):
await ctx.send(‘Hello! How are you?’)
@bot.command()
async def adios(ctx):
await ctx.send(‘Goodbye! Have a nice day!’)
bot.run(‘YOUR_TOKEN_HERE’)
«`
Handling of events and commands
Now that we have the basic structure, it's time to delve into event and command handling to make our bot more interactive and useful.
Events
Events allow the bot to respond to various actions on Discord, such as messages sent, users joining or leaving, etc. Here are some examples of common events:
- on_message: Triggered when a message is sent on a channel to which the bot has access.
«`python
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if ‘hello’ in message.content.lower():
await message.channel.send(‘Hello!’)
await bot.process_commands(message)
«`
- on_member_join: Activated when a new member joins a server.
«`python
@bot.event
async def on_member_join(member):
channel = discord.utils.get(member.guild.text_channels, name=’general’)
if channel:
await channel.send(f'Welcome to the server, {member.mention}!’)
«`
- on_member_remove: Activated when a member leaves the server.
«`python
@bot.event
async def on_member_remove(member):
channel = discord.utils.get(member.guild.text_channels, name=’general’)
if channel:
await channel.send(f'{member.mention} has left the server.’)
«`
Commands
Commands allow users to interact directly with the bot via text messages in Discord. Here are some examples of how to define and manage commands:
- Commands with arguments: A command that accepts arguments from the user.
«`python
@bot.command()
async def sum(ctx, a: int, b: int):
await ctx.send(f'The sum of {a} and {b} is {a + b}’)
«`
- Commands with permissions: A command that checks if the user has certain permissions before executing.
«`python
@bot.command()
@commands.has_permissions(manage_messages=True)
async def clean(ctx, quantity: int):
await ctx.channel.purge(limit=quantity + 1)
await ctx.send(f'{quantity} deleted messages.’, delete_after=5)
«`
- Customised commands: A command that responds with a custom message.
«`python
@bot.command()
async def info(ctx):
embed = discord.Embed(title=»Server Information», description=»Server Details», colour=0x00ff00)
embed.add_field(name=»Server», value=ctx.guild.name, inline=False)
embed.add_field(name=»Members», value=ctx.guild.member_count, inline=False)
await ctx.send(embed=embed)
«`
In order to make it as clear as possible, here is a complete example including events and commands:
«`python
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix=’!’, intents=intents)
@bot.event
async def on_ready():
print(f'{bot.user.name} is logged in.’)
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if ‘hello’ in message.content.lower():
await message.channel.send(‘Hello!’)
await bot.process_commands(message)
@bot.event
async def on_member_join(member):
channel = discord.utils.get(member.guild.text_channels, name=’general’)
if channel:
await channel.send(f'Welcome to the server, {member.mention}!’)
@bot.event
async def on_member_remove(member):
channel = discord.utils.get(member.guild.text_channels, name=’general’)
if channel:
await channel.send(f'{member.mention} has left the server.’)
@bot.command()
async def hello(ctx):
await ctx.send(‘Hello! How are you?’)
@bot.command()
async def adios(ctx):
await ctx.send(‘Goodbye! Have a nice day!’)
@bot.command()
async def sum(ctx, a: int, b: int):
await ctx.send(f'The sum of {a} and {b} is {a + b}’)
@bot.command()
@commands.has_permissions(manage_messages=True)
async def clean(ctx, quantity: int):
await ctx.channel.purge(limit=quantity + 1)
await ctx.send(f'{quantity} deleted messages.’, delete_after=5)
@bot.command()
async def info(ctx):
embed = discord.Embed(title=»Server Information», description=»Server Details», colour=0x00ff00)
embed.add_field(name=»Server», value=ctx.guild.name, inline=False)
embed.add_field(name=»Members», value=ctx.guild.member_count, inline=False)
await ctx.send(embed=embed)
bot.run(‘YOUR_TOKEN_HERE’)
«`
Bot deployment and testing
Once you have written the code for your Discord bot with Python and implemented its main functions, it is crucial to make sure everything is working properly before launching it. Deploying and testing the bot are essential steps to ensure its performance and reliability.
In this phase, you will connect your bot to a real Discord server, test its commands and functionality, and debug any issues that may arise. Thorough testing and effective debugging will help identify and fix bugs, thus improving the end-user experience.
Connecting to a Discord server
One of the last steps that will lead you to know how to create a Discord bot with Python is the connection to the server. For your bot to be available on your Discord server, you must invite it to the server and make sure it is online. To do this, you will need to follow these steps:
- Generate an invitation URL:
- Go to the [Discord Developer Portal](https://discord.com/developers/applications) and select your bot application.
- In the «OAuth2» section, select «URL Generator».
- Under «OAuth2 URL Generator», check the «bot» option in the «Scopes» field.
- Under «Bot Permissions», select the permissions your bot will need. For example, «Send Messages», «Manage Messages», and «Read Message History».
- Copy the generated URL.
- Invite the bot to the server:
- Paste the URL into your browser and select the server you want to add the bot to.
- Authorise the application to add the bot to your server.
- Check the connection:
- Once the bot is added to the server, you should see it in the server's member list.
- Run the bot locally (if it is not already running) with the following command in your terminal:
«`bash
python bot.py
«`
If the bot has successfully logged in, you should see a message in the console indicating that the bot is logged in. Try some of the commands you have set up, such as `!hello` or `!info`, to make sure the bot responds correctly.
Testing and debugging
Testing and debugging your Discord bot with Python is crucial to ensure that it works properly and provides a positive user experience. Let's take a look at some best practices for testing and debugging your bot:
- Testing of basic commands: Make sure that all commands you define respond correctly. For example, send `!hello` on your Discord server and check that the bot responds with «Hello! How are you?.
- Testing of permits: If you have commands that require specific permissions, test these commands with accounts that do and do not have the necessary permissions. For example, the `!clean` command should only work for users with message management permissions.
- Error handling: Implement error handlers to catch and respond to common errors. For example, if a user tries to use the `!add` command without providing numbers, the bot should handle the error appropriately:
«`python
@summar.error
async def sum_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send(‘Please provide two numbers to add.’)
«`
- Error and event logging: Use Python's `logging` module to log important errors and events. This will help you diagnose problems and better understand how your bot interacts with users.
«`python
import logging
logging.basicConfig(level=logging.INFO)
@bot.event
async def on_ready():
logging.info(f'{bot.user.name} is logged in.’)
@bot.event
async def on_command_error(ctx, error):
logging.error(f'Error in command {ctx.command}: {error}’)
await ctx.send(‘An error occurred. Please try again later.’)
«`
- Load and performance testing: Simulate the use of the bot under heavy load conditions to make sure it can handle multiple requests without problems. You can do this manually or use automated tools to send multiple commands at the same time.
- Integration tests: If your bot interacts with external APIs, make sure all integrations work correctly. Test different scenarios, such as successful responses and external API errors.
Here is a complete example including error handling and logging to improve debugging:
«`python
import discord
from discord.ext import commands
import logging
intents = discord.Intents.default()
intents.message_content = True
logging.basicConfig(level=logging.INFO)
bot = commands.Bot(command_prefix=’!’, intents=intents)
@bot.event
async def on_ready():
logging.info(f'{bot.user.name} is logged in.’)
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if ‘hello’ in message.content.lower():
await message.channel.send(‘Hello!’)
await bot.process_commands(message)
@bot.event
async def on_member_join(member):
channel = discord.utils.get(member.guild.text_channels, name=’general’)
if channel:
await channel.send(f'Welcome to the server, {member.mention}!’)
@bot.event
async def on_member_remove(member):
channel = discord.utils.get(member.guild.text_channels, name=’general’)
if channel:
await channel.send(f'{member.mention} has left the server.’)
@bot.command()
async def hello(ctx):
await ctx.send(‘Hello! How are you?’)
@bot.command()
async def adios(ctx):
await ctx.send(‘Goodbye! Have a nice day!’)
@bot.command()
async def sum(ctx, a: int, b: int):
await ctx.send(f'The sum of {a} and {b} is {a + b}’)
@summar.error
async def sum_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send(‘Please provide two numbers to add.’)
else:
logging.error(f'Error in add command: {error}’)
@bot.command()
@commands.has_permissions(manage_messages=True)
async def clean(ctx, quantity: int):
await ctx.channel.purge(limit=quantity + 1)
await ctx.send(f'{quantity} deleted messages.’, delete_after=5)
@bot.command()
async def info(ctx):
embed = discord.Embed(title=»Server Information», description=»Server Details», colour=0x00ff00)
embed.add_field(name=»Server», value=ctx.guild.name, inline=False)
embed.add_field(name=»Members», value=ctx.guild.member_count, inline=False)
await ctx.send(embed=embed)
@bot.event
async def on_command_error(ctx, error):
logging.error(f'Error in command {ctx.command}: {error}’)
await ctx.send(‘An error occurred. Please try again later.’)
bot.run(‘YOUR_TOKEN_HERE’)
«`
Conclusions
As we have seen, with Discord's steady growth as a communication platform, bots play a crucial role in automating tasks, moderating, and improving the user experience. Python, with its simple syntax and extensive `discord.py` library, presents itself as an excellent choice for this purpose.
In this sense, by following the steps described above you should be well prepared to create and deploy your own Discord bot in Python. Feel free to experiment with new features and additional libraries to expand your bot's capabilities. And always remember to test and debug thoroughly to ensure that your bot runs efficiently and smoothly in a real-world environment.
Knowing how to create a Discord bot with Python is a valuable skill that can open up many opportunities in the field of technology and community management. Good luck with your bot project and enjoy the development process!



