We are trying to make a telegram price bot but running into an issue that could be solved using third party code, however we can’t set the bot to send us the updated price every 5 minutes (or more) WITHOUT USING THIRD PARTY SOLUTIONS for security reasons.
How to loop from INSIDE this code, without using another third party Telegram bot?
Here is the code
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}%nn"
context.bot.send_message(chat_id=chat_id, text=message)
dispatcher.add_handler(CommandHandler("start", start))
updater.start_polling()
Any solution that correctly sends one message at a time without appending to the previous one? Thanks!
2
Answers
There are different ways to do this.
The first would be with a simple
time.sleep()
in awhile
loop:Another method might be using a background process scheduler, but you would probably refactor your
start
function and only schedule the part that creates/sends the message. (The part inside the while loop)Advanced Python Scheduler (
pip install apscheduler
) is a fantastic library for this, but it is a third party library, so maybe not appropriate for you. I have used it on many projects however.EDIT:
Here’s an example of scheduling with
apscheduler
:you should try to add setinterval or a pure millis() function and you will be good to go