簡體   English   中英

setTimeout()中的第二個函數未運行

[英]Second function in setTimeout() doesn't run

因此,我是不熟悉Botting和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)不起作用。 如果有人可以幫助我將這段代碼更改為使用異步並且如果可行的話,我也很喜歡。

我開始研究您的問題,這是我想出的系統。

這是機器人在偵聽來自不同用戶的消息。 用戶鍵入'?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的下一個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);
    }); 
}

如果您有任何疑問,或者正在尋找其他最終結果,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM