【问题标题】:How to make Discord Bot do multiple different responses?如何让 Discord Bot 做出多种不同的响应?
【发布时间】:2021-06-13 13:31:52
【问题描述】:

这就是我的 discord bot.js 的样子。

基本上,我认为当我输入“ten bot je fakt sračka”时,它会给出数组中的一个响应。

如果我输入“ahoj”,它会以几颗心做出回应。

而且当我输入“test”时,它应该回复“test”。

现在,当我运行机器人并输入三个消息中的任何一个时,如果只回复“测试”到“测试”。没有其他任何东西得到回应。我该怎么办?

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) {
    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]);
    }
}

function gotMessage(msg) {
    console.log(msg.content);
    if (msg.content === "ahoj") {
        msg.reply("Ahoj <3<3<3");
    }
}

function gotMessage(msg) {
    console.log(msg.content);
    if (msg.content === "test") {
        msg.reply("test");
    }
}

【问题讨论】:

    标签: javascript node.js discord discord.js


    【解决方案1】:

    这是因为你不断地覆盖你的函数 'gotMessage' 并且它的最后声明是你回复 test 的地方。

    client.on('message', gotMessage);
    
    function gotMessage(msg) {
        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');
        }
    }
    

    在这里,您在gotMessage 的一个声明中拥有所有 if 语句。由于它没有被覆盖,因此每个 if 都会被考虑在内。在这种情况下,最好使用else if,因为您正在检查一个值是否等于一件事或另一件事。

    附:切勿在线共享您的机器人的登录令牌,否则其他人可能会弄乱它

    【讨论】:

    • 是的,我一开始并没有复制它,但我决定将整个代码也包含在文本中。到时我会重置它。感谢您的代码!我对 Python 真的很陌生,我只是认为我可以通过复制粘贴提示来解决所有问题。
    猜你喜欢
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    • 2019-06-07
    • 1970-01-01
    • 2021-11-17
    • 2021-08-13
    • 2020-12-15
    • 2021-08-28
    相关资源
    最近更新 更多