javascript - 尝试创建仅在满足确切字数时才会继续的机器人命令。(不和谐机器人 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.');
}
});
}
});
解决方案
你在正确的轨道上,但犯了一个小错误。您正在检查.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'));
推荐阅读
- rasa-nlu - 使用自定义表单填充插槽时出现问题(无法提取插槽)
- celery - 扭曲的反应器在芹菜内无法正常运行
- javascript - 如何解决 Angular 中的 ISlimScrollOptions 导入错误?
- ssh - Jmeter 非 GUI 模式 csv 报告未显示延迟
- wordpress - 无法访问 wordpress 插件的设置
- angular - 应用加载时填充 Angular 数组的 HTTP 请求
- java - IntelliJ IDEA 早上搭建项目
- python - 合并 pandas 中的两个系列时间间隔(交集)
- python - 在 scikit-learn、keras、tensorflow 和 mxnet 中保存机器学习模型的所有格式是什么?
- unix - Bash Shell:通过更新学生的分数来更新文件中学生的顺序