def send_messages(self, messages): client = WebClient(self.token) sent_messages = 0 for m in messages: try: for r in m.recipients(): if r.startswith('#'): r = r[1:] if self.color: response = client.chat_postMessage(channel=r, as_user=True, attachments=[{ "color": self.color, "text": m.subject }]) else: response = client.chat_postMessage(channel=r, as_user=True, text=m.subject) logger.debug(response) if response['ok']: sent_messages += 1 else: raise RuntimeError( "Slack Notification unable to send {}: {} ({})". format(r, m.subject, response['error'])) except SlackApiError as e: logger.error( smart_text(_("Exception sending messages: {}").format(e))) if not self.fail_silently: raise return sent_messages
def main(command_data): reaction = command_data.get("text", None) channel_id = command_data["channel_id"][0] channel_name = command_data["channel_name"][0] user_id = command_data["user_id"][0] logger.info("Getting Slack clients") client = WebClient(token=SLACK_TOKEN) bot_client = WebClient(token=BOT_TOKEN) reacted = list(get_reacted_messages(client, channel_id, reaction[0]))[::-1] file_output = collate_timestamped_messages(client, reacted) export_msg = (f"Here's your export of *#{channel_name}*'s" f" messages marked with {reaction[0]}:") bot_client.chat_postMessage(channel=user_id, text=export_msg, as_user=True) if file_output: send_timeline_as_file(bot_client, user_id, file_output) else: logger.info("No messages had requested reaction") bot_client.chat_postMessage( channel=user_id, text=":sadparrot: No messages have the" f"{reaction[0]} reaction!", as_user=True, )
def custom_slack_on_pipeline_failure( context: PipelineFailureSensorContext): base_url = "http://localhost:3000" slack_client = WebClient( token=os.environ["SLACK_DAGSTER_ETL_BOT_TOKEN"]) run_page_url = f"{base_url}/instance/runs/{context.pipeline_run.run_id}" channel = "#yuhan-test" message = "\n".join([ f'Pipeline "{context.pipeline_run.pipeline_name}" failed.', f"error: {context.failure_event.message}", f"mode: {context.pipeline_run.mode}", f"run_page_url: {run_page_url}", ]) slack_client.chat_postMessage( channel=channel, blocks=[{ "type": "section", "text": { "type": "mrkdwn", "text": message } }], )
class SlackHelper: def __init__(self): self.slack_token = get_env('SLACK_TOKEN') # formerly known as slackclient self.slack_client = WebClient(token=self.slack_token) self.slack_channel = get_env('SLACK_CHANNEL') def post_message(self, msg, recipient): try: return self.slack_client.chat_postMessage( channel=recipient, text=msg, ) except SlackApiError as e: print(f"Error posting message: {e}") # return self.slack_client.api_call( # "chat.postMessage", # channel=recipient, # text=msg, # as_user=True # ) def post_message_to_channel(self, msg): try: return self.slack_client.chat_postMessage( channel=self.slack_channel, text=msg, ) except SlackApiError as e: print(f"Error posting message: {e}") # return self.slack_client.api_call( # "chat.postMessage", # channel=self.slack_channel, # text=msg, # username='******', # parse='full', # as_user=False # ) # additional methods to interact with slack def file_upload( self, file_content, file_name, file_type, title=None, ): return self.slack_client.api_call( "files.upload", channels=self.slack_channel, content=file_content, filename=file_name, filetype=file_type, initial_comment='{} Log File'.format(file_name), title=title) def user_info(self, uid): return self.slack_client.users_info(user=uid)
def send_slack_message(text, files): import os from slack_sdk import WebClient from slack_sdk.errors import SlackApiError client = WebClient(token=os.environ['SLACK_TOKEN']) if text != None: try: client.chat_postMessage(channel='#data-collection-notifications', text=text) except SlackApiError as e: # You will get a SlackApiError if "ok" is False assert e.response["ok"] is False assert e.response[ "error"] # str like 'invalid_auth', 'channel_not_found' print(f"Got an error: {e.response['error']}") if files != None: for one_file in files: if one_file == '': continue try: client.files_upload(channels='#data-collection-notifications', file=os.path.expanduser(one_file)) except SlackApiError as e: # You will get a SlackApiError if "ok" is False assert e.response["ok"] is False assert e.response[ "error"] # str like 'invalid_auth', 'channel_not_found' print(f"Got an error: {e.response['error']}")
def _send_message( jinja_env: JinjaEnv, slack_client: WebClient, msg: Dict[str, Any], date_: datetime, **kwargs: Any, ) -> int: """Send message to slack Args: jinja_env (JinjaEnv): jinja2 environment slack_client (WebClient): Slack client msg (Dict[str, Any]): Snowflake message date_ (datetime): Date valid Raises: MissingMessage: Message has no test or template Returns: int: status code """ status_code = 0 channel = kwargs.get("slack_channel") or msg.get("SLACK_CHANNEL", "") frequency = kwargs.get("slack_frequency") or msg.get("SLACK_FREQUENCY") or "always" msg_template = kwargs.get("slack_message_template") or msg.get( "SLACK_MESSAGE_TEMPLATE" ) msg_text = kwargs.get("slack_message_text") or msg.get("SLACK_MESSAGE_TEXT") tags = _get_frequency_tags(frequency) blocks = None if kwargs.get("dry_run") or _met_conditions(date_=date_, tags=tags): try: # If snowflake message contanins message template if msg_template: blocks = _render_template(jinja_env, msg_template, msg) # If snowflake message contanins message text elif msg_text: pass else: raise MissingMessage( "Every row in Snowflake table has to have `SLACK_MESSAGE_TEMPLATE`" " or/and `SLACK_MESSAGE_TEXT` columns!" ) if kwargs.get("dry_run"): logger.info(f"Channel: {channel}\nBlocks: {blocks}\nText: {msg_text}") else: slack_client.chat_postMessage( channel=channel, blocks=blocks, text=msg_text ) except ( jinja2.TemplateNotFound, jinja2.TemplateError, MissingMessage, SlackApiError, ) as e: logger.error(f"Snowflake row: {msg}\n" f"Error: {e}") if kwargs.get("fail_fast"): raise status_code = 1 return status_code
def sending_a_message(slack_token="", channel="", text="", thread_ts=""): """ ref https://slack.dev/python-slack-sdk/web/index.html#messaging :return: """ # slack_token = os.environ["SLACK_BOT_TOKEN"] client = WebClient(token=slack_token) try: if thread_ts == "": response = client.chat_postMessage( channel=channel, text=text ) else: response = client.chat_postMessage( channel=channel, thread_ts=thread_ts, text=text ) return response except SlackApiError as e: # You will get a SlackApiError if "ok" is False assert e.response["error"] # str like 'invalid_auth', 'channel_not_found'
async def events(event: EventCallback): if event.type == 'url_verification': # AppにRequest URLを登録した際に初回だけ送信されるURLの検証 # ref: https://api.slack.com/events/url_verification return JSONResponse({'challenge': event.challenge}) try: team_conf = TeamConf.get(event.team_id) except TeamConf.DoesNotExist: return Response(status_code=HTTPStatus.BAD_REQUEST) client = WebClient(team_conf.access_token) if event.event: if event.event.type == 'reaction_added': # 投稿にemojiでリアクションがあったイベントを処理する # ref: https://api.slack.com/events/reaction_added if event.event.reaction in team_conf.emoji_set: # リアクションのemojiが設定されている場合 if event.event.item: item = event.event.item url = client.chat_getPermalink( channel=item.channel, message_ts=item.ts).get('permalink') blocks = [ SectionBlock(text=MarkdownTextObject(text=f'<{url}>')), ActionsBlock(elements=[ ButtonElement(text='読んだ', action_id='mark_as_read', value='mark_as_read') ]) ] client.chat_postMessage(text=url, channel=event.event.user, unfurl_links=True, blocks=blocks) return Response()
def my_slack_on_run_success(context: RunStatusSensorContext): slack_client = WebClient(token=os.environ["SLACK_DAGSTER_ETL_BOT_TOKEN"]) slack_client.chat_postMessage( channel="#alert-channel", message=f'Job "{context.pipeline_run.pipeline_name}" succeeded.', )
def slack_send_mess(mess, **kwargs): import sql from slack_sdk import WebClient from slack_sdk.errors import SlackApiError if kwargs.get('slack_channel_id'): slacks = sql.get_slack_by_id(kwargs.get('slack_channel_id')) else: slacks = sql.get_slack_by_ip(kwargs.get('ip')) proxy = sql.get_setting('proxy') for slack in slacks: slack_token = slack[1] channel_name = slack[2] if proxy is not None and proxy != '' and proxy != 'None': proxies = dict(https=proxy, http=proxy) client = WebClient(token=slack_token, proxies=proxies) else: client = WebClient(token=slack_token) try: client.chat_postMessage(channel='#' + channel_name, text=mess) except SlackApiError as e: print('error: ' + str(e)) logging('localhost', str(e), haproxywi=1)
def main(): install_logging('Slack_Notifier.log') options = options_handler() server_url = options.url slack_token = options.slack_token ci_token = options.ci_token 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 = WebClient(token=slack_token) slack_client.chat_postMessage(channel=slack_channel, as_user=False, attachments=slack_msg_data, username=SLACK_USERNAME) if pipeline_failed_jobs and slack_channel == CONTENT_CHANNEL: # Return all failures for investigation to channel dmst-build. slack_client.chat_postMessage(channel=BUILD_NOTIFICATIONS_CHANNEL, as_user=False, attachments=slack_msg_data, username=SLACK_USERNAME)
class SlackClient(object): def __init__(self, token=None): self.client = WebClient(token=token or Config.SLACK_OAUTH_ACCESS_TOKEN) def post_message_to_channel(self, channel: str, message: str): try: response = self.client.chat_postMessage(channel=channel, text=message) return response.get('message') except SlackApiError as e: # You will get a SlackApiError if "ok" is False print(f"Got an error: {e.response['error']}") def post_blocks_message_to_channel(self, channel: str, blocks: list): try: response = self.client.chat_postMessage(channel=channel, blocks=blocks) return response.get('message') except SlackApiError as e: print(f"Got an error: {e.response['error']}") def create_direct_message(self, users: list): response = self.client.conversations_open(users=users) if response.data.get('ok'): return response.get('channel') def get_user_by_email(self, email: str) -> SlackResponse: user = self.client.api_call(api_method='users.lookupByEmail', params={"email": email}) if user.data.get('ok'): return user.data.get('user')
def send_slack_message(message: str) -> None: """slack_sdk を用いたメッセージ送信を行います。 Document: https://github.com/slackapi/python-slack-sdk/blob/main/tutorial/01-creating-the-slack-app.md # noqa: E501 Args: message (str): 送信したいメッセージ。 """ slack_client = WebClient(token=consts.SLACK_BOT_TOKEN) try: # NOTE: unfurl_links は時折鬱陶しいと思っている「リンクの展開機能」です。不要です。 False. slack_client.chat_postMessage( channel=consts.SLACK_MESSAGE_CHANNEL, text=message, unfurl_links=False) # 返却値の確認は行いません。 # NOTE: Slack api のドキュメントにあるコードなので追加していましたが排除します。 # リンクの含まれるメッセージを送信すると、返却値が勝手に変更されるため絶対一致しないからです。 # - リンクの前後に <, > がつく # - & -> & エスケープが起こる # assert response['message']['text'] == message except SlackApiError as e: assert e.response['ok'] is False # str like 'invalid_auth', 'channel_not_found' assert e.response['error'] logger.error(f'Got an error: {e.response["error"]}')
def send(message): try: client = WebClient(token=config.token) channel = client.conversations_open( users=config.admins)['channel']['id'] client.chat_postMessage(channel=channel, text=message) except Exception: traceback.print_exc()
def send_slack_notification(blocks): client = WebClient(token=config.SLACK_TOKEN) try: client.chat_postMessage(username="******", channel="#assist-dapp", blocks=blocks) except SlackApiError as e: LOG.info(f"Could not send slack notification: Error: {e}")
def my_slack_on_run_failure(context: RunFailureSensorContext): slack_client = WebClient(token=os.environ["SLACK_DAGSTER_ETL_BOT_TOKEN"]) slack_client.chat_postMessage( channel="#alert-channel", message= f'Job "{context.pipeline_run.pipeline_name}" failed. Error: {context.failure_event.message}', )
def _send_message_to_slack(user, kms): client = WebClient(token=os.environ['SLACK_BOT_TOKEN']) try: text = f'{user.name}さんが目標距離: {user.target_distance}kmを達成しました。現在の距離: {round(kms, 2)}km :100::woman-running::runner::man-running::skin-tone-3:' client.chat_postMessage(channel=os.environ['SLACK_CHANNEL'], text=text) except SlackApiError as e: print(f"Got an error: {e.response['error']}")
def notify_to_slack(message, channel='C01LD1QTEU8'): ssl_context = ssl.create_default_context() ssl_context.check_hostname = False ssl_context.verify_mode = ssl.CERT_NONE slack_token = os.environ.get('SERVERLESS_SLACK_BOT_API_TOKEN') client = WebClient(slack_token, ssl=ssl_context) client.chat_postMessage(channel=channel, as_user=True, text=message)
def slack_comment(permalink, title, name, created_utc, created_utc_format, body_short, sentiment): print(f"Comment on: *<https://reddit.com{permalink}|{title}>* by <https://reddit.com/u/{name}|{name}>\n*Posted*: <!date^{round(created_utc)}^{{date_short_pretty}} {{time}}|{created_utc_format}>") client = WebClient(token=slack_token) message = json.load(open("msg_template.json", "r")) message[0]["text"]["text"] = f"Comment on: *<https://reddit.com{permalink}|{title}>* by <https://reddit.com/u/{name}|{name}>\n*Posted*: <!date^{round(created_utc)}^{{date_short_pretty}} {{time}}|{created_utc_format}>" message[2]["text"]["text"] = f"{body_short}..." message[3]["elements"][0]["text"] = f"{sentiment}" client.chat_postMessage(channel = slack_channel, blocks = message) return
def post_message(): weekday = datetime.now().isoweekday() if 0 < weekday < 6: lucky_number = randint(1, 6) if lucky_number % 2 == 0: greeting = Greetings().get_greeting() ssl._create_default_https_context = ssl._create_stdlib_context client = WebClient(token=bot_token) client.chat_postMessage(channel=channel_id, text=greeting)
def slack_message(uredditor, age, verified_email, has_gold, submission_karma, comment_karma, subreddit_submissions_6, subreddit_comments_6, subreddit_submissions_3, subreddit_comments_3): print(f"Scan Complete!") client = WebClient(token=slack_token) message = json.load(open("redditor_template.json", "r")) message[0]["text"]["text"] = f"Redditor: *<https://reddit.com/u/{uredditor}|{uredditor}>*\nAccount Age: *{age}*\nEmail Verified: *{verified_email}*\nKarma: *{submission_karma}* Submission and *{comment_karma}* Comment\nPremium: {has_gold}" message[2]["text"]["text"] = f"*Activity in /r/{subreddit_name}:*\n6 Month Activity: {subreddit_submissions_6} Submissions and {subreddit_comments_6} Comments\n3 Year Activity: {subreddit_submissions_3} Submissions and {subreddit_comments_3} Comments" message[3]["text"]["text"] = f"" client.chat_postMessage(channel = slack_channel, blocks = message) return
def start_group_chats(self): """ Groups all participating people randomly and start group chats. Called by schedule_group_chats() """ db = DataBaseUtils(channel_name=self.channel_name) users_in_person = db.get_users(participate=True, virtual=False) users_virtual = db.get_users(participate=True, virtual=True) random.seed(round(time.time()) % 1e5 ) ## put random seed to make sure we don't get the same groups everytime random_groups_in_person = self._assign_random_groups(users_in_person) random_groups_virtual = self._assign_random_groups(users_virtual) # random_groups = random_groups_in_person + random_groups_virtual client = WebClient(token=os.environ.get(self.bot_token)) # initialize chats for each random group for group in random_groups_in_person: try: result = client.conversations_open( token=self.bot_token, users=','.join(group)) #TODO: edit the message to look better client.chat_postMessage( token=self.bot_token, channel=result['channel']['id'], text="Ta daa! \nDestiny created this group. Everyone here is up for IN-PERSON meetup. "+\ "Consider using <https://www.when2meet.com|when2meet> to schedule a time.\n"+\ "Now, answer the following question: \n\n" + random.sample(self.chat_prompts['responses'], 1)[0]) except SlackApiError as e: self.logger.error(f"Error scheduling message for users {group}: {e}") self.logger.info("finieshed creating in person random groups") for group in random_groups_virtual: try: result = client.conversations_open( token=self.bot_token, users=','.join(group)) #TODO: edit the message to look better client.chat_postMessage( token=self.bot_token, channel=result['channel']['id'], text="Ta daa! \nDestiny created this group. Everyone here is up for VIRTUAL meetup. "+\ "Consider using <https://www.when2meet.com|when2meet> to schedule a time.\n"+\ "Now, answer the following question: \n\n" + random.sample(self.chat_prompts['responses'], 1)[0]) except SlackApiError as e: self.logger.error(f"Error scheduling message for users {group}: {e}") self.logger.info("finieshed creating virtual random groups")
def slack_comment(text_1, text_2, text_3, divide): client = WebClient(token=slack_token) message = json.load(open("msg_template.json", "r")) if divide == False: message[1]["type"] = "" message[0]["text"]["text"] = text_1 message[2]["text"]["text"] = text_2 message[3]["elements"]["text"] = text_3 client.chat_postMessage(channel=slack_channel, blocks=message) return
def message(token, channel, mess): auth = WebClient(token=token) try: message = str(mess) auth.chat_postMessage(channel=channel, text=message) except SlackApiError as e: assert e.response["ok"] is False print(f"Received Error: {e.response['error']}")
def interaction_handler(message, _context): """ Handles interactive events from Slack elements like buttons """ response_url = message.get("response_url") interaction_type = message.get("type") team = message.get("team") team_id = team.get("id") slack_access_token = DynamoUtils.get_slack_access_token(team_id) client = WebClient(token=slack_access_token) if interaction_type == "view_submission": view = message.get("view") block_id = view.get("blocks")[0].get("block_id") action_id = view.get("blocks")[0].get("element").get("action_id") if action_id == "incident_resolution": incident_id = "" try: resolution_text = (view.get("state").get("values").get( block_id).get("incident_resolution").get("value")) incident_id = view.get("private_metadata") slack_events_handler = SlackEventsHandler(client, team_id) slack_events_handler.close_incident_and_add_resolution( incident_id, resolution_text) return "ok" except Exception as ex: logger.error( f"error closing incident for team {team_id} and incident {incident_id} {ex}" ) client.chat_postMessage( channel=incident_id, text= "There was an error closing the incident. Please contact support", ) return "failed" else: action = message.get("actions")[0] action_id = action.get("action_id") if action_id == "cancel": __update_original_message(response_url, "Incident creation cancelled") elif action_id == "create_incident": if "team" in message and "id" in message.get("team"): try: container = message.get("container") channel = container.get("channel_id") incident_name = action.get("value") slack_events_handler = SlackEventsHandler(client, team_id) slack_events_handler.create_new_incident( channel, incident_name) __delete_original_message(response_url) except Exception as e: logger.error(f"exception during incident creation {e}") return "error" return "ok"
def send(self, to, header, content): if to == '默认': logger.error('没有设置 channel 名称,无法发送 Slack 通知') raise Exception('没有设置 channel 名称,无法发送 Slack 通知') client = WebClient(token=self.token) try: client.chat_postMessage(channel=to, text='{}:{}'.format(header, content)) except SlackApiError as e: raise Exception(e.response['error'])
def slack_submission(permalink, title, name, created_utc, created_utc_format): print( f"*<https://reddit.com{permalink}|{title}>* by <https://reddit.com/u/{name}|{name}>\n*Posted*: <!date^{round(created_utc)}^{{date_short_pretty}} {{time}}|{created_utc_format}>" ) client = WebClient(token=slack_token) message = json.load(open("save_alert.json", "r")) message[0]["text"][ "text"] = f"<https://reddit.com{permalink}|{title}> by <https://reddit.com/u/{name}|{name}>\nPosted: <!date^{round(created_utc)}^{{date_short_pretty}} {{time}}|{created_utc_format}>" message[2]["text"][ "text"] = f"*This post is being monitored by the Reddit Team :reddit: :eyes:*" client.chat_postMessage(channel=slack_channel, blocks=message) return
class SlackManager: def __init__(self, token): self.client = WebClient(token=token) def send_message(self, user, message): response = self.client.users_lookupByEmail(email=user.email) if not response.data['ok']: return False user_slack_id = response.data['user']['id'] response = self.client.conversations_open(users=user_slack_id) if not response.data['ok']: return False channel = response.data['channel']['id'] self.client.chat_postMessage(channel=channel, text=message)
class Slack: HAPPY_TEMPLATE = { "type": "section", "text": { "type": "mrkdwn", "text": "GitBot is happy, all builds are passing! :green_heart:", }, } FAILURE_HEADER = { "type": "section", "text": { "type": "mrkdwn", "text": "GitBot is sad, some builds needs fixing. :cry:", }, } def build_failure_block(self, repo, workflow, url): return { "type": "section", "text": { "type": "mrkdwn", "text": f"<{url}|{repo} - {workflow}> :x:", }, } def __init__(self, token, channel): self.channel = channel self.client = WebClient(token=token) def _post(self, blocks, text): print(f"sending to channel {self.channel}") self.client.chat_postMessage(channel=self.channel, blocks=blocks, text=text) def notify_happy(self): self._post( blocks=[self.HAPPY_TEMPLATE], text="All builds are passing", ) def notify_failures(self, failures): blocks = [self.FAILURE_HEADER] for failure in failures: blocks.append(self.build_failure_block(**failure)) self._post(blocks=blocks, text="Build failures detected")
def slack_post_message(client: WebClient, message_blocks: List): """Post a message to a slack channel Args: client (WebClient): Slack web-client object. message_blocks (List): List of blocks representing the message blocks. Returns: (List): List containing a dictionary which represents the message title """ client.chat_postMessage(channel=SLACK_CHANNEL_TO_SEND_PR_TO, attachments=[{ "color": GREEN_COLOR, "blocks": message_blocks }])