【问题标题】:How to update time variable string in python-telegram-bot如何在 python-telegram-bot 中更新时间变量字符串
【发布时间】:2021-05-09 14:30:42
【问题描述】:

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

【问题讨论】:

    标签: python bots telegram python-telegram-bot


    【解决方案1】:

    您需要在方法中添加 global 关键字以确保您使用全局变量 dt_string 否则它将创建一个局部变量并且您不会更新全局变量。

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

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

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

    【讨论】:

      【解决方案2】:

      Krishna Chaurasia 的解决方案在所有方面都是正确的:使用global 变量和不推荐使用global 变量。

      更简单的解决方案是完全删除 def updatetime() 并在 repeater 函数上插入 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)
      

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

      【讨论】:

        猜你喜欢
        • 2020-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多