InlineKeyboardButton with callback_data doesn't work
InlineKeyboardButton
with callback_data
doesn't work. When I click on it, nothing happens.
Here is how I create the button:
from django.apps import apps
from asgiref.sync import sync_to_async
from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton, WebAppInfo
from telegram.ext import CommandHandler, ApplicationBuilder, MessageHandler, filters, CallbackQueryHandler
async def start(self, update: Update, context):
keyboard = InlineKeyboardMarkup([
[InlineKeyboardButton("Already registred", callback_data="already_registered")],
[InlineKeyboardButton("Register", web_app=WebAppInfo(url=WEB_APP_URL))]
])
await update.message.reply_text(
"Welcome",
reply_markup=keyboard
)
return
This is the callback query handler:
async def button(self, update: Update, context):
query = update.callback_query
if not query:
return
await query.answer()
if query.data == "already_registered":
await context.bot.send_message(
chat_id=update.message.chat_id,
text='Good'
)
return
and this is how I run:
def run(self):
TOKEN = apps.get_model('app.Config').objects.get_mailing_tg_bot_token()
app = ApplicationBuilder().token(TOKEN).build()
app.add_handler(CommandHandler('start', self.start))
app.add_handler(CallbackQueryHandler(self.button))
Try logging the callback data before the condition in the button handler to see what it contains. Maybe you confused something.
When I run it in console (without django
) and click button "Already registred"
then I see error
chat_id=update.message.chat_id,
AttributeError: 'NoneType' object has no attribute 'chat_id'
It seems message
is None
. Maybe InlineKeyboardButton
doesn't send message.
But in documentation you can see example inlinekeyboard.py and it uses
await query.edit_message_text(text= ...)
instead of await context.bot.send_message(...)
to send message.
And it doesn't need chat_id
. And it works for me.
async def button(update: Update, context):
query = update.callback_query
if not query:
return
await query.answer()
if query.data == "already_registered":
await query.edit_message_text(text='Good')
#await context.bot.send_message(
# chat_id=update.message.chat_id,
# text='Good'
#)
EDIT:
update.message
is None
but exists query.message
and it has query.message.chat.id
and this also works for me:
await context.bot.send_message(
# chat_id=update.message.chat_id,
chat_id=query.message.chat.it
text='Good'
)