如何让 Discord 机器人返回消息中的字数

时间:2021-01-05 13:12:30

标签: javascript node.js discord.js

client.on('message', message => {
    if (!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).trim().split(/ +/);
    const command = args.shift().toLowerCase();

    if (command === 'args-info') {
      if (!args.length) {
        return message.channel.send(`You didn't provide any arguments, ${message.author}!`);
      } else if (args[0] === 'foo') {
        return message.channel.send('bar');
      }

      message.channel.send(`Command name: ${command}\nArguments: ${args}`);
      message.channel.send(`Second argument: ${args[1]}`);
      message.channel.send(`Arguments: {}`);
    }
  }
}

这是与问题相关的部分。

如果您向机器人发送消息 “这是我的论点,您对此有何看法?”,我希望它返回:

Command name: args-info
Arguments: here,are,my,arguments,what,do,you,think,about,that
Second argument: are
**Arguments Length: 10** 

我需要找出计算句子中单词数的命令并更改它:message.channel.send(`Arguments: ${}`);

我对 Discord.js 函数不熟悉,不熟悉哪个函数可以算一个字符串。我会再看一些,但我还没有找到任何东西。我问的原因是这个人在他的代码中将其作为示例,但他从未展示如何返回答案的代码,我只是好奇。

https://discordjs.guide/creating-your-bot/commands-with-user-input.html#basic-arguments

2 个答案:

答案 0 :(得分:0)

发送这条消息,它应该会给你预期的结果。

message.channel.send(args.join(','));

要获取字符数,您可以这样做

message.channel.send(args.join(',').length);

参考资料

答案 1 :(得分:0)

args 已经是一个单词数组,因此您可以打印它的 .length 属性。它将返回该数组中元素的数量(在本例中为单词)。

message.channel.send(`Arguments length: ${args.length}`);

你可以在下面的代码中找到一些注释来更好地解释它:

client.on('message', (message) => {
  if (!message.content.startsWith(prefix) || message.author.bot) return;

  // args is an array of all the words
  // including "args-info"
  const args = message.content
    // .slice() removes the prefix from the message content
    .slice(prefix.length)
    // .trim() removes spaces from both ends
    .trim()
    // .split() creates a new array by dividing the string
    // it splits the string everywhere it finds one or more spaces
    .split(/ +/);

  // the shift() method removes the first element
  // it removes args-info in this case
  const command = args.shift().toLowerCase();

  if (command === 'args-info') {
    if (!args.length) {
      return message.channel.send(
        `You didn't provide any arguments, ${message.author}!`,
      );
    }
    if (args[0] === 'foo') {
      return message.channel.send('bar');
    }

    message.channel.send(`Command name: ${command}`);
    message.channel.send(`Arguments: ${args}`);
    message.channel.send(`Second argument: ${args[1]}`);
    // args.length is the number of words
    message.channel.send(`Arguments length: ${args.length}`);
  }
});

它似乎按预期工作:

enter image description here

相关问题