【问题标题】:How to loop inside a custom Telegram bot?如何在自定义 Telegram 机器人中循环?
【发布时间】:2021-09-18 17:22:30
【问题描述】:

我们正在尝试制作电报价格机器人,但遇到了可以使用第三方代码解决的问题,但是我们无法将机器人设置为每 5 分钟(或更长时间)向我们发送更新价格而不使用第三出于安全原因的派对解决方案。

如何在不使用其他第三方 Telegram 机器人的情况下从 INSIDE 循环代码?

这里是代码

import telegram
from telegram.ext import Updater
from telegram.ext import CommandHandler
from tracker import get_prices

telegram_bot_token = "mybot"

updater = Updater(token=telegram_bot_token, use_context=True)
dispatcher = updater.dispatcher


def start(update, context):
    chat_id = update.effective_chat.id
    message = ""

    crypto_data = get_prices()
    for i in crypto_data:
        coin = crypto_data[i]["coin"]
        price = crypto_data[i]["price"]
        change_day = crypto_data[i]["change_day"]
        change_hour = crypto_data[i]["change_hour"]
        message += f" {coin}={price:,.5f}$ \nHour Change: {change_hour:.3f}%\nDay Change: {change_day:.3f}%\n\n"

    context.bot.send_message(chat_id=chat_id, text=message)


dispatcher.add_handler(CommandHandler("start", start))
updater.start_polling()

任何解决方案可以一次正确发送一条消息而不附加到前一条消息?谢谢!

【问题讨论】:

    标签: telegram-bot


    【解决方案1】:

    有不同的方法可以做到这一点。

    第一个是在while 循环中使用简单的time.sleep():

    import time
    
    def start(update, context):
        chat_id = update.effective_chat.id
        while True:
            message = ""
            crypto_data = get_prices()
            for i in crypto_data:
                coin = crypto_data[i]["coin"]
                price = crypto_data[i]["price"]
                change_day = crypto_data[i]["change_day"]
                change_hour = crypto_data[i]["change_hour"]
                message += f" {coin}={price:,.5f}$ \nHour Change:{change_hour:.3f}%\nDay Change: {change_day:.3f}%\n\n"
    
    
            context.bot.send_message(chat_id=chat_id, text=message)
            time.sleep(300)
    

    另一种方法可能是使用后台进程调度程序,但您可能会重构 start 函数并仅调度创建/发送消息的部分。 (while循环里面的部分)

    Advanced Python Scheduler (pip install apscheduler) 是一个很棒的库,但它是第三方库,所以可能不适合你。不过,我在很多项目中都使用过它。

    编辑:

    这是一个使用apscheduler 进行调度的示例:

    from apscheduler.schedulers.background import BackgroundScheduler
    
    scheduler = BackgroundScheduler()
    
    def message_loop(chat_id, bot):
        message = ""
        crypto_data = get_prices()
        for i in crypto_data:
            coin = crypto_data[i]["coin"]
            price = crypto_data[i]["price"]
            change_day = crypto_data[i]["change_day"]
            change_hour = crypto_data[i]["change_hour"]
            message += f" {coin}={price:,.5f}$ \nHour Change: {change_hour:.3f}%\nDay Change: {change_day:.3f}%\n\n"
        bot.send_message(chat_id=chat_id, text=message)
    
    
    def start(update, context):
        chat_id = update.effective_chat.id
        bot = context.bot
        scheduler.add_job(message_loop, 'interval', minutes=5, args=(chat_id, bot))
        scheduler.start()
    
    # You might want to also add a stop function to your bot:
    
    def stop():
        scheduler.shutdown()
    
    dispatcher.add_handler(CommandHandler("start", start))
    dispatcher.add_handler(CommandHandler("stop", stop))
    updater.start_polling()
    

    【讨论】:

    • 谢谢!所以,第一个例子有效(“import time”)但不是“import time.sleep”;但是,它会将新消息附加到旧消息,因此会堆积很长的消息...您可以添加任何补丁来避免这种情况并永久修复它吗?
    • 对不起!我的错误,你需要在while循环中移动消息变量声明......我已经编辑了答案
    • 谢谢!我还修复了原始帖子,以澄清不应附加该消息
    【解决方案2】:

    你应该尝试添加 setinterval 或纯 millis() 函数,你会很好的去

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-08
      • 2019-01-25
      • 2019-02-17
      • 2021-09-01
      • 2018-09-17
      • 2019-02-09
      • 2022-12-15
      • 1970-01-01
      相关资源
      最近更新 更多