# Buggy code
def check_state(self) -> None:
    try:
        if self.sock is not None:
            is_stale = (
                self.last_ping_pong_time is not None
                and time.time() - self.last_ping_pong_time > self.ping_interval * 2
            )
            if is_stale:
                self.logger.info(
                    "The connection seems to be stale. Disconnecting..."
                    f" (session id: {self.session_id})"
                )
                self.disconnect()
            else:
                self.ping(f"{self.session_id}:{time.time()}")
        else:
            self.logger.debug(
                f"This connection is already closed. (session id: {self.session_id})"
            )
        self.consecutive_check_state_error_count = 0
    except Exception as e:
        self.logger.exception(
            "Failed to check the state of sock "
            f"(session id: {self.session_id}, error: {type(e).__name__}, message: {e})"
        )
        self.consecutive_check_state_error_count += 1
        if self.consecutive_check_state_error_count >= 5:
            self.disconnect()


# Traceback (SlackApiError)
2021-02-14 18:19:49,579 ERROR    slack_sdk.rtm.v2          Failed to establish a connection (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: _ssl.c:1108: The handshake operation timed out)
Traceback (most recent call last):
File "/opt/errbot/lib/python3.8/site-packages/slack_sdk/socket_mode/builtin/connection.py", line 109, in connect
sock.connect((hostname, port))
File "/usr/lib/python3.8/ssl.py", line 1342, in connect
self._real_connect(addr, False)
File "/usr/lib/python3.8/ssl.py", line 1333, in _real_connect
self.do_handshake()
File "/usr/lib/python3.8/ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
socket.timeout: _ssl.c:1108: The handshake operation timed out
2021-02-14 18:19:49,579 INFO     slack_sdk.rtm.v2          The connection has been closed (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO     slack_sdk.rtm.v2          The connection has been closed (session id: b88f63ee-d644-45a8-bf18-be36c8673728)
2021-02-14 18:19:49,579 INFO     slack_sdk.rtm.v2          A new session has been established (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO     slack_sdk.rtm.v2          Connected to a new endpoint...
2021-02-14 18:19:59,590 DEBUG    slack_sdk.rtm.v2          This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO     slack_sdk.rtm.v2          The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO     slack_sdk.rtm.v2          Connecting to a new endpoint...
2021-02-14 18:20:00,075 ERROR    slack_sdk.rtm.v2          Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:00,075 ERROR    slack_sdk.rtm.v2          Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:10,092 DEBUG    slack_sdk.rtm.v2          This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,117 INFO     slack_sdk.rtm.v2          The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,121 INFO     slack_sdk.rtm.v2          Connecting to a new endpoint...
2021-02-14 18:20:10,339 ERROR    slack_sdk.rtm.v2          Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:10,339 ERROR    slack_sdk.rtm.v2          Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:20,350 DEBUG    slack_sdk.rtm.v2          This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO     slack_sdk.rtm.v2          The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO     slack_sdk.rtm.v2          Connecting to a new endpoint...
2021-02-14 18:20:20,556 ERROR    slack_sdk.rtm.v2          Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:20,557 ERROR    slack_sdk.rtm.v2          Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:30,567 DEBUG    slack_sdk.rtm.v2          This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO     slack_sdk.rtm.v2          The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO     slack_sdk.rtm.v2          Connecting to a new endpoint...

# Fixed code
def check_state(self) -> None:
    try:
        if self.sock is not None:
            try:
                self.ping(f"{self.session_id}:{time.time()}")
            except ssl.SSLZeroReturnError as e:
                self.logger.info(
                    "Unable to send a ping message. Closing the connection..."
                    f" (session id: {self.session_id}, reason: {e})"
                )
                self.disconnect()
                return

            if self.last_ping_pong_time is not None:
                disconnected_seconds = int(time.time() - self.last_ping_pong_time)
                if self.trace_enabled and disconnected_seconds > self.ping_interval:
                    message = (
                        f"{disconnected_seconds} seconds have passed "
                        f"since this client last received a pong response from the server "
                        f"(session id: {self.session_id})"
                    )
                    self.logger.debug(message)

                is_stale = disconnected_seconds > self.ping_interval * 4
                if is_stale:
                    self.logger.info(
                        "The connection seems to be stale. Disconnecting..."
                        f" (session id: {self.session_id},"
                        f" reason: disconnected for {disconnected_seconds}+ seconds)"
                    )
                    self.disconnect()
                    return
        else:
            self.logger.debug(
                f"This connection is already closed. (session id: {self.session_id})"
            )
        self.consecutive_check_state_error_count = 0
    except Exception as e:
        self.logger.exception(
            "Failed to check the state of sock "
            f"(session id: {self.session_id}, error: {type(e).__name__}, message: {e})"
        )
        self.consecutive_check_state_error_count += 1
        if self.consecutive_check_state_error_count >= 5:
            self.disconnect()