discord.py rewrite 如何实现仅纯提及机器人时返回前缀
问题背景
使用discord.py rewrite开发Discord机器人时,需要实现仅当消息内容为纯@机器人、无其他额外内容时自动返回前缀提示的功能。现有代码只要检测到消息中包含对机器人的@提及就会触发回复,不符合预期。
问题相关截图
原有实现代码:
import discord from discord.ext import commands class Support(commands.Cog): def __init__(self, client): self.client = client @commands.Cog.listener() async def on_message(self, message): if self.client.user.mentioned_in(message): mention = discord.Embed( title = "The prefix is `,help`", colour = 0xeeffee ) await message.channel.send(embed = mention) def setup(client): client.add_cog(Support(client))
问题原因
self.client.user.mentioned_in(message)方法仅校验消息中是否存在对机器人的@提及,不会判断消息是否包含其他文本内容,因此只要消息携带机器人@就会触发回复逻辑。
修复方案
在原有判断逻辑基础上新增两层校验:
- 过滤机器人自身发送的消息,避免自回复循环
- 将消息内容去除首尾无意义空白字符后,校验是否完全等于机器人的@提及字符串,确保不存在其他额外内容
同时补充process_commands调用,避免重写on_message后拦截其他正常指令的分发。
修复后完整代码:
import discord from discord.ext import commands class Support(commands.Cog): def __init__(self, client): self.client = client @commands.Cog.listener() async def on_message(self, message): # 跳过机器人自身发送的消息 if message.author == self.client.user: return # 仅当消息去除首尾空白后完全为@机器人时,回复前缀提示 if message.content.strip() == self.client.user.mention: mention = discord.Embed( title = "The prefix is `,help`", colour = 0xeeffee ) await message.channel.send(embed = mention) # 保证其他前缀指令正常响应 await self.client.process_commands(message) def setup(client): client.add_cog(Support(client))
补充说明
- 使用
strip()处理消息内容,可以兼容用户不小心在@前后输入空格、换行的场景,不会因为无意义空白字符导致功能失效 - 如果不需要兼容@前后的空白字符,可以直接去掉
strip(),判断message.content == self.client.user.mention即可
内容的提问来源于stack exchange,提问作者ImAnthox
相关产品推荐
相关产品推荐

