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

如何实现Discord Bot多触发条件多响应?当前仅test指令生效

问题根源
  • JavaScript 中同名函数会按定义顺序逐层覆盖,最终仅保留最后一次定义的版本。你先后定义了 3 个gotMessage函数,只有最后一个处理「test」触发词的函数会被挂载到client.on("message", gotMessage)事件上,前两个对应「ten bot je fakt sračka」和「ahoj」的逻辑已经被完全覆盖,自然不会触发响应。
  • 额外隐患:未过滤 Bot 自身发送的消息,后续运行时可能出现消息死循环,建议补加判断。
修复方案

将所有触发判断逻辑合并到同一个gotMessage函数内,禁止重复定义同名处理函数,修复后完整代码如下:

const Discord = require("discord.js");
const client = new Discord.Client();
client.login("TOKEN");

client.on("ready", readyDiscord);

function readyDiscord() {
    console.log("123");
}

const replies = ["Stop it!", "Bot lives matter! <:ragey:776017536973013003>", "no", "<:jakjestvbiblipsno:776002959665266709>"];

client.on("message", gotMessage);

function gotMessage(msg) {
    // 过滤Bot自身消息,避免触发死循环
    if (msg.author.bot) return;
    console.log(msg.content);

    if (msg.content === "ten bot je fakt sračka") {
        const index = Math.floor(Math.random() * replies.length);
        msg.channel.send(replies[index]);
    } else if (msg.content === "ahoj") {
        msg.reply("Ahoj <3<3<3");
    } else if (msg.content === "test") {
        msg.reply("test");
    }
}

补充说明:如果使用 Discord.js v13 及以上版本,需要提前在创建客户端时开启对应消息读取的 Intent 权限,否则会收不到 message 事件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.30 01:36:02