
本教程旨在解决 Discord.py 应用命令(斜杠命令)开发中常见的 `Context` 与 `Interaction` 对象混淆问题。我们将详细阐述这两种对象的核心区别,解释为何应用命令必须使用 `Interaction` 对象作为其第一个参数,并提供正确的代码示例及响应机制,确保您的斜杠命令能够正常运行并与用户进行有效交互。
在 Discord.py 库中,存在两种主要的命令类型:传统的前缀命令(由 commands.Bot 管理)和现代的应用命令,也称为斜杠命令(由 client.tree 管理)。这两种命令在设计哲学和内部实现上有所不同,尤其是在处理命令调用时的第一个参数上。
前缀命令 (Prefix Commands):当用户输入以特定前缀开头的命令时(例如 !marry @user),Discord.py 会创建一个 discord.ext.commands.Context 对象,其中包含了命令的所有上下文信息,如消息对象、频道、作者、Bot 实例等。命令函数会接收这个 Context 对象作为其第一个参数。
应用命令 (Application Commands / Slash Commands):当用户通过 Discord 的斜杠菜单选择并执行一个应用命令时(例如 /marry @user),Discord 会发送一个 Interaction 事件给 Bot。Discord.py 随后会封装这个事件,并创建一个 discord.interactions.Interaction 对象。这个 Interaction 对象包含了关于该次交互的所有信息,如交互类型、用户、频道、命令名称等。应用命令函数必须接收这个 Interaction 对象作为其第一个参数。
尽管 Context 和 Interaction 都提供了命令执行的上下文信息,但它们是完全不同的对象类型,拥有不同的属性和方法。
| 特性 | discord.ext.commands.Context (前缀命令) | discord.interactions.Interaction (应用命令) |
|---|---|---|
| 来源 | 用户发送的普通消息 | Discord 客户端触发的应用命令交互 |
| 第一个参数 | 通常命名为 ctx | 通常命名为 interaction |
| 获取作者 | ctx.author | interaction.user |
| 发送回复 | await ctx.reply(...) await ctx.send(...) |
await interaction.response.send_message(...) |
| 后续消息 | await ctx.send(...) | await interaction.followup.send(...) |
| 对象类型 | discord.ext.commands.Context | discord.interactions.Interaction |
混淆这两种对象是导致应用命令无法正常工作或报错的常见原因。
考虑以下一个尝试创建斜杠命令的示例代码:
import discord
from discord.ext import commands
import asyncio
import configure # 假设 configure 模块包含 token 和 name
intents = discord.Intents.all()
BOT_TOKEN = configure.config["token"]
client = commands.Bot(intents=intents, command_prefix="/") # command_prefix 在这里对斜杠命令无效,但对Bot实例创建是必需的
@client.event
async def on_ready():
print("Online")
try:
synced = await client.tree.sync()
print(f"Synced {len(synced)} commands")
except Exception as e:
print(e)
@client.tree.command(name='marry', description="Suggest to marry")
async def marry(ctx, user: discord.Member): # 错误:这里应该是 interaction
print(f'{ctx}||{user}')
# 错误:Interaction 对象没有 .reply() 方法
ctx.reply(f'{ctx.author} make a proposal to marry {user}')
return
async def main():
await client.start(BOT_TOKEN)
asyncio.run(main())当执行 /marry @rayanutka 命令时,print(f'{ctx}||{user}') 的输出会是 discord.interactions.Interaction object at 0x...||rayanutka。这明确指出,ctx 变量实际上是一个 Interaction 对象,而不是 Context 对象。因此,尝试调用 ctx.reply() 方法会导致运行时错误,因为 Interaction 对象没有名为 reply 的直接方法。
本文档主要讲述的是Python之模块学习;python是由一系列的模块组成的,每个模块就是一个py为后缀的文件,同时模块也是一个命名空间,从而避免了变量名称冲突的问题。模块我们就可以理解为lib库,如果需要使用某个模块中的函数或对象,则要导入这个模块才可以使用,除了系统默认的模块(内置函数)不需要导入外。希望本文档会给有需要的朋友带来帮助;感兴趣的朋友可以过来看看
2
另一个常见的错误尝试是向 client.tree.command 装饰器传递非法的关键字参数,例如 contextlib = True:
@client.tree.command(name='marry', description="Suggest to marry", contextlib = True) # 错误:contextlib 不是有效参数
async def marry(ctx, user: discord.Member):
# ...这会立即引发 TypeError: CommandTree.command() got an unexpected keyword argument 'contextlib'。这是因为 CommandTree.command() 装饰器只接受预定义的参数,而 contextlib 并非其中之一。
要正确地处理应用命令,您需要将命令函数中的第一个参数定义为 Interaction 对象,并使用 Interaction 对象提供的方法来响应。
以下是修正后的代码示例:
import discord
from discord.ext import commands
import asyncio
import configure # 假设 configure 模块包含 token 和 name
intents = discord.Intents.all()
BOT_TOKEN = configure.config["token"]
# 创建 Bot 实例。command_prefix 对于斜杠命令不是必需的,但通常需要指定
client = commands.Bot(intents=intents, command_prefix="!") # 可以是任意前缀,只要不为空
@client.event
async def on_ready():
print("Bot is Online")
try:
# 同步斜杠命令到 Discord
synced = await client.tree.sync()
print(f"Synced {len(synced)} commands globally")
except Exception as e:
print(f"Error syncing commands: {e}")
@client.tree.command(name='marry', description="Suggest to marry someone")
async def marry(interaction: discord.Interaction, user: discord.Member): # 正确:第一个参数是 Interaction
print(f'Interaction received from {interaction.user} in {interaction.channel} for {user}')
# 使用 interaction.response.send_message() 来发送初始回复
# interaction.user 获取发起交互的用户,而不是 interaction.author
# 注意:必须使用 await 关键字,因为这是异步操作
await interaction.response.send_message(
f'{interaction.user.mention} make a proposal to marry {user.mention}'
)
# 如果需要发送后续消息,可以使用 interaction.followup.send()
# await interaction.followup.send("This is a follow-up message!")
return
async def main():
# 可以在这里添加 setup 逻辑,例如加载 Cog
await client.start(BOT_TOKEN)
if __name__ == "__main__":
asyncio.run(main())关键修正点:
Discord.py 的应用命令(斜杠命令)与传统前缀命令在处理上下文信息时使用了不同的对象模型。核心在于,应用命令函数接收的是 discord.interactions.Interaction 对象,而非 discord.ext.commands.Context 对象。
以上就是Discord.py 应用命令:深入理解 Interaction 对象的使用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号