discord.py修改机器人状态报错discord.ext.commands无change_presence属性
问题原因
change_presence不是discord.ext.commands模块的静态方法,它是Bot实例自身的异步方法,你需要通过self(也就是当前继承自commands.Bot的MusicBot实例)来调用,不能直接使用commands.change_presence- 你定义了两个
on_ready事件回调,后面定义的版本会覆盖前面的,之前设置client_id、打印启动信息的逻辑会直接失效 - 当前代码里的
setup、run、shutdown等方法都没有缩进进入MusicBot类的作用域,不属于类的成员方法,运行时会直接抛出属性不存在的错误
修复代码
首先把所有类方法缩进进MusicBot类,合并两个on_ready回调,修改change_presence的调用方式即可:
from pathlib import Path import discord from discord.ext import commands class MusicBot(commands.Bot): def __init__(self): self._cogs = [p.stem for p in Path(".").glob("./bot/cogs/*.py")] # 2.0以上版本discord.py需要额外配置Intents,见下方补充说明 super().__init__(command_prefix=self.prefix, case_insensitive=True) # 所有类方法都需要缩进在类内部 def setup(self): print("Yuki abrio sus ojitos...") for cog in self._cogs: self.load_extension(f"bot.cogs.{cog}") print(f" Loaded `{cog}` cog.") print("Yuki se esta visitendo...") def run(self): self.setup() with open("data/token.0", "r", encoding="utf-8") as f: TOKEN = f.read() print("Yuki se esta levantando :3...") super().run(TOKEN, reconnect=True) async def shutdown(self): print("Closing connection to Discord...") await super().close() async def close(self): print("Closing on keyboard interrupt...") await self.shutdown() async def on_connect(self): print(f" Connected to Discord (latency: {self.latency*1000:,.0f} ms).") async def on_resumed(self): print("Bot resumed.") async def on_disconnect(self): print("Bot disconnected.") async def on_error(self, err, *args, **kwargs): raise async def on_command_error(self, ctx, exc): raise getattr(exc, "original", exc) # 合并两个on_ready回调,修改change_presence调用逻辑 async def on_ready(self): self.client_id = (await self.application_info()).id print("Yuki ya desperto uwu") # 用self调用change_presence,活动类型用枚举写法更清晰易维护 activity = discord.Activity(type=discord.ActivityType.watching, name="自定义活动名称") await self.change_presence(status=discord.Status.idle, activity=activity) async def prefix(self, bot, msg): return commands.when_mentioned_or("<")(bot, msg) async def process_commands(self, msg): ctx = await self.get_context(msg, cls=commands.Context) if ctx.command is not None: await self.invoke(ctx) async def on_message(self, msg): if not msg.author.bot: await self.process_commands(msg)
如果你使用的是discord.py 2.0及以上版本,需要先配置Intents权限,初始化Bot时补充intents参数即可:
intents = discord.Intents.default() # 需要监听普通消息的话要额外开启消息内容权限,同时要在Discord开发者后台开启对应开关 intents.message_content = True super().__init__(command_prefix=self.prefix, case_insensitive=True, intents=intents)
内容的提问来源于stack exchange,提问作者wimark 363
相关产品推荐
相关产品推荐

