skip to Main Content

I am building a Telegram bot that tells me the price of Bitcoin in USD whenever I send the bot a “/price” command on Telegram. It works, however the price does not update unless I re-run the Python script.
How can I keep the script running forever so that I do not need to constantly click “run”?
Here is my code:

import requests
import telebot


# BITCOIN DATA
url = 'https://api.coinbase.com/v2/prices/USD/spot?'
response = requests.get(url).json()



# BOT STUFF
bot = telebot.TeleBot("1135809125:AAHHx7sZ5276Kg34VWYDuwHIJB76s5QS9UQ")


@bot.message_handler(commands=['price'])
def send_welcome(message):
    bot.reply_to(message, "The current price of Bitcoin in USD is " + response['data'][0]['amount'])


@bot.message_handler(func=lambda message: True)
def echo_all(message):
    bot.reply_to(message, message.text)


bot.polling()

3

Answers


  1. Use a while loop:

    import requests
    import telebot
    
    # BITCOIN DATA
    url = 'https://api.coinbase.com/v2/prices/USD/spot?'
    response = requests.get(url).json()
    
    
    
    # BOT STUFF
    bot = telebot.TeleBot("1135809125:AAHHx7sZ5276Kg34VWYDuwHIJB76s5QS9UQ")
    
    
    @bot.message_handler(commands=['price'])
    def send_welcome(message):
        bot.reply_to(message, "The current price of Bitcoin in USD is " + response['data'][0]['amount'])
    
    
    @bot.message_handler(func=lambda message: True)
    def echo_all(message):
        bot.reply_to(message, message.text)
    
    while True:
    
        bot.polling()
    
    Login or Signup to reply.
  2. Maybe try with itertools:

    import itertools
    for x in itertools.repeat(1):
        bot.polling()
    

    Or itertools.count():

    import itertools
    for elt in itertools.count():
        bot.polling()
    

    Or according to link, you can try this:

    if __name__ == '__main__':
         bot.polling(none_stop=True)
    
    Login or Signup to reply.
  3. response should be inside send_welcome to get the current price everytime you send a /price command.

        @bot.message_handler(commands=['price'])
        def send_welcome(message):
            response = requests.get(url).json()
            bot.reply_to(message, "The current price of Bitcoin in USD is " + response['data'][0]['amount'])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search