Telegraf.js将数据从按钮传递到处理WizardScene的函数

问题描述

我需要传递从数据库中检索到的一些数据。

当我单击一个按钮时,我会向出现问题的用户发送私人消息。我需要将某些数据从该按钮传递到已发送的消息。因为,在该消息中,我有一个按钮可以启动WizardScene。所以我该怎么做传递数据?谢谢。

这是我的代码

功能可以发布带有说明和回调按钮的照片。

my function() {
...
let productId = //obtain from a db;
await bot.telegram.sendPhoto(
      channel_id,{ source: filepath },{
        caption: description.join("\n"),parse_mode: 'MarkdownV2',reply_markup: productButtons.reply_markup
      }
    )
  return productId;
...}

按钮是:

const productButtons = Extra.markup((m) =>
  m.inlineKeyboard([
    [m.callbackButton('TEST','test_btn')],])
)

当有人询问时,它会向私人用户发送以下消息:

bot.action('testa_btn',(ctx) => {
    console.log('testa')
    let text = `My text about ${productId}`

    ctx.telegram.sendMessage(ctx.from.id,o_functions.escapeReplace(text),{
      parse_mode: 'MarkdownV2',reply_markup: startBtn.reply_markup
    })
    
  });

这将发送一个文本,我需要在其中写入我的productid,另一个是我开始向导场景的按钮:

const startBtn = Extra.markup((m) =>
  m.inlineKeyboard([
    [m.callbackButton('START','start_btn_wizard')],])
);

bot.action('start_btn_wizard',(ctx) => {
    return ctx.scene.enter('super-wizard');
  })

那么我如何将我的productId变量首先传递给按钮TEST,然后传递给向导场景?我需要在用户对话框的向导中使用它。

谢谢

解决方法

您需要做一些事情来将数据从回调按钮传递到处理程序,然后再传递到向导场景。

  1. 将所需数据添加到按钮。请注意我如何将产品 ID 附加到回调数据中。

    const startBtn = Extra.markup((m) =>
      m.inlineKeyboard([
        [m.callbackButton('START',`start_btn_wizard_${product_id}`)],])
    );
    
  2. 使用正则表达式而不是文字字符串接收按钮回调,并从回调数据中提取产品 ID。

    bot.action(/start_btn_wizard_+/,(ctx) => {
        let product_id = ctx.match.input.substring(17);
    
        // add all necessary validations for the product_id here
        return ctx.scene.enter('super-wizard');
    });
    
  3. 将获取的 id 传递给向导场景,并使用 ctx.scene.state 从场景内部再次提取它。

    bot.action(/start_btn_wizard_+/,(ctx) => {
        let product_id = ctx.match.input.substring(17);
    
        // add all necessary validations for the product_id here
        return ctx.scene.enter('super-wizard',{product_id: product_id});
    });
    

从向导内部,您可以使用 ctx.scene.state.product_id 访问 product_id。

希望这对某人有所帮助,即使对于 OP 来说可能为时已晚