Search code examples
node.jstelegraf.js

How do I add parameters to nodejs telegraf.js commands?


I add parameters to my commands and try to get results according to those parameters, for example

/query -name mars

When I write this, I want it to be detected according to the name here, how do I do it?


Solution

  • You can use telegraf's middleware system. Here is a sample code:

    const { Telegraf } = require('telegraf');
    const bot = new Telegraf('YOUR_BOT_TOKEN');
    bot.command('query', (ctx) => {
      const commandArgs = ctx.message.text.split(' ');
      for (let i = 1; i < commandArgs.length; i++) {
        const arg = commandArgs[i];
        
        if (arg.startsWith('-')) {
          const paramName = arg.substring(1); 
          const paramValue = commandArgs[i + 1] || '';
          switch (paramName) {
            case 'name':
              queryByName(ctx, paramValue);
              break;      
            default:
              ctx.reply(`Unknown parameter: ${paramName}`);
              break;
          }
          
          i++;
        }
      }
    });
    
    function queryByName(ctx, name) {
      ctx.reply(`Querying by name: ${name}`);
    }
    bot.launch();