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

使用Discord.js如何在指定webhook触发时让Bot推送消息到指定频道

Discord.js v14 实现方案

前置要求

  • Bot已在Discord开发者后台开启 Message Content Intent(无该权限无法读取消息元数据与内容)
  • Bot拥有目标频道(ID: 1234567890)的发送消息权限
  • 使用Discord.js v14+ 版本(旧版本API逻辑存在差异,需自行适配)

核心实现代码

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

// 目标配置
const TARGET_WEBHOOK_ID = '0000000000';
const TARGET_CHANNEL_ID = '1234567890';

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

client.on('messageCreate', async (message) => {
  // 过滤非目标webhook发送的消息
  if (!message.webhookId || message.webhookId !== TARGET_WEBHOOK_ID) return;

  try {
    // 获取目标频道
    const targetChannel = await client.channels.fetch(TARGET_CHANNEL_ID);
    if (!targetChannel || !targetChannel.isTextBased()) return;

    // 发送自定义消息,可根据需求修改内容、添加嵌入/附件等
    await targetChannel.send('监测到目标webhook触发,这是自动发送的通知消息');
  } catch (err) {
    console.error('消息发送失败:', err);
  }
});

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

可选扩展逻辑

  • 如需读取触发webhook的消息内容填充到自动发送的消息中,可直接调用message.content、message.embeds等属性获取对应内容
  • 如需过滤特定内容的webhook消息,可在webhookID匹配判断后新增内容校验规则
  • 生产环境建议完善错误捕获逻辑,覆盖无权限、频道不存在等异常场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 05:36:00