Discord机器人DM中无法通过表情删除消息问题求助
解决Discord机器人DM中无法通过表情删除消息的问题
问题原因
你的代码在服务器中正常运行,但DM里报错AttributeError: 'NoneType' object has no attribute 'fetch_message',是因为get_channel()只会从机器人的本地缓存中读取频道信息。如果机器人之前没和该用户交互过,DM频道不在缓存里,就会返回None,后续调用fetch_message自然失败。
修复方案
用fetch_channel()替代get_channel(),它会直接向Discord API请求频道数据,不管频道是否在缓存中,同时注意on_raw_reaction_add的参数是payload而非ctx(你的代码里参数名写错了,不影响功能但容易混淆):
self = discord.Bot() @self.event async def on_raw_reaction_add(payload): if payload.emoji.name == '❌': # 获取频道(支持服务器频道和DM频道) channel = await self.fetch_channel(payload.channel_id) # 获取对应消息 message = await channel.fetch_message(payload.message_id) # 删除消息 await message.delete()
补充说明
- 在DM场景下,机器人只能删除自己发送的消息,如果尝试删除用户的消息会因权限不足失败,这是Discord的限制。
- 如果需要确保只有消息作者或特定角色能触发删除,可以在代码里增加判断逻辑,比如:
if payload.user_id == message.author.id: await message.delete()
内容的提问来源于stack exchange,提问作者Kilvoctu
相关产品推荐
相关产品推荐

