discord-py
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesediscord.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 - it conflicts with the library.
discord.pypython
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.pyCritical: 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 privilegedpython
intents = discord.Intents.default() # 常用Intents,不包含特权IntentsEnabling 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:
- Message Content Intent - Required for reading message text
- Server Members Intent - Required for member events and accurate member lists
- Presence Intent - Required for tracking user status/activity
Go to: Discord Developer Portal > Your App > Bot > Privileged Gateway Intents
以下三个Intents还必须在Discord开发者门户中启用:
- Message Content Intent - 读取消息文本所需
- Server Members Intent - 成员事件和准确成员列表所需
- Presence Intent - 跟踪用户状态/活动所需
访问路径:Discord开发者门户 > 你的应用 > Bot > Privileged Gateway Intents
Client vs Bot
Client vs Bot
| Use Case | Class | Import |
|---|---|---|
| Basic events, no commands | | |
| Prefix commands (!help) | | |
| Slash commands | Either + | |
| 使用场景 | 类 | 导入方式 |
|---|---|---|
| 基础事件,无命令 | | |
| 前缀命令(如!help) | | |
| 斜杠命令 | 任意一种 + | |
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 or ):
@client.event@bot.event| Event | When it fires |
|---|---|
| Bot connected and cache ready |
| Message received |
| User joined guild (needs members intent) |
| User left guild |
| Reaction added |
| Bot joined a server |
| Uncaught exception in event |
常见事件(使用或装饰):
@client.event@bot.event| 事件 | 触发时机 |
|---|---|
| 机器人连接成功且缓存就绪 |
| 收到消息时 |
| 用户加入服务器(需要members intent) |
| 用户离开服务器时 |
| 收到表情反应时 |
| 机器人加入服务器时 |
| 事件中出现未捕获的异常时 |
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
undefinedpython
undefinedIn 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')
undefinedawait interaction.response.defer()
await interaction.followup.send('Delayed response')
undefinedCommon 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 errorpython
@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 errorFetching Latest Documentation
获取最新文档
When you need up-to-date API details or are unsure about a feature, fetch the official documentation:
undefined当你需要最新的API细节或对某个功能不确定时,请获取官方文档:
undefinedCore 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
额外资源
- For detailed API reference, see reference.md
- For complete code examples, see examples.md
- Official docs: https://discordpy.readthedocs.io/en/latest/
- 详细API参考请见reference.md
- 完整代码示例请见examples.md
- 官方文档:https://discordpy.readthedocs.io/en/latest/