|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import json |
| 4 | +from typing import cast |
| 5 | +from typing import TypedDict |
| 6 | + |
| 7 | +import urllib.request |
| 8 | + |
| 9 | +from bot.config import Config |
| 10 | +from bot.data import command |
| 11 | +from bot.data import esc |
| 12 | +from bot.data import format_msg |
| 13 | +from bot.message import Message |
| 14 | + |
| 15 | +PRONOUNS_ENDPOINT = "https://api.pronouns.alejo.io/v1/pronouns/" |
| 16 | +USER_ENDPOINT = "https://api.pronouns.alejo.io/v1/users/" |
| 17 | + |
| 18 | + |
| 19 | +class UserData(TypedDict): |
| 20 | + channel_id: str |
| 21 | + channel_login: str |
| 22 | + pronoun_id: str |
| 23 | + alt_pronoun_id: str | None |
| 24 | + |
| 25 | + |
| 26 | +class PronounData(TypedDict): |
| 27 | + name: str |
| 28 | + subject: str |
| 29 | + object: str |
| 30 | + singular: bool |
| 31 | + |
| 32 | + |
| 33 | +def _get_user_data(username: str) -> UserData | None: |
| 34 | + try: |
| 35 | + resp = urllib.request.urlopen(USER_ENDPOINT + username) |
| 36 | + except urllib.error.HTTPError: |
| 37 | + return None |
| 38 | + else: |
| 39 | + return cast("UserData", json.load(resp)) |
| 40 | + |
| 41 | + |
| 42 | +def _get_pronouns() -> dict[str, PronounData]: |
| 43 | + resp = urllib.request.urlopen(PRONOUNS_ENDPOINT) |
| 44 | + return cast("dict[str, PronounData]", json.load(resp)) |
| 45 | + |
| 46 | + |
| 47 | +# TODO: add this to bot's setup instead |
| 48 | +PRONOUNS = _get_pronouns() |
| 49 | + |
| 50 | + |
| 51 | +def _get_user_pronouns(username: str) -> tuple[str, str] | None: |
| 52 | + user_data = _get_user_data(username) |
| 53 | + |
| 54 | + if user_data is None: |
| 55 | + return None |
| 56 | + |
| 57 | + pronoun_data = PRONOUNS[user_data["pronoun_id"]] |
| 58 | + return (pronoun_data["subject"], pronoun_data["object"]) |
| 59 | + |
| 60 | + |
| 61 | +@command('!pronouns') |
| 62 | +async def cmd_pronouns(config: Config, msg: Message) -> str: |
| 63 | + # TODO: handle display name |
| 64 | + username = msg.optional_user_arg.lower() |
| 65 | + pronouns = _get_user_pronouns(username) |
| 66 | + |
| 67 | + if pronouns is None: |
| 68 | + return format_msg(msg, f'user not found {esc(username)}') |
| 69 | + |
| 70 | + (subject, object_) = pronouns |
| 71 | + |
| 72 | + return format_msg(msg, f'{username}\'s pronouns are: {subject}/{object_}') |
0 commit comments