Discord机器人/say命令报错:'Command'对象不可调用,求拆分方案
解决Discord机器人/say命令拆分模块后的TypeError问题
错误原因
- 命名冲突:main.py中定义的斜杠命令函数名也是
say,和从commandall导入的say模块重名,导致原函数被覆盖为Command对象,调用时触发“不是可调用对象”的错误。 - 上下文类型不匹配:Discord斜杠命令(app command)的回调参数是
Interaction对象,而非传统命令的ctx上下文,原代码中用ctx.send的调用方式不符合斜杠命令的API要求。
修复步骤
1. 修改main.py
调整导入方式避免命名冲突,同时修正斜杠命令的参数类型:
import discord from discord import app_commands from discord.ext import commands # 导入模块内的say函数并重命名,规避命名冲突 from commandall.say import say as say_command bot = commands.Bot(intents = discord.Intents().all(), command_prefix='!') @bot.event async def on_ready(): print("================== >>Bot is Online<< ================== Log in acc is", bot.user) try: synced = await bot.tree.sync() print(f'synced {len(synced)} command(s)') except Exception as e: print(e) # 斜杠命令的参数为Interaction对象,而非ctx @bot.tree.command(name='say', description='让机器人重复你输入的内容') async def say(interaction: discord.Interaction, text: str): # 调用独立模块中的处理函数 await say_command(interaction, text) bot.run('你的机器人Token')
2. 修改commandall/say.py
适配斜杠命令的Interaction对象进行消息发送:
import discord async def say(interaction: discord.Interaction, text: str): # 斜杠命令需用interaction.response.send_message完成回复 await interaction.response.send_message(text) # 打印日志时判断是否在服务器环境,避免DM场景报错 if interaction.guild: print(f'{interaction.guild.name} >> {interaction.author.name} > SAY > {text} (✅)')
3. 验证修复
重启机器人后调用/say命令,机器人将正常重复输入文本,控制台也会输出正确的操作日志,TypeError错误不再出现。
内容的提问来源于stack exchange,提问作者shane
相关产品推荐
相关产品推荐

