Hana Celeste commited on
Commit
d1addcf
·
verified ·
1 Parent(s): 22e2a01

Create discord_logic.py

Browse files
Files changed (1) hide show
  1. app/discord_logic.py +44 -0
app/discord_logic.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import aiohttp
2
+ import os
3
+
4
+ class DiscordApp:
5
+ def __init__(self):
6
+ self.token = os.getenv("DISCORD_TOKEN")
7
+ self.base_url = "https://discord.com/api/v10"
8
+
9
+ async def get_user_info(self, uid: str):
10
+ if not self.token:
11
+ return {"status": "error", "message": "Chưa cài đặt DISCORD_TOKEN trong Secret!"}
12
+
13
+ headers = {"Authorization": f"Bot {self.token}"}
14
+
15
+ async with aiohttp.ClientSession() as session:
16
+ async with session.get(f"{self.base_url}/users/{uid}", headers=headers) as resp:
17
+ if resp.status == 200:
18
+ data = await resp.json()
19
+
20
+ user_id = data.get("id")
21
+ avatar_hash = data.get("avatar")
22
+
23
+ if avatar_hash:
24
+ fmt = "gif" if avatar_hash.startswith("a_") else "png"
25
+ avatar_url = f"https://cdn.discordapp.com/avatars/{user_id}/{avatar_hash}.{fmt}?size=1024"
26
+ else:
27
+ default_index = (int(user_id) >> 22) % 6
28
+ avatar_url = f"https://cdn.discordapp.com/embed/avatars/{default_index}.png"
29
+
30
+ return {
31
+ "status": "success",
32
+ "data": {
33
+ "uid": user_id,
34
+ "username": data.get("username"),
35
+ "display_name": data.get("global_name"),
36
+ "avatar": avatar_url,
37
+ "banner": f"https://cdn.discordapp.com/banners/{user_id}/{data.get('banner')}.png?size=1024" if data.get("banner") else None,
38
+ "accent_color": data.get("accent_color")
39
+ }
40
+ }
41
+ elif resp.status == 401:
42
+ return {"status": "error", "message": "Invalid Token (Unauthorised)"}
43
+ else:
44
+ return {"status": "error", "message": f"Discord API returns an error: {resp.status}"}