Discord.py如何检测指令调用时提及的用户是机器人还是其他成员
代码不生效原因
- 你没有正确获取指令中被用户提及的目标对象,现有代码中的
user变量并非你要检测的被@的用户 - 主流Discord机器人库(如discord.py)中,用户ID为整数类型,你用带引号的字符串
"878176818564317184"做等值判断,类型不匹配,判断逻辑永远返回假,因此不会触发回复
实现方案
方案1:通过命令参数自动解析提及用户(推荐)
适合用命令框架开发的场景,通过参数注解直接自动解析出指令中提及的成员:
import discord from discord.ext import commands # 初始化机器人,按需开启对应权限 bot = commands.Bot(command_prefix="!", intents=discord.Intents.all()) @bot.command() async def your_command(ctx, mentioned_user: discord.Member): # 直接对比提及用户ID和机器人自身ID即可,不需要硬编码ID if mentioned_user.id == bot.user.id: await ctx.send("Trying to rickroll me") else: await ctx.send(f"提及的是服务器成员:{mentioned_user.name}")
方案2:手动从消息中提取所有提及用户
如果不需要显式传参,直接从当前消息的提及列表中遍历判断即可:
@bot.command() async def your_command(ctx): # 获取当前消息里所有被@的用户列表 mentioned_users = ctx.message.mentions if not mentioned_users: await ctx.send("未提及任何用户") return for user in mentioned_users: if user.id == bot.user.id: await ctx.send("你提及了我") else: await ctx.send(f"你提及了成员:{user.name}")
内容的提问来源于stack exchange,提问作者Zook780
相关产品推荐
相关产品推荐

