首页 > 解决方案 > 在 Node.js 问题中使用 Telegraf 的 Telegram 机器人

问题描述

我对 Node.js 还是很陌生,我正在尝试制作一个提示用户搜索单词然后在 MySQL 数据库中查找匹配行的机器人。搜索过程应分为两个步骤:

  1. 用户被要求通过内联键盘选择一个选项,然后;
  2. 要求用户写出要搜索的单词。

机器人应在步骤 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();

使用向导是最好的方法吗?谢谢!,我刚刚开始:)

标签: javascriptnode.jstelegramtelegraf

解决方案


推荐阅读