Как сделать так, чтобы мой сценарий Python работал бесконечно (l oop)? - PullRequest
0 голосов
/ 19 июня 2020

Я создаю бота Telegram, который сообщает мне цену Bitcoin в долларах США всякий раз, когда я отправляю боту команду «/ price» в Telegram. Это работает, однако цена не обновляется, если я не перезапущу сценарий Python. Как мне сохранить выполнение скрипта вечно, чтобы мне не приходилось постоянно нажимать «запустить»? Вот мой код:

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 ]

1 голос
/ 19 июня 2020

Может быть, попробуйте с itertools:

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

Или itertools.count():

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

Или по ссылке , вы можете попробовать это:

if __name__ == '__main__':
     bot.polling(none_stop=True)
1 голос
/ 21 июня 2020

ответ должен быть внутри send_welcome, чтобы получать текущую цену каждый раз, когда вы отправляете команду / price.

    @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'])
0 голосов
/ 19 июня 2020

Используйте while l oop:

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