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
You need to add
global
keyword in the methods to make sure you use the global variabledt_string
else it will create a local variable and you would not be updating the global variable.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.
The solution by Krishna Chaurasia is right about everything: the use of
global
variables and the not recommended use ofglobal
variables.A simpler solution is to remove
def updatetime()
entirely and insert thedt_string
onrepeater
function, like this:This will make you code short and easier to read.