-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
executable file
·68 lines (51 loc) · 1.72 KB
/
Copy pathserver.py
File metadata and controls
executable file
·68 lines (51 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import asyncio
import os
from contextlib import asynccontextmanager
import discord
import uvicorn
from fastapi import FastAPI, Request
bot: discord.Bot = None
token = os.getenv("PINGME_BOT_TOKEN")
address = os.getenv("PINGME_ADDRESS")
port = os.getenv("PINGME_PORT")
if not token:
raise RuntimeError("Missing necessary environment variable: PINGME_BOT_TOKEN")
if not address:
raise RuntimeError("Missing necessary environment variable: PINGME_ADDRESS")
if not port:
raise RuntimeError("Missing necessary environment variable: PINGME_PORT")
@asynccontextmanager
async def lifespan(app: FastAPI):
global token
global bot
bot = discord.Bot()
@bot.event
async def on_ready():
print(f"Logged in as {bot.user.name}.")
bot_task = asyncio.create_task(bot.start(token))
try:
yield
finally:
await bot.close()
try:
await bot_task
except asyncio.CancelledError:
pass
server = FastAPI(lifespan=lifespan)
@server.post("/notify")
async def notify(request: Request) -> dict:
try:
global user_id
payload = await request.json()
if not payload["content"] or not payload["user_id"]:
return {"error": "Malformed JSON contents."}
if not str.isdigit(payload["user_id"]):
return {"error": "user_id must be an integer."}
if len(payload["content"]) > 2000:
return {"error": "content must be less than 2001 characters."}
user = await bot.fetch_user(int(payload["user_id"]))
await user.send(payload["content"])
return {"content": "you got it boss"}
except Exception as e:
return {"exception": e}
uvicorn.run(server, host=address, port=int(port))