Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
if self.proxies and 'http' in self.proxies:
parts = parse_url(self.proxies['http'])
proxy_host, proxy_port = parts.host, parts.port
auth = parts.auth
proxy_auth = auth and auth.split(':')
else:
proxy_auth, proxy_port, proxy_host = None, None, None
try:
self.websocket = create_connection(ws_url,
http_proxy_host=proxy_host,
http_proxy_port=proxy_port,
http_proxy_auth=proxy_auth)
self.websocket.sock.setblocking(0)
except Exception as e:
raise SlackConnectionError(message=str(e))
# Main loop
log.info("Bot is running...")
while self.running:
message = self.slack_wrapper.read()
if message:
self.handle_message(message)
time.sleep(self.read_websocket_delay)
else:
log.error("Connection failed. Invalid slack token or bot id?")
self.running = False
except websocket._exceptions.WebSocketConnectionClosedException:
log.exception("Web socket error. Executing reconnect...")
except SlackConnectionError:
# Try to reconnect if slackclient auto_reconnect didn't work out. Keep an eye on the logfiles,
# and remove the superfluous exception handling if auto_reconnect works.
log.exception("Slack connection error. Trying manual reconnect in 5 seconds...")
time.sleep(5)
except:
log.exception("Unhandled error. Try reconnect...")
time.sleep(5)
log.info("Shutdown complete...")
if e.errno == 2:
# errno 2 occurs when trying to read or write data, but more
# data needs to be received on the underlying TCP transport
# before the request can be fulfilled.
#
# Python 2.7.9+ and Python 3.3+ give this its own exception,
# SSLWantReadError
return ""
raise
except WebSocketConnectionClosedException:
logging.debug("RTM disconnected")
self.connected = False
if self.auto_reconnect:
self.rtm_connect(reconnect=True)
else:
raise SlackConnectionError(
"Unable to send due to closed RTM websocket"
)
return data.rstrip()
"""
# rtm.start returns user and channel info, rtm.connect does not.
connect_method = "rtm.start" if use_rtm_start else "rtm.connect"
# If the `auto_reconnect` param was passed, set the server's `auto_reconnect` attr
if "auto_reconnect" in kwargs:
self.auto_reconnect = kwargs["auto_reconnect"]
# If this is an auto reconnect, rate limit reconnect attempts
if self.auto_reconnect and reconnect:
# Raise a SlackConnectionError after 5 retries within 3 minutes
recon_count = self.reconnect_count
if recon_count == 5:
logging.error("RTM connection failed, reached max reconnects.")
raise SlackConnectionError(
"RTM connection failed, reached max reconnects."
)
# Wait to reconnect if the last reconnect was less than 3 minutes ago
if (time.time() - self.last_connected_at) < 180:
if recon_count > 0:
# Back off after the the first attempt
backoff_offset_multiplier = random.randint(1, 4)
retry_timeout = (
backoff_offset_multiplier * recon_count * recon_count
)
logging.debug("Reconnecting in %d seconds", retry_timeout)
time.sleep(retry_timeout)
self.reconnect_count += 1
else:
self.reconnect_count = 0
reply = self.api_requester.do(
self.token, connect_method, post_data=kwargs, timeout=timeout
)
if reply.status_code != 200:
if self.rtm_connect_retries < 5 and reply.status_code == 429:
self.rtm_connect_retries += 1
retry_after = int(reply.headers.get("retry-after", 120))
logging.debug(
"HTTP 429: Rate limited. Retrying in %d seconds", retry_after
)
time.sleep(retry_after)
self.rtm_connect(reconnect=reconnect, timeout=timeout)
else:
raise SlackConnectionError(
"RTM connection attempt was rate limited 5 times."
)
else:
self.rtm_connect_retries = 0
login_data = reply.json()
if login_data["ok"]:
self.ws_url = login_data["url"]
self.connect_slack_websocket(self.ws_url)
if not reconnect:
self.parse_slack_login_data(login_data, use_rtm_start)
else:
raise SlackLoginError(reply=reply)
def rtm_connect(self, reconnect=False, timeout=None, use_rtm_start=True, **kwargs):
# rtm.start returns user and channel info, rtm.connect does not.
connect_method = "rtm.start" if use_rtm_start else "rtm.connect"
reply = self.api_requester.do(self.token, connect_method, timeout=timeout, post_data=kwargs)
if reply.status_code != 200:
raise SlackConnectionError(reply=reply)
else:
login_data = reply.json()
if login_data["ok"]:
self.ws_url = login_data['url']
self.connect_slack_websocket(self.ws_url)
if not reconnect:
self.parse_slack_login_data(login_data, use_rtm_start)
else:
raise SlackLoginError(reply=reply)
def __init__(self, message="", reply=None):
super(SlackConnectionError, self).__init__(message)
self.reply = reply