Skip to content

Commit

Permalink
PARSING WORKS OML FUCK YEAH
Browse files Browse the repository at this point in the history
  • Loading branch information
transcental committed Dec 1, 2024
1 parent d7e5783 commit c7ea55b
Show file tree
Hide file tree
Showing 4 changed files with 103 additions and 37 deletions.
6 changes: 4 additions & 2 deletions events/views/create_event.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
from datetime import datetime, timezone

from utils.env import env
from utils.utils import rich_text_to_md, md_to_mrkdwn
from utils.utils import rich_text_to_md, rich_text_to_mrkdwn
from views.app_home import get_home
import json


def handle_create_event_view(ack: Callable, body: dict[str, Any], client: WebClient):
Expand Down Expand Up @@ -52,7 +53,8 @@ def handle_create_event_view(ack: Callable, body: dict[str, Any], client: WebCli
user_id = body.get("user", {}).get("id", "")
host_mention = f"for <@{host_id}>" if host_id != user_id else ""
host_str = f"<@{user_id}> {host_mention}"
mrkdwn = md_to_mrkdwn(md)
rich_text = json.loads(event["fields"]["Raw Description"])
mrkdwn = rich_text_to_mrkdwn(rich_text)
client.chat_postMessage(
channel=env.slack_approval_channel,
text=f"New event request by <@{body['user']['id']}>!\nTitle: {title[0]}\nDescription: {mrkdwn}\nStart Time: {start_time[0]}\nEnd Time: {end_time[0]}",
Expand Down
5 changes: 3 additions & 2 deletions events/views/edit_event.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from datetime import datetime, timezone

from utils.env import env
from utils.utils import rich_text_to_md, md_to_mrkdwn
from utils.utils import rich_text_to_md, rich_text_to_mrkdwn
from views.app_home import get_home

import json
Expand Down Expand Up @@ -66,7 +66,8 @@ def handle_edit_event_view(ack: Callable, body: dict[str, Any], client: WebClien
user_id = body.get("user", {}).get("id", "")
host_mention = f"for <@{host_id}>" if host_id != user_id else ""
host_str = f"<@{user_id}> {host_mention}"
mrkdwn = md_to_mrkdwn(md)
rich_text = json.loads(raw_description_string)
mrkdwn = rich_text_to_mrkdwn(rich_text)
client.chat_postMessage(
channel=env.slack_approval_channel,
text=f"New event request by <@{body['user']['id']}>!\nTitle: {title[0]}\nDescription: {mrkdwn}\nStart Time: {start_time[0]}\nEnd Time: {end_time[0]}",
Expand Down
120 changes: 90 additions & 30 deletions utils/utils.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
from .env import env
from slack_sdk import WebClient
from urllib.parse import quote

import re
import mistune

from slack_sdk import WebClient

client = WebClient(token=env.slack_bot_token)

ZWSP = '\u200B'

def user_in_safehouse(user_id: str):
sad_members = client.conversations_members(channel=env.slack_sad_channel)["members"]
Expand All @@ -18,17 +20,36 @@ def parse_elements(elements):
if element["type"] == "text":
text = element["text"]
if "style" in element:
if element["style"].get("bold"):
styles = element["style"]
if styles.get("bold") and styles.get("italic"):
text = f"**_{text}_**"
elif styles.get("bold"):
text = f"**{text}**"
if element["style"].get("italic"):
text = f"*{text}*"
if element["style"].get("strike"):
elif styles.get("italic"):
text = f"_{text}_"
if styles.get("strike"):
text = f"~~{text}~~"
if element["style"].get("code"):
if styles.get("code"):
text = f"`{text}`"
markdown += text
elif element["type"] == "link":
markdown += f"[{element['text']}]({element['url']})"
elif element["type"] == "user":
markdown += f"<@{element['user_id']}>"
elif element["type"] == "emoji":
markdown += f":{element['name']}:"
elif element["type"] == "channel":
markdown += f"<#{element['channel_id']}>"
elif element["type"] == "subteam":
markdown += f"<!subteam^{element['subteam_id']}|{element['name']}>"
elif element["type"] == "date":
markdown += f"<!date^{element['timestamp']}^{element['format']}|{element['fallback']}>"
elif element["type"] == "url":
markdown += f"<{element['url']}>"
elif element["type"] == "line_break":
markdown += "\n"
elif element["type"] == "usergroup":
markdown += f"<!subteam^{element['usergroup_id']}>"
return markdown


Expand Down Expand Up @@ -59,26 +80,65 @@ def rich_text_to_md(input_data, indent_level=0, in_quote=False):
return markdown


def md_to_mrkdwn(md):
# Convert bold and italic text (bold first to avoid conflicts)
md = re.sub(r"\*\*\*(.*?)\*\*\*", r"***\1***", md) # Bold and italic
md = re.sub(r"\*\*(.*?)\*\*", r"*\1*", md) # Bold
md = re.sub(r"\b\*(.*?)\*\b", r"_\1_", md) # Italic
# Convert strikethrough text
md = re.sub(r"~~(.*?)~~", r"~\1~", md)
# Convert inline code
md = re.sub(r"`(.*?)`", r"`\1`", md)
# Convert links
md = re.sub(r"\[(.*?)\]\((.*?)\)", r"<\2|\1>", md)
# Convert blockquotes
md = re.sub(r"^> (.*)", r"> \1", md, flags=re.MULTILINE)
# Convert code blocks
md = re.sub(r"```(.*?)```", r"```\1```", md, flags=re.DOTALL)
# Convert unordered lists
md = re.sub(r"^\s*-\s+(.*)", r"• \1", md, flags=re.MULTILINE)
# Convert ordered lists
md = re.sub(r"^\s*\d+\.\s+(.*)", r"1. \1", md, flags=re.MULTILINE)
# Handle nested lists
md = re.sub(r"(\n\s*)•", r"\1 •", md)
md = re.sub(r"(\n\s*)1\.", r"\1 1.", md)
return md
def parse_elements_to_mrkdwn(elements):
mrkdwn = ""
for element in elements:
if element["type"] == "text":
text = element["text"]
if "style" in element:
styles = element["style"]
words = re.split(r'(\s+)', text) # Split by whitespace but keep the whitespace
formatted_words = []
for word in words:
if word.strip(): # Only apply formatting to non-whitespace words
if styles.get("bold") and styles.get("italic"):
word = f"*_{word.strip()}_*"
elif styles.get("bold"):
word = f"*{word.strip()}*"
elif styles.get("italic"):
word = f"_{word.strip()}_"
if styles.get("strike"):
word = f"~{word.strip()}~"
if styles.get("code"):
word = f"`{word.strip()}`"
formatted_words.append(word)
text = "".join(formatted_words) # Join without adding extra spaces
mrkdwn += text
elif element["type"] == "link":
mrkdwn += f"<{element['url']}|{element['text']}>"
elif element["type"] == "user":
mrkdwn += f"<@{element['user_id']}>"
elif element["type"] == "emoji":
mrkdwn += f":{element['name']}:"
elif element["type"] == "channel":
mrkdwn += f"<#{element['channel_id']}>"
elif element["type"] == "subteam":
mrkdwn += f"<!subteam^{element['subteam_id']}|{element['name']}>"
elif element["type"] == "date":
mrkdwn += f"<!date^{element['timestamp']}^{element['format']}|{element['fallback']}>"
elif element["type"] == "url":
mrkdwn += f"<{element['url']}>"
elif element["type"] == "line_break":
mrkdwn += "\n"
elif element["type"] == "usergroup":
mrkdwn += f"<!subteam^{element['usergroup_id']}>"
return mrkdwn

def rich_text_to_mrkdwn(data):
mrkdwn = ""
for block in data:
if isinstance(block, dict) and block["type"] == "rich_text_section":
mrkdwn += parse_elements_to_mrkdwn(block["elements"]) + "\n"
elif isinstance(block, dict) and block["type"] == "rich_text_quote":
mrkdwn += "> " + parse_elements_to_mrkdwn(block["elements"]) + "\n"
# Handle nested lists within quotes
mrkdwn += rich_text_to_mrkdwn(block["elements"])
elif isinstance(block, dict) and block["type"] == "rich_text_preformatted":
mrkdwn += "```\n" + parse_elements_to_mrkdwn(block["elements"]) + "\n```\n"
elif isinstance(block, dict) and block["type"] == "rich_text_list":
for item in block["elements"]:
mrkdwn += f"- {parse_elements_to_mrkdwn(item['elements'])}\n"
# Recursively parse nested lists
if "elements" in item:
mrkdwn += rich_text_to_mrkdwn(item["elements"])
return mrkdwn
9 changes: 6 additions & 3 deletions views/app_home.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
from slack_sdk import WebClient

from utils.env import env
from utils.utils import user_in_safehouse, md_to_mrkdwn
from utils.utils import user_in_safehouse, rich_text_to_mrkdwn
import json


def get_home(user_id: str, client: WebClient):
Expand Down Expand Up @@ -47,7 +48,8 @@ def get_home(user_id: str, client: WebClient):
"Ends at %I:%M %p"
)
formatted_time = f"<!date^{int(datetime.fromisoformat(event['fields']['End Time']).timestamp())}^Ends at {{time}}|{fallback_time}>"
mrkdwn = md_to_mrkdwn(event["fields"]["Description"])
rich_text = json.loads(event["fields"]["Raw Description"])
mrkdwn = rich_text_to_mrkdwn(rich_text['elements'])
current_events_blocks.append(
{
"type": "section",
Expand Down Expand Up @@ -117,7 +119,8 @@ def get_home(user_id: str, client: WebClient):
"%A, %B %d at %I:%M %p"
)
formatted_time = f"<!date^{int(datetime.fromisoformat(event['fields']['Start Time']).timestamp())}^{{date_long_pretty}} at {{time}}|{fallback_time}>"
mrkdwn = md_to_mrkdwn(event["fields"]["Description"])
rich_text = json.loads(event["fields"]["Raw Description"])
mrkdwn = rich_text_to_mrkdwn(rich_text['elements'])
upcoming_events_blocks.append(
{
"type": "section",
Expand Down

0 comments on commit c7ea55b

Please sign in to comment.