【问题标题】:How can I create a dynamic chat in a Discord.js bot?如何在 Discord.js 机器人中创建动态聊天?
【发布时间】:2020-01-22 21:50:22
【问题描述】:

我的意思是像 React for Roles 机器人这样的聊天:当您执行命令 rr!reactionrole 以创建新的反应角色时,它会要求您输入一个频道,并且在您完全回答之后新消息,机器人的消息已被编辑,您必须在另一条新消息中回答新问题。这怎么可能?我希望我已经正确地解释了自己。谢谢

【问题讨论】:

    标签: bots discord discord.js


    【解决方案1】:

    Discord.js 有一个可以用于此目的的方法,MessageCollector。将其设置为TextChannel 后,它将根据CollectorFilterMessageCollectorOptions 收集消息。

    即得到答案,但无缝编辑原始问题消息,它只是使用Message#edit()存储消息ID的方法。

    例如:

    const questions = ['What role?', 'What message?', 'What emoji?'];
    
    const question = await message.channel.send(questions[0]); // store the question message object to a constant to be used later
    
    const filter = msg => msg.author.id === message.author.id; // creates the filter where it will only look for messages sent by the message author
    const collector = message.channel.createMessageCollector(filter, { time: 60 * 1000 }); // creates a message collector with a time limit of 60 seconds - upon that, it'll emit the 'end' event
    
    const answers = []; // basic way to store to the answers, for this example
    
    collector.on('collect', msg => { // when the collector finds a new message
      answers.push(msg.content);
      questions.shift();
      if (questions.length <= 0) return collector.stop('done'); // sends a string so we know the collector is done with the answers
      question.edit(questions[0]).catch(error => { // catch the error if the question message was deleted - or you could create a new question message
        console.error(error);
        collector.stop();
      });
    });
    
    collector.on('end', (collected, reason) => {
      if (reason && reason === 'stop') {
        // when the user has answered every question, do some magic
      }
      message.channel.send('You did not answer all the questions in time or the original message was deleted!');
    });
    

    注意:我没有测试过这个,它的制作不是很好,但你应该能够适应你的使用。我建议read this guide 来解释更多关于异步收集器和更多有趣的东西!

    【讨论】:

      【解决方案2】:

      在某种意义上实现这一点的一种方法是为机器人从中读取消息的每个通道保持一个“状态”。这个想法是,每当机器人从某个频道收到新消息时,它首先检查它是否已经在对话中。根据此状态的值和输入,机器人会执行适当的操作。

      var state = 0;
      
      //on rr!reactionrole
      {
      switch(state) {
       case 0: //start the conversation and change the state to 1; break;
       case 1: //continue the conversation, edit the message, set state to 2; break;
       //other cases
      }
      }
      

      【讨论】:

        猜你喜欢
        • 2022-12-23
        • 1970-01-01
        • 1970-01-01
        • 2022-01-10
        • 2020-08-27
        • 2017-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多