diff --git a/__init__.py b/__init__.py index 4cb7173..c5d4be5 100644 --- a/__init__.py +++ b/__init__.py @@ -10,8 +10,9 @@ logger = logging.getLogger('luoxu_plugins.analytics') class GroupAnalyticsHandler: - def __init__(self, client): + def __init__(self, client, db): self.client = client + self.db = db async def get(self, request: web.Request): if cid_str := request.query.get('cid'): @@ -22,7 +23,7 @@ class GroupAnalyticsHandler: raise web.HTTPForbidden(headers={ 'Cache-Control': 'public, max-age=86400', }) - return web.json_response(await get_group_data(uid, self.client)) + return web.json_response(await get_group_data(uid, self.client, self.db)) else: raise web.HTTPNotFound @@ -30,7 +31,7 @@ class GroupAnalyticsHandler: async def register(indexer, client: TelegramClient): port: int = int(indexer.config['plugin']['analytics']['port']) - handler = GroupAnalyticsHandler(client) + handler = GroupAnalyticsHandler(client, indexer.dbstore) app = web.Application() app.router.add_get('/api/group_analytics', handler.get) diff --git a/group_data.py b/group_data.py index 74d3615..17cbb06 100644 --- a/group_data.py +++ b/group_data.py @@ -1,4 +1,6 @@ -from typing import List, Dict +from typing import List, Dict, Optional + +import asyncpg from cashews import cache from telethon import TelegramClient @@ -11,7 +13,7 @@ cache.setup("mem://") @cache(ttl="1h", key="{cid}") -async def get_group_data(cid: int, client: TelegramClient) -> List[Dict]: +async def get_group_data(cid: int, client: TelegramClient, db) -> List[Dict]: group = get_input_channel(await client.get_input_entity(cid)) try: result: MegagroupStats = await client(GetMegagroupStatsRequest( @@ -24,4 +26,22 @@ async def get_group_data(cid: int, client: TelegramClient) -> List[Dict]: channel=group, dark=True )) - return [i.to_dict() for i in result.top_posters] + data = [i.to_dict() for i in result.top_posters] + for i in data: + i['name'] = await get_user_name(db, i['user_id']) + return data + + +async def get_user_name(db, uid: int) -> str: + async with db.get_conn() as conn: + conn: "asyncpg.pool.connection.Connection" + sql = f"""\ + SELECT name + FROM usernames + WHERE {uid} = ANY ( uid ) + ORDER BY last_seen DESC + LIMIT 1;""" + value = await conn.fetchval(sql) + if value: + return value + return "Unknown" diff --git a/requirements.txt b/requirements.txt index 6e3b181..e9f7909 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,4 @@ telethon aiohttp +asyncpg cashews==6.2.0