Search code examples
discord.js

Arguments for Discord.js


how do I read args in discord.js? I am trying to create a support bot and I want to have an !help {topic} command. how do I do that? my current code is very basic

const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = ("!")
const token = ("removed")

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

client.on('message', msg => {
  if (msg.content === 'ping') {
    msg.reply('pong');
  }
  if (msg.content === 'help') {
    msg.reply('type -new to create a support ticket');
  }

});

client.login(token);

Solution

  • You can make use of a prefix and arguments like so...

    const prefix = '!'; // just an example, change to whatever you want
    
    client.on('message', message => {
      if (!message.content.startsWith(prefix)) return;
    
      const args = message.content.trim().split(/ +/g);
      const cmd = args[0].slice(prefix.length).toLowerCase(); // case INsensitive, without prefix
    
      if (cmd === 'ping') message.reply('pong');
    
      if (cmd === 'help') {
        if (!args[1]) return message.reply('Please specify a topic.');
        if (args[2]) return message.reply('Too many arguments.');
    
        // command code
      }
    });