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

如何让Discord Bot将私信消息发送至指定Endpoint?

解决方案

你的代码已经正确配置了接收私信所需的Intent(DirectMessages和MessageContent),只需要调整messageCreate事件的触发条件,让它在收到私信或者在服务器频道中被提及时,都执行转发逻辑即可。

修改后的完整代码

const { Client, GatewayIntentBits } = require('discord.js');
const axios = require('axios');
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.DirectMessages,
    GatewayIntentBits.MessageContent,
  ],
});

const YOUR_BOT_TOKEN = 'tokenx';
const YOUR_ENDPOINT = 'https://endpointlambda';

client.once('ready', () => {
  console.log('Bot is online!');
});

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

  // 判断条件:要么是私信,要么在服务器中被提及
  const shouldForward = message.channel.type === 'DM' || message.mentions.has(client.user);

  if (shouldForward) {
    try {
      await axios.post(YOUR_ENDPOINT, {
        content: message.content,
        author: message.author.username,
        id: message.author.id,
        // 可选:添加消息来源类型,方便后端区分是私信还是服务器消息
        sourceType: message.channel.type === 'DM' ? 'direct_message' : 'guild_mention'
      });
      console.log('消息已转发至端点:', message.content);
    } catch (error) {
      console.error('转发消息至端点失败:', error);
    }
  }
});

client.login(YOUR_BOT_TOKEN);

关键修改点说明

  • 添加了shouldForward变量,通过两个条件判断是否需要转发消息:
    • message.channel.type === 'DM':检测当前消息是否为用户私信
    • message.mentions.has(client.user):检测当前消息是否在服务器频道中@了机器人
  • 将原有的Promise链式调用改为async/await写法,提升代码可读性与错误处理的直观性
  • 可选新增sourceType字段,方便后端区分消息的来源类型(私信/服务器提及)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 22:32:36