Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
107 views
in Technique[技术] by (71.8m points)

How to update time variable string in python-telegram-bot

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 + "
"+ 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
question from:https://stackoverflow.com/questions/66060046/how-to-update-time-variable-string-in-python-telegram-bot

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...