discord.py (Official Discord API Wrapper for Python)

2.3.2 · active · verified Thu Apr 16

discord.py is a modern, easy-to-use, feature-rich, and async-ready API wrapper for Discord written in Python. It simplifies interaction with the Discord API, enabling developers to create bots with various functionalities, from simple message responders to complex moderation tools. The library is actively maintained, with new releases typically following Discord API updates, and currently requires Python 3.8 or higher. [1, 2, 7]

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a basic Discord bot using `discord.ext.commands.Bot`. It includes essential setup like defining intents (crucial for `discord.py` v2.0+), handling the `on_ready` event, and a simple 'ping' command. Remember to enable the 'Message Content Intent' in your bot's settings on the Discord Developer Portal for the bot to read message content and process text commands. [3, 7, 16]

import discord
from discord.ext import commands
import os

# Configure intents: message_content is a privileged intent
intents = discord.Intents.default()
intents.message_content = True # Required for text commands that read message content [7]

# Initialize the bot with a command prefix and intents
bot = commands.Bot(command_prefix='!', intents=intents)

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user} (ID: {bot.user.id})')
    print('------')

@bot.command()
async def ping(ctx):
    """Responds with pong!"""
    await ctx.send('pong!')

@bot.event
async def on_message(message):
    # Ignore messages from the bot itself
    if message.author == bot.user:
        return

    # Process commands (needed if you also have on_message event handler)
    await bot.process_commands(message)

# Get the bot token from an environment variable for security
BOT_TOKEN = os.environ.get('DISCORD_BOT_TOKEN', 'YOUR_BOT_TOKEN_HERE')
if BOT_TOKEN == 'YOUR_BOT_TOKEN_HERE':
    print("WARNING: Replace 'YOUR_BOT_TOKEN_HERE' with your actual bot token or set DISCORD_BOT_TOKEN env var.")

# Run the bot
bot.run(BOT_TOKEN)

view raw JSON →