[英]How to keep my Python script running infinitely (loop)?
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.我正在构建一个 Telegram 机器人,每当我在 Telegram 上向机器人发送“/price”命令时,它会告诉我比特币的美元价格。 It works, however the price does not update unless I re-run the Python script.
它可以工作,但是除非我重新运行 Python 脚本,否则价格不会更新。 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()
Maybe try with itertools
:也许尝试使用
itertools
:
import itertools
for x in itertools.repeat(1):
bot.polling()
Or itertools.count()
:或
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)
response should be inside send_welcome
to get the current price everytime you send a /price command.每次发送 /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'])
Use a while
loop:使用
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.