Python开发Discord Bot 8-ball命令报TypeError: 'str' object is not callable求助
报错修复方案
直接报错原因
你代码中bot.add_command = ('eight_ball')这行错误将Bot内置的add_command注册方法覆盖成了字符串'eight_ball',后续装饰器尝试调用add_command方法时,实际调用的是字符串,因此抛出str object is not callable错误,直接删除这行即可,@bot.command装饰器会自动完成命令注册,不需要手动修改内置方法。
其他需要修复的问题
- 重复初始化客户端:你同时创建了
discord.Client和commands.Bot两个实例,后者本身是前者的子类,完全可以替代前者的所有功能。你当前最后调用的是client.run(),会导致所有绑定在bot上的命令完全不生效,直接删除client = discord.Client()相关的初始化逻辑,把on_ready事件绑定到bot上即可。 - 列表语法错误:
possible_responses列表中多个字符串末尾缺少逗号,会被Python自动拼接为同一个字符串,导致可选回复数量缺失,需要给每个回复字符串末尾补全逗号。 - 弃用参数:
@bot.command中的pass_context参数在discord.py v1.0之后就默认开启,无需显式声明,可以直接删除。 - 缺少Intent配置:当前Discord API要求必须显式声明消息内容权限才能读取普通前缀命令,需要在代码中开启
message_content权限,同时在Discord开发者后台的Bot设置页开启Message Content Intent开关。
修复后完整代码
import os import random import discord from discord.ext import commands # 初始化Bot,配置基础权限 bot = commands.Bot( command_prefix='$', intents=discord.Intents.default() ) # 开启消息内容权限,才能读取前缀命令 bot.intents.message_content = True @bot.event async def on_ready(): print(f'We have logged in as {bot.user}') @bot.command( name='eight_ball', description="Answers a yes/no question.", brief="Answers from the beyond.", aliases=['eightball', '8-ball'] ) async def eight_ball(context): possible_responses = [ 'Yes- definitely', 'As I see it, yes.', 'Yes', 'Signs point to yes.', 'Can\'t be certain.', '...', 'It\'s better not tell you now.', 'My reply is no.', 'My sources say no.', 'Outlook not so good' ] await context.send(f"{random.choice(possible_responses)}, {context.author.mention}") bot.run(os.environ['TOKEN'])
内容的提问来源于stack exchange,提问作者bigfatloser404
相关产品推荐
相关产品推荐

