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

answer_callback_query not responding even when passing query id#4555

Unanswered
henriquesati asked this question inQ&A
Discussion options

I want to respond a inlinekeyboard selecting just with a simple Answer from the bot, but its not woking although i'm passing the queryid and the text message as arguments

importloggingfromtelegramimportUpdate,InlineKeyboardButton,InlineKeyboardMarkup,Botfromtelegram.extimport (ApplicationBuilder,CommandHandler,CallbackContext,CallbackQueryHandler,ContextTypes,)logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",level=logging.INFO)logging.getLogger("httpx").setLevel(logging.WARNING)logger=logging.getLogger(__name__)asyncdefstart(update:Update,context:ContextTypes.DEFAULT_TYPE):awaitcontext.bot.send_message(chat_id=update.effective_chat.id,text="I'm a bot, please talk to me!")asyncdefchain_to_send_menu(update:Update,context:CallbackContext):keyboard= [        [InlineKeyboardButton("Option 1",callback_data="option1")],        [InlineKeyboardButton("Option 2",callback_data="option2")],    ]reply_markup=InlineKeyboardMarkup(keyboard)awaitupdate.message.reply_text("Welcome! Please choose an option:",reply_markup=reply_markup    )asyncdefbutton(update:Update,context:CallbackContext):query=update.callback_queryawaitquery.answer()ifquery.data=="option1":awaitquery.edit_message_text(text="You selected Option 1.")elifquery.data=="option2":awaitquery.edit_message_text(text="You selected Option 2.")else:awaitquery.edit_message_text(text="Unknown option selected.")#  await context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a bot, please talk to me!")awaitcontext.answer_callback_query(callback_query_id=query.id,text="ereeeer@@")defmain():application= (ApplicationBuilder()        .token(TOKEN)        .read_timeout(10)        .write_timeout(10)        .concurrent_updates(True)        .build()    )CommandHandler('start',start)start_handler=CommandHandler('start',start)menu_handler=CommandHandler('menu',chain_to_send_menu)x=CallbackQueryHandler(button)application.add_handler(menu_handler)application.add_handler(start_handler)application.add_handler(x)application.run_polling()if__name__=="__main__":main()

I saw thatUpdate hascallback_query object, that has as attributeid, that i'm passing toanswer, so i'm not being able to find WHERE im missreading or doing mistakes

You must be logged in to vote

Replies: 2 comments 13 replies

Comment options

Hi. I see two things that go wrong here:

  1. context.answer_callback_query is not a thing - you are looking forcontext.bot.answer_callback_query. Note that callingawait context.bot.answer_callback_query(callback_query_id=query.id, text="ereeeer@@") does exactly the same as callingawait query.answer(text="ereeeer@@")
  2. Youre answering the query twice - once withawait query.answer() and once withanswer_callback_query. You can answer each query only once.
You must be logged in to vote
13 replies
@Bibo-Joshi
Comment options

If you want to send a completely new message that is unrelated to the message the button was attached to, you can e.g. useupdate.effective_user.send_message("some text").

howeve, withawait query.answer('sefoda', show_alert=True) the text should show. please make sure that you try on different clients, e.g. TG android, TG desktop and TG web. for me it looks like this:

image

@henriquesati
Comment options

ok, worked for you, I tried

async def button(update: Update, context: CallbackContext):    query = update.callback_query    if query.data == "option1":        await query.edit_message_text(text="Yo")    elif query.data == "option2":        await query.answer('sefoda',  show_alert=True)    else:        await query.answer('sefoda',  show_alert=True)    update.effective_user.send_message("some text")

still no response, just the button loading

@henriquesati
Comment options

now tell me, how it works for you and not for me?

@Bibo-Joshi
Comment options

I don't know. I just took your MWE and replaced thebutton function with the one in#4555 (reply in thread). Please double check your console for any error messages that you might have missed. And again, please also ry a differnt client.

@henriquesati
Comment options

pleade upload the code that is working for you

Comment options

