inbox/services/core.py
Untone ac829b8086
All checks were successful
deploy / deploy (push) Successful in 1m11s
debug-get-author
2023-10-16 23:46:33 +03:00

90 lines
3.0 KiB
Python

from datetime import datetime
from httpx import AsyncClient
from settings import API_BASE
from validators.member import ChatMember
headers = {"Content-Type": "application/json"}
async def get_author(author_id):
gql = {
"query": """query GetAuthorById($author_id: Int!) {
getAuthorById(author_id: $author_id) {
id slug userpic name lastSeen
}
}""",
"operation": "GetAuthorById",
"variables": {"author_id": int(author_id)},
}
async with AsyncClient() as client:
try:
response = await client.post(API_BASE, headers=headers, json=gql)
except Exception:
import traceback
traceback.print_exc()
print(f"[services.core] get_author: {response.status_code} {response.text}")
if response.status_code != 200:
return None
r = response.json()
a = r.get("data", {}).get("getAuthorById")
if a:
last_seen = a.get("lastSeen")
dt = datetime.strptime(last_seen, "%Y-%m-%dT%H:%M:%S.%f")
timestamp = int(dt.timestamp())
a["lastSeen"] = timestamp
author: ChatMember = a
return author
async def get_network(author_id: int, limit: int = 50, offset: int = 0) -> list:
gql = {
"query": """query LoadAuthors($author_id: Int!, $limit: Int, $offset: Int) {
authorFollowings(author_id: $author_id, limit: $limit, offset: $offset) {
id slug userpic name
}
}""",
"operation": "LoadAuthors",
"variables": {"author_id": author_id, "limit": limit, "offset": offset},
}
followings = []
try:
async with AsyncClient() as client:
response = await client.post(API_BASE, headers=headers, json=gql)
if response.status_code != 200:
return []
r = response.json()
followings = r.get("data", {}).get("authorFollowings", [])
more_amount = limit - len(followings)
if more_amount > 0:
followers = await get_followers(author_id, more_amount)
followings.extend(followers)
except Exception as e:
print(e)
return followings
async def get_followers(author_id, amount):
gql = {
"query": """query LoadAuthors($author_id: Int!, $limit: Int, $offset: Int) {
authorFollowers(author_id: $author_id, limit: $limit) {
id slug userpic name
}
}""",
"operation": "LoadAuthors",
"variables": {"author_id": author_id, "limit": amount},
}
try:
async with AsyncClient() as client:
response = await client.post(API_BASE, headers=headers, json=gql)
if response.status_code != 200:
return []
r = response.json()
return r.get("data", {}).get("authorFollowers", [])
except Exception as e:
print(e)
return []