【问题标题】:Second function in setTimeout() doesn't runsetTimeout() 中的第二个函数不运行
【发布时间】:2018-04-20 13:16:44
【问题描述】:

所以我是不和谐机器人和 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) 不起作用。如果有人可以帮助我更改此代码以使用异步并等待是否可行,我也会很高兴。

【问题讨论】:

    标签: javascript discord discord.js


    【解决方案1】:

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

    这是收听来自不同用户的消息的机器人。一旦用户输入'?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 被解析,这会触发 runWordGame 中的下一个 .then(... 方法。

    // 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);
        }); 
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-04
      • 2016-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多