Skip to content

Commit

Permalink
fix: condense app home incident list output (#287)
Browse files Browse the repository at this point in the history
  • Loading branch information
echoboomer committed Jul 16, 2023
1 parent 2e42792 commit f0a25c5
Show file tree
Hide file tree
Showing 9 changed files with 47 additions and 144 deletions.
57 changes: 15 additions & 42 deletions backend/bot/slack/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,7 @@
Reusable variables
"""
all_workspace_groups = (
slack_web_client.usergroups_list()
if not config.is_test_environment
else []
slack_web_client.usergroups_list() if not config.is_test_environment else []
)
bot_user_id = (
slack_web_client.auth_test().get("user_id")
Expand All @@ -35,10 +33,7 @@
else "test"
)
slack_workspace_id = (
slack_web_client.auth_test()
.get("url")
.replace("https://", "")
.split(".")[0]
slack_web_client.auth_test().get("url").replace("https://", "").split(".")[0]
if not config.is_test_environment
else "test"
)
Expand All @@ -64,9 +59,7 @@ def check_user_in_group(user_id: str, group_name: str) -> bool:
return True
return False
except Exception as error:
logger.error(
f"Error looking for user {user_id} in group {group_name}: {error}"
)
logger.error(f"Error looking for user {user_id} in group {group_name}: {error}")


def get_channel_history(channel_id: str) -> str:
Expand Down Expand Up @@ -98,9 +91,7 @@ def get_channel_name(channel_id: str) -> str:
def get_digest_channel_id() -> str:
# Get channel id of the incidents digest channel to send updates to
channels = return_slack_channel_info()
index = tools.find_index_in_list(
channels, "name", config.active.digest_channel
)
index = tools.find_index_in_list(channels, "name", config.active.digest_channel)
if index == -1:
raise IndexNotFoundError(
"Could not find index for digest channel in Slack conversations list"
Expand All @@ -116,24 +107,16 @@ def get_formatted_channel_history(channel_id: str, channel_name: str) -> str:
channel_name -- The name of the Slack channel to retrieve history from
"""
users = slack_web_client.users_list()["members"]
replaced_messages_string = replace_user_ids(
get_channel_history(channel_id), users
)
replaced_messages_string = replace_user_ids(get_channel_history(channel_id), users)
formatted_channel_history = str()
formatted_channel_history += (
f"Slack channel history for incident {channel_name}\n"
)
formatted_channel_history += f"Slack channel history for incident {channel_name}\n"
for message in replaced_messages_string:
user = message["user"]
text = message["text"]
timestamp = datetime.datetime.fromtimestamp(
int(message["ts"].split(".")[0])
)
timestamp = datetime.datetime.fromtimestamp(int(message["ts"].split(".")[0]))
prefix = f"* {timestamp}"
if "has joined the channel" in text:
formatted_channel_history += (
f"{prefix} {user} joined the channel\n"
)
formatted_channel_history += f"{prefix} {user} joined the channel\n"
elif "set the channel topic" in text:
formatted_channel_history += f"{prefix} {user} {text}\n"
elif "This content can't be displayed." in text:
Expand Down Expand Up @@ -180,9 +163,7 @@ def invite_user_to_channel(channel_id: str, user: str):
try:
if (
not user
in slack_web_client.conversations_members(channel=channel_id)[
"members"
]
in slack_web_client.conversations_members(channel=channel_id)["members"]
and user not in skip_invite_for_users
):
invite = slack_web_client.conversations_invite(
Expand Down Expand Up @@ -215,9 +196,7 @@ def return_slack_channel_info() -> Dict[str, str]:
):
channels = channels + page.get("channels")
except Exception as error:
logger.error(
f"Error getting channel list from Slack workspace: {error}"
)
logger.error(f"Error getting channel list from Slack workspace: {error}")
return channels


Expand All @@ -239,11 +218,7 @@ def store_slack_user_list():
jdata = sorted(users_array, key=lambda d: d["name"])
# Delete if exists
if Session.query(OperationalData).filter_by(id="slack_users").all():
existing = (
Session.query(OperationalData)
.filter_by(id="slack_users")
.one()
)
existing = Session.query(OperationalData).filter_by(id="slack_users").one()
Session.delete(existing)
Session.commit()
# Store
Expand All @@ -269,19 +244,17 @@ def check_bot_user_in_digest_channel():
digest_channel_id = get_digest_channel_id()
if (
bot_user_id
not in slack_web_client.conversations_members(
channel=digest_channel_id
)["members"]
not in slack_web_client.conversations_members(channel=digest_channel_id)[
"members"
]
):
try:
slack_web_client.conversations_join(channel=digest_channel_id)
logger.info(
f"Added bot user to digest channel #{get_channel_name(channel_id=digest_channel_id)}"
)
except SlackApiError as error:
logger.error(
f"Error auto joining bot user to digest channel: {error}"
)
logger.error(f"Error auto joining bot user to digest channel: {error}")
else:
logger.info(
f"Bot user is already present in digest channel #{get_channel_name(channel_id=digest_channel_id)}"
Expand Down
20 changes: 5 additions & 15 deletions backend/bot/slack/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,9 +129,7 @@ def parse_action(body) -> Dict[str, Any]:
def handle_incident_export_chat_logs(ack, body):
logger.debug(body)
ack()
asyncio.run(
inc_actions.export_chat_logs(action_parameters=parse_action(body))
)
asyncio.run(inc_actions.export_chat_logs(action_parameters=parse_action(body)))


@app.action("incident.add_on_call_to_channel")
Expand All @@ -150,9 +148,7 @@ def handle_incident_archive_incident_channel(ack, body):
logger.debug(body)
ack()
asyncio.run(
inc_actions.archive_incident_channel(
action_parameters=parse_action(body)
)
inc_actions.archive_incident_channel(action_parameters=parse_action(body))
)


Expand Down Expand Up @@ -292,9 +288,7 @@ def reaction_added(event, say):
user=get_user_name(user_id=message["user"]),
)
except Exception as error:
logger.error(
f"Error when trying to retrieve a message: {error}"
)
logger.error(f"Error when trying to retrieve a message: {error}")
finally:
try:
slack_web_client.reactions_add(
Expand All @@ -304,9 +298,7 @@ def reaction_added(event, say):
)
except Exception as error:
if "already_reacted" in str(error):
reason = (
"It looks like I've already pinned that content."
)
reason = "It looks like I've already pinned that content."
else:
reason = f"Something went wrong: {error}"
say(
Expand Down Expand Up @@ -389,9 +381,7 @@ def handle_message_events(body, logger):
)
# Update the sent message with its own timestamp
existing_blocks = sent_message["messages"][0]["blocks"]
existing_blocks[2]["elements"][1]["value"] = result["message"][
"ts"
]
existing_blocks[2]["elements"][1]["value"] = result["message"]["ts"]
try:
slack_web_client.chat_update(
channel=body["event"]["channel"],
Expand Down
8 changes: 2 additions & 6 deletions backend/bot/slack/incident_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,7 @@ def read(
else:
logger.warning(f"No audit log record for {incident_id}")
except Exception as error:
logger.error(
f"Audit log row lookup failed for incident {incident_id}: {error}"
)
logger.error(f"Audit log row lookup failed for incident {incident_id}: {error}")
finally:
database_session.close()
database_session.remove()
Expand Down Expand Up @@ -67,9 +65,7 @@ def write(
database_session.add(obj)
database_session.commit()
except Exception as error:
logger.error(
f"Audit log row create failed for incident {incident_id}: {error}"
)
logger.error(f"Audit log row create failed for incident {incident_id}: {error}")
database_session.rollback()
finally:
database_session.close()
Expand Down
58 changes: 11 additions & 47 deletions backend/bot/slack/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,7 @@ def help_menu(include_header: bool = True) -> List:
return blocks


def incident_list_message(
incidents: List, all: bool = False
) -> List[Dict[str, str]]:
def incident_list_message(incidents: List, all: bool = False) -> List[Dict[str, str]]:
"""Return a message containing details on incidents
Keyword arguments:
Expand Down Expand Up @@ -96,53 +94,23 @@ def incident_list_message(
formatted_incidents.append(
{
"type": "section",
"fields": [
{
"type": "mrkdwn",
"text": f"*Incident Name:* <#{inc.channel_id}>",
},
{
"type": "mrkdwn",
"text": f"*Current Severity:* {inc.severity.upper()}",
},
{
"type": "mrkdwn",
"text": f"*Creation Time:* {inc.created_at}",
},
{
"type": "mrkdwn",
"text": f"*Current Status:* {inc.status.title()}",
},
],
"text": {
"type": "mrkdwn",
"text": f"> <#{inc.channel_id}> *|* _Severity_ *{inc.severity.upper()}* *|* _Status_ *{inc.status.title()}* *|* _Creation Time_ *{inc.created_at}*",
},
}
)
formatted_incidents.append({"type": "divider"})
elif all == False:
if inc.status != "resolved":
formatted_incidents.append(
{
"type": "section",
"fields": [
{
"type": "mrkdwn",
"text": f"*Incident Name:* <#{inc.channel_id}>",
},
{
"type": "mrkdwn",
"text": f"*Current Severity:* {inc.severity.upper()}",
},
{
"type": "mrkdwn",
"text": f"*Creation Time:* {inc.created_at}",
},
{
"type": "mrkdwn",
"text": f"*Current Status:* {inc.status.title()}",
},
],
"text": {
"type": "mrkdwn",
"text": f"> <#{inc.channel_id}> *|* _Severity_ *{inc.severity.upper()}* *|* _Status_ *{inc.status.title()}* *|* _Creation Time_ *{inc.created_at}*",
},
}
)
formatted_incidents.append({"type": "divider"})
if len(formatted_incidents) == 0:
return none_found_block
else:
Expand Down Expand Up @@ -246,9 +214,7 @@ def pd_on_call_message(data: Dict) -> List:
{
"text": {
"type": "plain_text",
"text": "{} {}".format(
v["escalation_level"], v["user"]
),
"text": "{} {}".format(v["escalation_level"], v["user"]),
},
"value": user_mention,
},
Expand Down Expand Up @@ -300,9 +266,7 @@ def pd_on_call_message(data: Dict) -> List:
return base_block


def sp_incident_list_message(
incidents: List[Dict[str, str]]
) -> List[Dict[str, str]]:
def sp_incident_list_message(incidents: List[Dict[str, str]]) -> List[Dict[str, str]]:
"""Return a message containing details on Statuspage incidents
Keyword arguments:
Expand Down
Loading

0 comments on commit f0a25c5

Please sign in to comment.