Discord.py
Discord.py is a modern, easy to use, feature-rich, and async ready API wrapper for Discord, written in Python. The current version is 2.7.1, and it is actively maintained with regular updates to support Discord API changes and new features.
Warnings
- breaking Discord.py v2.0 and later require Python 3.8 or higher. Projects on older Python versions must upgrade to use the latest library features.
- breaking Gateway Intents are now a mandatory keyword argument for `discord.Client` and `discord.ext.commands.Bot` instances. Failing to provide them will raise an error.
- breaking The `message_content` intent is now a privileged intent. To access `message.content`, `message.embeds`, or `message.attachments`, this intent must be enabled both in your bot's code (`intents.message_content = True`) and on the Discord Developer Portal.
- breaking User account (self-bot) support has been completely removed in v2.0 due to violations of Discord's Terms of Service.
- breaking The `Client.logout()` method has been removed. Use `Client.close()` instead to properly close the connection to Discord.
- gotcha Do not name your bot's Python file `discord.py` as this will cause import conflicts with the library itself.
- gotcha Your bot token is a sensitive secret. Never hardcode it directly in your code or share it publicly. Use environment variables (e.g., `os.environ.get('DISCORD_TOKEN')`) to store and retrieve it securely.
Install
-
pip install -U discord.py -
pip install -U "discord.py[voice]"
Imports
- Client
import discord client = discord.Client(intents=...)
- Bot
from discord.ext import commands bot = commands.Bot(command_prefix='!', intents=...)
- Intents
intents = discord.Intents.default() intents.message_content = True
Quickstart
import os
import discord
intents = discord.Intents.default()
intents.message_content = True # Required for on_message to access message.content
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
# Replace 'YOUR_BOT_TOKEN' with your actual bot token, ideally from environment variables.
# Ensure DISCORD_TOKEN is set in your environment for production.
client.run(os.environ.get('DISCORD_TOKEN', 'YOUR_BOT_TOKEN'))