setTimeout()中的第二个函数不会运行

时间:2017-11-08 00:43:03

标签: javascript discord discord.js

所以我不喜欢诋毁僵尸和js,而且我正在玩我自己的机器人。我想打字迷你游戏。当您在聊天中键入?type时,机器人会在聊天中说些什么,然后在倒计时时编辑该消息。倒计时结束后,将显示随机生成的单词。玩家需要在聊天中输入确切的随机单词,机器人将显示总时间。

这是我的代码:

case "type":
        let randomWord = Math.random().toString(36).replace(/[^a-z]+/g, '');
        let timer = 3;
        message.channel.send("Generating a new word..")
          .then((msg)=> {
            var interval = setInterval(function () {
              msg.edit(`Starting in **${timer--}**..`)
            }, 1000)
          });
        setTimeout(function() {
          clearInterval(interval);
          message.channel.send(randomWord)
          .then(() => {
            message.channel.awaitMessages(response => response.content == randomWord, {
              max: 1,
              time: 10000,
              errors: ['time'],
            })
            .then(() => {
              message.channel.send(`Your time was ${(msg.createdTimestamp - message.createdTimestamp) / 1000} seconds.`);
            })
            .catch(() => {
              message.channel.send('There was no collected message that passed the filter within the time limit!');
            });
          });
        }, 5000);
        break;

目前代码在计数到0后停止。 我不明白为什么message.channel.send(randomWord)不起作用。我也很乐意,如果有人可以帮助我改变这段代码以使用asynch并等待它是否可行。

1 个答案:

答案 0 :(得分:0)

我开始研究你的问题,这就是我想出的系统。

这是听取来自不同用户的消息的机器人。用户输入'?type'后,会调用函数runWordGame,并传入邮件的频道。

// set message listener 
client.on('message', message => {
    switch(message.content.toUpperCase()) {
        case '?type':
            runWordGame(message.channel);
            break;
    }
});

runWordGame中,机器人创建一个随机单词,然后向用户显示倒计时(请参阅下面的displayMessageCountdown)。倒计时结束后,将使用随机字编辑消息。接下来,机器人等待1条消息10秒钟 - 等待用户输入随机字。如果成功,则发送成功消息。否则,将发送错误消息。

// function runs word game
function runWordGame(channel) {
    // create random string
    let randomWord = Math.random().toString(36).replace(/[^a-z]+/g, '');

    channel.send("Generating a new word..")
    .then(msg => {
        // display countdown with promise function :)
        return displayMessageCountdown(channel);
    })
    .then(countdownMessage => {
        // chain promise - sending message to channel
        return countdownMessage.edit(randomWord);
    })
    .then(randomMsg => {
        // setup collector
        channel.awaitMessages(function(userMsg) {
            // check that user created msg matches randomly generated word :)
            if (userMsg.id !== randomMsg.id && userMsg.content === randomWord)
                return true;
        }, {
            max: 1,
            time: 10000,
            errors: ['time'],
        })
        .then(function(collected) {
            // here, a message passed the filter!
            let successMsg = 'Success!\n';

            // turn collected obj into array
            let collectedArr = Array.from(collected.values());

            // insert time it took user to respond
            for (let msg of collectedArr) {
                let timeDiff = (msg.createdTimestamp - randomMsg.createdTimestamp) / 1000;

                successMsg += `Your time was ${timeDiff} seconds.\n`;
            }

            // send success message to channel
            channel.send(successMsg);
        })
        .catch(function(collected) {
            // here, no messages passed the filter
            channel.send(
                `There were no messages that passed the filter within the time limit!`
            );
        });
    })
    .catch(function(err) {
        console.log(err);
    });
}

此功能推断倒计时信息显示。编辑相同的消息对象,直到计时器变为零,然后Promise得到解决,从而触发.then(...内的下一个runWordGame方法。

// Function displays countdown message, then passes Message obj back to caller
function displayMessageCountdown(channel) {
    let timer = 3;

    return new Promise( (resolve, reject) => {
        channel.send("Starting in..")
        .then(function(msg) {
            var interval = setInterval(function () {
                msg.edit(`Starting in **${timer--}**..`);

                // clear timer when it gets to 0
                if (timer === 0) {
                    clearInterval(interval);
                    resolve(msg);
                }
            }, 1000);
        })
        .catch(reject);
    }); 
}

如果您有疑问,或者您正在寻找不同的最终结果,请告诉我。