Python 通过 RTM API 与 Slack 通信的程序随机崩溃。如何捕获并纠正代码以避免崩溃?

Python program to communicate with Slack via RTM API crashes randomly. How to catch and correct in code to avoid crash out?

我有一个简单的 python 代码可以帮助我跟踪 Raspbian Jessie OS 中 Raspberry Pi 上的多个设备 运行。它工作得很好,除了它随机停止并显示错误消息:

Traceback (most recent call last):
  File "/home/pi/pibot.py", line 50, in <module>
    for message in slack_client.rtm_read():
  File "/usr/local/lib/python2.7/dist-packages/slackclient/client.py", line 235, in rtm_read
    json_data = self.server.websocket_safe_read()
  File "/usr/local/lib/python2.7/dist-packages/slackclient/server.py", line 301, in websocket_safe_read
    "Unable to send due to closed RTM websocket"
slackclient.server.SlackConnectionError: Unable to send due to closed RTM websocket

相关代码如下;它来自错误中提到的pibot.py。
第 50 行是 for message in slack_client.rtm_read();

添加了 while 1<6 以试图避免崩溃。没有成功。

我试图了解是否有办法在代码中捕获这些错误并加以处理,而不是让程序崩溃,但我似乎找不到这样的方法。任何帮助将不胜感激。

# Start connection
if slack_client.rtm_connect():
   print "Connected!"

while 1<6:
    if True:  
        for message in slack_client.rtm_read():
            if 'text' in message and message['text'].startswith("<@%s>" % slack_user_id):

                print "Message received: %s" % json.dumps(message, indent=2)

                message_text = message['text'].\
                    split("<@%s>" % slack_user_id)[1].\
                    strip()

                if re.match(r'.*(DAC).*', message_text, re.IGNORECASE):

                    if re.match(r'.*(cpu).*', message_text, re.IGNORECASE):
                        cpu_pct = psutil.cpu_percent(interval=1, percpu=False)

                        slack_client.api_call(
                            "chat.postMessage",
                            channel=message['channel'],
                            text="This is %s. My CPU is at %s%%." % (ID, cpu_pct),
                            as_user=True)

                    if re.match(r'.*(memory|ram).*', message_text, re.IGNORECASE):
                        mem = psutil.virtual_memory()
                        mem_pct = mem.percent

                        slack_client.api_call(
                            "chat.postMessage",
                            channel=message['channel'],
                            text="This is %s. My RAM is at %s%%." % (ID, mem_pct),
                            as_user=True)

                    if re.match(r'.*(ip|IP|address|where).*', message_text, re.IGNORECASE):
                        mem = psutil.virtual_memory()
                        mem_pct = mem.percent

                        slack_client.api_call(
                            "chat.postMessage",
                            channel=message['channel'],
                            text="This is %s. My IP address is at %s." % (ID, ip),
                            as_user=True)

        time.sleep(10)

因为这个错误是偶发的,所以花了一些时间来验证解决方案。但我发现使用 try: except: 允许通过以下代码修改解决问题。

# Start connection
if slack_client.rtm_connect():
   print "Connected!"

   while 1<6:
      if True:  
        try:
            for message in slack_client.rtm_read():
                if 'text' in message and message['text'].startswith("<@%s>" % slack_user_id):

                    print "Message received: %s" % json.dumps(message, indent=2)

                    message_text = message['text'].\
                        split("<@%s>" % slack_user_id)[1].\
                        strip()

                    if re.match(r'.*(DAC).*', message_text, re.IGNORECASE):

                        if re.match(r'.*(cpu).*', message_text, re.IGNORECASE):
                            cpu_pct = psutil.cpu_percent(interval=1, percpu=False)

                            slack_client.api_call(
                                "chat.postMessage",
                                channel=message['channel'],
                                text="This is %s. My CPU is at %s%%." % (ID, cpu_pct),
                                as_user=True)

                        if re.match(r'.*(memory|ram).*', message_text, re.IGNORECASE):
                            mem = psutil.virtual_memory()
                            mem_pct = mem.percent

                            slack_client.api_call(
                                "chat.postMessage",
                                channel=message['channel'],
                                text="This is %s. My RAM is at %s%%." % (ID, mem_pct),
                                as_user=True)

                        if re.match(r'.*(ip|IP|address|where).*', message_text, re.IGNORECASE):
                            mem = psutil.virtual_memory()
                            mem_pct = mem.percent

                            slack_client.api_call(
                                "chat.postMessage",
                                channel=message['channel'],
                                text="This is %s. My IP address is at %s." % (ID, ip),
                                as_user=True)
        except:
            print("Oops!", sys.exc_info()[0], "occurred.  Let's try to reconnect!")
            slack_client.rtm_connect()

        time.sleep(10)