Initial Commit
This commit is contained in:
52
modules/board/routes.py
Normal file
52
modules/board/routes.py
Normal file
@@ -0,0 +1,52 @@
|
||||
import os, time, requests
|
||||
GUILD = os.getenv("DISCORD_GUILD_ID","")
|
||||
CHANNEL = os.getenv("DISCORD_CHANNEL_ID","")
|
||||
WEBHOOK = os.getenv("DISCORD_WEBHOOK_URL","")
|
||||
|
||||
|
||||
_cache = {"ts":0, "messages":[]}
|
||||
TTL = 10
|
||||
|
||||
|
||||
def _headers():
|
||||
if not BOT: raise RuntimeError("Missing DISCORD_BOT_TOKEN")
|
||||
return {"Authorization": f"Bot {BOT}"}
|
||||
|
||||
|
||||
@board_bp.get("/")
|
||||
@require_perms("board.view")
|
||||
def index():
|
||||
return render_template("board/index.html")
|
||||
|
||||
|
||||
@board_bp.get("/api/messages")
|
||||
@require_perms("board.view")
|
||||
def api_messages():
|
||||
now = time.time()
|
||||
if now - _cache["ts"] < TTL and _cache["messages"]:
|
||||
return jsonify(_cache["messages"])
|
||||
url = f"{DISCORD_API}/channels/{CHANNEL}/messages"
|
||||
r = requests.get(url, headers=_headers(), params={"limit":40}, timeout=10)
|
||||
msgs = []
|
||||
if r.status_code == 200:
|
||||
for m in reversed(r.json()):
|
||||
a = m.get("author", {})
|
||||
msgs.append({
|
||||
"id": m.get("id"),
|
||||
"content": m.get("content",""),
|
||||
"username": a.get("global_name") or a.get("username","user"),
|
||||
"timestamp": m.get("timestamp"),
|
||||
})
|
||||
_cache.update({"ts":now, "messages":msgs})
|
||||
return jsonify(msgs)
|
||||
|
||||
|
||||
@board_bp.post("/api/post")
|
||||
@require_perms("board.post")
|
||||
def api_post():
|
||||
data = request.get_json(force=True)
|
||||
content = (data.get("content") or "").strip()
|
||||
if not content: return jsonify({"ok":False,"error":"Empty"}),400
|
||||
if not WEBHOOK: return jsonify({"ok":False,"error":"No webhook"}),500
|
||||
r = requests.post(WEBHOOK, json={"content": content[:1800]}, timeout=10)
|
||||
return (jsonify({"ok":True}), 200) if r.status_code in (200,204) else (jsonify({"ok":False}), 502)
|
||||
Reference in New Issue
Block a user