discord.py 2.1.0斜杠命令获取引用消息ID报错求助
Discord.py 2.1.0 斜杠命令翻译功能报错解决办法
错误原因分析
这个报错通常是因为在await表达式中调用了非异步函数/返回None的对象,或是混淆了discord.py 1.x前缀命令与2.x斜杠命令的写法导致的,核心问题点包括:
- 错误使用了旧版前缀命令的装饰器,未切换为斜杠命令专用装饰器
- 用了1.x的
Context上下文参数,而非2.x斜杠命令要求的Interaction对象 - 同步翻译函数未做异步处理,阻塞事件循环导致返回异常
新旧代码对比与修正方案
旧版1.7.3前缀命令代码(示例)
from discord.ext import commands import translators as ts class Translate(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def translate(self, ctx, *, text): result = ts.translate_text(text, to_language='en') await ctx.send(f"翻译结果:{result}") def setup(bot): bot.add_cog(Translate(bot))
错误的2.1.0斜杠命令代码(问题示例)
from discord.ext import commands import translators as ts class Translate(commands.Cog): def __init__(self, bot): self.bot = bot # 错误:仍使用旧版装饰器,且上下文参数与回复方式不匹配 @commands.command() async def translate(self, ctx, *, text: str): result = ts.translate_text(text, to_language='en') await ctx.response.send_message(f"翻译结果:{result}") def setup(bot): bot.add_cog(Translate(bot))
正确的2.1.0斜杠命令代码
from discord.ext import commands from discord import app_commands import translators as ts import asyncio class Translate(commands.Cog): def __init__(self, bot): self.bot = bot # 使用斜杠命令专用装饰器,指定命令名称与描述 @app_commands.command(name="translate", description="将文本翻译为英文") async def translate(self, interaction, text: str): # 同步翻译函数需包装到线程池,避免阻塞事件循环 loop = asyncio.get_event_loop() result = await loop.run_in_executor(None, ts.translate_text, text, 'en') # 用Interaction对象的response方法回复 await interaction.response.send_message(f"翻译结果:{result}") # 同步斜杠命令到Discord服务器 @commands.Cog.listener() async def on_ready(self): await self.bot.tree.sync() print("翻译斜杠命令已同步") def setup(bot): bot.add_cog(Translate(bot))
关键修正点
- 替换装饰器:将
@commands.command()改为@app_commands.command(),并补充命令名称和描述 - 更换上下文参数:把
ctx换成interaction,斜杠命令的上下文是Interaction对象而非旧版Context - 同步函数异步处理:如果翻译库是同步实现,必须用
asyncio.run_in_executor包装,防止阻塞事件循环(这是触发NoneType错误的高频原因) - 调整回复方式:用
await interaction.response.send_message()替代await ctx.send() - 命令同步:在
on_ready事件中执行await self.bot.tree.sync(),确保命令注册到Discord服务器
额外注意事项
- 若翻译库提供异步版本,优先使用异步方法,无需线程池包装
- 确保机器人邀请链接包含
scope=bot%20applications.commands权限 - 测试时可在
tree.sync()中指定guild=discord.Object(id=服务器ID),加快命令同步速度
内容的提问来源于stack exchange,提问作者Gianpi
相关产品推荐
相关产品推荐

