def create_slack_channel(self): try: slack_token = config["SLACK"]["oauth_token"] client = WebClient(token=slack_token) response = client.conversations_create( name=self.channel, is_private=False ) channel_id = response["channel"]["id"] logger.info("channel created with id: {channel_id}".format(channel_id=channel_id)) return channel_id except SlackApiError as e: logger.error(e.response["error"])
class ChannelManager(object): def __init__(self, token=Path('SLACK_OAUTH_TOKEN').read_text()): self.token = token self.client = WebClient(token=self.token) self.channels = [ ] # Sets the internal channels field def list(self): resp = self.client.conversations_list(exclude_archived=True, types="public_channel,private_channel", limit=500) assert resp.data['ok'] self.channels = [] for channel in resp.data['channels']: self.channels.append({ 'ID': channel['id'], 'Channel Name': channel['name'], 'Purpose': channel['purpose']['value'] }) def exists(self, name): for channel in self.channels: if channel['Channel Name'] == name: return True return False def get_id(self, name): for channel in self.channels: if channel['Channel Name'] == name: return channel['ID'] return False def get_purpose(self, name): for channel in self.channels: if channel['Channel Name'] == name: return channel['Purpose'] return False def create(self, name, is_private): print(f'Creating channel {name} ...') resp = self.client.conversations_create(name=name, is_private=is_private) return resp def set_purpose(self, name, purpose): chan_id = self.get_id(name) # TODO(arjun): Hack. The name that comes back has HTML entities for # special characters. God help us all. if self.get_purpose(name) != "": return print(f'Setting purpose for {name} ...') self.client.conversations_setPurpose(channel=chan_id, purpose=purpose) def post(self, name, message): channel_id = self.get_id(name) if not channel_id: return False try: resp = self.client.chat_postMessage(channel=channel_id, text=message) if resp.data['ok']: return True else: print(f"Response was {resp.data}") return False except SlackApiError as e: if e.response["error"] != "not_in_channel": raise e self.client.conversations_join(channel=channel_id) self.client.chat_postMessage(channel=channel_id, text=message) return True
class Slack: def __init__(self, token, channel_name=None, channel_id=None): self.client = WebClient(token) self.channel_id = channel_id channels = self.client.conversations_list( types='public_channel,private_channel') if channel_name: for channel in channels['channels']: if channel['name'] == channel_name: self.channel_id = channel['id'] break if not self.channel_id: self.channel_id = self.client.conversations_create( name=channel_name.lower(), is_private=True)['channel']['id'] admins = [ u['id'] for u in self.client.users_list()['members'] if u.get('is_admin') or u.get('is_owner') ] self.client.conversations_invite(channel=self.channel_id, users=admins) def send_snippet(self, title, initial_comment, code, code_type='python', thread_ts=None): return self.client.files_upload( channels=self.channel_id, title=title, initial_comment=initial_comment.replace('<br>', ''), content=code, filetype=code_type, thread_ts=thread_ts)['ts'] def send_exception_snippet(self, domain, event, code_type='python', thread_ts=None): message = traceback.format_exc() + '\n\n\n' + dumps(event, indent=2) subject = 'Error occurred in ' + domain self.send_snippet(subject, subject, message, code_type=code_type, thread_ts=thread_ts) def send_raw_message(self, blocks, thread_ts=None): return self.client.chat_postMessage(channel=self.channel_id, blocks=blocks, thread_ts=thread_ts)['ts'] def update_raw_message(self, ts, blocks): self.client.chat_update(channel=self.channel_id, blocks=blocks, ts=ts) def get_perm_link(self, ts): return self.client.chat_getPermalink(channel=self.channel_id, message_ts=ts)['permalink'] def send_message(self, message, attachment=None, thread_ts=None): blocks = [{ 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': message.replace('<br>', '') } }, { 'type': 'divider' }] if attachment: blocks[0]['accessory'] = { 'type': 'button', 'text': { 'type': 'plain_text', 'text': attachment['text'], 'emoji': True }, 'url': attachment['value'] } return self.send_raw_message(blocks, thread_ts)