0
我有一個簡單的Python電報機器人,下面的代碼:如何在請求中正常處理連接錯誤?
import requests
import json
from time import sleep
import os
filename = 'bot_last_update'
target = open(filename, 'r')
update_from_file = target.read()
# check update from file
update_from_file = update_from_file.strip()
last_update = int(update_from_file)
token = xxxx
url = 'https://api.telegram.org/bot%s/' % token
# We want to keep checking for updates. So this must be a never ending loop
while True:
# My chat is up and running, I need to maintain it! Get me all chat updates
get_updates = json.loads(requests.get(url + 'getUpdates').content)
# Ok, I've got 'em. Let's iterate through each one
for update in get_updates['result']:
# First make sure I haven't read this update yet
if last_update < update['update_id']:
last_update = update['update_id']
target = open(filename, 'w')
target.truncate()
target.write(str(last_update))
target.close()
if update['message']['chat']['type'] == 'private':
# I've got a new update. Let's see what it is.
if update['message']['text'] == 'do something':
requests.get(url + 'sendMessage', params=dict(chat_id=update['message']['chat']['id'], text='doing it'))
os.system('/srv/scripts/do_something.sh')
sleep(10)
requests.get(url + 'sendMessage', params=dict(chat_id=update['message']['chat']['id'], text='done!'))
else:
pass
# Let's wait a few seconds for new updates
sleep(1)
它工作正常,但每次我有我的網絡中的一些問題時我有這樣的錯誤:
Traceback (most recent call last):
File "my_telegram_bot.py", line 21, in <module>
get_updates = json.loads(requests.get(url + 'getUpdates').content)
File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 70, in get
return request('get', url, params=params, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 56, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 475, in request
resp = self.send(prep, **send_kwargs)
File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 596, in send
r = adapter.send(request, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/requests/adapters.py", line 473, in send
raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', error(113, 'No route to host'))
,會是什麼避免這種錯誤的最佳方法?我希望隨時保持這個機器人的狀態,所以在這些事件中它不應該以關鍵的方式失敗(或者如果是這樣,它應該自動恢復/重新啓動)。
如果你想避免錯誤,你需要找出網絡問題(可能是防火牆)。如果你想處理錯誤(嘗試自動恢復),你應該考慮添加一個[try/except](https://docs.python.org/3/tutorial/errors.html#handling-exceptions)塊。 – etemple1