discord-py

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

discord.py Quick Reference

discord.py 快速参考

This skill provides guidance for building Discord bots with the discord.py library.
本技能提供使用discord.py库构建Discord机器人的指导。

Quick Start: Minimal Bot

快速入门:最简机器人

python
import discord

intents = discord.Intents.default()
intents.message_content = True  # Required for reading message content

client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print(f'Logged in as {client.user}')

@client.event
async def on_message(message):
    if message.author == client.user:
        return  # Ignore self
    if message.content.startswith('$hello'):
        await message.channel.send('Hello!')

client.run('YOUR_BOT_TOKEN')
Important: Never name your file
discord.py
- it conflicts with the library.
python
import discord

intents = discord.Intents.default()
intents.message_content = True  # Required for reading message content

client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print(f'Logged in as {client.user}')

@client.event
async def on_message(message):
    if message.author == client.user:
        return  # Ignore self
    if message.content.startswith('$hello'):
        await message.channel.send('Hello!')

client.run('YOUR_BOT_TOKEN')
重要提示:请勿将你的文件命名为
discord.py
——这会与库本身冲突。

Critical: Intents Setup

关键配置:Intents设置

Intents are required in discord.py 2.0+. They control which events your bot receives.
在discord.py 2.0及以上版本中,Intents是必填项。它们控制机器人可以接收哪些事件。

Basic Setup

基础配置

python
intents = discord.Intents.default()  # Common intents, excludes privileged
python
intents = discord.Intents.default()  # 常用Intents,不包含特权Intents

Enabling Specific Intents

启用特定Intents

python
intents = discord.Intents.default()
intents.message_content = True  # Read message text (privileged)
intents.members = True          # Member join/leave events (privileged)
intents.presences = True        # Status updates (privileged)
python
intents = discord.Intents.default()
intents.message_content = True  # 读取消息文本(特权Intents)
intents.members = True          # 成员加入/离开事件(特权Intents)
intents.presences = True        # 状态更新(特权Intents)

Privileged Intents Require Portal Setup

特权Intents需要在开发者门户中配置

These three intents must ALSO be enabled in the Discord Developer Portal:
  1. Message Content Intent - Required for reading message text
  2. Server Members Intent - Required for member events and accurate member lists
  3. Presence Intent - Required for tracking user status/activity
Go to: Discord Developer Portal > Your App > Bot > Privileged Gateway Intents
以下三个Intents还必须在Discord开发者门户中启用:
  1. Message Content Intent - 读取消息文本所需
  2. Server Members Intent - 成员事件和准确成员列表所需
  3. Presence Intent - 跟踪用户状态/活动所需
访问路径:Discord开发者门户 > 你的应用 > Bot > Privileged Gateway Intents

Client vs Bot

Client vs Bot

Use CaseClassImport
Basic events, no commands
Client
discord.Client
Prefix commands (!help)
Bot
commands.Bot
Slash commandsEither +
CommandTree
app_commands
使用场景导入方式
基础事件,无命令
Client
discord.Client
前缀命令(如!help)
Bot
commands.Bot
斜杠命令任意一种 +
CommandTree
app_commands

When to Use Bot (commands extension)

何时使用Bot(commands扩展)

python
from discord.ext import commands

intents = discord.Intents.default()
intents.message_content = True

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

@bot.command()
async def ping(ctx):
    await ctx.send('Pong!')

bot.run('TOKEN')
python
from discord.ext import commands

intents = discord.Intents.default()
intents.message_content = True

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

@bot.command()
async def ping(ctx):
    await ctx.send('Pong!')

bot.run('TOKEN')

Event Handling

事件处理

Common events (decorate with
@client.event
or
@bot.event
):
EventWhen it fires
on_ready()
Bot connected and cache ready
on_message(message)
Message received
on_member_join(member)
User joined guild (needs members intent)
on_member_remove(member)
User left guild
on_reaction_add(reaction, user)
Reaction added
on_guild_join(guild)
Bot joined a server
on_error(event, *args)
Uncaught exception in event
常见事件(使用
@client.event
@bot.event
装饰):
事件触发时机
on_ready()
机器人连接成功且缓存就绪
on_message(message)
收到消息时
on_member_join(member)
用户加入服务器(需要members intent)
on_member_remove(member)
用户离开服务器时
on_reaction_add(reaction, user)
收到表情反应时
on_guild_join(guild)
机器人加入服务器时
on_error(event, *args)
事件中出现未捕获的异常时

Commands Extension Basics

Commands扩展基础

python
from discord.ext import commands

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

@bot.command()
async def greet(ctx, name: str):
    """Greet someone by name."""
    await ctx.send(f'Hello, {name}!')

@bot.command(name='add')
async def add_numbers(ctx, a: int, b: int):
    """Add two numbers."""
    await ctx.send(f'{a} + {b} = {a + b}')
python
from discord.ext import commands

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

@bot.command()
async def greet(ctx, name: str):
    """Greet someone by name."""
    await ctx.send(f'Hello, {name}!')

@bot.command(name='add')
async def add_numbers(ctx, a: int, b: int):
    """Add two numbers."""
    await ctx.send(f'{a} + {b} = {a + b}')

