首页 > 解决方案 > 如何使机器人将单词输入到预设的文本块中(Discord.js)

问题描述

我是代码的初学者,我想让我的机器人输入一个单词,然后用一段预先写好的文本,把这个词放在文本中。

命令:[prefix] [command] [word]

所以,一个抱怨油条的例子:ch complain churros

如果预设文字是:每天,我会在[单词]的气味中醒来。我厌倦了[单词]。

那么,我希望命令的输出是:每天,我醒来时都会闻到油条的味道。我厌倦了油条。

我怎样才能做到这一点?一个如何编码的例子将不胜感激。:) 谢谢!

标签: javascriptnode.jsdiscorddiscord.jsbots

解决方案


您可以使用.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));
  }
});

它的工作原理是这样的:

在此处输入图像描述


推荐阅读