首页 > 解决方案 > 尝试创建仅在满足确切字数时才会继续的机器人命令。(不和谐机器人 Node.js)

问题描述

尝试创建仅在满足确切字数时才会继续的机器人命令。

我正在努力寻找有关我需要的信息的蚂蚁类文档。基本上,我试图让机器人等待响应,并且响应必须恰好有 4 个单词,否则,它将通过替代响应。

我认为下面的这个片段会让我到达某个地方,但我认为我做得不对。有谁知道如何解决这一问题?

if (collected.first().content.length == 4 ) {}

实际代码如下。感谢您的阅读!


bot.on('message', (message) => {
    if (message.content === '!host') {
        message.reply('Please send (Insert 4 word requirement here)');
        message.channel.awaitMessages(m => m.author.id == message.author.id, {
            max: 1,
            time: 30000
        }).then(collected => {
            if (collected.first().content.length == 4) { //This is where I'm struggling. I want the bot to check if the collected message has exactly 4 words. If not, it should give the else if response.
                var embed = new Discord.RichEmbed()
                    .setAuthor(message.author.username, message.author.avatarURL)
                    .setDescription(collected.first().content + '\n \n(Insert message here).')
                    .setTimestamp(new Date())
                    .setColor('0x7346EE');
                DChannel.send(embed); //This section is another part of my working bot. 
            } else if (collected.first().content.length != "4") {
                message.channel.send('Please try again in the correct format.');
            }
        });
    }
});

标签: javascriptnode.jsdiscorddiscord.js

解决方案


你在正确的轨道上,但犯了一个小错误。您正在检查.length收集的消息内容的属性,这是一个字符串。调用.length它会给你字符串长度(因此它具有的字符数量),所以只有 4 个字母的消息会匹配你的if语句。

通过首先在空格上拆分消息内容,我们可以获得消息中的单词数量。看看下面的示例代码并试一试。

.then(collected => {
  // Check if we got a message before moving on
  if (!collection.size) return;

  // Get the first collected message and split its contents on a space
  const messageWords = collection.first().content.split(' ');

  // Check if the array of words has a length of 4
  if (messageWords.length === 4) {
    var embed = new Discord.RichEmbed()
      .setAuthor(message.author.username, message.author.avatarURL)
      .setDescription(collected.first().content + '\n \n(Insert message here).')
      .setTimestamp(new Date())
      .setColor('0x7346EE');
      
    DChannel.send(embed);
  } else {
    message.channel.send('Please try again in the correct format.');
  }
});

根据评论更新

如果你想让每个单词都换行,有两种方法。您可以.addField()对每个单词使用该方法,也可以对整个数组使用一次。

如果您想为每个单词添加一个新字段,您可以在定义嵌入之后和发送之前执行以下操作。它将为每个单词添加一个新字段:

messageWords.forEach((word, index) => {
  embed.addField(`Word ${index}`, word);
});

如果您只想添加一个所有单词由换行符分隔的字段,您可以执行以下操作(同样在定义嵌入之后和发送之前):

embed.addField('Message words', messageWords.join('\n'));

推荐阅读