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

使用discord.js v12实现接收消息后向多个指定频道转发的问题问询

Discord.js v12 跨服务器多频道消息转发实现方案

前置准备

  1. 调整你的频道ID存储JSON文件为合法JSON格式,命名为channels.json,示例如下:
{
  "blablabla": ["id 1", "id 2", "id 3", "id 4"]
}

注意去掉ID字符串前后的多余空格,避免匹配失败

  1. 安装discord.js v12版本,执行命令:
    npm install discord.js@12
  2. 前往Discord开发者后台,在你的Bot设置页面开启MESSAGE CONTENT INTENT权限,否则无法读取消息内容。同时确保Bot已加入所有目标频道所在的服务器,且拥有对应频道的发送消息、读取消息、上传附件权限。

核心实现代码

// 引入依赖和配置文件
const Discord = require('discord.js');
const client = new Discord.Client();
// 加载你的频道ID配置文件
const forwardConfig = require('./channels.json');
// 填入你的机器人Token
const BOT_TOKEN = '你的机器人Token';

client.on('ready', () => {
  console.log(`已登录为 ${client.user.tag}`);
});

// 监听消息事件
client.on('message', async (message) => {
  // 排除机器人自己发送的消息,避免循环转发
  if (message.author.bot) return;
  // 获取当前转发频道列表
  const channelList = forwardConfig.blablabla;
  // 判断当前消息所在频道是否在转发列表内
  if (!channelList.includes(message.channel.id)) return;

  // 遍历转发列表,排除来源频道,转发消息到其余所有频道
  for (const targetChannelId of channelList) {
    // 跳过消息来源频道
    if (targetChannelId === message.channel.id) continue;
    try {
      const targetChannel = await client.channels.fetch(targetChannelId);
      // 转发消息内容、嵌入、附件,你可以按需调整转发内容
      await targetChannel.send({
        content: `**${message.author.tag} 来自 ${message.guild.name} #${message.channel.name}:**\n${message.content}`,
        embeds: message.embeds,
        files: message.attachments.array()
      });
    } catch (err) {
      // 捕获异常,比如频道不存在、无权限发送等情况
      console.log(`无法转发到频道 ${targetChannelId}:`, err.message);
    }
  }
});

client.login(BOT_TOKEN);

注意事项

  • 如需自定义转发消息格式,可修改targetChannel.send内的内容参数
  • 不要删除机器人消息过滤逻辑,否则会出现循环转发导致Bot被Discord官方限制
  • 新增/删除转发频道时直接修改channels.json文件后重启Bot即可生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 17:48:02