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 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 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_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 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(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 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 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 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 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 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_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_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 test_issue_919_response_url_flag_options(self): client = WebhookClient("http://localhost:8888") resp = client.send( text="hello!", response_type="ephemeral", replace_original=True, 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", delete_original=True, blocks=[ SectionBlock(text="Some text"), ImageBlock(image_url="image.jpg", alt_text="an image"), ], ) self.assertEqual("ok", resp.body)
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 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 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])
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] channel_name = os.environ[ SLACK_SDK_TEST_INCOMING_WEBHOOK_CHANNEL_NAME].replace("#", "") client = WebClient(token=token) channel_id = None for resp in client.conversations_list(limit=10): for c in resp["channels"]: if c["name"] == channel_name: channel_id = c["id"] break if channel_id is not None: break history = client.conversations_history(channel=channel_id, limit=1) self.assertIsNotNone(history) actual_text = history["messages"][0]["text"] self.assertEqual("Hello!", actual_text)
def post_slack_message(subject, content, test=False): """Post a status message to Slack. Parameters ---------- subject : str a subject string to post. body : str a text body to post. test : bool a flag for test mode (False by default). """ url = os.getenv("SLACK_WEBHOOK_URL", None) if url is None: raise RuntimeError('Define "SLACK_WEBHOOK_URL" env var!') webhook = WebhookClient(url) server_name = socket.gethostname() subject = f"Sirepo monitoring @ {server_name}: {subject}" if test: print(content) else: text = f"*{subject}*\n\n{content}" response = webhook.send( text=text, blocks=[{ "type": "section", "text": { "type": "mrkdwn", "text": text, }, }], ) return response
def main(): auth = tweepy.OAuth1UserHandler(consumer_key, consumer_secret, access_token, access_token_secret) api = tweepy.API(auth) statuses = api.user_timeline( screen_name=username) # Getting latest tweets from current user mentions = api.mentions_timeline( since_id=statuses[0].id ) # Getting the latest mention after the latest tweet from the current user for s in mentions: sn = "@" + s.user.screen_name sid = s.id m = "Hey! " + sn + ", thanks for reaching out!" api.update_status(status=m, in_reply_to_status_id=sid) #Replying to the Tweet url = "https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX" webhook = WebhookClient(url) response = webhook.send(text=sn + " mentioned you on Twitter. Please check!" ) #Sending message to Slack webhook return response