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

Viewed 80

I have a simple python code to help me keep track of several devices running on Raspberry Pi in the Raspbian Jessie OS. It works quite well, except that it randomly halts with the error message:

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

The relevant code is below; it is from pibot.py mentioned in the errors.
Line 50 is the line for message in slack_client.rtm_read();

The while 1<6 was added to try to circumvent crash out. It did not succeed.

I have tried to understand if there might be a way to catch these errors in code and deal with it rather than having the program crash out, but I cannot seem to find such a means. Any help would be greatly appreciated.

# 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)
1 Answers

Because this error occurs sporadically, it took some time to verify a solution. But I found that using try: except: allowed the problem to resolved with the following code modification.

# 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)
Related