Python开发Discord机器人出现discord无command属性AttributeError报错求助
错误根因
discord.Client类本身没有内置命令注册能力,@discord.command()不是给原生Client类使用的装饰器,调用不存在的属性直接触发AttributeError- 代码存在冗余导入、变量未定义、类方法参数错误等多个语法问题,同时将消息前缀判断逻辑和命令装饰器逻辑混写,逻辑冲突
- 冗余导入
from discord import client可能和后续变量命名产生冲突
修复方案
将继承类改为支持命令的commands.Bot,修正逻辑冲突和语法错误,修改后可运行的代码如下:
import discord from discord.ext import commands # 开启必要的意图,必须去开发者后台开启Message Content Intent权限 intents = discord.Intents.default() intents.message_content = True intents.members = True # 改为继承commands.Bot,指定命令前缀,这里用/作为前缀示例 class MyClient(commands.Bot): def __init__(self): super().__init__(command_prefix="/", intents=intents) async def setup_hook(self): # 同步全局斜杠命令,第一次运行需要等1小时左右生效,测试可以同步到指定服务器 await self.tree.sync() print(f"Logged on as {self.user}") async def on_message(self, message): # 不响应自身消息 if message.author == self.user: return if message.content == "/id": await message.channel.send(str(message.channel.id)) if message.content == ".read": with open("database.txt", "r", encoding="utf-8") as f: content = f.read() await message.channel.send(content) # 原来的/apply逻辑如果要走消息判断可以放在这里,不需要额外写命令装饰器 if message.content == "/apply" and message.author.guild_permissions.administrator: with open("database.txt", "a", encoding="utf-8") as f: f.write(f"\n{str(message.channel.id)}") await message.channel.send(f"Data stored successfully: {str(message.channel.id)}") # 保留命令处理逻辑 await self.process_commands(message) # 斜杠命令写法示例,如果你要做斜杠命令用这个写法 @commands.has_permissions(administrator=True) @commands.hybrid_command(name="admins_only", description="仅管理员可使用的测试命令") async def admins_only_command(self, ctx, *, args: str = None): await ctx.send(f"管理员命令触发成功,传入参数:{args if args else '无'}") TOKEN = "替换为你自己的机器人TOKEN" client = MyClient() client.run(TOKEN)
额外注意事项
- 必须进入Discord开发者平台的对应机器人设置页,在
Privileged Gateway Intents板块开启Message Content Intent权限,否则机器人无法读取用户发送的消息内容 - 首次同步斜杠命令全局生效需要Discord后台缓存更新,最长等待1小时,测试阶段可以指定同步到单服务器,秒生效
- 不要同时用消息前缀判断和命令装饰器处理同一个触发词,避免逻辑重复执行
内容的提问来源于stack exchange,提问作者Blo
相关产品推荐
相关产品推荐

