Python编写Discord机器人如何实现被@提及后返回当前指令前缀?
问题原因
当前你仅为机器人配置了固定指令前缀-,discord.py 框架的默认命令处理逻辑只会响应以指定前缀开头的消息,你发送的@Hu Tao bot prefix未携带-前缀,不会进入命令处理流程,因此既不会触发响应也不会生成报错信息。
解决方案
方案1:配置全局支持@机器人触发指令
通过动态前缀函数,同时支持固定前缀和@机器人作为全局触发前缀,配置完成后直接定义prefix命令即可:
import discord from discord.ext import commands # 开启消息内容权限,为必填项 intents = discord.Intents.default() intents.message_content = True # 定义动态前缀规则 def get_prefix(client, message): base_prefix = ['-'] # 允许@机器人作为前缀使用 return commands.when_mentioned_or(*base_prefix)(client, message) # 初始化时传入动态前缀函数 client = commands.Bot(command_prefix=get_prefix, intents=intents) # 定义prefix命令 @client.command() async def prefix(ctx): await ctx.send(f"当前指令前缀为:`-`,你也可以直接@我触发所有指令")
方案2:单独监听@查询前缀的消息
如果不想修改全局前缀规则,可以通过on_message事件单独匹配查询前缀的请求:
import discord from discord.ext import commands intents = discord.Intents.default() intents.message_content = True client = commands.Bot(command_prefix='-', intents=intents) @client.event async def on_message(message): # 忽略机器人自己发送的消息 if message.author.bot: return # 匹配@机器人且包含prefix的消息 if client.user.mentioned_in(message) and 'prefix' in message.content.lower(): await message.channel.send(f"当前指令前缀为:`-`") # 必须保留该行,否则其他前缀命令会全部失效 await client.process_commands(message)
必要检查项
- 前往Discord开发者平台的机器人管理页面,在「Privileged Gateway Intents」分类下开启
Message Content Intent权限 - 确认机器人拥有对应频道的发送消息权限
内容的提问来源于stack exchange,提问作者BasicLol
相关产品推荐
相关产品推荐

