How to change command word for the CommandHandler in Python Telegram Bot during its run?

Viewed 24

I want to make a custumizeble command word which is changing everytime user run it. For example (it is not working during run, only after I close bot and open again, for some reason it does not unpdate rnd_word command word inside CommandHandler):

from telegram import Update
from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler


rnd_word = open('random_word.txt', encoding="utf-8").read()

def wordgenerator():
    THIS DOES NOT MATTER IT IS A FUNCTION WHICH JUST MAKE NEW WORD FOR COMMAND
    
async def random_command(update, context):
    global rnd_word
    rnd_word = wordgenerator()
    new_word = open('random_word.txt', 'w',encoding="utf-8")
    new_word.write(rnd_word)
    new_word.close()
    rnd_word = open('random_word.txt', encoding="utf-8").read().rstrip()
    random_command_handler = CommandHandler(rnd_word, random_command)

if __name__ == '__main__':
    
    application = ApplicationBuilder().token("TOKEN").build()
    
    application.add_handler(CommandHandler(rnd_word, random_command))
   
    application.run_polling()
1 Answers

CommandHandler is not designed to change the command(s) at runtime. TBH I don't really understand your use case, but you might be interested in implementing a custom handler by implementing the BaseHandler interface class.


Disclaimer: I'm currently the maintainer of python-telegram-bot.

Related