Skip to content
Noah Loomans edited this page Jul 14, 2017 · 6 revisions

Commands

You can listen on incoming command requests using the command method of bot. Commands can use the argument parser of telegram-api which parses commands for you.

Commands have two syntaxes:

  • Simple -> /command
  • Groups -> /command@BotUserName (e.g. /start@JavaScriptBot)

Using the command method, we listen on both, and we strip the @BotUserName part, so when listening on command messages, you can make sure you always get the first syntax.

bot.command('say', message => {
  bot.send(new Message().text(message.text.slice(4)).to(message.chat.id));
});

// /say Hi => Hi
// /say@JavaScriptBot => Hi

Arguments

Arguments are split into three types

  • Required => <argname> – If a required argument is not supplied, the bot will ask for it with this message: Enter value for ${argname}, and the listener is called only when all the required arguments have been supplied
  • Optional => [argname]
  • Rest => ...argname – This type allow for multi-word arguments which take up rest of the arguments
bot.command('fetch <url> [repeat]', message => {
  console.log(message.args);
});
// Saying "/fetch dat 5" will log => { url: 'dat', repeat: '5' }

Rest

bot.command('say ...msg', message => {
  console.log(message.args.msg);
});
// Saying "/say hey wassup" will log => {msg: 'hey wassup'}

Not Found

You can listen on command-notfound event of bot to get notified about commands which you are not accepting. Please note that it's a good practice not to spam groups about commands you don't support, so we suggest you don't sends messages like "Command Not Found!" to groups.

To do this, you should know that groups have negative chat.ids, so you can detect if the message is coming from a group or not, see this:

bot.on('command-notfound', message => {
  if (message.chat.id > 0) {
    bot.send(new Message().text('Command not found').to(message.chat.id));
  }
});
Clone this wiki locally