From 8babc7ea1cef0835830e28e174c05611d97e16c7 Mon Sep 17 00:00:00 2001 From: Real Python Bot <42617967+realpython-bot@users.noreply.github.com> Date: Sat, 5 Dec 2026 22:19:01 +0000 Subject: [PATCH] Add how-to-make-a-discord-bot-python materials folder Companion code for the updated How to Make a Discord Bot in Python tutorial (discord.py 2.7.1, python-dotenv 1.2.4). Co-Authored-By: Claude Opus 5.5 --- how-to-make-a-discord-bot-python/.env.example | 2 + .../01_connect.py | 18 ++++++ .../02_guild_info.py | 26 ++++++++ .../03_guild_members.py | 30 ++++++++++ .../04_utils_find.py | 23 ++++++++ .../05_utils_get.py | 23 ++++++++ .../06_custom_client.py | 17 ++++++ .../07_welcome_members.py | 27 +++++++++ .../08_respond_to_messages.py | 48 +++++++++++++++ .../09_raise_exception.py | 50 ++++++++++++++++ .../10_handle_exceptions.py | 59 +++++++++++++++++++ .../11_bot_connect.py | 22 +++++++ .../12_bot_commands.py | 40 +++++++++++++ .../13_bot_checks.py | 31 ++++++++++ how-to-make-a-discord-bot-python/README.md | 49 +++++++++++++++ .../requirements.txt | 2 + 16 files changed, 467 insertions(+) create mode 100644 how-to-make-a-discord-bot-python/.env.example create mode 100644 how-to-make-a-discord-bot-python/01_connect.py create mode 100644 how-to-make-a-discord-bot-python/02_guild_info.py create mode 100644 how-to-make-a-discord-bot-python/03_guild_members.py create mode 100644 how-to-make-a-discord-bot-python/04_utils_find.py create mode 100644 how-to-make-a-discord-bot-python/05_utils_get.py create mode 100644 how-to-make-a-discord-bot-python/06_custom_client.py create mode 100644 how-to-make-a-discord-bot-python/07_welcome_members.py create mode 100644 how-to-make-a-discord-bot-python/08_respond_to_messages.py create mode 100644 how-to-make-a-discord-bot-python/09_raise_exception.py create mode 100644 how-to-make-a-discord-bot-python/10_handle_exceptions.py create mode 100644 how-to-make-a-discord-bot-python/11_bot_connect.py create mode 100644 how-to-make-a-discord-bot-python/12_bot_commands.py create mode 100644 how-to-make-a-discord-bot-python/13_bot_checks.py create mode 100644 how-to-make-a-discord-bot-python/README.md create mode 100644 how-to-make-a-discord-bot-python/requirements.txt diff --git a/how-to-make-a-discord-bot-python/.env.example b/how-to-make-a-discord-bot-python/.env.example new file mode 100644 index 0000000000..ed3ad10a4a --- /dev/null +++ b/how-to-make-a-discord-bot-python/.env.example @@ -0,0 +1,2 @@ +DISCORD_TOKEN={your-bot-token} +DISCORD_GUILD={your-guild-name} diff --git a/how-to-make-a-discord-bot-python/01_connect.py b/how-to-make-a-discord-bot-python/01_connect.py new file mode 100644 index 0000000000..7dd1498ab5 --- /dev/null +++ b/how-to-make-a-discord-bot-python/01_connect.py @@ -0,0 +1,18 @@ +import os + +import discord +from dotenv import load_dotenv + +load_dotenv() +TOKEN = os.getenv("DISCORD_TOKEN") + +intents = discord.Intents.default() +client = discord.Client(intents=intents) + + +@client.event +async def on_ready(): + print(f"{client.user} has connected to Discord!") + + +client.run(TOKEN) diff --git a/how-to-make-a-discord-bot-python/02_guild_info.py b/how-to-make-a-discord-bot-python/02_guild_info.py new file mode 100644 index 0000000000..7fef7d6c5c --- /dev/null +++ b/how-to-make-a-discord-bot-python/02_guild_info.py @@ -0,0 +1,26 @@ +import os + +import discord +from dotenv import load_dotenv + +load_dotenv() +TOKEN = os.getenv("DISCORD_TOKEN") +GUILD = os.getenv("DISCORD_GUILD") + +intents = discord.Intents.default() +client = discord.Client(intents=intents) + + +@client.event +async def on_ready(): + for guild in client.guilds: + if guild.name == GUILD: + break + + print( + f"{client.user} is connected to the following guild:\n" + f"{guild.name}(id: {guild.id})" + ) + + +client.run(TOKEN) diff --git a/how-to-make-a-discord-bot-python/03_guild_members.py b/how-to-make-a-discord-bot-python/03_guild_members.py new file mode 100644 index 0000000000..fdb27fc40b --- /dev/null +++ b/how-to-make-a-discord-bot-python/03_guild_members.py @@ -0,0 +1,30 @@ +import os + +import discord +from dotenv import load_dotenv + +load_dotenv() +TOKEN = os.getenv("DISCORD_TOKEN") +GUILD = os.getenv("DISCORD_GUILD") + +intents = discord.Intents.default() +intents.members = True +client = discord.Client(intents=intents) + + +@client.event +async def on_ready(): + for guild in client.guilds: + if guild.name == GUILD: + break + + print( + f"{client.user} is connected to the following guild:\n" + f"{guild.name}(id: {guild.id})\n" + ) + + members = "\n - ".join([member.name for member in guild.members]) + print(f"Guild Members:\n - {members}") + + +client.run(TOKEN) diff --git a/how-to-make-a-discord-bot-python/04_utils_find.py b/how-to-make-a-discord-bot-python/04_utils_find.py new file mode 100644 index 0000000000..350c59b488 --- /dev/null +++ b/how-to-make-a-discord-bot-python/04_utils_find.py @@ -0,0 +1,23 @@ +import os + +import discord +from dotenv import load_dotenv + +load_dotenv() +TOKEN = os.getenv("DISCORD_TOKEN") +GUILD = os.getenv("DISCORD_GUILD") + +intents = discord.Intents.default() +client = discord.Client(intents=intents) + + +@client.event +async def on_ready(): + guild = discord.utils.find(lambda g: g.name == GUILD, client.guilds) + print( + f"{client.user} is connected to the following guild:\n" + f"{guild.name}(id: {guild.id})" + ) + + +client.run(TOKEN) diff --git a/how-to-make-a-discord-bot-python/05_utils_get.py b/how-to-make-a-discord-bot-python/05_utils_get.py new file mode 100644 index 0000000000..2f43440c37 --- /dev/null +++ b/how-to-make-a-discord-bot-python/05_utils_get.py @@ -0,0 +1,23 @@ +import os + +import discord +from dotenv import load_dotenv + +load_dotenv() +TOKEN = os.getenv("DISCORD_TOKEN") +GUILD = os.getenv("DISCORD_GUILD") + +intents = discord.Intents.default() +client = discord.Client(intents=intents) + + +@client.event +async def on_ready(): + guild = discord.utils.get(client.guilds, name=GUILD) + print( + f"{client.user} is connected to the following guild:\n" + f"{guild.name}(id: {guild.id})" + ) + + +client.run(TOKEN) diff --git a/how-to-make-a-discord-bot-python/06_custom_client.py b/how-to-make-a-discord-bot-python/06_custom_client.py new file mode 100644 index 0000000000..083c4fab51 --- /dev/null +++ b/how-to-make-a-discord-bot-python/06_custom_client.py @@ -0,0 +1,17 @@ +import os + +import discord +from dotenv import load_dotenv + +load_dotenv() +TOKEN = os.getenv("DISCORD_TOKEN") + + +class CustomClient(discord.Client): + async def on_ready(self): + print(f"{self.user} has connected to Discord!") + + +intents = discord.Intents.default() +client = CustomClient(intents=intents) +client.run(TOKEN) diff --git a/how-to-make-a-discord-bot-python/07_welcome_members.py b/how-to-make-a-discord-bot-python/07_welcome_members.py new file mode 100644 index 0000000000..bccc190e17 --- /dev/null +++ b/how-to-make-a-discord-bot-python/07_welcome_members.py @@ -0,0 +1,27 @@ +import os + +import discord +from dotenv import load_dotenv + +load_dotenv() +TOKEN = os.getenv("DISCORD_TOKEN") + +intents = discord.Intents.default() +intents.members = True +client = discord.Client(intents=intents) + + +@client.event +async def on_ready(): + print(f"{client.user.name} has connected to Discord!") + + +@client.event +async def on_member_join(member): + await member.create_dm() + await member.dm_channel.send( + f"Hi {member.name}, welcome to my Discord server!" + ) + + +client.run(TOKEN) diff --git a/how-to-make-a-discord-bot-python/08_respond_to_messages.py b/how-to-make-a-discord-bot-python/08_respond_to_messages.py new file mode 100644 index 0000000000..88460cbe2d --- /dev/null +++ b/how-to-make-a-discord-bot-python/08_respond_to_messages.py @@ -0,0 +1,48 @@ +import os +import random + +import discord +from dotenv import load_dotenv + +load_dotenv() +TOKEN = os.getenv("DISCORD_TOKEN") + +intents = discord.Intents.default() +intents.members = True +intents.message_content = True +client = discord.Client(intents=intents) + + +@client.event +async def on_ready(): + print(f"{client.user.name} has connected to Discord!") + + +@client.event +async def on_member_join(member): + await member.create_dm() + await member.dm_channel.send( + f"Hi {member.name}, welcome to my Discord server!" + ) + + +@client.event +async def on_message(message): + if message.author == client.user: + return + + brooklyn_99_quotes = [ + "I'm the human form of the 💯 emoji.", + "Bingpot!", + ( + "Cool. Cool cool cool cool cool cool cool, " + "no doubt no doubt no doubt no doubt." + ), + ] + + if message.content == "99!": + response = random.choice(brooklyn_99_quotes) + await message.channel.send(response) + + +client.run(TOKEN) diff --git a/how-to-make-a-discord-bot-python/09_raise_exception.py b/how-to-make-a-discord-bot-python/09_raise_exception.py new file mode 100644 index 0000000000..9be0a16ed1 --- /dev/null +++ b/how-to-make-a-discord-bot-python/09_raise_exception.py @@ -0,0 +1,50 @@ +import os +import random + +import discord +from dotenv import load_dotenv + +load_dotenv() +TOKEN = os.getenv("DISCORD_TOKEN") + +intents = discord.Intents.default() +intents.members = True +intents.message_content = True +client = discord.Client(intents=intents) + + +@client.event +async def on_ready(): + print(f"{client.user.name} has connected to Discord!") + + +@client.event +async def on_member_join(member): + await member.create_dm() + await member.dm_channel.send( + f"Hi {member.name}, welcome to my Discord server!" + ) + + +@client.event +async def on_message(message): + if message.author == client.user: + return + + brooklyn_99_quotes = [ + "I'm the human form of the 💯 emoji.", + "Bingpot!", + ( + "Cool. Cool cool cool cool cool cool cool, " + "no doubt no doubt no doubt no doubt." + ), + ] + + if message.content == "99!": + response = random.choice(brooklyn_99_quotes) + await message.channel.send(response) + elif message.content == "raise-exception": + raise discord.DiscordException + + +client.run(TOKEN) diff --git a/how-to-make-a-discord-bot-python/10_handle_exceptions.py b/how-to-make-a-discord-bot-python/10_handle_exceptions.py new file mode 100644 index 0000000000..db17f563af --- /dev/null +++ b/how-to-make-a-discord-bot-python/10_handle_exceptions.py @@ -0,0 +1,59 @@ +import os +import random + +import discord +from dotenv import load_dotenv + +load_dotenv() +TOKEN = os.getenv("DISCORD_TOKEN") + +intents = discord.Intents.default() +intents.members = True +intents.message_content = True +client = discord.Client(intents=intents) + + +@client.event +async def on_ready(): + print(f"{client.user.name} has connected to Discord!") + + +@client.event +async def on_member_join(member): + await member.create_dm() + await member.dm_channel.send( + f"Hi {member.name}, welcome to my Discord server!" + ) + + +@client.event +async def on_message(message): + if message.author == client.user: + return + + brooklyn_99_quotes = [ + "I'm the human form of the 💯 emoji.", + "Bingpot!", + ( + "Cool. Cool cool cool cool cool cool cool, " + "no doubt no doubt no doubt no doubt." + ), + ] + + if message.content == "99!": + response = random.choice(brooklyn_99_quotes) + await message.channel.send(response) + elif message.content == "raise-exception": + raise discord.DiscordException + + +@client.event +async def on_error(event, *args, **kwargs): + with open("err.log", "a") as f: + if event == "on_message": + f.write(f"Unhandled message: {args[0]}\n") + else: + raise + + +client.run(TOKEN) diff --git a/how-to-make-a-discord-bot-python/11_bot_connect.py b/how-to-make-a-discord-bot-python/11_bot_connect.py new file mode 100644 index 0000000000..128de25231 --- /dev/null +++ b/how-to-make-a-discord-bot-python/11_bot_connect.py @@ -0,0 +1,22 @@ +import os +from dotenv import load_dotenv + +# 1 +import discord +from discord.ext import commands + +load_dotenv() +TOKEN = os.getenv("DISCORD_TOKEN") + +# 2 +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} has connected to Discord!") + + +bot.run(TOKEN) diff --git a/how-to-make-a-discord-bot-python/12_bot_commands.py b/how-to-make-a-discord-bot-python/12_bot_commands.py new file mode 100644 index 0000000000..de99cac47e --- /dev/null +++ b/how-to-make-a-discord-bot-python/12_bot_commands.py @@ -0,0 +1,40 @@ +import os +import random + +import discord +from discord.ext import commands +from dotenv import load_dotenv + +load_dotenv() +TOKEN = os.getenv("DISCORD_TOKEN") + +intents = discord.Intents.default() +intents.message_content = True +bot = commands.Bot(command_prefix="!", intents=intents) + + +@bot.command(name="99", help="Responds with a random quote from Brooklyn 99") +async def nine_nine(ctx): + brooklyn_99_quotes = [ + "I'm the human form of the 💯 emoji.", + "Bingpot!", + ( + "Cool. Cool cool cool cool cool cool cool, " + "no doubt no doubt no doubt no doubt." + ), + ] + + response = random.choice(brooklyn_99_quotes) + await ctx.send(response) + + +@bot.command(name="roll_dice", help="Simulates rolling dice.") +async def roll(ctx, number_of_dice: int, number_of_sides: int): + dice = [ + str(random.choice(range(1, number_of_sides + 1))) + for _ in range(number_of_dice) + ] + await ctx.send(", ".join(dice)) + + +bot.run(TOKEN) diff --git a/how-to-make-a-discord-bot-python/13_bot_checks.py b/how-to-make-a-discord-bot-python/13_bot_checks.py new file mode 100644 index 0000000000..7f4bb70050 --- /dev/null +++ b/how-to-make-a-discord-bot-python/13_bot_checks.py @@ -0,0 +1,31 @@ +import os + +import discord +from discord.ext import commands +from dotenv import load_dotenv + +load_dotenv() +TOKEN = os.getenv("DISCORD_TOKEN") + +intents = discord.Intents.default() +intents.message_content = True +bot = commands.Bot(command_prefix="!", intents=intents) + + +@bot.command(name="create-channel") +@commands.has_role("admin") +async def create_channel(ctx, channel_name="real-python"): + guild = ctx.guild + existing_channel = discord.utils.get(guild.channels, name=channel_name) + if not existing_channel: + print(f"Creating a new channel: {channel_name}") + await guild.create_text_channel(channel_name) + + +@bot.event +async def on_command_error(ctx, error): + if isinstance(error, commands.errors.CheckFailure): + await ctx.send("You do not have the correct role for this command.") + + +bot.run(TOKEN) diff --git a/how-to-make-a-discord-bot-python/README.md b/how-to-make-a-discord-bot-python/README.md new file mode 100644 index 0000000000..06d92a9155 --- /dev/null +++ b/how-to-make-a-discord-bot-python/README.md @@ -0,0 +1,49 @@ +# How to Make a Discord Bot in Python + +This folder contains the code for the Real Python tutorial [How to Make a Discord Bot in Python](https://realpython.com/how-to-make-a-discord-bot-python/). + +## Setup + +You need Python 3.8 or later. The code was tested on Python 3.14 and 3.15. + +Create and activate a [virtual environment](https://realpython.com/python-virtual-environments-a-primer/), then install the pinned dependencies: + +```sh +$ python -m venv venv +$ source venv/bin/activate +(venv) $ python -m pip install -r requirements.txt +``` + +Follow the tutorial to create an application, a bot user, and a guild in the [Discord Developer Portal](https://discord.com/developers/applications). On the bot's *Bot* page, switch on *Server Members Intent* and *Message Content Intent* under *Privileged Gateway Intents*. + +Then copy `.env.example` to `.env` and fill in your bot's token and your guild's name: + +```sh +(venv) $ cp .env.example .env +``` + +Never commit your `.env` file, because the token is your bot's password. + +## Usage + +Each script matches one stage of the tutorial. Run any of them from this folder: + +```sh +(venv) $ python 01_connect.py +``` + +- `01_connect.py`: connects a `Client` to Discord +- `02_guild_info.py`: prints the name and ID of your guild +- `03_guild_members.py`: lists the guild's members (needs the members intent) +- `04_utils_find.py`: finds the guild with `discord.utils.find()` +- `05_utils_get.py`: finds the guild with `discord.utils.get()` +- `06_custom_client.py`: handles `on_ready()` in a `Client` subclass +- `07_welcome_members.py`: sends a direct message to new members +- `08_respond_to_messages.py`: answers `99!` with a Brooklyn Nine-Nine quote +- `09_raise_exception.py`: raises a `DiscordException` when someone types `raise-exception` +- `10_handle_exceptions.py`: writes those errors to `err.log` with a custom `on_error()` +- `11_bot_connect.py`: connects a `commands.Bot` instead of a `Client` +- `12_bot_commands.py`: adds the `!99` and `!roll_dice` commands with converters +- `13_bot_checks.py`: adds `!create-channel`, which requires the `admin` role + +Stop a running bot with Ctrl+C. diff --git a/how-to-make-a-discord-bot-python/requirements.txt b/how-to-make-a-discord-bot-python/requirements.txt new file mode 100644 index 0000000000..9760e2b8eb --- /dev/null +++ b/how-to-make-a-discord-bot-python/requirements.txt @@ -0,0 +1,2 @@ +discord.py==2.7.1 +python-dotenv==1.2.4