You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Node.js Telegraf.js命令添加参数并解析参数值?

在Telegraf.js中为命令添加并解析参数

下面提供两种实用的实现方式,帮你处理类似/query -name mars的命令参数解析:

方法一:手动正则解析(无需额外依赖)

直接通过正则表达式提取参数键值对,适合简单的参数场景:

const { Telegraf } = require('telegraf');
const bot = new Telegraf('你的机器人Token');

bot.command('query', (ctx) => {
  // 剥离命令本身,获取参数部分
  const argsContent = ctx.message.text.replace(/^\/query\s*/, '').trim();
  
  if (!argsContent) {
    return ctx.reply('请提供参数,示例:/query -name mars');
  }

  // 用正则匹配 `-key value` 格式的参数
  const params = {};
  const paramMatcher = /-(\w+)\s+(\S+)/g;
  let matchResult;
  
  while ((matchResult = paramMatcher.exec(argsContent)) !== null) {
    params[matchResult[1]] = matchResult[2];
  }

  // 根据参数返回对应结果
  if (params.name) {
    ctx.reply(`你指定的名称参数是:${params.name}`);
  } else {
    ctx.reply('未检测到name参数,请使用格式:/query -name 目标名称');
  }
});

bot.launch();

方法二:使用minimist库处理复杂参数

如果需要支持更复杂的参数格式(比如带空格的值、短参数缩写等),可以用minimist这个轻量的参数解析库:

  1. 先安装依赖:
npm install minimist
  1. 实现代码:
const { Telegraf } = require('telegraf');
const minimist = require('minimist');
const bot = new Telegraf('你的机器人Token');

bot.command('query', (ctx) => {
  // 拆分命令后的参数为数组(跳过命令本身)
  const argsArray = ctx.message.text.split(/\s+/).slice(1);
  // 用minimist解析参数
  const parsedParams = minimist(argsArray);

  if (parsedParams.name) {
    ctx.reply(`查询到名称参数:${parsedParams.name}`);
  } else {
    ctx.reply('请提供name参数,示例:/query -name mars');
  }
});

bot.launch();

注意事项

  • 如果参数值包含空格,使用minimist时可以用引号包裹值,比如/query -name "mars red",库会自动识别完整值;
  • 手动解析的正则可以根据需求调整,比如支持不带值的布尔参数(如/query -active)。

内容的提问来源于stack exchange,提问作者mars0j

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 13:00:02