Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

CallbackQueryHandler stopped receiving updates#4767

AnsweredbyBibo-Joshi
neonaddict asked this question inQ&A
Discussion options

Recently I wrote a bot for my friends group chat that rolls a dice for you(sends dice message) and add a winning to user virtual balance.
Bot have admin rights, group is superchat.

Now I'm trying to implement /transfer command using ConversationHandler (code below).

What logic I want to implement:

  • call /transfer command in chat
  • show buttons with usernames in reply to that call
  • click on button
  • after click in reply to message with buttons wait for text input with number amount from user
  • User types amount -> show message in reply that transfer is successful

(I omitted DB-related and other commands logic, because they works perfectly)

importreimportosimportloggingfromtelegramimport (Update,InlineKeyboardButton,InlineKeyboardMarkup)fromtelegram.extimport (ConversationHandler,CommandHandler,MessageHandler,CallbackQueryHandler,Application,ContextTypes,filters)CHOOSING_USER,TYPING_AMOUNT=range(2)TOKEN=os.getenv("TOKEN")# Enable logginglogging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",level=logging.INFO)# set higher logging level for httpx to avoid all GET and POST requests being logged# logging.getLogger("httpx").setLevel(logging.WARNING)logger=logging.getLogger(__name__)defbuild_transfer_users_inline_keyboard_markup(users):keyboard= []foruserinusers:keyboard.append([InlineKeyboardButton(f"Transfer to{user.username}({int(user.balance)})",callback_data=f"{user.username}")])returnInlineKeyboardMarkup(keyboard)asyncdeftransfer(update:Update,context:ContextTypes.DEFAULT_TYPE)->int:logger.info("Got transfer")current_user=find_user_by_telegram_user_id(update.message.from_user.id)all_users_except_current=User.select().where(User.id!=current_user.id).order_by(User.balance.desc())awaitupdate.message.reply_text(f"Current balance -{int(current_user.balance)}.\nChoose a user for transfer:",reply_markup=build_transfer_users_inline_keyboard_markup(all_users_except_current))returnCHOOSING_USERasyncdeftransfer_user_choice(update:Update,context:ContextTypes.DEFAULT_TYPE)->int:logger.info("Got transfer_user_choice update")logger.info(update)query=update.callback_queryawaitquery.answer()logger.info("Waited for query answer")logger.info("Query data")logger.info(query.data)current_user=find_user_by_telegram_user_id(query.from_user.id)transfer_username=query.datatransfer_user=find_user_by_telegram_username(transfer_username)context.user_data["transfer_username"]=transfer_user.usernameawaitquery.message.reply_text(f'Enter amount (from 1 to{int(current_user.balance)}).')returnTYPING_AMOUNTasyncdeftransfer_amount(update:Update,context:ContextTypes.DEFAULT_TYPE)->int:current_user=find_user_by_telegram_user_id(update.message.from_user.id)transfer_username=context.user_data["transfer_username"]transfer_amount=int(update.message.text)if (current_user.balance-transfer_amount)<0.0:awaitupdate.message.reply_text('Insufficient balance. Enter another amount!')returnTYPING_AMOUNTtransfer_user=find_user_by_telegram_username(transfer_username)decrease_user_balance(current_user,transfer_amount)increase_user_balance(transfer_user,transfer_amount)awaitupdate.message.reply_text(f'{transfer_amount} sucessfully transfered to @{transfer_user.username}!')returnConversationHandler.ENDasyncdeftransfer_not_recognized(update:Update,context:ContextTypes.DEFAULT_TYPE)->int:context.user_data.clear()awaitupdate.message.reply_text("Transfer fallback")returnConversationHandler.ENDdefmain()->None:"""Start the bot."""# Create the Application and pass it your bot's token.application=Application.builder().token(TOKEN).build()transfer_handler=ConversationHandler(entry_points=[CommandHandler("transfer",transfer)],states={CHOOSING_USER: [CallbackQueryHandler(transfer_user_choice)            ],TYPING_AMOUNT: [MessageHandler(filters.Regex(re.compile(r"^\d+$"))&~(filters.COMMAND),transfer_amount                )            ],        },fallbacks=[MessageHandler(filters.COMMAND&filters.Regex("^/cancel_transfer"),transfer_not_recognized)]    )application.add_handler(MessageHandler(filters.Dice.DICE,check_for_dice))# delete dice message is sended not by bot, allow only to roll using /rollapplication.add_handler(CommandHandler("join_game",join_game))# creates Userapplication.add_handler(CommandHandler("balance",balance))# show current User balanceapplication.add_handler(CommandHandler("roll",roll_slot))# roll a diceapplication.add_handler(CommandHandler("all_users_balance",all_users_balance))# show all Users balanceapplication.add_handler(transfer_handler)application.run_polling(allowed_updates=[Update.ALL_TYPES])if__name__=="__main__":main()

And here is the part I don't understand.
Bot doesn't receive any updates when I click a button. transfer_user_choice func is not called ever (I added logs and they are empty).
I tried revoking token and use new, but it works only once or twice and then again nothing happens.
Also I noticed, I have another token for tests and when I run bot with test token it works like a charm - I receive update after clicking the button, etc.

So, main questions:

  • Can it be infrustructure related? Why it works only with one token? Can Telegram block updates if bot doesn't answer queryCallback fast enough?
  • Can it be related to InlineKeyboardMarkup size? When using "test" token number of buttons is around 5-6 and when using "production" token there can be around 20-22 buttons.
  • Or I just implemented wrong ConversationHandler logic?

Thanks for help in advance!

You must be logged in to vote

Hi. I don't see anything obviously wrong. As a first debugging step I suggest that you ensure the update is actually reaching your bot. For this you can do two things

  1. Set logging level to debug if the application:logging.getLogger("telegram.ext Application"). This should then show you all incoming updates in the logs. If you do see the callback query there, then something is going wrong in the application/handler setup. If it does not show, then the update does not reach your bot and the problem may lie on Telegrams end
  2. After the buttons show in the chat, stop the python script. Then open in your browser:https://api.telegram.org/bot/getUpdates. This is basically what your bot would do.…

Replies: 1 comment 1 reply

Comment options

Hi. I don't see anything obviously wrong. As a first debugging step I suggest that you ensure the update is actually reaching your bot. For this you can do two things

  1. Set logging level to debug if the application:logging.getLogger("telegram.ext Application"). This should then show you all incoming updates in the logs. If you do see the callback query there, then something is going wrong in the application/handler setup. If it does not show, then the update does not reach your bot and the problem may lie on Telegrams end
  2. After the buttons show in the chat, stop the python script. Then open in your browser:https://api.telegram.org/bot/getUpdates. This is basically what your bot would do. If the callback query is visible in the json reply then telegram is in fact forwarding the update to your bot and the problem is either in your bot receiving it or in the app/handler logic. Otherwise, it's telegrams fault for not reporting the update

I hope that was understandable.
Let me know what your findings are :)

You must be logged in to vote
1 reply
@neonaddict
Comment options

I don't know why, I just restarted bot and it magically started working as expected. Anyway, thanks a lot for you answer!

Answer selected byneonaddict
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Category
Q&A
Labels
None yet
2 participants
@neonaddict@Bibo-Joshi

[8]ページ先頭

©2009-2025 Movatter.jp