You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用discord.py的Slash命令检测消息是否包含提及?

问题描述

我正在用discord.py开发Discord机器人,想要实现Slash命令交互功能:

  • 输入类似/mention @好友的指令时,机器人回复“Lexanspe提及了@好友!”
  • 若未提及任何人,则回复“你需要提及某个人!”

之前咨询Copilot得到的方案有错误,搜论坛也没找到针对Slash命令的解决方法。现有代码如下,请问怎么在Slash命令里检测是否包含提及?

import discord
from discord import app_commands
from discord.ext import commands

bot = commands.Bot(command_prefix="!", intents=discord.Intents.default(), activity=discord.Game(name='with arda'))

@bot.event
async def on_ready():
    print("started")
    try:
        synced = await bot.tree.sync()
        print(f"Synced {len(synced)} commands(s)")
    except Exception as e:
        print(e)

@bot.tree.command(name = "gizli")
async def sa(interaction: discord.Interaction):
    await interaction.response.send_message(f"as {interaction.user.mention}, slash komudu calisti ezzzzz", ephemeral=True)

@bot.tree.command(name = "ping")
@app_commands.describe(kimi = "say something")
async def say(interaction: discord.Interaction, kimi: str):
    await interaction.response.send_message(f"{interaction.user.mention} mentioned {kimi}")

@bot.tree.command(name = "say")
@app_commands.describe(message = "say something")
async def say(interaction: discord.Interaction, message: str):
    await interaction.response.send_message(f"{interaction.user.mention} said {message}")

bot.run("token")
解决方案

在discord.py的Slash命令里,不需要手动解析字符串里的提及,直接用discord.User类型的参数就能让Discord自动处理用户选择/提及的逻辑,既准确又省事儿。

修改后的完整代码如下:

import discord
from discord import app_commands
from discord.ext import commands

# 必须开启成员意图,否则无法正确获取用户信息,Discord开发者后台也要同步开启对应特权网关意图
intents = discord.Intents.default()
intents.members = True

bot = commands.Bot(command_prefix="!", intents=intents, activity=discord.Game(name='with arda'))

@bot.event
async def on_ready():
    print("机器人已启动")
    try:
        synced = await bot.tree.sync()
        print(f"同步了 {len(synced)} 条命令")
    except Exception as e:
        print(f"同步命令出错: {e}")

@bot.tree.command(name = "gizli")
async def sa(interaction: discord.Interaction):
    await interaction.response.send_message(f"as {interaction.user.mention}, slash komudu calisti ezzzzz", ephemeral=True)

# 实现需求的/mention命令
@bot.tree.command(name="mention", description="提及一位用户并让机器人播报")
@app_commands.describe(target="你要提及的用户")
async def mention_user(interaction: discord.Interaction, target: discord.User = None):
    if target:
        await interaction.response.send_message(f"Lexanspe提及了{target.mention}!")
    else:
        await interaction.response.send_message("你需要提及某个人!")

@bot.tree.command(name = "say")
@app_commands.describe(message = "要发送的内容")
async def say(interaction: discord.Interaction, message: str):
    await interaction.response.send_message(f"{interaction.user.mention} 说: {message}")

bot.run("你的机器人令牌")

关键说明

  • 权限配置:开启members意图是核心,否则机器人无法正常获取用户对象,要同时在Discord开发者后台开启对应的特权网关意图。
  • 参数类型优化:把原来的字符串参数换成discord.User类型,并设置默认值为None,这样用户可以选择是否提及他人,Discord会自动提供用户选择界面。
  • 逻辑判断:直接通过target是否为空来判断是否有提及,为空就提示用户,不为空则播报提及内容。
  • 命令命名:把功能对应的命令改成mention更直观,如果你一定要用/ping实现,只需要把上面的命令名改成ping即可:
@bot.tree.command(name="ping", description="提及一位用户并让机器人播报")
@app_commands.describe(target="你要提及的用户")
async def ping_with_mention(interaction: discord.Interaction, target: discord.User = None):
    if target:
        await interaction.response.send_message(f"Lexanspe提及了{target.mention}!")
    else:
        await interaction.response.send_message("你需要提及某个人!")

内容的提问来源于stack exchange,提问作者Lexanspe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 13:37:52