import slack import os import re import ssl as ssl_lib import certifi from message import SlackMessage class SlackReceiver() : def __init__(self, token, log, callback) : self.token = token self.ssl_context = ssl_lib.create_default_context(cafile=certifi.where()) self.callback = callback self.log = log def start(self) : self.rtm_client = slack.RTMClient(token=self.token, ssl=self.ssl_context) @slack.RTMClient.run_on(event="message") def receive(**payload) : msg = self.parse(payload) if msg is not None: self.receive(msg) print("Starting") self.rtm_client.start() def parse(self, payload) : self.log.debug("slack message received: {}".format(payload)) if 'data' in payload and 'bot_id' in payload['data'] and payload['data']['bot_id'] == 'BNYAX72BB': # it's the bot's response, ignore it return None if 'data' in payload and 'user' in payload['data'] and payload['data']['user'] == 'UNS0QKMMY': # it's the bot uploading files, ignore it return None if 'data' in payload and ( ('text' in payload['data'] and '<@UNS0QKMMY>' not in payload['data']['text']) and ('channel' in payload['data'] and not payload['data']['channel'].startswith('DP')) ): # message in a channel and the bot wasn't pinged, or was not a direct message - ignore self.log.debug("received message, but I wasn't pinged or DM'ed") return None if 'data' in payload and 'text' in payload['data'] and '<@UNS0QKMMY>' in payload['data']['text']: # remove the ping text payload['data']['text'] = re.sub('\\<@UNS0QKMMY\\>', '', payload['data']['text']) return SlackMessage(payload) def receive(self, msg) : text = msg.text.split() channel = msg.channel ID = text[0] if len(text) > 0 else None interval = text[1] if len(text) > 1 else None step = text[2] if len(text) > 2 else None self.callback(channel, ID, interval, step)