Вы должны удалить query.answer()
и отправить его только тогда, когда вы не хотите отправлять оповещения
def buttons(update, context):
query = update.callback_query
# query.answer() # <-- move it to `else:`
if query.data == 'cat':
context.bot.answer_callback_query(callback_query_id=query.id, text='you chose cat', show_alert=True)
elif query.data == 'dog':
context.bot.answer_callback_query(callback_query_id=query.id, text='you chose dog', show_alert=True)
else:
query.answer() # <-- send it only when you have no alert
или более читабельными
def buttons(update, context):
query = update.callback_query
if query.data == 'cat':
query.answer(text='you chose cat', show_alert=True)
elif query.data == 'dog':
query.answer(text='you chose dog', show_alert=True)
else:
query.answer()
Мой код для test - мне пришлось добавить updater.idle()
, чтобы он работал.
#!/usr/bin/env python3.7
import logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (
Updater,
CommandHandler,
CallbackQueryHandler,
)
token = 'MY_TOKEN'
updater = Updater(token=token, use_context=True)
dispatcher = updater.dispatcher
def start(update, context):
keyboard = [
[
InlineKeyboardButton("dog", callback_data='dog'),
InlineKeyboardButton("cat", callback_data='cat'),
],
]
reply_markup = InlineKeyboardMarkup(keyboard)
# context.bot.send_message(
# chat_id=update.effective_chat.id,
# text=f'Hello {update.message.chat.first_name}!',
# reply_markup=reply_markup,
# )
update.message.reply_text(f'Hello {update.message.chat.first_name}!', reply_markup=reply_markup)
def buttons(update, context):
logger.info('Update: "%s"\nContext: "%s"', update, context.error)
query = update.callback_query
# query.answer() # <-- move it to `else`
if query.data == 'cat':
#context.bot.answer_callback_query(callback_query_id=query.id, text='you chose cat', show_alert=True)
query.answer(text='you chose cat!', show_alert=True)
elif query.data == 'dog':
#context.bot.answer_callback_query(callback_query_id=query.id, text='you chose dog', show_alert=True)
query.answer(text='you chose dog!', show_alert=True)
else:
query.answer('nothing')
start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)
buttons_handler = CallbackQueryHandler(buttons)
dispatcher.add_handler(buttons_handler)
updater.start_polling()
print('Running... [Press Ctrl+C to stop]')
updater.idle() # need to keep running