def send_slack_alert(err_msg): url = os.getenv('SLACK_WEBHOOK_URL') assert url is not None or not "", 'SLACK_WEBHOOK_URL env variable needs to be set' slack_webhook = WebhookClient(url) response = slack_webhook.send(text=err_msg) assert response.status_code == 200 assert response.body == "ok"
def main(argv): # Slack config: "HOOK_URL1,HOOK_URL2,HOOK_URL3,..." slack_config = os.environ.get('CUPY_CI_SLACK_CONFIG', None) # Gitter config: "TOKEN:ROOM1,ROOM2,ROOM3,..." gitter_config = os.environ.get('CUPY_CI_GITTER_CONFIG', None) subdesc = os.environ.get('FLEXCI_SUB_DESCRIPTION', '') if subdesc == '': subdesc = os.environ.get('FLEXCI_DESCRIPTION', '(no description)') url = os.environ.get('FLEXCI_JOB_URL', '<no url>') msg = argv[1] body = '''\ *{}:* {} ``` {} ``` '''.format(msg, url, subdesc) if slack_config is not None: from slack_sdk.webhook import WebhookClient for hook_url in slack_config.split(','): slack = WebhookClient(hook_url) slack.send(text=body) if gitter_config is not None: from gitterpy.client import GitterClient token, rooms = gitter_config.split(':') gitter = GitterClient(token) for room in rooms.split(','): gitter.messages.send(room, body)
def execute(config: Configuration, output_all: bool, output_file: str, output_slack: bool): with open(output_file, "w", newline='') as f: writer = csv.DictWriter( f, fieldnames=["secret", "project", "repository", "file", "commit"]) writer.writeheader() for repo_info, repo_config, secrets in scan(config, output_all): for secret in secrets: row = { "secret": secret["line"].strip() or secret["file"], "project": repo_info.project, "repository": repo_info.name, "file": secret["file"], "commit": secret["commit"] } print(row) writer.writerow(row) if output_slack and repo_config.slack_webhook: webhook = WebhookClient(repo_config.slack_webhook) for blocks in SlackMessageBuilder(repo_info, secrets).build(): response = webhook.send(text="fallback", blocks=blocks) if response.status_code != 200: raise SlackRequestError( f"Error when sending message blocks to slack: {response.body}" )
def __call__( self, text: Union[str, dict] = "", blocks: Optional[List[Union[dict, Block]]] = None, attachments: Optional[List[Union[dict, Attachment]]] = None, response_type: Optional[str] = None, replace_original: Optional[bool] = None, delete_original: Optional[bool] = None, ) -> WebhookResponse: if self.response_url is not None: client = WebhookClient(self.response_url) text_or_whole_response: Union[str, dict] = text if isinstance(text_or_whole_response, str): text = text_or_whole_response message = _build_message( text=text, blocks=blocks, attachments=attachments, response_type=response_type, replace_original=replace_original, delete_original=delete_original, ) return client.send_dict(message) elif isinstance(text_or_whole_response, dict): message = _build_message(**text_or_whole_response) return client.send_dict(message) else: raise ValueError( f"The arg is unexpected type ({type(text_or_whole_response)})" ) else: raise ValueError( "respond is unsupported here as there is no response_url")
def home(): # coins to search coins = ['EUR', 'CLP', 'PEN'] # Request Yahoo! and Save test_request(coins) # Catch Data of BD records = test_get_data() # Service webhook url = 'https://webhook.site/8bea820e-bbdd-4486-b606-fb1963e066d2' messages = [] for row in records: messages.append({ 'CoinDollar': row[3], 'date': str(row[2]), 'Change_value': str(row[1]) }) message_headers = {'Content-Type': 'application/json; charset=UTF-8'} webhook = WebhookClient(url) response = webhook.send(text=dumps(messages)) print(response) return dumps(messages)
def test_with_attachments(self): url = os.environ[SLACK_SDK_TEST_INCOMING_WEBHOOK_URL] webhook = WebhookClient(url) response = webhook.send( text="fallback", attachments=[ Attachment( text="attachment text", title="Attachment", fallback="fallback_text", pretext="some_pretext", title_link="link in title", fields=[ AttachmentField(title=f"field_{i}_title", value=f"field_{i}_value") for i in range(5) ], color="#FFFF00", author_name="John Doe", author_link="http://johndoeisthebest.com", author_icon="http://johndoeisthebest.com/avatar.jpg", thumb_url="thumbnail URL", footer="and a footer", footer_icon="link to footer icon", ts=123456789, markdown_in=["fields"], ) ], ) self.assertEqual(200, response.status_code) self.assertEqual("ok", response.body)
def test_user_agent_customization_issue_769(self): client = WebhookClient( url="http://localhost:8888/user-agent-this_is-test", user_agent_prefix="this_is", user_agent_suffix="test", ) resp = client.send_dict({"text": "hi!"}) self.assertEqual(resp.body, "ok")
def sendWebHook(fallbackMsg: str, data: List[SlackData]) -> None: blocks = buildSection(data) webhook = WebhookClient(slackWebHookUrl) response = webhook.send(text=fallbackMsg, blocks=blocks) assert response.status_code == 200 assert response.body == "ok"
def send_message_to_channel_via_response_url( client: WebhookClient, *, message: Message, response_url: str, **kwargs ) -> None: payload = build_message_payload(message) client.send( **payload, response_type=message.visibility.value, replace_original=False, )
def test_send(self): client = WebhookClient("http://localhost:8888") resp: WebhookResponse = client.send(text="hello!") self.assertEqual(200, resp.status_code) self.assertEqual("ok", resp.body) resp = client.send(text="hello!", response_type="in_channel") self.assertEqual("ok", resp.body)
def test_send_blocks(self): client = WebhookClient("http://localhost:8888") resp = client.send( text="hello!", response_type="ephemeral", blocks=[ SectionBlock(text="Some text"), ImageBlock(image_url="image.jpg", alt_text="an image"), ], ) self.assertEqual("ok", resp.body) resp = client.send( text="hello!", response_type="ephemeral", blocks=[ { "type": "section", "text": { "type": "mrkdwn", "text": "This is a mrkdwn section block :ghost: *this is bold*, and ~this is crossed out~, and <https://google.com|this is a link>", }, }, { "type": "divider" }, { "type": "section", "text": { "type": "mrkdwn", "text": "Pick a date for the deadline." }, "accessory": { "type": "datepicker", "initial_date": "1990-04-28", "placeholder": { "type": "plain_text", "text": "Select a date", }, }, }, ], ) self.assertEqual("ok", resp.body) resp = client.send( text="hello!", response_type="ephemeral", blocks=[ SectionBlock(text="Some text"), ImageBlock(image_url="image.jpg", alt_text="an image"), ], ) self.assertEqual("ok", resp.body)
def _send_to_slack(self): if not BAD_ACTOR_NOTIFICATION_URL: raise ConfigurationException("BAD_ACTOR_NOTIFICATION_URL unset") blocks = self._slackify_all() webhook = WebhookClient(BAD_ACTOR_NOTIFICATION_URL) response = webhook.send(blocks=blocks) logging.info(response)
def hit_webhook(): url = 'https://webhook.site/8bea820e-bbdd-4486-b606-fb1963e066d2' messages = [{'message': 'Rodney'}] message_headers = {'Content-Type': 'application/json; charset=UTF-8'} webhook = WebhookClient(url) print('This is my f*****g Function') response = webhook.send(text=json.dumps(messages)) print(response) return url
def _send_to_slack(text): """Send message to slack channel.""" webhook = WebhookClient(url=os.environ["SLACK_TEST_URL"]) try: response = webhook.send(text=text) assert response.status_code == 200 assert response.body == "ok" except SlackApiError as e: assert e.response["error"] click.echo(f"Got an error: {e.response['error']}")
def test_send(self): retry_handler = MyRetryHandler(max_retry_count=2) client = WebhookClient( "http://localhost:8888/remote_disconnected", retry_handlers=[retry_handler], ) try: client.send(text="hello!") self.fail("An exception is expected") except Exception as _: pass self.assertEqual(2, retry_handler.call_count)
def test_with_attachments_dict(self): url = os.environ[SLACK_SDK_TEST_INCOMING_WEBHOOK_URL] webhook = WebhookClient(url) response = webhook.send( text="fallback", attachments=[{ "author_name": "John Doe", "fallback": "fallback_text", "text": "attachment text", "pretext": "some_pretext", "title": "Attachment", "footer": "and a footer", "id": 1, "author_link": "http://johndoeisthebest.com", "color": "FFFF00", "fields": [ { "title": "field_0_title", "value": "field_0_value", }, { "title": "field_1_title", "value": "field_1_value", }, { "title": "field_2_title", "value": "field_2_value", }, { "title": "field_3_title", "value": "field_3_value", }, { "title": "field_4_title", "value": "field_4_value", }, ], "mrkdwn_in": ["fields"], }], ) self.assertEqual(200, response.status_code) self.assertEqual("ok", response.body)
def test_webhook(self): url = os.environ[SLACK_SDK_TEST_INCOMING_WEBHOOK_URL] webhook = WebhookClient(url) response = webhook.send(text="Hello!") self.assertEqual(200, response.status_code) self.assertEqual("ok", response.body) token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] client = WebClient(token=token) history = client.conversations_history(channel=self.channel_id, limit=1) self.assertIsNotNone(history) actual_text = history["messages"][0]["text"] self.assertEqual("Hello!", actual_text)
def send_to_slack(failing_rules, slack_token): webhook = WebhookClient(slack_token) blocks = [] for rule in failing_rules: # pprint(convert_to_slack_block(rule)) blocks.append({"type": "divider"}) blocks.append(convert_to_slack_block(rule)) logger.info("Printing blocks:") pprint(blocks) try: response = webhook.send(text='Failing Rules...', blocks=blocks) logger.info(response.status_code) logger.info('Message successfully posted in Slack...') except Exception as e: logger.error('Exception {} occurred in {}...'.format(e, send_to_slack)) logger.error(response.status_code)
def event_test(body, say, context: BoltContext, logger): logger.info(body) say(":wave: What's up?") found_rows = list( SlackInstallation.objects.filter( enterprise_id=context.enterprise_id).filter( team_id=context.team_id).filter( incoming_webhook_url__isnull=False).order_by( F("installed_at").desc())[:1]) if len(found_rows) > 0: webhook_url = found_rows[0].incoming_webhook_url logger.info(f"webhook_url: {webhook_url}") client = WebhookClient(webhook_url) client.send( text=":wave: This is a message posted using Incoming Webhook!")
def notify(): url = os.environ['WEBHOOK'] webhook = WebhookClient(url) text = ( f"Hello World\nThis is from Python.\n" f":exclamation: This is second line.\n" ) blocks = [{ "type": "section", "text": { "type": "mrkdwn", "text": text } }] response = webhook.send(text="fallback", blocks=blocks)
def send_to_slack(problematic_certs): settings = Settings.instance() client = WebhookClient(settings.slack_webhook_url) formatted_certs_block = get_list_of_problematic_certs(problematic_certs) blocks = BLOCKS blocks.append(formatted_certs_block) response = client.send(text=FALLBACK_TEXT, blocks=blocks) if response.status_code != 200: print("Failed to send to Slack.") if settings.debug: print(response)
def send_slack_message(environment, message, type='SUCCESS'): webhook_url = environment['SLACK_WEBHOOK'] project_name = environment['PROJECT_NAME'] color_map = { 'SUCCESS': '#36a64f', 'FAIL': '#ee2700', 'OTHER': '#FFCC00' } fallback_color = '#808080' logger.info(message) if project_name and len(project_name) > 0: project_name += " " if not webhook_url: return try: client = WebhookClient(webhook_url) response = client.send( attachments=[ { "color": color_map.get(type, fallback_color), "blocks": [ { "type": "header", "text": { "type": "plain_text", "text": f"{project_name}Glacierizer" } }, { "type": "section", "text": { "type": "plain_text", "text": message } } ] } ] ) except Exception as e: logger.exception(e)
def post(df): header = __make_header(df) main_messages = __make_main_messages(df) divider = __make_divider(df) fields = __make_fields(df) # Slackに送るメッセージをセット blocks = [] blocks.append(header) blocks.extend(main_messages) blocks.extend([divider, fields]) url = '' webhook = WebhookClient(url) response = webhook.send(blocks=blocks) print(response.status_code) print(response.body)
def hit_webhook(): # Catch Data of BD records = test_get_data() # Service webhook url = 'https://webhook.site/8bea820e-bbdd-4486-b606-fb1963e066d2' messages = [] for row in records: messages.append({ 'type_weather': row[1], 'date': str(row[2]), 'value_number': str(row[3]) }) message_headers = {'Content-Type': 'application/json; charset=UTF-8'} webhook = WebhookClient(url) response = webhook.send(text=dumps(messages)) print(response)
def test_with_unfurls_off(self): url = os.environ[SLACK_SDK_TEST_INCOMING_WEBHOOK_URL] token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] webhook = WebhookClient(url) client = WebClient(token=token) # send message that does not unfurl response = webhook.send( text= "<https://imgs.xkcd.com/comics/desert_golfing_2x.png|Desert Golfing>", unfurl_links=False, unfurl_media=False, ) self.assertEqual(200, response.status_code) self.assertEqual("ok", response.body) # wait to allow Slack API to edit message with attachments time.sleep(2) history = client.conversations_history(channel=self.channel_id, limit=1) self.assertIsNotNone(history) self.assertTrue("attachments" not in history["messages"][0])
def weaHOOKSLACK(service, settings, args): if not settings.get('Alerts',{}).get('Profiles'): raise WError('no alerts profiles found for {}'.format(service)) if not settings.get('Slack',{}).get('Webhooks'): raise WError('no Slack webhooks found for {}'.format(service)) clients, sent, profiles, hooks = {}, 0, settings['Alerts']['Profiles'], settings['Slack']['Webhooks'] for line in sys.stdin: alert = json.loads(line.strip()) ch,txt = profiles.get(alert['profile'],profiles['default']).get('slack'), alert['short'] if ch not in clients: clients[ch] = WebhookClient(hooks.get(ch, hooks['default'])) # blocks have replaced attachments if clients[ch].send(text=txt).status_code == 200: sent += 1 sys.stdout.write('{}\n'.format(sent))
def send_file_to_channel( client: WebhookClient, *, channel_id: str, file_pointer_name: str, team_id: str, **kwargs ) -> None: return client.files_upload( channels=channel_id, file=file_pointer_name, )
def test_with_blocks(self): url = os.environ[SLACK_SDK_TEST_INCOMING_WEBHOOK_URL] webhook = WebhookClient(url) response = webhook.send( text="fallback", blocks=[ SectionBlock( block_id="sb-id", text=MarkdownTextObject( text="This is a mrkdwn text section block."), fields=[ PlainTextObject(text="*this is plain_text text*", emoji=True), MarkdownTextObject(text="*this is mrkdwn text*"), PlainTextObject(text="*this is plain_text text*", emoji=True), ], ), DividerBlock(), ActionsBlock(elements=[ ButtonElement( text=PlainTextObject(text="Create New Task", emoji=True), style="primary", value="create_task", ), ButtonElement( text=PlainTextObject(text="Create New Project", emoji=True), value="create_project", ), ButtonElement( text=PlainTextObject(text="Help", emoji=True), value="help", ), ], ), ], ) self.assertEqual(200, response.status_code) self.assertEqual("ok", response.body)
def send( webhook_url: str, header: Optional[str], message: Optional[str], fields: Sequence[str], footer: Optional[str], color: Optional[str], ) -> None: webhook = WebhookClient(url=webhook_url) attachments = Attachments( color=color, header=header, message=message, fields=fields, footer=footer, ) response = webhook.send(attachments=attachments.to_payload()) status_code, body = response.status_code, response.body if status_code != 200 or body != "ok": raise SlackClientError( f"Webhook request was failed - status: {status_code}, body: {body}" )
def test_with_unfurls_on(self): # Slack API rate limits unfurls of unique links so test will # fail when repeated. For testing, either use a different URL # for text option or delete existing attachments in webhook channel. url = os.environ[SLACK_SDK_TEST_INCOMING_WEBHOOK_URL] token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] webhook = WebhookClient(url) client = WebClient(token=token) # send message that does unfurl response = webhook.send( text="<https://imgs.xkcd.com/comics/red_spiders_small.jpg|Spiders>", unfurl_links=True, unfurl_media=True, ) self.assertEqual(200, response.status_code) self.assertEqual("ok", response.body) # wait to allow Slack API to edit message with attachments time.sleep(2) history = client.conversations_history(channel=self.channel_id, limit=1) self.assertIsNotNone(history) self.assertTrue("attachments" in history["messages"][0])