2017-11-08 11 views
1

그래서 저는 botting과 js를 혼란에 빠뜨리므로 내 자신의 봇과 놀고 있습니다. 나는 타이핑 미니 게임을 만들고 싶다. 채팅에 ?type을 입력하면 봇에서 채팅 내용을 말하고 카운트 다운하는 동안 해당 메시지를 편집합니다. 카운트 다운이 끝나면 임의로 생성 된 단어가 표시됩니다. 플레이어는 채팅에서 정확한 임의의 단어를 입력해야하며 봇은 총 소요 시간을 표시합니다. 이 아래로 0 내가 message.channel.send(randomWord) 작동하지 않는 이유를 이해 해달라고을 계산 한 후 현재 코드가 중지setTimeout()의 두 번째 함수가 실행되지 않습니다.

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; 

:

여기 내 코드입니다. 또한 누군가가 내가 asynch를 사용하기 위해이 코드를 변경하도록 도와 줄 수 있다면 그것이 좋을 것이다.

답변

0

나는 당신의 문제를 연구하기 시작했고, 내가 생각해 낸 시스템이있다.

다른 사용자의 메시지를 듣는 봇입니다. 사용자가 '?type'을 입력하면 메시지 채널에서 전달되는 runWordGame 함수가 호출됩니다. 여기에서 runWordGame

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

는 보트 후, 임의의 단어를 생성하여 사용자에게 표시 카운트 (displayMessageCountdown 아래 참조). 카운트 다운이 끝나면 메시지는 임의의 단어로 편집됩니다. 그런 다음, 봇은 사용자가 임의의 단어를 입력 할 때까지 기다리는 동안 10 초 동안 1 개의 메시지를 기다립니다. 성공하면 성공 메시지가 전송됩니다. 그렇지 않으면 오류 메시지가 전송됩니다.

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

이 기능은 카운트 다운 메시지 표시를 추정합니다. 타이머가 0이 될 때까지 동일한 메시지 개체가 편집되고 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); 
    }); 
} 

궁금한 점이 있거나 다른 결과가 필요한 경우 알려주십시오.