Here is the MWE that I'm running. I modified it a bit from your MWE to better showcase the different options and to setup logging such that we can see what's going an. Thebutton callback does three things:

  1. it edits the message where the button is attached
  2. it sends a new message to the user that presses the button
  3. it answers the button press with a pop-up text that needs to be conifrmed by the user
importloggingfromtelegramimportUpdate,InlineKeyboardButton,InlineKeyboardMarkupfromtelegram.extimport (ApplicationBuilder,CommandHandler,CallbackQueryHandler,ContextTypes,)logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",level=logging.DEBUG)logging.getLogger("httpx").setLevel(logging.WARNING)logging.getLogger("httpcore").setLevel(logging.WARNING)asyncdefchain_to_send_menu(update:Update,context:ContextTypes.DEFAULT_TYPE):keyboard= [        [InlineKeyboardButton("Option 1",callback_data="option1")],        [InlineKeyboardButton("Option 2",callback_data="option2")],    ]reply_markup=InlineKeyboardMarkup(keyboard)awaitupdate.message.reply_text("Welcome! Please choose an option:",reply_markup=reply_markup    )asyncdefbutton(update:Update,context:ContextTypes.DEFAULT_TYPE):query=update.callback_queryawaitquery.edit_message_text(text=f"Edited Message. Selected option:{query.data}")awaitupdate.effective_user.send_message(f"Sent New Message: Selected option:{query.data}")awaitquery.answer(text=f"Answered Qurey: Selected option:{query.data}",show_alert=True)defmain():application=ApplicationBuilder().token("TOKEN").build()application.add_handler(CommandHandler("menu",chain_to_send_menu))application.add_handler(CallbackQueryHandler(button))application.run_polling()if__name__=="__main__":main()

I'm running on:

python -m telegrampython-telegram-bot 21.7 (v21.7-0-g15112374)Bot API 7.11Python 3.11.9 (tags/v3.11.9:de54cf5, Apr  2 2024, 10:12:12) [MSC v.1938 64 bit (AMD64)]

Here is the log output. I've commented a bit to explain where we see that the updates are processed successfully

