discord.py:将命令定义在独立文件中时命令无法正常执行的问题求助
解决discord.py扩展中命令无法触发的问题
你的问题主要出在命令函数的参数定义上,还有可能是Intents配置不完整,我来帮你一步步修复:
1. 修正命令函数的参数
discord.py 中用@commands.command()装饰的函数,第一个参数必须是commands.Context对象(通常命名为ctx),而不是直接传message。你原来的代码里参数用了message,导致命令的参数签名不匹配,所以触发后不会执行函数体。
修改BotCommands.py中的hello函数:
from discord.ext import commands @commands.command() async def hello(ctx, arg): # 把message改成ctx print("inside hello") await ctx.send('Hello {0}.'.format(arg)) # 用ctx.send发送消息 def setup(bot): print("Inside Setup") bot.add_command(hello)
这里的ctx(上下文对象)包含了所有和命令触发相关的信息,比如ctx.message就是你原来想用的消息对象,ctx.send()是发送消息的便捷方法。
2. 确保Intents配置正确
discord.py v2.0及以上版本,必须显式开启必要的intents才能接收消息。你的main.py里提到了intents变量,但没看到定义,这可能也是机器人收不到命令的原因之一。补充完整main.py的intents配置:
import discord from discord.ext import commands import BotCommands # 配置intents intents = discord.Intents.default() intents.message_content = True # 必须开启这个才能接收消息内容 client = commands.Bot(command_prefix="!", intents=intents) client.load_extension("BotCommands") # 别忘了添加启动机器人的代码 client.run("你的机器人Token")
3. 验证步骤
- 确保机器人的Token正确,并且已经邀请到目标服务器,拥有发送消息的权限
- 重启机器人,发送
!hello test,现在应该能看到控制台打印inside hello,并且机器人回复你Hello test.
如果还有问题,可以检查服务器的权限设置,或者确认机器人是否在命令所在的频道有发言权限。
内容的提问来源于stack exchange,提问作者Ishan Bhargava
相关产品推荐
相关产品推荐

