使用discord.py开发Discord机器人遇'client has no attribute command'错误求助
问题解决:Discord机器人
client has no attribute command错误 错误原因
你导入了discord.ext.commands.Bot但实际用discord.Client()创建客户端,而Client类不具备command装饰器功能——这个装饰器是Bot类专属的,用于实现命令框架。另外Client也不支持command_prefix参数,你之前的写法会被直接忽略。
修复步骤及完整代码
- 用
Bot类替换Client类实例化客户端 - 在
on_message事件末尾添加await client.process_commands(message),避免事件拦截命令消息 - 给修改状态的命令添加权限验证,确保仅你(开发者)能使用
- 修正命令的文档字符串(原描述与功能不符)
修改后的完整代码:
import discord from discord.ext.commands import Bot import RavensTools import random as r intents = discord.Intents.default() intents.message_content = True # 用Bot类实例化,替代原来的Client client = Bot( command_prefix='.', intents=intents, activity=discord.Game(name=f"Heres a goofy random number: {r.randint(1,1000)}") ) @client.event async def on_ready(): print(f'We have logged in as {client.user}') prefix = '.' @client.event async def on_message(message): if message.author == client.user: return if message.content.startswith(prefix+'hello'): await message.channel.send('Hello!') if message.content.startswith(prefix+'add'): if message.author.name == 'RavenVR': f = open(r'goody.txt', 'r+') f.seek(0) a = int(RavensTools.LTS(f.readlines())) f.truncate() a += 5 f.seek(0) f.writelines(str(a)) f.seek(0) await message.channel.send("current number is: {}".format(RavensTools.LTS(f.readlines()))) f.close() else: await message.channel.send("You do not have permission to use this command!") # 必须添加这行,让Bot处理命令消息 await client.process_commands(message) # 修复命令装饰器,添加权限检查 @client.command() async def p(ctx, *, text: str): """修改机器人的状态文本""" # 验证命令使用者是你自己 if ctx.author.name != 'RavenVR': await ctx.send("You do not have permission to use this command!") return await client.change_presence(activity=discord.Game(name=text)) await ctx.send("状态已更新") client.run('TOKEN')
额外说明
- 命令参数里的
*, text: str允许你输入带空格的状态文本,否则只能输入单个单词 pass_context=True在新版本discord.py中已经默认启用,不需要手动指定- 务必确保
intents.message_content已经启用,否则机器人无法读取消息内容
内容的提问来源于stack exchange,提问作者Raven
相关产品推荐
相关产品推荐

