def answer_false(event, action): value = action["value"] value = json.loads(value) print_json({ "type": "Slack", "message": "Interactive Event Value", "value": value, }) message = event["message"] alert_id = value["SystemAlertId"] user = event["user"], channel_id = event["container"]["channel_id"] blocks = message["blocks"] blocks[2] = { "type": "section", "block_id": "reason", "fields": [ {"type": "mrkdwn", "text": "*応答*"}, {"type": "mrkdwn", "text": "心当たりがない"}, {"type": "mrkdwn", "text": "*応答ユーザー*"}, {"type": "mrkdwn", "text": user[0]["username"]} ] } set_status(alert_id, False) slack_api_token = kms_decrypted("SLACK_API_TOKEN") slack_chat = Slack.Chat(token=slack_api_token) post_args = { "channel": channel_id, "text": message["text"], "ts": message["ts"], "blocks": blocks, } slack_chat.update_message(**post_args)
def DailySummary(): message_lines = [] sunlight = Query.HoursOfSunlight() message_lines.append(f'{sunlight:.1f} hours of sunlight in the last 24 hours') temp_range = Query.TempRange() message_lines.append(f'Temp range: {temp_range} Celcius') Slack.SendMessage(message='\n'.join(message_lines))
def PingShinobi(): '''Check Cameras and send picture to Slack.''' # TODO: Configure monitor_id and group_key in env variables. logging.info('Checking Shinobi') monitor_id = os.environ['SHINOBI_MONITOR_ID'] group_key = os.environ['SHINOBI_GROUP_KEY'] image_loc = Shinobi.GetMonitorImage(monitor_id, group_key) Slack.UploadFile(image_loc, 'test.jpg')
def PingForecast(): '''Check hourly 2-day forcast and send summary to Slack.''' logging.info('Checking hourly forecast') forecast = Weather.FetchForecast() status = Weather.CheckForecast(forecast) message = Weather.ForecastMessage(status) # Send status to slack Slack.SendMessage(message='2 day Forecast:\n' + message)
def set_user_committees(my_committees, token): user = User.get_member_info(user_id_token=token) github_username = user["github_username"] for committee in all_committees: myfirebase.put('/members/' + user["uid"], "/committees/" + committee, committee in my_committees) for committee in my_committees: github_team_id, slack_channel_id = get_committee_info(committee) if github_team_id is not None: Github.add_member_to_team(github_username, github_team_id) if slack_channel_id is not None: Slack.invite_user_to_channel(slack_channel_id, email=user["rowan_email"])
def sign_in(google_login_token): user = User.get_member_info(user_id_token=google_login_token) if user is None: return RESPONSE_INVALID_INPUT is_new_member = update_user_info(user) # If they are already on slack this won't do anything Slack.invite_to_slack(email=user["rowan_email"]) if is_new_member: email_new_member(user) if not is_attendance_enabled(): if is_new_member: return RESPONSE_REGISTERED return RESPONSE_ATTENDANCE_DISABLED # The location of the current attendance in the database current = myfirebase.get('/attendance/status/current', None) # If the member already signed in, return RESPONSE_ALREADY_SIGNED_IN if is_already_signed_in(current, user): return RESPONSE_ALREADY_SIGNED_IN # Sign the user in to the meeting myfirebase.put('/attendance/', current + "/" + user["uid"], { "uid": user["uid"], "name": user["name"], "email": user["rowan_email"] }) # Increment signed in count increment_signed_in_count(current) if is_new_member: increment_new_member_count() increment_meeting_count(user) if is_new_member: return RESPONSE_SUCCESSFUL_NEW return RESPONSE_SUCCESSFUL_EXISTING
def make_announcement(title, body, author=None, snippet=None, committee=None, icon_url=None, url=None, also_post_on_slack=False): """ Post an announcement on the website and app :param title: Title of the announcement :param body: Full body of the message :param author: Name of the person who made the announcement :param snippet: What to show before clicking for the full text. If None, take the beginning of body :param committee: general, app, web, robotics, ai, game :param icon_url: If 'None', an icon will be chosen for you (recommended) To choose your own, specify it here :param url: (Optional) A link to include with the announcement :param also_post_on_slack: If true, post on slack to the appropriate channel :return: void """ if committee is None: committee = "general" committee_name = get_committee_name(committee) if icon_url is None: icon_url = get_announcement_icon(committee) if snippet is None: snippet = get_shortened(body) announce = {"author": author, "committee": committee_name, "committee_id": committee, "icon": icon_url, "title": title, "text": body, "snippet": snippet, "timestamp": int(time.time()), "url": url} myfirebase.post("/announcements", announce) if also_post_on_slack: Slack.post_announcement_on_slack(announce)
def view_submission(event): """ @brief 入力用Modal ViewからSubmitssion Callbackの受け取り @params[in] event イベントペイロード @details 入力値を取得しprivate_metadataから呼出元メッセージを特定し @n chat.update APIにて入力値を呼び出し元に反映します """ view = event["view"] private_metadata = json.loads(view["private_metadata"]) container = private_metadata["container"] message = private_metadata["message"] channel_id = container["channel_id"] blocks = message["blocks"] user = private_metadata["user"] action_value = private_metadata["action_value"] reason = view["state"]["values"]["reason_input"]["reason_text"]["value"] status = action_value["Status"] alert_id = action_value["SystemAlertId"] message_id = action_value["MessageId"] blocks[2] = { "type": "section", "block_id": "reason", "fields": [ {"type": "mrkdwn", "text": "*応答*"}, {"type": "mrkdwn", "text": "意図している"}, {"type": "mrkdwn", "text": "*応答ユーザー*"}, {"type": "mrkdwn", "text": user["username"]}, {"type": "mrkdwn", "text": "*理由*"}, {"type": "mrkdwn", "text": reason} ] } reason = "[{}]{}".format(user["username"], reason) result = set_status(alert_id, status, reason) if result: slack_api_token = kms_decrypted("SLACK_API_TOKEN") slack_chat = Slack.Chat(token=slack_api_token) post_args = { "channel": channel_id, "text": message["text"], "ts": message["ts"], "blocks": blocks, } print_json({ "type": "Slack", "message": "Update Message", "metadata": post_args }) slack_chat.update_message(**post_args) remove_message(message_id, alert_id)
def update_user_info(user): name = user["name"] email = user["rowan_email"] uid = user["uid"] username = email.split("@")[0] on_slack = Slack.is_user_on_slack(email) is_member_new = myfirebase.get('/members/' + uid + "/email", None) != email myfirebase.put('/members/', uid + "/email", email) myfirebase.put('/members/', uid + "/username", username) myfirebase.put('/members/', uid + "/name", name) myfirebase.put('/members/', uid + "/uid", uid) myfirebase.put('/members/', uid + "/on_slack", on_slack) return is_member_new
def call_modal(event): """ @brief 入力用Modal Viewの表示 @params[in] event イベントペイロード @details メッセージ上のBlocksに表示されたボタンのaction_idが @n answer_trueである場合に呼び出されます。 @n 呼出元のBlocksのチャンネル情報とメッセージ情報を @n private_metadataに格納しModal Viewを画面上に表示されます。 """ slack_api_token = kms_decrypted("SLACK_API_TOKEN") trigger_id = event["trigger_id"] action = event["actions"][0] action_value = action["value"] action_value = json.loads(action_value) data = json.dumps({ "container": event["container"], "channel": event["channel"], "message": event["message"], "user": event["user"], "action_value": action_value }) slack_views = Slack.Views(token=slack_api_token) view = { "type": "modal", "private_metadata": data, "callback_id": "modal_reason", "title": {"type": "plain_text", "text": "Azure Sentinel 通知"}, "submit": {"type": "plain_text", "text": "Submit"}, "close": {"type": "plain_text", "text": "Cancel"}, "blocks": [{ "type": "input", "block_id": "reason_input", "element": { "type": "plain_text_input", "multiline": True, "action_id": "reason_text" }, "label": {"type": "plain_text", "text": "理由"} }] } slack_views.open(trigger_id, view)
def main_function(events): slack_api_token = kms_decrypted("SLACK_API_TOKEN") slack_bot_token = kms_decrypted("SLACK_BOT_TOKEN") channel_id = kms_decrypted("SLACK_CHANNEL_ID") slack_chat = Slack.Chat(token=slack_api_token) for event in events: body = event.get("body", None) if body is None: continue id = set_ignore_queue(body) body = json.loads(body) username = body["Name"].replace('assumed-role/sso/', '') body["MessageId"] = id blocks = [] blocks.append({ "type": "section", "block_id": "alert", "text": { "type": "mrkdwn", "text": "@{}\nAzure Sentinel 警告通知".format(username) }, "fields": [ { "type": "mrkdwn", "text": "*アラート名*" }, { "type": "mrkdwn", "text": body["AlertName"] }, { "type": "mrkdwn", "text": "*アラート概要*" }, { "type": "mrkdwn", "text": body["Description"] }, ] }) blocks.append({"type": "divider"}) elements = [] body["Status"] = True elements.append({ "action_id": "answer_true", "type": "button", "text": { "type": "plain_text", "text": "意図している" }, "value": json.dumps(body) }) body["Status"] = False elements.append({ "action_id": "answer_false", "type": "button", "text": { "type": "plain_text", "text": "心当たりがない" }, "value": json.dumps(body) }) blocks.append({ "block_id": "answer", "type": "actions", "elements": elements }) post_args = { "channel": channel_id, "text": "Azure Sentinel 警告通知", "blocks": blocks, "link_names": True, "mrkdwn": True } print_json({ "type": "Slack", "message": "メッセージ送信", "channel-id": channel_id, "payload": post_args, }) result = slack_chat.post_message(**post_args)
def get_member_info(user_id_token=None, uid=None): if user_id_token is None and uid is None: return None if uid is None: try: decoded_token = auth.verify_id_token(user_id_token) except: return None uid = decoded_token['uid'] member = myfirebase.get("/members/", uid) slack_id, slack_username, slack_picture = Slack.get_user_info(email=member["email"]) github_username = myfirebase.get("members/" + uid, "github-username") if github_username is None: github_username = Github.get_github_username(member["email"]) myfirebase.put("members/" + uid, "github-username", github_username) my_committees = [] committees = myfirebase.get("members/" + uid, "committees") if committees is not None: for committee_name, joined_committee in committees.iteritems(): if joined_committee: my_committees.append(committee_name) committee_text = "No committee selected" if "eboard" in my_committees: committee_text = "Eboard" elif "ai" in my_committees: committee_text = "AI Committee" elif "app" in my_committees: committee_text = "App Committee" elif "game" in my_committees: committee_text = "Animation/Game Committee" elif "robotics" in my_committees: committee_text = "Robotics Committee" elif "web" in my_committees: committee_text = "Web Dev Committee" is_eboard = myfirebase.get("members/" + uid, "committees/eboard") is True is_admin = myfirebase.get("members/" + uid, "admin") is True meeting_count = myfirebase.get("members/" + uid, "meeting_count") if meeting_count is None: meeting_count = 0 name = member["name"] rowan_email = member["email"] phone_number = None user = {"name": name, "rowan_email": rowan_email, "phone_number": phone_number, "is_eboard": is_eboard, "is_admin": is_admin, "on_github": github_username is not None, "github_username": github_username, "on_slack": slack_username is not None, "slack_username": slack_username, "profile_picture": slack_picture, "meeting_count": meeting_count, "committee_list": my_committees, "committee_string": committee_text, "member_since": "September 2016", # TODO "uid": uid} user["todo_list"] = get_user_todo_list(user) return user
def main_function(data, context): credential_setting() body = data.get("body", {}) event = body.get("event", {}) text = event.get("text", None) channel_id = event.get("channel", None) channel_type = event.get("channel_type", None) ts = event.get("ts", None) files = event.get("files", []) user_id = event.get("user") thread_ts = event.get("thread_ts", None) blocks = event.get("blocks", None) links = [] for file in files: try: id, name, link = transfer(file, event) links.append(link) except urllib.error.HTTPError as e: if e.code == 404: print_json({ "level": "warning", "type": "Slack", "message": "Slack上にFileが存在しません", "id": file["id"], "name": file["name"] }) continue raise e except Exception as e: raise e if len(links) == 0: return # Slack処理 user_info = slack_user.info(user_id) profile = user_info["user"]["profile"] user_icon = profile.get("image_original", profile["image_192"]) user_name = profile.get("display_name") if user_name == "": user_name = profile.get("real_name") if channel_type == "im": channel_id = user_id try: slack_chat = Slack.Chat(token=slack_bot_token) message = { "channel": channel_id, "text": "{}\n{}".format(text, "\n".join(links)), "link_names": True, "username": user_name, "icon_url": user_icon, "thread_ts": thread_ts } print_json({ "type": "Slack", "message": "Slack上にメッセージをPostします", "data": message }) slack_chat.post_message(**message) except Exception as e: raise e # 古いメッセージを削除 try: print_json({ "type": "Slack", "message": "Slack上の古いメッセージを削除します", "channel": channel_id, "ts": ts }) slack_chat = Slack.Chat(token=slack_token) slack_chat.delete(channel=channel_id, ts=ts, as_user=True) except Exception as e: print_json({ "type": "Slac", "level": "error", "request-id": lambda_tools.aws_request_id, "channel": channel_id, "ts": ts, "message": "メッセージ削除に失敗しました[{}]".format(str(e)) }) # Slack上のファイルを削除 slack_file = Slack.File(token=slack_token) for file in files: try: print_json({ "type": "Slack", "message": "Slack上のファイルを削除します", "file": file["id"], "name": file["name"] }) slack_file.delete(file=file["id"]) except Exception as e: print_json({ "type": "lambda", "level": "error", "request-id": lambda_tools.aws_request_id, "message": "ファイル削除に失敗しました[{}]".format(str(e)), "file": file["id"], "name": file["name"] })
import Box import GSuite import urllib.request import logging from urllib.parse import parse_qs import lambda_tools from lambda_tools import invoke from lambda_tools import print_json from lambda_tools import kms_decrypted from lambda_tools import get_lambda_info from lambda_tools import slack_verification slack_token = kms_decrypted("SLACK_TOKEN") slack_bot_token = kms_decrypted("SLACK_BOT_TOKEN") slack_user = Slack.User(token=slack_bot_token) slack_channel_ids = kms_decrypted("SLACK_CHANNEL_IDS", None) if not (slack_channel_ids is None or slack_channel_ids == ""): slack_channel_ids = slack_channel_ids.split(",") box_folder = None box_file = None gdrive = None gdrive_permission = None upload_type = kms_decrypted("UPLOAD_TYPE").lower() def credential_setting(): # Box用設定 if "box" == upload_type: global box_file