我已经使用python-telegram-bot创建了echo chat telegram bot。随着时间的推移,它将回显我输入的所有内容。但是问题是自机器人启动以来,它总是回显相同的时间字符串。
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()
预期结果是
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
但这是实际结果
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
您需要global
在方法中添加关键字以确保您使用全局变量,dt_string
否则它将创建局部变量,并且您不会更新全局变量。
def updatetime():
global dt_string
t = datetime.now()
dt_string = time.strftime("%b/%d/%Y %H:%M:%S", t)
您需要对所有方法和所有变量执行相同的操作。
请注意,不建议使用global,因此您应尝试重构代码以避免使用global变量。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句