|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from typing import TypedDict |
| 4 | + |
| 5 | +import aiohttp |
| 6 | +import async_lru |
| 7 | + |
| 8 | +from bot.config import Config |
| 9 | +from bot.data import command |
| 10 | +from bot.data import esc |
| 11 | +from bot.data import format_msg |
| 12 | +from bot.message import Message |
| 13 | + |
| 14 | + |
| 15 | +class UserData(TypedDict): |
| 16 | + channel_id: str |
| 17 | + channel_login: str |
| 18 | + pronoun_id: str |
| 19 | + alt_pronoun_id: str | None |
| 20 | + |
| 21 | + |
| 22 | +class PronounData(TypedDict): |
| 23 | + name: str |
| 24 | + subject: str |
| 25 | + object: str |
| 26 | + singular: bool |
| 27 | + |
| 28 | + |
| 29 | +async def _get_user_data(username: str) -> UserData | None: |
| 30 | + url = f'https://api.pronouns.alejo.io/v1/users/{username}' |
| 31 | + |
| 32 | + async with aiohttp.ClientSession() as session: |
| 33 | + async with session.get(url) as resp: |
| 34 | + if resp.status != 200: |
| 35 | + return None |
| 36 | + |
| 37 | + return (await resp.json()) |
| 38 | + |
| 39 | + |
| 40 | +@async_lru.alru_cache(maxsize=1) |
| 41 | +async def pronouns() -> dict[str, PronounData]: |
| 42 | + url = 'https://api.pronouns.alejo.io/v1/pronouns/' |
| 43 | + |
| 44 | + async with aiohttp.ClientSession() as session: |
| 45 | + async with session.get(url) as resp: |
| 46 | + return (await resp.json()) |
| 47 | + |
| 48 | + |
| 49 | +async def _get_user_pronouns(username: str) -> tuple[str, str] | None: |
| 50 | + user_data = await _get_user_data(username) |
| 51 | + |
| 52 | + if user_data is None: |
| 53 | + return None |
| 54 | + |
| 55 | + pronoun_data = (await pronouns())[user_data['pronoun_id']] |
| 56 | + return (pronoun_data['subject'], pronoun_data['object']) |
| 57 | + |
| 58 | + |
| 59 | +@command('!pronouns') |
| 60 | +async def cmd_pronouns(config: Config, msg: Message) -> str: |
| 61 | + # TODO: handle display name |
| 62 | + username = msg.optional_user_arg.lower() |
| 63 | + pronouns = await _get_user_pronouns(username) |
| 64 | + |
| 65 | + if pronouns is None: |
| 66 | + return format_msg(msg, f'user not found {esc(username)}') |
| 67 | + |
| 68 | + (subj, obj) = pronouns |
| 69 | + return format_msg(msg, f'{username}\'s pronouns are: {subj}/{obj}') |
0 commit comments