英文:
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('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();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论