Discord 机器人在检测到一个单词时会显示多条消息

Discord bot with multiple messages when detected a word

我有一个discord bot,说一个词就会触发,我本来只让它说一件事(原post在这里供参考:)但我现在想要它有多个说法,所以我使用了一个带有随机数生成器函数生成的随机数的 switch 语句,它在消息输出的 switch 语句中被调用。出于某种原因,我的代码不起作用,我不确定为什么。

                let Discord;
                let Database;
                if(typeof window !== "undefined"){
                    Discord = DiscordJS;
                    Database = EasyDatabase;
                } else {
                    Discord = require("discord.js");
                    Database = require("easy-json-database");
                }
                const delay = (ms) => new Promise((resolve) => setTimeout(() => resolve(), ms));
                const s4d = {
                    Discord,
                    client: null,
                    tokenInvalid: false,
                    reply: null,
                    joiningMember: null,
                    database: new Database("./db.json"),
                    checkMessageExists() {
                        if (!s4d.client) throw new Error('You cannot perform message operations without a Discord.js client')
                        if (!s4d.client.readyTimestamp) throw new Error('You cannot perform message operations while the bot is not connected to the Discord API')
                    }
                };
                s4d.client = new s4d.Discord.Client({
                    fetchAllMembers: true
                });
                s4d.client.on('raw', async (packet) => {
                    if(['MESSAGE_REACTION_ADD', 'MESSAGE_REACTION_REMOVE'].includes(packet.t)){
                        const guild = s4d.client.guilds.cache.get(packet.d.guild_id);
                        if(!guild) return;
                        const member = guild.members.cache.get(packet.d.user_id) || guild.members.fetch(d.user_id).catch(() => {});
                        if(!member) return;
                        const channel = s4d.client.channels.cache.get(packet.d.channel_id);
                        if(!channel) return;
                        const message = channel.messages.cache.get(packet.d.message_id) || await channel.messages.fetch(packet.d.message_id).catch(() => {});
                        if(!message) return;
                        s4d.client.emit(packet.t, guild, channel, message, member, packet.d.emoji.name);
                    }
                });
                s4d.client.login('TOKEN').catch((e) => { s4d.tokenInvalid = true; s4d.tokenError = e; });


function GetRandomInteger(a, b){

    if (a > b){
        small = b;
        large = a;
    }
    else{
        small = a;
        large = b;
    }


s4d.client.on('message', async (s4dmessage) => {
    if (s4dmessage.author.bot) return;
  if (s4dmessage.content.includes('apples')) {
    switch(GetRandomInteger(1,5)){
        case 1: s4dmessage.channel.send(String('yum I love apples!')); break;
        case 2: s4dmessage.channel.send(String('apples are the best')); break;
        case 3: s4dmessage.channel.send(String('did someone say apples?')); break;
        case 4: s4dmessage.channel.send(String('apples are great!')); break;
        case 5: s4dmessage.channel.send(String('yum yum!')); break;
    }


  }


});

s4d;
        

正如 Fabio 提到的,GetRandomInteger() 函数后缺少一个大括号,但该函数不会 return 任何东西。

无需生成随机整数并使用 switch 语句,您只需将响应存储在一个数组中并随机选择其中一个即可。

像这样的东西应该可以工作,而且代码少得多:

s4d.client.on('message', async (s4dmessage) => {
  if (s4dmessage.author.bot) return;
  let responses = [
    'yum I love apples!',
    'apples are the best',
    'did someone say apples?',
    'apples are great!',
    'yum yum!',
  ];

  if (s4dmessage.content.includes('apples')) {
    s4dmessage.channel.send(getRandom(responses));
  }
});

function getRandom(arr) {
  let index = Math.floor(Math.random() * arr.length);
  return arr[index];
}

您甚至可以更进一步,将您对不同水果的响应数组添加到一个对象中,其中键是水果名称,值是响应。这样你就可以检查消息是否包含一个键,并从数组中发送一个随机响应,其中键是找到的水果名称。

如果你想添加一个新的水果,你可以简单地把它添加到你的responses对象中,如果你想add/remove/update一个响应,你可以编辑相应的数组。

查看下面的示例:

s4d.client.on('message', async (s4dmessage) => {
  if (s4dmessage.author.bot) return;
  let responses = {
    apples: [
      'yum I love apples!',
      'apples are the best',
      'did someone say apples?',
      'apples are great!',
      'yum yum!',
    ],
    kiwi: [
      ' simply the best.. ',
      'yummmy',
      'kiwi, kiwi, get in my belly',
      'am I the only one who loves kiwi?'
    ],
    oranges: [
      'yum I love oranges!',
      'I love eating oranges!',
      'did someone mention oranges?',
      ' love them',
      'yummmm!',
    ],
  };

  // check if the message contains any of the keys of responses
  // returns the key if found, undefined otherwise
  let firstKeyword = Object.keys(responses).find((str) =>
    s4dmessage.content.includes(str),
  );

  if (firstKeyword) {
    s4dmessage.channel.send(getRandom(responses[firstKeyword]));
  } else {
    // message contains no apples, kiwi, or oranges
  }
});

function getRandom(arr) {
  let index = Math.floor(Math.random() * arr.length);
  return arr[index];
}