skip to Main Content

I’ve created echo chat telegram bot with python-telegram-bot. It’ll echo everything that I typed in with time. But the problem is It always echoes same time string since the bot start.

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, Dispatcher
import logging
import datetime
logging.basicConfig(format='%(levelname)s - %(message)s',
                    level=logging.DEBUG)
logger = logging.getLogger(__name__)
updater = None

t = datetime.now()
dt_string = time.strftime("%b/%d/%Y %H:%M:%S", t)

sitepath=""
filename="output.txt"

def updatetime():
    t = datetime.now()
    dt_string = time.strftime("%b/%d/%Y %H:%M:%S", t)
    
def repeater(update, context):
    updatetime()
    update.message.reply_text("Done: " + update.message.text + "n"+ dt_string)

def start_bot():
    global updater
    updater = Updater(
        '##Token##', use_context=True)
    dispatcher = updater.dispatcher
    dispatcher.add_handler(MessageHandler(Filters.text, repeater))
    updater.start_polling()
    updater.idle()
start_bot()

Expected result is

Done: This is a message
Feb/05/2021 15:13:34

Done: 10 Second have passed
Feb/05/2021 15:13:44

Done: 10 Second have passed
Feb/05/2021 15:13:54

But this is the actual result

Done: This is a message
Feb/05/2021 15:13:34

Done: 10 Second have passed
Feb/05/2021 15:13:34

Done: 10 Second have passed
Feb/05/2021 15:13:34

2

Answers


  1. You need to add global keyword in the methods to make sure you use the global variable dt_string else it will create a local variable and you would not be updating the global variable.

    def updatetime():
        global dt_string
        t = datetime.now()
        dt_string = time.strftime("%b/%d/%Y %H:%M:%S", t)
    

    You need to do the same for all methods and all variables.

    Note that the use of global is not recommended so you should try to refactor your code to avoid use of global variables.

    Login or Signup to reply.
  2. The solution by Krishna Chaurasia is right about everything: the use of global variables and the not recommended use of global variables.

    A simpler solution is to remove def updatetime() entirely and insert the dt_string on repeater function, like this:

    def repeater(update, context):
        ## dt_string will update everytime you call repeater
        ## datetime.now() it's not necessary
        dt_string = time.strftime("%b/%d/%Y %H:%M:%S")
        update.message.reply_text("Done: " + update.message.text + "n"+ dt_string)
    

    This will make you code short and easier to read.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search