如何在Discord.js漫游器中创建动态聊天?

时间:2019-09-22 18:06:27

标签: bots discord discord.js

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

2 个答案:

答案 0 :(得分:0)

从某种意义上讲,可以实现该方法的一种方式是,使机器人从中读取消息的每个通道保持一个“状态”。这个想法是,只要漫游器从某个特定频道收到新消息,它就会首先检查它是否已经在对话过程中。根据该状态的值和输入,机器人将执行适当的操作。

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
}
}

答案 1 :(得分:0)

Discord.js具有可用于此目的的方法MessageCollector。将其设置为TextChannel后,它将根据CollectorFilterMessageCollectorOptions收集邮件。

这是为了获得答案,但要无缝地编辑原始问题消息,只需在存储的消息ID方法上使用Message#edit()

例如:

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来详细解释异步收集器和更多有趣的东西!