繁体   English   中英

如何让我的 Python 脚本无限运行(循环)?

[英]How to keep my Python script running infinitely (loop)?

我正在构建一个 Telegram 机器人,每当我在 Telegram 上向机器人发送“/price”命令时,它会告诉我比特币的美元价格。 它可以工作,但是除非我重新运行 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()

也许尝试使用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)

每次发送 /price 命令时,响应都应该在send_welcome中以获取当前价格。

    @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'])

使用while循环:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM