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

如何为基础Discord.js机器人添加自动回复功能

在Discord.js机器人中实现自动回复功能

实现步骤

1. 配置必要的机器人意图

Discord.js v14及以上版本中,读取消息内容需要启用MessageContent意图。先确保客户端配置包含该意图:

const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent // 必须添加此意图才能读取消息内容
  ]
});

2. 添加消息监听与回复逻辑

通过messageCreate事件监听用户消息,判断内容后发送对应回复:

client.on('messageCreate', (message) => {
  // 忽略机器人自身发送的消息,防止无限循环
  if (message.author.bot) return;

  // 精确匹配用户发送的"Hai"(不区分大小写)
  if (message.content.toLowerCase() === 'hai') {
    message.reply('Halo');
  }

  // 可扩展更多匹配规则,比如关键词包含匹配
  if (message.content.toLowerCase().includes('hello')) {
    message.channel.send('Hi there!');
  }
});

3. 完整示例代码

将逻辑整合到index.js中的完整代码如下:

const { Client, GatewayIntentBits } = require('discord.js');
const token = '你的机器人令牌'; // 替换为你的机器人令牌

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent
  ]
});

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

client.on('messageCreate', (message) => {
  if (message.author.bot) return;

  // 用switch-case管理多组回复规则
  switch(message.content.toLowerCase()) {
    case 'hai':
      message.reply('Halo');
      break;
    case 'hey':
      message.reply('Hello!');
      break;
    // 可继续添加更多case
    default:
      // 无匹配时可留空或添加默认回复
      break;
  }
});

client.login(token);

注意事项

  • 需在Discord开发者门户的Bot选项卡中,开启Message Content Intent权限(位于Privileged Gateway Intents下)。
  • 使用toLowerCase()可以让匹配规则不区分大小写,提升用户交互体验。
  • 若需要模糊匹配而非精确触发,可使用includes()或正则表达式来匹配消息中的关键词。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 05:52:43