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

如何让Discord自定义机器人检测消息中是否@我?

实现Discord.js机器人检测消息中提及自己的功能

要让机器人检测消息任意位置是否提及自己,你可以利用Discord.js提供的message.mentions对象,它会自动解析消息中的所有用户提及。具体实现如下:

关键判断逻辑

在messageCreate事件中添加以下判断,该逻辑会检测消息是否在任意位置@了机器人:

if (message.mentions.users.has(client.user.id)) {
  // 这里写被提及后的回复逻辑
  message.channel.send("你@我啦!有什么需要帮忙的吗?");
}

修改后的完整代码

const express = require('express');
const app = express()

app.get('/', function(req, res) {
  res.send("Hello!")
})

app.listen(3000, () => {
  console.log("The server is running!")
})

const Discord = require('discord.js')

const client = new Discord.Client({
  intents: [
    "Guilds",
    "GuildMessages",
    "MessageContent",
    "GuildMembers"
  ],
  partials: [
    Discord.Partials.Message,
    Discord.Partials.Channel,
    Discord.Partials.GuildMember,
  ],
})

client.on("ready", () => {
  console.log("The bot is online!!!")
})

client.on("messageCreate", message => {
  // 检测是否被提及
  if (message.mentions.users.has(client.user.id)) {
    message.channel.send("你@我啦!有什么需要帮忙的吗?");
  }

  if (message.content == "test098") {
    message.channel.send("working dont disturb")
  }

  if (message.content == "embed098") {
    const embed = new Discord.EmbedBuilder()
      .setColor('#FFFF00')
      .setTitle('The Strategy Razan is AFK')
      .setDescription('Hey there sorry i am not available, If you have queries related to it please contact the mod')
      .setTimestamp()
      .setFooter({ text: 'Sorry' });

    message.channel.send({embeds: [embed]})
  }
})

client.login(process.env.token)

补充说明

  • message.mentions.users是一个包含所有被提及用户的集合,调用has(client.user.id)就能快速判断机器人是否被提及,不管@符号在消息的开头、中间还是结尾。
  • 你可以根据需求替换被提及后的回复内容,比如改成发送Embed消息,或者调用其他功能逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 00:35:06