CallbackQueryHandler stopped receiving updates #4767
-
|
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. Now I'm trying to implement /transfer command using ConversationHandler (code below). What logic I want to implement:
(I omitted DB-related and other commands logic, because they works perfectly) import re
import os
import logging
from telegram import (
Update,
InlineKeyboardButton,
InlineKeyboardMarkup
)
from telegram.ext import (
ConversationHandler,
CommandHandler,
MessageHandler,
CallbackQueryHandler,
Application,
ContextTypes,
filters
)
CHOOSING_USER, TYPING_AMOUNT = range(2)
TOKEN=os.getenv("TOKEN")
# Enable logging
logging.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__)
def build_transfer_users_inline_keyboard_markup(users):
keyboard = []
for user in users:
keyboard.append([InlineKeyboardButton(f"Transfer to {user.username}({int(user.balance)})", callback_data=f"{user.username}")])
return InlineKeyboardMarkup(keyboard)
async def transfer(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())
await update.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))
return CHOOSING_USER
async def transfer_user_choice(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
logger.info("Got transfer_user_choice update")
logger.info(update)
query = update.callback_query
await query.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.data
transfer_user = find_user_by_telegram_username(transfer_username)
context.user_data["transfer_username"] = transfer_user.username
await query.message.reply_text(f'Enter amount (from 1 to {int(current_user.balance)}).')
return TYPING_AMOUNT
async def transfer_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:
await update.message.reply_text('Insufficient balance. Enter another amount!')
return TYPING_AMOUNT
transfer_user = find_user_by_telegram_username(transfer_username)
decrease_user_balance(current_user, transfer_amount)
increase_user_balance(transfer_user, transfer_amount)
await update.message.reply_text(f'{transfer_amount} sucessfully transfered to @{transfer_user.username}!')
return ConversationHandler.END
async def transfer_not_recognized(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
context.user_data.clear()
await update.message.reply_text("Transfer fallback")
return ConversationHandler.END
def main() -> 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 /roll
application.add_handler(CommandHandler("join_game", join_game)) # creates User
application.add_handler(CommandHandler("balance", balance)) # show current User balance
application.add_handler(CommandHandler("roll", roll_slot)) # roll a dice
application.add_handler(CommandHandler("all_users_balance", all_users_balance)) # show all Users balance
application.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. So, main questions:
Thanks for help in advance! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
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
I hope that was understandable. |
Beta Was this translation helpful? Give feedback.
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
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