luoxu-analytics-plugin/group_data.py

48 lines
1.4 KiB
Python
Raw Normal View History

2023-09-14 14:21:47 +00:00
from typing import List, Dict, Optional
import asyncpg
2023-09-14 13:24:36 +00:00
from cashews import cache
from telethon import TelegramClient
2023-09-14 13:43:30 +00:00
from telethon.errors import StatsMigrateError
2023-09-14 13:24:36 +00:00
from telethon.tl.functions.stats import GetMegagroupStatsRequest
from telethon.utils import get_input_channel
from telethon.tl.types.stats import MegagroupStats
cache.setup("mem://")
@cache(ttl="1h", key="{cid}")
2023-09-14 14:21:47 +00:00
async def get_group_data(cid: int, client: TelegramClient, db) -> List[Dict]:
2023-09-14 13:24:36 +00:00
group = get_input_channel(await client.get_input_entity(cid))
2023-09-14 13:43:30 +00:00
try:
result: MegagroupStats = await client(GetMegagroupStatsRequest(
channel=group,
dark=True
))
except StatsMigrateError as e:
sender = await client._borrow_exported_sender(e.dc)
result: MegagroupStats = await client._call(sender, GetMegagroupStatsRequest(
channel=group,
dark=True
))
2023-09-14 14:21:47 +00:00
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"