2017-06-09 37 views
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')) 

,會是什麼避免這種錯誤的最佳方法?我希望隨時保持這個機器人的狀態,所以在這些事件中它不應該以關鍵的方式失敗(或者如果是這樣,它應該自動恢復/重新啓動)。

+0

如果你想避免錯誤,你需要找出網絡問題(可能是防火牆)。如果你想處理錯誤(嘗試自動恢復),你應該考慮添加一個[try/except](https://docs.python.org/3/tutorial/errors.html#handling-exceptions)塊。 – etemple1

回答

1

您需要實施重試機制。這裏是python How to retry after exception in python?中的一個例子。重試機制將保持機器人上升並避免錯誤,假設連接在合理的時間內自行糾正。

查看Python requests exception handling獲取捕捉您特定異常的示例。

結合這兩個例子,我們得到:

from requests import ConnectionError 
import requests 
import json 
from time import sleep 
import os 
connection_timeout = 30 # seconds 

...

# My chat is up and running, I need to maintain it! Get me all chat updates 
start_time = time.time() 
while True: 
    try: 
     get_updates = json.loads(requests.get(url + 'getUpdates').content) 
     break 
    except ConnectionError: 
     if time.time() > start_time + connection_timeout: 
      raise Exception('Unable to get updates after {} seconds of ConnectionErrors'.format(connection_timeout)) 
     else: 
      time.sleep(1) # attempting once every second 
# Ok, I've got 'em. Let's iterate through each one 

...

這將重試調用getUpdates每秒30秒,直到將連接權利本身。您可以根據需要將connection_timeout調整爲大或小,以覆蓋間歇性連接。

相關問題