Discord.js разрешите больше слов за командой

#javascript #node.js #discord #discord.js #command

Вопрос:

Я пытаюсь создавать команды, однако они срабатывают только при написании определенного слова… !price только для примера.. Я хочу, чтобы он срабатывал даже после того, как любой текст будет написан после команды !price random text bla bla bla Я вроде как не могу понять, так как пытаюсь использовать разные файлы для каждой команды, чтобы в главном файле не было всего .js .

 // Require the necessary discord.js classes
const { Client, Intents } = require('discord.js');
const config = require("./configtest.json");
const ping = require("./commands/ping.js")
const price = require("./commands/price.js")

const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });

//Commands
client.on("messageCreate", (message) => {
  if (message.author.bot) return;
  var command = (message.content == "!price" || message.content == "!ping")
  if(command){ // Check if content is defined command
    if (message.content.toLowerCase() == "!price" ) command = price
    if (message.content.toLowerCase() == "!ping" ) command = ping
      command(message); // Call .reply() on the channel object the message was sent in
    }
  });
 

Это работает нормально , однако, если я что-нибудь поставлю за !price операционной !ping , они не сработают.

Я тоже пробовал это, но у меня это не работает…

 client.on("messageCreate", (message) => {
  if (message.author.bot) return;
  var command = (message.content == "!price" || message.content == "!ping")
  if(command){ // Check if content is defined command
    const args = message.content.slice(config.prefix.length).trim().split(/  /g);
    const cmd = args.shift().toLowerCase();
    if (cmd === "!price" ) command = price
    if (cmd === "!ping" ) command = ping
      command(message); // Call .send() on the channel object the message was sent in
    }
  });
 

Ошибка: command(message); // Call .send() on the channel object the message was sent in ^TypeError: command is not a function

Мой ping.js файл выглядит так

 module.exports = (message) => { // Function with 'message' parameter
    message.reply("Pong!").catch(e => console.log(e));
}
 

Ответ №1:

Вместо использования оператора равенства вы можете использовать String.prototype.startsWith , чтобы вы могли видеть, начинается ли он с команды, а не является точно командой.

 var command = (message.content.startsWith("!price") || message.content.startsWith("!ping"))
 

Это будет работать, потому что строка типа !ping abc начинается с !ping . Однако это не работает, если оно находится посередине (обычно это не то, что люди хотят от ботов), как это: abc !ping abc

Комментарии:

1. Это тоже интересное решение 🙂 Протестировал его и работает нормально.

2. Вы можете отметить это как правильное, нажав на галочку, если это помогло!

3. Сделано хе-хе, 😉 Я нашел другое решение, но это тоже очень полезно! Хорошего дня/вечера.

Ответ №2:

Я смог найти решение, сначала определить команду благодаря нашим аргументам, а затем сравнить в операторе if, известна ли отправленная нами команда.

 client.on("messageCreate", (message) => {
  if (message.author.bot) return;
  const args = message.content.slice(config.prefix.length).trim().split(/  /g);
  const cmd = args.shift().toLowerCase();
  var command = (cmd === "price" || cmd === "ping")
  if(command){ // Check if content is defined command
    if (cmd === "price") command = price
    if (cmd === "ping") command = ping
      command(message); // Call .send() on the channel object the message was sent in
    }
  });
 

Вы также можете удалить .slice(config.prefix.length) , если вы не хотите использовать определенный префикс в своем config.json , поэтому здесь нам пришлось добавить ! перед спусковым word крючком .

 client.on("messageCreate", (message) => {
  if (message.author.bot) return;
  const args = message.content.trim().split(/  /g);
  const cmd = args.shift().toLowerCase();
  var command = (cmd === "!price" || cmd === "!ping")
  if(command){ // Check if content is defined command
    if (cmd === "!price") command = price
    if (cmd === "!ping") command = ping
      command(message); // Call .send() on the channel object the message was sent in
    }
  });