通过 RTM API 与 Slack 通信的 Python 程序随机崩溃如何在代码中捕获和更正以避免崩溃?

问题描述

我有一个简单的 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).*',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).*',re.IGnorECASE):
                        mem = psutil.virtual_memory()
                        mem_pct = mem.percent

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

                    if re.match(r'.*(ip|IP|address|where).*',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).*',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).*',re.IGNORECASE):
                            mem = psutil.virtual_memory()
                            mem_pct = mem.percent

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

                        if re.match(r'.*(ip|IP|address|where).*',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)