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

discord.js如何将Bot接收的DM私信消息记录到指定频道

实现方案

该功能可直接通过discord.js的消息监听事件实现,以下是完整实现方案:

前提条件

  • 已在Discord开发者后台的Bot配置页开启Message Content Intent权限,否则Bot无法读取非命令类的消息内容
  • Bot已经加入你要转发日志的目标服务器,且对目标日志频道拥有发送消息、嵌入链接、上传附件权限
  • 已获取目标日志频道的ID(开启Discord客户端开发者模式后右键频道即可复制)

代码示例(基于discord.js v14 版本)

const { Client, GatewayIntentBits, ChannelType } = require('discord.js');
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.DirectMessages, // 监听私信消息必需
    GatewayIntentBits.MessageContent // 读取消息内容必需
  ]
});

// 替换为你自己的日志频道ID
const LOG_CHANNEL_ID = '替换为你自己的日志频道ID';

client.on('messageCreate', async (message) => {
  // 过滤Bot自身发送的消息,避免循环触发
  if (message.author.bot) return;
  // 仅处理私信类型的消息
  if (message.channel.type !== ChannelType.DM) return;

  try {
    const logChannel = await client.channels.fetch(LOG_CHANNEL_ID);
    // 校验频道是否存在、且为可发送消息的文本类频道
    if (!logChannel?.isTextBased()) return;

    // 发送日志到指定频道
    await logChannel.send({
      content: `📩 新私信 | 用户:${message.author.tag} \`${message.author.id}\``,
      embeds: [
        {
          description: message.content || '*该消息无文本内容,可能仅包含附件*',
          timestamp: new Date(),
          color: 0x2ECC71
        }
      ],
      // 附带用户发送的所有附件(图片、文件、视频等)
      files: Array.from(message.attachments.values())
    });
  } catch (err) {
    console.error('私信转发失败:', err);
  }
});

client.login('你的Bot Token');

常见问题排查

  • 收不到转发消息:先检查Message Content Intent是否开启,Bot是否拥有目标频道的发送权限,频道ID是否填写正确
  • 低版本discord.js适配:v13及以下版本的频道类型枚举为'DM',不需要导入ChannelType,直接判断message.channel.type === 'DM'即可
  • 如需记录消息的引用回复、贴纸、反应等信息,可自行扩展message对象的字段读取逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 02:45:04