|
| 1 | +import re |
| 2 | +from argparse import ArgumentParser |
| 3 | +from functools import partial |
| 4 | + |
| 5 | +from kizuna.models import User |
| 6 | + |
| 7 | + |
| 8 | +def format_slack_mention(slack_id: str): |
| 9 | + return f"<@{slack_id}>" |
| 10 | + |
| 11 | + |
| 12 | +user_id_regex = '^<@(U[A-Za-z0-9]{8,})>$' |
| 13 | + |
| 14 | + |
| 15 | +def extract_mentions(text): |
| 16 | + return set(re.findall(r"<@(\S+)>", text, re.DOTALL)) |
| 17 | + |
| 18 | + |
| 19 | +def get_user_id_from_mention(m: str): |
| 20 | + match = re.match(user_id_regex, m) |
| 21 | + if not match: |
| 22 | + return None |
| 23 | + |
| 24 | + return match.group(1) |
| 25 | + |
| 26 | + |
| 27 | +def is_user_mention(s: str) -> bool: |
| 28 | + """user mentions should be in format <@UXXXXXXXX>""" |
| 29 | + |
| 30 | + if not s or not re.match(user_id_regex, s): |
| 31 | + return False |
| 32 | + |
| 33 | + return True |
| 34 | + |
| 35 | + |
| 36 | +def send(slack_client, channel, text): |
| 37 | + return slack_client.api_call("chat.postMessage", |
| 38 | + channel=channel, |
| 39 | + text=text, |
| 40 | + as_user=True) |
| 41 | + |
| 42 | + |
| 43 | +def reply(slack_client, message, text): |
| 44 | + return slack_client.api_call("chat.postMessage", |
| 45 | + channel=message['channel'], |
| 46 | + text=f"{format_slack_mention(message['user'])} {text}", |
| 47 | + as_user=True) |
| 48 | + |
| 49 | + |
| 50 | +def send_factory(slack_client, channel): |
| 51 | + return partial(send, slack_client, channel) |
| 52 | + |
| 53 | + |
| 54 | +def send_ephemeral(slack_client, channel, user, text): |
| 55 | + if isinstance(user, User): |
| 56 | + user = user.slack_id |
| 57 | + |
| 58 | + return slack_client.api_call("chat.postEphemeral", |
| 59 | + channel=channel, |
| 60 | + user=user, |
| 61 | + text=text, |
| 62 | + as_user=True) |
| 63 | + |
| 64 | + |
| 65 | +def send_ephemeral_factory(slack_client, channel, user): |
| 66 | + return partial(send_ephemeral, slack_client, channel, user) |
| 67 | + |
| 68 | + |
| 69 | +class SlackArgumentParserException(Exception): |
| 70 | + pass |
| 71 | + |
| 72 | + |
| 73 | +class SlackArgumentParser(ArgumentParser): |
| 74 | + def error(self, message): |
| 75 | + raise SlackArgumentParserException(message) |
| 76 | + |
| 77 | + |
| 78 | +def slack_link(text, url): |
| 79 | + return '<{}|{}>'.format(url, text) |
0 commit comments