【问题标题】:How to make a custom embed based on input gathered from user input through a prompt - Discord.js如何根据通过提示从用户输入收集的输入进行自定义嵌入 - Discord.js
【发布时间】:2021-06-23 14:50:46
【问题描述】:

我正在尝试发出建议命令,如果用户在服务器中键入 =suggest,它将在他们的 DM 中创建一个提示,要求提供不同的规范。

但是,我不确定如何获取用户输入并在嵌入中使用该输入。我该怎么做?

例如: 机器人会在 DM 的 中询问“你希望标题是什么?”,然后用户会用他们想要的标题进行响应,并将该输入设置为标题。

【问题讨论】:

    标签: javascript node.js discord.js


    【解决方案1】:

    您可以使用消息收集器。我在这里使用channel.awaitMessages

    const prefix = '!';
    
    client.on('message', (message) => {
      if (message.author.bot || !message.content.startsWith(prefix)) return;
      const args = message.content.slice(prefix.length).split(/ +/);
      const command = args.shift().toLowerCase();
    
      if (command === 'suggest') {
        // send the question
        message.channel.send('What would you like the title to be?');
    
        // use a filter to only collect a response from the message author
        const filter = (response) => response.author.id === message.author.id;
        // only accept a maximum of one message, and error after one minute
        const options = { max: 1, time: 60000, errors: ['time'] };
    
        message.channel
          .awaitMessages(filter, options)
          .then((collected) => {
            // the first collected message's content will be the title
            const title = collected.first().content;
            const embed = new MessageEmbed()
              .setTitle(title)
              .setDescription('This embed has a custom title');
    
            message.channel.send(embed);
          })
          .catch((collected) =>
            console.log(`After a minute, only collected ${collected.size} messages.`),
          );
      }
    });
    

    我刚刚注意到您想通过 DM 发送它。在这种情况下,你可以.send()第一条消息,等待它被解析,这样你就可以使用channel.createMessageCollector()在频道中添加一个消息收集器。我添加了一些 cmets 来解释它:

    const prefix = '!';
    
    client.on('message', async (message) => {
      if (message.author.bot || !message.content.startsWith(prefix)) return;
    
      const args = message.content.slice(prefix.length).split(/ +/);
      const command = args.shift().toLowerCase();
      const MINUTES = 5;
    
      if (command === 'suggest') {
        const questions = [
          { answer: null, field: 'title' },
          { answer: null, field: 'description' },
          { answer: null, field: 'author name' },
          { answer: null, field: 'colour' },
        ];
        let current = 0;
    
        // wait for the message to be sent and grab the returned message
        // so we can add the message collector
        const sent = await message.author.send(
          `**Question 1 of ${questions.length}:**\nWhat would you like the ${questions[current].field} be?`,
        );
    
        const filter = (response) => response.author.id === message.author.id;
        // send in the DM channel where the original question was sent
        const collector = sent.channel.createMessageCollector(filter, {
          max: questions.length,
          time: MINUTES * 60 * 1000,
        });
    
        // fires every time a message is collected
        collector.on('collect', (message) => {
          // add the answer and increase the current index
          questions[current++].answer = message.content;
          const hasMoreQuestions = current < questions.length;
    
          if (hasMoreQuestions) {
            message.author.send(
              `**Question ${current + 1} of ${questions.length}:**\nWhat would you like the ${questions[current].field} be?`,
            );
          }
        });
    
        // fires when either times out or when reached the limit
        collector.on('end', (collected, reason) => {
          if (reason === 'time') {
            return message.author.send(
              `I'm not saying you're slow but you only answered ${collected.size} questions out of ${questions.length} in ${MINUTES} minutes. I gave up.`,
            );
          }
    
          const embed = new MessageEmbed()
            .setTitle(questions[0].answer)
            .setDescription(questions[1].answer)
            .setAuthor(questions[2].answer)
            .setColor(questions[3].answer);
    
          message.author.send('Here is your embed:');
          message.author.send(embed);
          // send a message for confirmation
          message.author.send('Would you like it to be published? `y[es]/n[o]`');
          message.author.dmChannel
            .awaitMessages(
              // set up a filter to only accept y, yes, n, and no
              (m) => ['y', 'yes', 'n', 'no'].includes(m.content.toLowerCase()),
              { max: 1 },
            )
            .then((coll) => {
              let response = coll.first().content.toLowerCase();
              if (['y', 'yes'].includes(response)) {
                // publish embed, like send in a channel, etc
                // then let the member know that you've finished
                message.author.send('Great, the embed is published.');
              } else {
                // nothing else to do really, just let them know what happened
                message.author.send('Publishing the embed is cancelled.');
              }
            })
            .catch((coll) => console.log('handle error'));
        });
      }
    });
    

    PS:你可以在DiscordJS.guide了解更多关于消息收集器的信息。

    【讨论】:

    • 嘿!惊人的代码,它工作得很好。我如何让它发送最终嵌入到 DM 中,然后用“是/否”提示提示用户?
    猜你喜欢
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    相关资源
    最近更新 更多