javascript - 如何使机器人将单词输入到预设的文本块中(Discord.js)
问题描述
我是代码的初学者,我想让我的机器人输入一个单词,然后用一段预先写好的文本,把这个词放在文本中。
命令:[prefix] [command] [word]
所以,一个抱怨油条的例子:ch complain churros
如果预设文字是:每天,我会在[单词]的气味中醒来。我厌倦了[单词]。
那么,我希望命令的输出是:每天,我醒来时都会闻到油条的味道。我厌倦了油条。
我怎样才能做到这一点?一个如何编码的例子将不胜感激。:) 谢谢!
解决方案
您可以使用.replaceAll()
来替换字符串中每个出现的字符串。如果您想替换[word]
为“每天,我醒来时都会闻到 [word] 的气味。我厌倦了 [word]。” 您可以执行以下操作:
const text = "everyday, I wake up to the smell of [word]. I'm sick of [word]."
console.log(text.replaceAll('[word]', 'churros'))
在 Discord.js 中,您可以获取传入消息并替换字符串,如下所示:
const { Client } = require('discord.js');
const client = new Client();
const prefix = '!';
client.on('message', (message) => {
if (message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'complain') {
// grab the first word after the command
const [word] = args;
const text = "Everyday, I wake up to the smell of [word]. I'm sick of [word].";
if (!word) {
return message.reply('You need to send a word to complain about!');
}
message.channel.send(text.replaceAll('[word]', word));
}
});
它的工作原理是这样的:
推荐阅读
- reactjs - 更新嵌套数组中的对象,react-redux
- java - 如何解决recyclerview中按钮的自动点击问题?那是一个错误吗?
- javascript - Fullcalendar 事件属性验收
- linkedin - 如何从我是页面管理员的 LinkedIn 获取组织的帖子
- php - 我如何使用 curl 修复此登录
- python - pyzotero 批量更新字段
- python-3.x - 为什么python代码不能到达else语句?
- spring-boot - 我可以在 Spring Boot 1.5.x 中使用“Spring Data JDBC”吗?
- c - 为什么要打印两个指针相减的结果并抛出警告?
- c# - 定期使用 SignalR (Core) 会导致线程挂起