2024-11-0518:14:41,958-asyncio-DEBUG-Usingproactor:IocpProactor2024-11-0518:14:41,959-telegram.ext.ExtBot-DEBUG-CallingBotAPIendpoint`getMe`withparameters`{}`2024-11-0518:14:42,076-telegram.ext.ExtBot-DEBUG-CalltoBotAPIendpoint`getMe`finishedwithreturnvalue`{'id': 703777048, 'is_bot': True, 'first_name': 'null', 'username': 'MahlerHomeConstruction_bot', 'can_join_groups': True, 'can_read_all_group_messages': False, 'supports_inline_queries': True, 'can_connect_to_business': False, 'has_main_web_app': False}`2024-11-0518:14:42,076-telegram.ext.ExtBot-DEBUG-ThisBotisalreadyinitialized.2024-11-0518:14:42,078-telegram.ext.Updater-DEBUG-Updaterstarted (polling)2024-11-0518:14:42,078-telegram.ext.Updater-DEBUG-Startnetworkloopretrybootstrapdelwebhook2024-11-0518:14:42,079-telegram.ext.Updater-DEBUG-Deletingwebhook2024-11-0518:14:42,079-telegram.ext.ExtBot-DEBUG-CallingBotAPIendpoint`deleteWebhook`withparameters`{}`2024-11-0518:14:42,148-telegram.ext.ExtBot-DEBUG-CalltoBotAPIendpoint`deleteWebhook`finishedwithreturnvalue`True`2024-11-0518:14:42,148-telegram.ext.Updater-DEBUG-Bootstrapdone2024-11-0518:14:42,148-telegram.ext.Updater-DEBUG-Waitingforpollingtostart2024-11-0518:14:42,148-telegram.ext.Updater-DEBUG-PollingupdatesfromTelegramstarted2024-11-0518:14:42,149-telegram.ext.Updater-DEBUG-StartnetworkloopretrygettingUpdates2024-11-0518:14:42,150-telegram.ext.ExtBot-DEBUG-CallingBotAPIendpoint`getUpdates`withparameters`{'timeout': 10, 'offset': 0}`2024-11-0518:14:42,152-apscheduler.scheduler-INFO-Schedulerstarted2024-11-0518:14:42,152-telegram.ext.Application-DEBUG-JobQueuestarted2024-11-0518:14:42,153-telegram.ext.Application-INFO-Applicationstarted2024-11-0518:14:42,154-apscheduler.scheduler-DEBUG-Lookingforjobstorun2024-11-0518:14:42,154-apscheduler.scheduler-DEBUG-Nojobs;waitinguntilajobisadded# Bot fetched the /menu message from TG2024-11-0518:14:45,775-telegram.ext.ExtBot-DEBUG-CalltoBotAPIendpoint`getUpdates`finishedwithreturnvalue`[{'update_id': 219021127, 'message': {'message_id': 33120, 'from': {'id': 1145108092, 'is_bot': False, 'first_name': 'Hinrich', 'last_name': 'Mahler (@Bibo-Joshi)', 'username': 'BiboJoshi', 'language_code': 'de'}, 'chat': {'id': 1145108092, 'first_name': 'Hinrich', 'last_name': 'Mahler (@Bibo-Joshi)', 'username': 'BiboJoshi', 'type': 'private'}, 'date': 1730826885, 'text': '/menu', 'entities': [{'offset': 0, 'length': 5, 'type': 'bot_command'}]}}]`2024-11-0518:14:45,775-telegram.ext.ExtBot-DEBUG-Gettingupdates: [219021127]# The application starts processing it and sends the reply2024-11-0518:14:45,777-telegram.ext.Application-DEBUG-ProcessingupdateUpdate(message=Message(channel_chat_created=False,chat=Chat(first_name='Hinrich',id=1145108092,last_name='Mahler (@Bibo-Joshi)',type=<ChatType.PRIVATE>,username='BiboJoshi'),date=datetime.datetime(2024,11,5,17,14,45,tzinfo=<UTC>),delete_chat_photo=False,entities=(MessageEntity(length=5,offset=0,type=<MessageEntityType.BOT_COMMAND>),),from_user=User(first_name='Hinrich',id=1145108092,is_bot=False,language_code='de',last_name='Mahler (@Bibo-Joshi)',username='BiboJoshi'),group_chat_created=False,message_id=33120,supergroup_chat_created=False,text='/menu'),update_id=219021127)2024-11-0518:14:45,778-telegram.ext.ExtBot-DEBUG-CallingBotAPIendpoint`sendMessage`withparameters`{'chat_id': 1145108092, 'text': 'Welcome! Please choose an option:', 'reply_markup': InlineKeyboardMarkup(inline_keyboard=((InlineKeyboardButton(callback_data='option1', text='Option 1'),), (InlineKeyboardButton(callback_data='option2', text='Option 2'),)))}`2024-11-0518:14:45,781-telegram.ext.ExtBot-DEBUG-CallingBotAPIendpoint`getUpdates`withparameters`{'timeout': 10, 'offset': 219021128}`2024-11-0518:14:45,955-telegram.ext.ExtBot-DEBUG-CalltoBotAPIendpoint`sendMessage`finishedwithreturnvalue`{'message_id': 33121, 'from': {'id': 703777048, 'is_bot': True, 'first_name': 'null', 'username': 'MahlerHomeConstruction_bot'}, 'chat': {'id': 1145108092, 'first_name': 'Hinrich', 'last_name': 'Mahler (@Bibo-Joshi)', 'username': 'BiboJoshi', 'type': 'private'}, 'date': 1730826885, 'text': 'Welcome! Please choose an option:', 'reply_markup': {'inline_keyboard': [[{'text': 'Option 1', 'callback_data': 'option1'}], [{'text': 'Option 2', 'callback_data': 'option2'}]]}}`# Bot fetches the button press update from TG2024-11-0518:14:48,553-telegram.ext.ExtBot-DEBUG-CalltoBotAPIendpoint`getUpdates`finishedwithreturnvalue`[{'update_id': 219021128, 'callback_query': {'id': '4918201809386639830', 'from': {'id': 1145108092, 'is_bot': False, 'first_name': 'Hinrich', 'last_name': 'Mahler (@Bibo-Joshi)', 'username': 'BiboJoshi', 'language_code': 'de'}, 'message': {'message_id': 33121, 'from': {'id': 703777048, 'is_bot': True, 'first_name': 'null', 'username': 'MahlerHomeConstruction_bot'}, 'chat': {'id': 1145108092, 'first_name': 'Hinrich', 'last_name': 'Mahler (@Bibo-Joshi)', 'username': 'BiboJoshi', 'type': 'private'}, 'date': 1730826885, 'text': 'Welcome! Please choose an option:', 'reply_markup': {'inline_keyboard': [[{'text': 'Option 1', 'callback_data': 'option1'}], [{'text': 'Option 2', 'callback_data': 'option2'}]]}}, 'chat_instance': '3208997988570222114', 'data': 'option1'}}]`2024-11-0518:14:48,553-telegram.ext.ExtBot-DEBUG-Gettingupdates: [219021128]# The application starts processing it2024-11-0518:14:48,554-telegram.ext.Application-DEBUG-ProcessingupdateUpdate(callback_query=CallbackQuery(chat_instance='3208997988570222114',data='option1',from_user=User(first_name='Hinrich',id=1145108092,is_bot=False,language_code='de',last_name='Mahler (@Bibo-Joshi)',username='BiboJoshi'),id='4918201809386639830',message=Message(channel_chat_created=False,chat=Chat(first_name='Hinrich',id=1145108092,last_name='Mahler (@Bibo-Joshi)',type=<ChatType.PRIVATE>,username='BiboJoshi'),date=datetime.datetime(2024,11,5,17,14,45,tzinfo=<UTC>),delete_chat_photo=False,from_user=User(first_name='null',id=703777048,is_bot=True,username='MahlerHomeConstruction_bot'),group_chat_created=False,message_id=33121,reply_markup=InlineKeyboardMarkup(inline_keyboard=((InlineKeyboardButton(callback_data='option1',text='Option 1'),), (InlineKeyboardButton(callback_data='option2',text='Option 2'),))),supergroup_chat_created=False,text='Welcome! Please choose an option:')),update_id=219021128)# Bot edits the message that has the buttons attached2024-11-0518:14:48,554-telegram.ext.ExtBot-DEBUG-CallingBotAPIendpoint`editMessageText`withparameters`{'text': 'Edited Message. Selected option: option1', 'chat_id': 1145108092, 'message_id': 33121}`2024-11-0518:14:48,557-telegram.ext.ExtBot-DEBUG-CallingBotAPIendpoint`getUpdates`withparameters`{'timeout': 10, 'offset': 219021129}`2024-11-0518:14:48,660-telegram.ext.ExtBot-DEBUG-CalltoBotAPIendpoint`editMessageText`finishedwithreturnvalue`{'message_id': 33121, 'from': {'id': 703777048, 'is_bot': True, 'first_name': 'null', 'username': 'MahlerHomeConstruction_bot'}, 'chat': {'id': 1145108092, 'first_name': 'Hinrich', 'last_name': 'Mahler (@Bibo-Joshi)', 'username': 'BiboJoshi', 'type': 'private'}, 'date': 1730826885, 'edit_date': 1730826888, 'text': 'Edited Message. Selected option: option1'}`# Bot sends a new message to the user2024-11-0518:14:48,661-telegram.ext.ExtBot-DEBUG-CallingBotAPIendpoint`sendMessage`withparameters`{'chat_id': 1145108092, 'text': 'Sent New Message: Selected option: option1'}`2024-11-0518:14:48,776-telegram.ext.ExtBot-DEBUG-CalltoBotAPIendpoint`sendMessage`finishedwithreturnvalue`{'message_id': 33122, 'from': {'id': 703777048, 'is_bot': True, 'first_name': 'null', 'username': 'MahlerHomeConstruction_bot'}, 'chat': {'id': 1145108092, 'first_name': 'Hinrich', 'last_name': 'Mahler (@Bibo-Joshi)', 'username': 'BiboJoshi', 'type': 'private'}, 'date': 1730826888, 'text': 'Sent New Message: Selected option: option1'}`# Bot answers the callback query2024-11-0518:14:48,778-telegram.ext.ExtBot-DEBUG-CallingBotAPIendpoint`answerCallbackQuery`withparameters`{'callback_query_id': '4918201809386639830', 'text': 'Answered Qurey: Selected option: option1', 'show_alert': True}`2024-11-0518:14:48,853-telegram.ext.ExtBot-DEBUG-CalltoBotAPIendpoint`answerCallbackQuery`finishedwithreturnvalue`True`2024-11-0518:14:53,549-telegram.ext.Application-DEBUG-Applicationreceivedstopsignal.Shuttingdown.2024-11-0518:14:53,550-telegram.ext.Updater-DEBUG-StoppingUpdater2024-11-0518:14:53,550-telegram.ext.Updater-DEBUG-Waitingbackgroundpollingtasktofinishup.2024-11-0518:14:53,550-telegram.ext.Updater-DEBUG-NetworkloopretrygettingUpdateswascancelled2024-11-0518:14:53,552-telegram.ext.Updater-DEBUG-Calling`get_updates`onemoretimetomarkallfetchedupdatesasread.2024-11-0518:14:53,552-telegram.ext.ExtBot-DEBUG-CallingBotAPIendpoint`getUpdates`withparameters`{'timeout': 0, 'offset': 219021129}`2024-11-0518:14:53,645-telegram.ext.ExtBot-DEBUG-CalltoBotAPIendpoint`getUpdates`finishedwithreturnvalue`[]`2024-11-0518:14:53,645-telegram.ext.ExtBot-DEBUG-Nonewupdatesfound.2024-11-0518:14:53,645-telegram.ext.Updater-DEBUG-Updater.stop()iscomplete2024-11-0518:14:53,645-telegram.ext.Application-INFO-Applicationisstopping.Thismighttakeamoment.2024-11-0518:14:53,645-telegram.ext.Application-DEBUG-Waitingforupdate_queuetojoin2024-11-0518:14:53,646-telegram.ext.Application-DEBUG-Applicationstoppedfetchingofupdates.2024-11-0518:14:53,646-telegram.ext.Application-DEBUG-Waitingforrunningjobstofinish2024-11-0518:14:53,646-apscheduler.scheduler-INFO-Schedulerhasbeenshutdown2024-11-0518:14:53,646-telegram.ext.Application-DEBUG-JobQueuestopped2024-11-0518:14:53,646-telegram.ext.Application-DEBUG-Waitingfor`create_task`callstobeprocessed2024-11-0518:14:53,646-telegram.ext.Application-INFO-Application.stop()complete2024-11-0518:14:53,647-telegram.ext.ExtBot-DEBUG-ThisBotisalreadyshutdown.Returning.2024-11-0518:14:53,647-telegram.ext.Updater-DEBUG-ShutdownofUpdatercomplete

Here is a screenshot of how the result looks like for me:

image

Please copy the MWE verbatin to your machine. Plug in your bot token, but change nothing else. Then run it. Compare the log output with the one that I attched. If one of the 3 responses the bot should give does not show for you, check in the logs what you see about that. Please then also attach your log output so that we can have a look at that together. Make sure to remove any sensitive data first.


Apart from that, let me give a comment about yesterdays discussion.

The story from my perspective is the following.
I had already spent some time trying to help you in this thread, beforeI saw that you had already gotten help by someone else without including that information in here. I asked you to link to previous discussions on the same topic if you open new threads.
Later, you opened#4558, again without linking to previous discussion. I asked you to only open a new bug ticket if you had proof that there is a bug in PTB.
You then opened#4559 without attaching proof.

For me this means that I had been spending my spare time, after work, to try and help you in the context of a project that I am the maintainer ("boss") of and you were simply ignoring requests that I made to you. This is not a gratifying feeling and I have no intention of spending my leisure time on things that annoy me.

I would very much appreciate it if you keep my perspective in mind when making requests to PTB or any other project that is moderated by people in their spare time.

You must be logged in to vote
0 replies
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
@henriquesati@Bibo-Joshi

[8]ページ先頭

©2009-2025 Movatter.jp