xooniverse / televerse

Your gateway to seamless Telegram Bot Development 💙
https://televerse.xooniverse.com
BSD 3-Clause "New" or "Revised" License
60 stars 10 forks source link

`requestContact` handler callback doesn't works #288

Closed kitsuniru closed 1 month ago

kitsuniru commented 1 month ago

Hi! requestContact in KeyboardMenu doesn't works, it just ignores handler callback and does literally nothing

import 'package:televerse/televerse.dart';

void main(List<String> arguments) async {
  final bot = Bot('___', loggerOptions: LoggerOptions());

  bot.command("start", (ctx) async {
    final menu = KeyboardMenu(
      resizeKeyboard: true,
      oneTimeKeyboard: true,
    ).requestContact("Send my number", (ctx) {
    // These ignored
      final phone = ctx.message?.contact?.phoneNumber;
    // These ignored
      print('Got number: $phone');

    });

    await ctx.reply(
      "Halo!",
      replyMarkup: menu,
    );
  });

  await bot.start();
}
kitsuniru commented 1 month ago

Expectation: 1) "Halo!" arrives with a keyboard (+) 2) We press on "Send my number" (+) 3) Number sended and printed out in logs (-)

HeySreelal commented 1 month ago

Hey, thanks for bringing this up. I'll investigate this quickly and get back to you as soon as I can. Thanks :)

HeySreelal commented 1 month ago

Yep, I'm back :)

I just tried your code. Actually, there's a small mistake or I should say one line that you've missed.

For menus to work - I mean to make them interactive, you should attach the menu to your bot. Here's how to:

  bot.attachMenu(menu);

So, in best practice your code should be something like:

import 'dart:io';
import 'package:televerse/televerse.dart';

void main(List<String> arguments) async {
  final bot = Bot(
    Platform.environment["BOT_TOKEN"]!,
    loggerOptions: LoggerOptions(),
  );

  // Create the menu outside the 'start' handler
  final menu = KeyboardMenu(
    resizeKeyboard: true,
    oneTimeKeyboard: true,
  ).requestContact("Send my number", (ctx) {
    final phone = ctx.message?.contact?.phoneNumber;
    print('Got number: $phone');
  });

  // ✨ Important: Attach the menu to the bot to make it interactive
  bot.attachMenu(menu);

  bot.command("start", (ctx) async {
    // Use the Menu :)
    await ctx.reply(
      "Halo!",
      replyMarkup: menu,
    );
  });

  await bot.start();
}

Why?

Creating and attaching menu inside handlers can cause to memory leaks - as they would be created and redundantly attached every time the "start" handler is called.

Please let me know if this still not working.

Hope this helps :)

HeySreelal commented 1 month ago

Btw, just bringing to your attention, please feel free to join our Telegram group if you're stuck at any point with your bot development - you're most likely to get your questions answered much quicker there. (Completely optional, but feel free to).

Happy Televersing! 🚀

kitsuniru commented 1 month ago

Yeah, that works, thank you!