Monday, 6 September 2021

(Python) How to send a InlineKeyboardButton in telegram bot, periodically?

I'm trying to send an InlineKeyboardHandler every x second. for that purpose I used updater.job_queue.run_repeating but it acts wired.

The keyboard doesn't work unless I have another interaction with the bot first. I've written a simple piece of code that you can test.

from telegram import Update,InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler,   ConversationHandler, CallbackContext, CallbackQueryHandler
#################################
user_id = *********
tlg_token = '******************************'
SELECTING_COMMAND=1
keyboard = [[InlineKeyboardButton('Button: Print Clicked', callback_data=1)],]
reply_markup = InlineKeyboardMarkup(keyboard)
#################################

def menu(update: Update, context: CallbackContext) -> int:
    update.message.reply_text('sent by command button:',reply_markup=reply_markup)
    return SELECTING_COMMAND

def InlineKeyboardHandler(update: Update, _: CallbackContext) -> None:
    print('clicked')
    return 1

def cancel(update: Update, context: CallbackContext) -> int:
    return ConversationHandler.END    

updater = Updater(tlg_token, use_context=True)
dispatcher = updater.dispatcher

conv_handler = ConversationHandler(
    entry_points=[CommandHandler('request_button', menu)],
    states={
        SELECTING_COMMAND: [CallbackQueryHandler(InlineKeyboardHandler)],
    },
    fallbacks=[CommandHandler('cancel', cancel)],
)
dispatcher.add_handler(conv_handler)

j= updater.job_queue
def talker(update):    
    update.bot.sendMessage(chat_id=user_id, text='sent by talker:', reply_markup=reply_markup)
        
j.run_repeating(talker,interval = 10  ,first= 0)
updater.start_polling()
updater.bot.sendMessage(chat_id=user_id, text='/request_button')
updater.idle()
    

I expect I can see 'clicked' printed after clicking on the button but it's not going to work unless you click on the /request_button first. why? and how can I fix it?



from (Python) How to send a InlineKeyboardButton in telegram bot, periodically?

No comments:

Post a Comment