1

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

当我点击一个按钮时,我会向已点击的用户发送一条私人消息。我需要将该按钮中的一些数据传递给发送的消息。因为,在那条消息中,我有一个启动 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,然后传递给向导场景?我需要在用户对话框上的向导上使用它。

谢谢你

4

1 回答 1

1

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

  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.

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

于 2021-03-29T17:07:09.547 回答