Command Groups

命令组

python
@bot.group()
async def settings(ctx):
    if ctx.invoked_subcommand is None:
        await ctx.send('Use !settings <subcommand>')

@settings.command()
async def show(ctx):
    await ctx.send('Current settings: ...')
python
@bot.group()
async def settings(ctx):
    if ctx.invoked_subcommand is None:
        await ctx.send('Use !settings <subcommand>')

@settings.command()
async def show(ctx):
    await ctx.send('Current settings: ...')

Slash Commands Basics

斜杠命令基础

python
import discord
from discord import app_commands

intents = discord.Intents.default()
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)

@tree.command(name='ping', description='Check bot latency')
async def ping(interaction: discord.Interaction):
    await interaction.response.send_message(f'Pong! {round(client.latency * 1000)}ms')

@client.event
async def on_ready():
    await tree.sync()  # Sync commands with Discord
    print(f'Synced commands for {client.user}')

client.run('TOKEN')
python
import discord
from discord import app_commands

intents = discord.Intents.default()
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)

@tree.command(name='ping', description='Check bot latency')
async def ping(interaction: discord.Interaction):
    await interaction.response.send_message(f'Pong! {round(client.latency * 1000)}ms')

@client.event
async def on_ready():
    await tree.sync()  # Sync commands with Discord
    print(f'Synced commands for {client.user}')

client.run('TOKEN')

Slash Command with Parameters

带参数的斜杠命令

python
@tree.command(name='greet', description='Greet a user')
@app_commands.describe(user='The user to greet')
async def greet(interaction: discord.Interaction, user: discord.Member):
    await interaction.response.send_message(f'Hello, {user.mention}!')
python
@tree.command(name='greet', description='Greet a user')
@app_commands.describe(user='The user to greet')
async def greet(interaction: discord.Interaction, user: discord.Member):
    await interaction.response.send_message(f'Hello, {user.mention}!')

Sending Messages

发送消息

python
undefined
python
undefined

In event handler

在事件处理器中

await message.channel.send('Hello!') await message.channel.send('With embed', embed=embed) await message.channel.send('With file', file=discord.File('image.png'))
await message.channel.send('Hello!') await message.channel.send('With embed', embed=embed) await message.channel.send('With file', file=discord.File('image.png'))

Reply to message

回复消息

await message.reply('Replying to you!')
await message.reply('Replying to you!')

In slash command

在斜杠命令中

await interaction.response.send_message('Response') await interaction.response.send_message('Only you see this', ephemeral=True)
await interaction.response.send_message('Response') await interaction.response.send_message('Only you see this', ephemeral=True)

Edit/followup for slash commands

斜杠命令的编辑/后续回复

await interaction.response.defer() await interaction.followup.send('Delayed response')
undefined
await interaction.response.defer() await interaction.followup.send('Delayed response')
undefined

Common Patterns

常见模式

Check if Message Author is Bot Owner

检查消息发送者是否为机器人所有者

python
@bot.command()
@commands.is_owner()
async def shutdown(ctx):
    await ctx.send('Shutting down...')
    await bot.close()
python
@bot.command()
@commands.is_owner()
async def shutdown(ctx):
    await ctx.send('Shutting down...')
    await bot.close()

Permission Checks

权限检查

python
@bot.command()
@commands.has_permissions(manage_messages=True)
async def clear(ctx, amount: int):
    await ctx.channel.purge(limit=amount + 1)
python
@bot.command()
@commands.has_permissions(manage_messages=True)
async def clear(ctx, amount: int):
    await ctx.channel.purge(limit=amount + 1)

Error Handling

错误处理

python
@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send('You lack permissions for this command.')
    elif isinstance(error, commands.CommandNotFound):
        pass  # Ignore unknown commands
    else:
        raise error
python
@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send('You lack permissions for this command.')
    elif isinstance(error, commands.CommandNotFound):
        pass  # Ignore unknown commands
    else:
        raise error

Fetching Latest Documentation

获取最新文档

When you need up-to-date API details or are unsure about a feature, fetch the official documentation:
undefined
当你需要最新的API细节或对某个功能不确定时,请获取官方文档:
undefined

Core API reference

核心API参考

Commands extension

Commands扩展

Slash commands (app_commands)

斜杠命令(app_commands)

Intents guide

Intents指南

Quickstart guide

快速入门指南

Frequently asked questions

常见问题


Always fetch documentation when:
- The user asks about a feature not covered in this skill
- You need to verify exact method signatures or parameters
- Working with less common features (webhooks, voice, threads)
- The user reports behavior different from what you expect

**Note**: Forum channels are documented in [reference.md](reference.md#forum-channels) with examples in [examples.md](examples.md#forum-channel-operations).

在以下情况时请务必获取文档:
- 用户询问本技能未涵盖的功能
- 你需要验证确切的方法签名或参数
- 处理不太常见的功能(如webhooks、语音、线程)
- 用户报告的行为与预期不符

**注意**:论坛频道的相关文档在[reference.md](reference.md#forum-channels)中,示例代码在[examples.md](examples.md#forum-channel-operations)中。

Additional Resources

额外资源