繁体   English   中英

如何在 python-telegram-bot 中更新时间变量字符串

[英]How to update time variable string in python-telegram-bot

我用 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)

您需要对所有方法和所有变量执行相同的操作。

请注意,不建议使用全局变量,因此您应该尝试重构代码以避免使用全局变量。

Krishna Chaurasia 的解决方案对一切都是正确的:使用global变量和不推荐使用global变量。

一个更简单的解决方案是完全删除def updatetime()并在repeater function 上插入dt_string ,如下所示:

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)

这将使您的代码更简短且更易于阅读。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM