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

问题描述 投票:1回答:1

所以我是新手,不和僵尸和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并等待,如果这是可行的,我也会喜欢它。

javascript discord discord.js
1个回答
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);
    }); 
}

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

© www.soinside.com 2019 - 2024. All rights reserved.