class Output(cowrie.core.output.Output): """ slack output """ def start(self): self.slack_channel = CowrieConfig.get("output_slack", "channel") self.slack_token = CowrieConfig.get("output_slack", "token") def stop(self): pass def write(self, logentry): for i in list(logentry.keys()): # Remove twisted 15 legacy keys if i.startswith("log_"): del logentry[i] self.sc = SlackClient(self.slack_token) self.sc.api_call( "chat.postMessage", channel=self.slack_channel, text="{} {}".format( time.strftime("%Y-%m-%d %H:%M:%S"), json.dumps(logentry, indent=4, sort_keys=True), ), )
def __init__(self, token): self._client = SlackClient(token) # create slack client self._output = Queue() self._exit = Event() self._read_int = 1 super(Reader, self).__init__() self.daemon = True # die on process exit self._log = _log.getChild('reader') self._id, self._user, = self._retrieve_id() self._channel_cache = {}
def write(self, logentry): for i in list(logentry.keys()): # Remove twisted 15 legacy keys if i.startswith('log_'): del logentry[i] self.sc = SlackClient(self.slack_token) self.sc.api_call("chat.postMessage", channel=self.slack_channel, text="{} {}".format( time.strftime('%Y-%m-%d %H:%M:%S'), json.dumps(logentry, indent=4, sort_keys=True)))
def send_message(self, schedules, options): if schedules: s = schedules[0] client = SlackClient(os.environ['SLACK_TOKEN']) last = s.get('last_pipeline') if last: if last['status'] == 'failed': self.send_slack_message(client, last, 'danger', 'Scheduled tests have failed', 'FAILED', options) elif last['status'] == 'success': self.send_slack_message( client, last, 'good', 'Scheduled tests have passed successfully', 'SUCCESS', options, ) elif last['status'] == 'running': self.send_slack_message( client, last, '#439FE0', 'Scheduled tests are still running', 'RUNNING', options, )
def slack_notifier(slack_token, secret_conf_path, server, user, password, build_url, build_number): logging.info("Starting Slack notifications about instances") attachments, integrations_counter = get_attachments(secret_conf_path, server, user, password, build_url) sc = SlackClient(slack_token) # Failing instances list sc.api_call( "chat.postMessage", json={ 'channel': 'dmst-content-lab', 'username': '******', 'as_user': '******', 'attachments': attachments, 'text': "You have {0} instances configurations".format(integrations_counter) } ) # Failing instances file sc.api_call( "chat.postMessage", json={ 'channel': 'dmst-content-lab', 'username': '******', 'as_user': '******', 'text': "Detailed list of failing instances could be found in the following link:\n" "https://{}-60525392-gh.circle-artifacts.com/0/artifacts/failed_instances.txt".format(build_number) } )
def send_message(self, users, from_date, to_date, options): client = SlackClient(os.environ['SLACK_TOKEN']) text = self.format_message(users, from_date, to_date) markdown = "```{}```".format(text) title = "Click for detailed view" pretext = "Report from {} to {}".format(from_date, to_date) attachments = [{ "fallback": text, "pretext": pretext, "title": title, "title_link": "http://team.gettipsi.com/?from_date={}&to_date={}".format( from_date, to_date), "text": markdown, "mrkdwn_in": ["text"], "color": options.get('slack_color', "#7CD197"), }] client.chat_postMessage( channel=options['slack_channel'], attachments=attachments, as_user=True, ) return text
def slack_notifier(build_url, slack_token, test_type, env_results_file_name=None, packs_results_file=None, job_name=""): branches = run_command("git branch") branch_name_reg = re.search(r'\* (.*)', branches) branch_name = branch_name_reg.group(1) if branch_name == 'master': logging.info("Extracting build status") if test_type == UNITTESTS_TYPE: logging.info( "Starting Slack notifications about nightly build - unit tests" ) content_team_attachments = get_attachments_for_unit_test(build_url) elif test_type == SDK_UNITTESTS_TYPE: logging.info( "Starting Slack notifications about SDK nightly build - unit tests" ) content_team_attachments = get_attachments_for_unit_test( build_url, is_sdk_build=True) elif test_type == 'test_playbooks': logging.info( "Starting Slack notifications about nightly build - tests playbook" ) content_team_attachments, _ = get_attachments_for_test_playbooks( build_url, env_results_file_name) elif test_type == SDK_FAILED_STEPS_TYPE: logging.info( 'Starting Slack notifications about SDK nightly build - test playbook' ) content_team_attachments = get_attachments_for_all_steps( build_url, build_title=SDK_BUILD_TITLE) elif test_type == BucketUploadFlow.BUCKET_UPLOAD_TYPE: logging.info( 'Starting Slack notifications about upload to production bucket build' ) content_team_attachments = get_attachments_for_bucket_upload_flow( build_url=build_url, job_name=job_name, packs_results_file_path=packs_results_file) elif test_type == SDK_RUN_AGAINST_FAILED_STEPS_TYPE: content_team_attachments = get_attachments_for_all_steps( build_url, build_title=SDK_XSOAR_BUILD_TITLE) else: raise NotImplementedError( 'The test_type parameter must be only \'test_playbooks\' or \'unittests\'' ) logging.info(f'Content team attachments:\n{content_team_attachments}') logging.info("Sending Slack messages to #content-team") slack_client = SlackClient(slack_token) slack_client.api_call("chat.postMessage", json={ 'channel': 'dmst-content-team', 'username': '******', 'as_user': '******', 'attachments': content_team_attachments })
def _read_slackid(self, **kwargs): if self.ckpython() == 3: from slack import WebClient as SlackClient else: from slackclient import SlackClient #check bot id kwargs = self.setkeys(kwargs) _token = kwargs['token'] if _token is None: self.logger.info('Warning: set token first') return else: slack_client = SlackClient(_token) _idl = {} for _list,_att in zip(["users.list", "channels.list"], \ ['members', 'channels']): api_call = slack_client.api_call(_list) if api_call.get('ok'): # retrieve all users so we can find our bot for user in api_call.get(_att): if 'name' in user: _idl[user.get('name')] = user.get('id') return _idl
def main(): install_logging('Slack_Notifier.log') options = options_handler() server_url = options.url slack_token = options.slack_token ci_token = options.ci_token # env_results_file_name = options.env_results_file_name # ci_artifacts_path = options.ci_artifacts project_id = options.gitlab_project_id pipeline_id = options.pipeline_id triggering_workflow = options.triggering_workflow # ci workflow type that is triggering the slack notifier slack_channel = options.slack_channel gitlab_client = gitlab.Gitlab(server_url, private_token=ci_token) pipeline_url, pipeline_failed_jobs = collect_pipeline_data( gitlab_client, project_id, pipeline_id) slack_msg_data = construct_slack_msg(triggering_workflow, pipeline_url, pipeline_failed_jobs) slack_client = SlackClient(slack_token) username = '******' slack_client.api_call("chat.postMessage", json={ 'channel': slack_channel, 'username': username, 'as_user': '******', 'attachments': slack_msg_data })
def send_msg_2_slack(msg): with open("config/conf.yaml", 'r') as stream: data_loaded = yaml.load(stream) TOKEN = data_loaded['slack']['bot_oauth'] client = SlackClient(TOKEN) response = client.chat_postMessage(channel="CPAK5A4G2", text=msg) return response
def slack_notifier(build_url, slack_token, test_type, build_number, env_results_file_name=None, packs_results_file=None, job_name="", slack_channel=CONTENT_CHANNEL, gitlab_server=None): branches = run_command("git branch") branch_name_reg = re.search(r'\* (.*)', branches) branch_name = branch_name_reg.group(1) if branch_name == 'master' or slack_channel.lower() != CONTENT_CHANNEL: logging.info("Extracting build status") if test_type == UNITTESTS_TYPE: logging.info("Starting Slack notifications about nightly build - unit tests") content_team_attachments = get_attachments_for_unit_test(build_url, build_number) elif test_type == SDK_UNITTESTS_TYPE: logging.info("Starting Slack notifications about SDK nightly build - unit tests") content_team_attachments = get_attachments_for_unit_test(build_url, build_number, is_sdk_build=True) elif test_type == 'test_playbooks': logging.info("Starting Slack notifications about nightly build - tests playbook") content_team_attachments, _ = get_attachments_for_test_playbooks(build_url, env_results_file_name) elif test_type == SDK_FAILED_STEPS_TYPE: logging.info('Starting Slack notifications about SDK nightly build - test playbook') content_team_attachments = get_attachments_for_all_steps(build_url, SDK_BUILD_TITLE, build_number) elif test_type == BucketUploadFlow.BUCKET_UPLOAD_TYPE: logging.info('Starting Slack notifications about upload to production bucket build') content_team_attachments = get_attachments_for_bucket_upload_flow(build_url, job_name, build_number, packs_results_file) elif test_type == SDK_RUN_AGAINST_FAILED_STEPS_TYPE: logging.info("Starting Slack notifications about SDK nightly build - run against an xsoar instance") content_team_attachments = get_attachments_for_all_steps(build_url, SDK_XSOAR_BUILD_TITLE, build_number) elif job_name and test_type == job_name: if job_name.startswith(DMST_SDK_NIGHTLY_GITLAB_JOBS_PREFIX): # We run the various circleci sdk nightly builds in a single pipeline in GitLab # as different jobs so it requires different handling logging.info(f"Starting Slack notifications for {job_name}") if 'unittest' in job_name: content_team_attachments = get_attachments_for_unit_test(build_url, build_number, is_sdk_build=True) # override the 'title' from the attachment to be the job name content_team_attachments[0]['title'] = content_team_attachments[0]['title'].replace( 'SDK Nightly Unit Tests', job_name ) else: content_team_attachments = get_attachments_for_all_steps(build_url, job_name, build_number) # override the 'fields' from the attachment since any failure will be the same as the job name content_team_attachments[0]['fields'] = [] else: raise NotImplementedError('The test_type parameter must be only \'test_playbooks\' or \'unittests\'') logging.info(f'Content team attachments:\n{content_team_attachments}') logging.info(f"Sending Slack messages to {slack_channel}") slack_client = SlackClient(slack_token) username = '******' if gitlab_server else 'Content CircleCI' slack_client.api_call( "chat.postMessage", json={'channel': slack_channel, 'username': username, 'as_user': '******', 'attachments': content_team_attachments} )
def send_img_2_slack(img): with open("config/conf.yaml", 'r') as stream: data_loaded = yaml.load(stream) TOKEN = data_loaded['slack']['bot_oauth'] client = SlackClient(TOKEN) attachments = [{"title": "Candidate", "image_url": img}] response = client.chat_postMessage(channel='CPAK5A4G2', text='Potential Candidate', attachments=attachments) return response
def sendSlackMessage(payload): """Send generated slack message .""" slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN')) response = slack_client.api_call(api_method="chat.postMessage", json=payload) logger = logging.getLogger(__name__) if not response.get('ok'): logger.warning('Unable to send message. Response: %s\nPayload:\n%s', response, payload) else: logger.info('Success!')
def getSlackUserNameByGithubUserName(github_username): """Get slack username based on github username.""" slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN')) response = slack_client.api_call("users.list") users = response.get('members', []) if github_username: slack_username = matchSlackGithubUserName(users, github_username) if not slack_username: full_name = lookupGithubFullName(github_username) slack_username = matchSlackUserNameByFullName(users, full_name) return slack_username return None
class Output(cowrie.core.output.Output): """ slack output """ def start(self): self.slack_channel = CowrieConfig().get('output_slack', 'channel') self.slack_token = CowrieConfig().get('output_slack', 'token') def stop(self): pass def write(self, logentry): for i in list(logentry.keys()): # Remove twisted 15 legacy keys if i.startswith('log_'): del logentry[i] self.sc = SlackClient(self.slack_token) self.sc.api_call("chat.postMessage", channel=self.slack_channel, text="%s %s" % (time.strftime('%Y-%m-%d %H:%M:%S'), json.dumps(logentry, indent=4, sort_keys=True)))
def send_slack(**kwargs): """send out KOBE products via slack """ self.ckpython() if self.pythonversion == 3: from slack import WebClient as SlackClient else: from slackclient import SlackClient # self.texts, self.attachments = [], [] kwargs = self.setkeys(kwargs) _token = kwargs['token'] if _token is None: self.logger.info('Warning: set token first') return else: slack_client = SlackClient(_token) _idlist = self._read_slackid() if channel in _idlist: # channel is name, need to find id channel = _idlist[channel] if _msg: if sys.version_info > (3, 0, 0): slack_client.api_call("chat.postMessage", \ json={'channel':channel,'text':content}) else: slack_client.api_call("chat.postMessage", channel=channel, text=content, as_user=True) for _file in _files: if sys.version_info > (3, 0, 0): slack_client.files_upload(channels=channel, file=_file) else: slack_client.api_call("files.upload", channels=channel, file=open(_file, 'rb'), filename=_file)
# pip install slackclient # https://github.com/JPStrydom/Crypto-Trading-Bot/issues/10 from slack import WebClient as SlackClient legacy_token = "" # https://api.slack.com/custom-integrations/legacy-tokens slack_client = SlackClient(legacy_token) def list_channels(): name_to_id = {} res = slack_client.api_call( "groups.list", # groups are private channels, conversations are public channels. Different API. ) list_channels = {"private_channels": []} for channel in res['groups']: list_channels['private_channels'].append( {channel['name']: channel['id']}) return list_channels
import uvicorn from slack import WebClient as SlackClient from starlette.applications import Starlette from starlette.routing import Mount from slackevent_responder import SlackEventApp # Our app's Slack Event Adapter for receiving actions via the Events API slack_signing_secret = os.environ["SLACK_SIGNING_SECRET"] slack_events_app = SlackEventApp(path="/slack/events", slack_signing_secret=slack_signing_secret) # Create a SlackClient for your bot to use for Web API requests slack_bot_token = os.environ["SLACK_BOT_TOKEN"] slack_client = SlackClient(slack_bot_token) app = Starlette(debug=True, routes=[Mount("/", slack_events_app)]) # Example responder to greetings @slack_events_app.on("message") def handle_message(event_data): message = event_data["event"] # If the incoming message contains "hi", then respond with a "Hello" message if message.get("subtype") is None and "hi" in message.get("text"): channel = message["channel"] message = "Hello <@%s>! :tada:" % message["user"] slack_client.chat_postMessage(channel=channel, text=message)
class Reader(Thread): def __init__(self, token): self._client = SlackClient(token) # create slack client self._output = Queue() self._exit = Event() self._read_int = 1 super(Reader, self).__init__() self.daemon = True # die on process exit self._log = _log.getChild('reader') self._id, self._user, = self._retrieve_id() self._channel_cache = {} def _handle_event(self, event): self._log.debug('got event type: %s' % event['type']) self._output.put(event) def _retrieve_id(self): # resp = json.loads(self._client.api_call('auth.test')) success, resp = self._client.api_call('auth.test') if not success: raise Exception('Invalid slack credentials') return resp['user_id'], resp['user'] def _is_public(self, channel): if not channel in self._channel_cache: success, resp = self._client.api_call('im.list') if success: private = [ch['id'] for ch in resp.get('ims', [])] self._channel_cache[channel] = not channel in private return self._channel_cache[channel] @property def events(self): while not self._exit.isSet(): try: event = self._output.get(True, 5) if event: event['public'] = self._is_public(event['channel']) yield event except QueueEmpty: pass def run(self): delay = 1 self._log.debug('starting reader, initial backoff %i' % delay) while not self._exit.isSet(): self._log.debug('connecting to slack rtm...') if self._client.rtm_connect(): self._log.debug('connected, waiting for events...') delay = 2 while not self._exit.isSet(): event = self._client.rtm_read() if event and not event.get( 'user') == self._id and 'channel' in event: self._handle_event(event) else: self._log.debug('connection failed') if delay <= 16: delay += delay self._log.debug('increasing backoff to %i' % delay) time.sleep(delay) def join(self): self._exit.set() self._log.debug('reader exiting...') self._client.rtm_close() return super(Reader, self).join()
def send_message(self, message, options): client = SlackClient(os.environ['SLACK_TOKEN']) client.chat_postMessage(channel=options['slack_channel'], text=message, as_user=True)
def __init__(self, *args: Any, **kwarg: Any): self.slack_client = SlackClient(*args, **kwarg)
# updateMsg = slack_client.api_call( # "chat.postMessage", # channel='CPCUZ2JB0', # text=msg updateMsg = slack_client.chat_postMessage(channel='CPCUZ2JB0', text=msg) # check if the request was a success if updateMsg['ok'] is not True: logging.error(updateMsg) else: logging.debug(updateMsg) if __name__ == "__main__": SLACK_BOT_TOKEN = config['SLACKBOT_TOKEN'] slack_client = SlackClient(SLACK_BOT_TOKEN) logging.debug("authorized slack client") # # For testing msg = "Good Morning!" schedule.every(60).seconds.do(lambda: sendMessage(slack_client, msg)) # schedule.every().monday.at("13:15").do(lambda: sendMessage(slack_client, msg)) logging.info("entering loop") while True: schedule.run_pending() time.sleep(5) # sleep for 5 seconds between checks on the scheduler