aboutsummaryrefslogtreecommitdiffstats
path: root/slack/slack_message.py
blob: 1cbce43848ce48055193da79c8e2c3a89cfcf394 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
from __future__ import annotations

import re
from typing import TYPE_CHECKING, List, Match, Optional

from slack.shared import shared
from slack.slack_user import SlackUser, SlackUsergroup, format_bot_nick
from slack.task import gather
from slack.util import with_color

if TYPE_CHECKING:
    from slack_api.slack_conversations_history import SlackMessage as SlackMessageDict

    from slack.slack_conversation import SlackConversation
    from slack.slack_workspace import SlackWorkspace


class SlackMessage:
    def __init__(self, conversation: SlackConversation, message_json: SlackMessageDict):
        self._message_json = message_json
        self.conversation = conversation
        self.ts = message_json["ts"]

    @property
    def workspace(self) -> SlackWorkspace:
        return self.conversation.workspace

    @property
    def sender_user_id(self) -> Optional[str]:
        return self._message_json.get("user")

    async def render_message(self) -> str:
        prefix_coro = self._prefix()
        message_coro = self._unfurl_refs(self._message_json["text"])
        prefix, message = await gather(prefix_coro, message_coro)
        return f"{prefix}\t{message}"

    async def _prefix(self) -> str:
        if (
            "subtype" in self._message_json
            and self._message_json["subtype"] == "bot_message"
        ):
            username = self._message_json.get("username")
            if username:
                return format_bot_nick(username, colorize=True)
            else:
                bot = await self.workspace.bots[self._message_json["bot_id"]]
                return bot.nick(colorize=True)
        else:
            user = await self.workspace.users[self._message_json["user"]]
            return user.nick(colorize=True)

    async def _unfurl_refs(self, message: str) -> str:
        re_mention = re.compile(r"<@(?P<user>[^>]+)>|<!subteam\^(?P<usergroup>[^>]+)>")
        mention_matches = list(re_mention.finditer(message))

        user_ids: List[str] = [
            match["user"] for match in mention_matches if match["user"]
        ]
        usergroup_ids: List[str] = [
            match["usergroup"] for match in mention_matches if match["usergroup"]
        ]

        users_list = await gather(
            *(self.workspace.users[user_id] for user_id in user_ids),
            return_exceptions=True,
        )
        users = dict(zip(user_ids, users_list))

        usergroups_list = await gather(
            *(
                self.workspace.usergroups[usergroup_id]
                for usergroup_id in usergroup_ids
            ),
            return_exceptions=True,
        )
        usergroups = dict(zip(usergroup_ids, usergroups_list))

        def unfurl_ref(match: Match[str]):
            if match["user"]:
                return unfurl_user(match["user"])
            elif match["usergroup"]:
                return unfurl_usergroup(match["usergroup"])
            else:
                return match[0]

        def unfurl_user(user_id: str):
            user = users[user_id]
            return (
                with_color(
                    shared.config.color.user_mention_color.value, "@" + user.nick()
                )
                if isinstance(user, SlackUser)
                else f"@{user_id}"
            )

        def unfurl_usergroup(usergroup_id: str):
            usergroup = usergroups[usergroup_id]
            return (
                with_color(
                    shared.config.color.usergroup_mention_color.value,
                    "@" + usergroup.handle(),
                )
                if isinstance(usergroup, SlackUsergroup)
                else f"@{usergroup_id}"
            )

        return re_mention.sub(unfurl_ref, message)