如何在定制的电报机器人中循环? [英] How to loop inside a custom Telegram bot?

查看:17
本文介绍了如何在定制的电报机器人中循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

如何在不使用其他第三方电报机器人的情况下从此代码内部循环?

以下是代码

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}$ 
Hour Change: {change_hour:.3f}%
Day Change: {change_day:.3f}%

"

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


dispatcher.add_handler(CommandHandler("start", start))
updater.start_polling()
有没有一次正确发送一条消息而不附加到前一条消息的解决方案?谢谢!

推荐答案

执行此操作有不同的方法。

第一个是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}$ 
Hour Change:{change_hour:.3f}%
Day Change: {change_day:.3f}%

"


        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}$ 
Hour Change: {change_hour:.3f}%
Day Change: {change_day:.3f}%

"
    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()

这篇关于如何在定制的电报机器人中循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