首页 > 解决方案 > Discord JS函数返回未定义

问题描述

我正在使用收集器构建一个 Discord 机器人,并试图为几轮游戏收集选票。但是,机器人不断返回错误的值。它通常会返回undefined[object Object]。stringifier() 函数应该返回一轮的名称,但它返回的是未定义的。例如,如果我在 Discord 上输入“spleef”,它应该在控制台和 Discord 中输出“Spleef”,但它在两者中都返回未定义或仅返回错误。

更新:我发现变量返回布尔值(变量是从battleBoxVotes 到cTFVotes)。

稍后更新:所以我解决了这个问题,但我现在的新问题是,如果变量没有值,我无法让bbv它们ctfv不返回错误。控制台记录以下内容:(node:8700) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'content' of undefined

const filter = m => (m.author.id != client.user.id);
      const channel = message.channel;
      const collector = channel.createMessageCollector(filter, { time: 5000 });
      collector.on('collect', m => console.log(`Collected ${m.content}`));
      collector.on('end', async collected => {

        var bb = collected.find(collected => collected.content === 'battle box');
        var pw = collected.find(collected => collected.content === 'spleef');
        var s = collected.find(collected => collected.content === 'spleef');
        var sw = collected.find(collected => collected.content === 'skywars');
        var ctf = collected.find(collected => collected.content === 'capture the flag');

        const bbv = bb.content || null;
        const pwv = pw.content || null;
        const sv = s.content || null;
        const swv = sw.content || null;
        const ctfv = ctf.content || null;

        const stringifier = function(a, b, c, d, e) {
          let results;
          if (a>b&&a>c&&a>d&&a>e) {results = "Battle Box"}
          else if (b>a&&b>c&&b>d&&b>e) {results = "Parkour Warrior"}
          else if (c>a&&c>b&&c>d&&c>e) {results = "Spleef"}
          else if (d>a&&d>b&&d>c&&d>e) {results = "SkyWars"}
          else if (e>a&&e>b&&e>c&&e>c) {results = "Capture the Flag"}
          return results;
        }

          message.channel.send(`And the winner is... ${stringifier(bbv, pwv, sv, swv, ctfv)}!`),
          console.log(stringifier(bbv, pwv, sv, swv, ctfv))

      });

标签: javascriptnode.jsdiscord.js

解决方案


这种比较的逻辑绝对打破了我的大脑,首先阅读起来很痛苦。这是一个改编的版本,应该会更好一些。

此解决方案遍历收到的消息并根据switch-case 表达式为每个游戏模式增加一个计数器。(请记住,这并不能阻止用户简单地向他们想要的任何游戏模式发送垃圾邮件......)

getAllIndexes该功能的功劳(用于确定关系)


const filter = m => (m.author.id != client.user.id);
const channel = message.channel;
const collector = channel.createMessageCollector(filter, { time: 5000 });
collector.on('collect', m => console.log(`Collected ${m.content}`));
collector.on('end', async collected => {
    let msgs = Array.from(collected.keys()).map(m=>m?.content.toLowerCase().trim());
    let modes = [ "Battle Box", "Parkour Warrior", "Spleef", "SkyWars", "Capture the Flag" ] // Define the names of the GameModes
    let scores = [ 0, 0, 0, 0, 0 ] // Set up the default scores
    msgs.forEach(m => {
        switch(m) {
        case "bb": // Fallthrough case for aliases
        case "battlebox":
        case "battle box":
            scores[0]++; // Increment BattleBox (0) Counter
            break;
        case "pw":
        case "parkour":
        case "parkour warrior":
            scores[1]++; // Increment ParkourWarrior (1) counter
            break;
        case "spleef":
            scores[2]++; // Increment Spleef (2) counter
            break;
        case "sw":
        case "sky":
        case "skywars":
            scores[3]++; // Increment SkyWars (3) counter
            break;
        case "ctf":
        case "capture the flag":
            scores[4]++; // Increment CaptureTheFlag (4) counter
            break;
    });

    // Now to find who won...
    let winningCount = Math.max(scores);
    let winningIndexes = getAllIndexes(scores, winningCount);

    if(winningIndexes.length = 1) { // Single Winner
        message.channel.send(`And the winner is... ${modes[winningIndexes[0]]}!`);
    } else { // tie!
       message.channel.send(`It's a tie! There were ${winningIndexes.length} winners. (${winningIndexes.map(i=>modes[i]).join(", ")})`);
    }
j});


// Get All Indexes function...
function getAllIndexes(arr, val) {
    var indexes = [], i;
    for(i = 0; i < arr.length; i++)
        if (arr[i] === val) indexes.push(i);
    return indexes;
}

推荐阅读