如何向 Node.js 的 telegraf.js 命令添加参数?

huangapple go评论62阅读模式
英文:

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

问题

我向我的命令添加参数,并尝试根据这些参数获取结果,例如

/query -name mars

当我写这个命令时,我希望根据这里的"name"参数来检测它,我该如何做呢?

英文:

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?

答案1

得分: 0

你可以使用Telegraf的中间件系统。以下是示例代码:

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();

请注意,我已经将代码翻译成中文。

英文:

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

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

function queryByName(ctx, name) {
  ctx.reply(`Querying by name: ${name}`);
}
bot.launch();

huangapple
  • 本文由 发表于 2023年6月30日 01:47:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76583473.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定