javascript - 在 Node.js 问题中使用 Telegraf 的 Telegram 机器人
问题描述
我对 Node.js 还是很陌生,我正在尝试制作一个提示用户搜索单词然后在 MySQL 数据库中查找匹配行的机器人。搜索过程应分为两个步骤:
- 用户被要求通过内联键盘选择一个选项,然后;
- 要求用户写出要搜索的单词。
机器人应在步骤 1 中由选项选择的表中搜索数据库,以查找在步骤 2 中输入的单词并检索该行。此外,机器人应该处理多个用户。我尝试过使用 Wizards,但由于文档不多,我无法处理内联键盘回调。Sql 部分问题不大,我使用的是 npm "mysql"。
这是我想出的代码:
const { Telegraf } = require('telegraf');
const session = require('telegraf/session');
const Stage = require('telegraf/stage');
const WizardScene = require('telegraf/scenes/wizard');
const bot = new Telegraf('token-here');
bot.start( (ctx) => {
ctx.reply('Bot started!');
})
const menuKeyboard = [
[
{text: 'OPT1', callback_data: 'CB_OPT1'},
{text: 'OPT2', callback_data: 'CB_OPT2'},
{text: 'OPT3', callback_data: 'CB_OPT3'}
],
[
{text: 'OPT4', callback_data: 'CB_OPT4'},
{text: 'OPT5', callback_data: 'CB_OPT5'},
{text: 'OPT6', callback_data: 'CB_OPT6'}
]
]
bot.action(['CB_OPT1', 'CB_OPT2', 'CB_OPT3', 'CB_OPT4', 'CB_OPT5', 'CB_OPT6'], (ctx) => {
ctx.deleteMessage();
ctx.reply(`Insert search term:`);
return ctx.wizard.steps[1](ctx); //Re-enters wizard?
})
//Wizzard setup
const superWizard = new WizardScene('super-wizard',
//Step 1 - Ask option
ctx => {
ctx.reply("Select an option:", {
reply_markup: {
inline_keyboard: menuKeyboard
}
});
ctx.wizard.state.data = {};
return ctx.wizard.next();
//Callback calls bot.action above
},
ctx => {
ctx.deleteMessage();
ctx.wizard.state.data.option = ctx.message.text;
}
);
const stage = new Stage([superWizard]);
bot.use(session());
bot.use(stage.middleware());
bot.command('search', (ctx) => {
//ctx.scene.enter('super-wizard');
ctx.reply("Select an option:", {
reply_markup: {
inline_keyboard: menuKeyboard
}
});
})
bot.launch();
使用向导是最好的方法吗?谢谢!,我刚刚开始:)
解决方案
推荐阅读
- ruby-on-rails - Cloudinary 使用“未初始化的常量 Cloudinary”打破 RSpec 测试
- spartacus-storefront - 如何正确覆盖默认的 spartacus 组件
- google-sheets - 如果选中复选框,则突出显示列的公式 - Google 表格
- powershell - Powershell 不会在电子邮件 html 正文中输出“£”
- scala - Apache Spark根据列的不同值计算列值
- gcc - 用于堆栈与堆访问的 gcc 程序集
- android - RecyclerView 仅显示两个文本视图?其他不显示...项目不显示
- python - 为什么 Pycharm 不突出 TODO 的?
- html - 将一个元素放在另一个垂直居中的下方
- c - 指向作为函数参数的指针的指针