Files
KittyRec2018-Leak/core/discord.py
2026-07-24 15:38:31 +00:00

211 lines
6.4 KiB
Python

import json
import os
import threading
import time
import urllib.request
from core.config import discord as _discord_cfg, base_url as _BASE_URL
_WEBHOOK_PUBLIC = _discord_cfg.get("webhook_public", "")
_WEBHOOK_ADMIN = _discord_cfg.get("webhook_admin", "")
_WEBHOOK_ANTICHEAT = _discord_cfg.get("webhook_anticheat", "")
_throttle: dict[str, float] = {}
_throttle_lock = threading.Lock()
_PUBLIC_GLOBAL_COOLDOWN = 8
_CONCURRENT_MILESTONES = {5, 10, 20, 50, 100}
_concurrent_peak = 0
_concurrent_peak_lock = threading.Lock()
_FIRST_LOGIN_FILE = os.path.join(
os.path.dirname(os.path.dirname(__file__)), "tracking", "discord_first_login.json"
)
_first_login_notified: set[int] = set()
_first_login_lock = threading.Lock()
_signup_times: list[float] = []
_signup_lock = threading.Lock()
_SIGNUP_BURST_WINDOW = 60
_SIGNUP_BURST_THRESHOLD = 5
def _load_state() -> None:
global _first_login_notified, _concurrent_peak
try:
with open(_FIRST_LOGIN_FILE) as f:
data = json.load(f)
with _first_login_lock:
_first_login_notified = set(data.get("notified", []))
with _concurrent_peak_lock:
_concurrent_peak = int(data.get("peak", 0))
except Exception:
pass
def _save_state() -> None:
try:
os.makedirs(os.path.dirname(_FIRST_LOGIN_FILE), exist_ok=True)
with _first_login_lock:
notified = list(_first_login_notified)
with _concurrent_peak_lock:
peak = _concurrent_peak
with open(_FIRST_LOGIN_FILE, "w") as f:
json.dump({"notified": notified, "peak": peak}, f)
except Exception as e:
print(f"[Discord] Failed to save state: {e}")
def mark_first_login(pid: int) -> bool:
with _first_login_lock:
if pid in _first_login_notified:
return False
_first_login_notified.add(pid)
threading.Thread(target=_save_state, daemon=True).start()
return True
def record_signup() -> bool:
now = time.monotonic()
with _signup_lock:
_signup_times.append(now)
cutoff = now - _SIGNUP_BURST_WINDOW
while _signup_times and _signup_times[0] < cutoff:
_signup_times.pop(0)
count = len(_signup_times)
return count >= _SIGNUP_BURST_THRESHOLD and count % _SIGNUP_BURST_THRESHOLD == 0
def _can_fire(key: str, cooldown: float) -> bool:
now = time.monotonic()
with _throttle_lock:
if now - _throttle.get(key, 0) < cooldown:
return False
_throttle[key] = now
return True
def _send(url: str, payload: dict) -> None:
try:
data = json.dumps(payload).encode()
req = urllib.request.Request(
url, data=data,
headers={"Content-Type": "application/json", "User-Agent": "KittyRecBot/1.0"},
method="POST",
)
urllib.request.urlopen(req, timeout=5)
except Exception as e:
print(f"[Discord] Webhook failed: {e}")
def _fire(url: str, payload: dict) -> None:
threading.Thread(target=_send, args=(url, payload), daemon=True).start()
def send_public(
title: str,
color: int,
fields: list,
description: str = None,
thumbnail_url: str = None,
throttle_key: str = "global",
throttle_secs: float = None,
) -> None:
if throttle_secs is None:
throttle_secs = _PUBLIC_GLOBAL_COOLDOWN
if not _can_fire(f"pub_{throttle_key}", throttle_secs):
return
embed = {"title": title, "color": color, "fields": fields}
if description:
embed["description"] = description
if thumbnail_url:
embed["thumbnail"] = {"url": thumbnail_url}
_fire(_WEBHOOK_PUBLIC, {"embeds": [embed]})
def send_admin(title: str, color: int, fields: list, description: str = None) -> None:
embed = {"title": title, "color": color, "fields": fields}
if description:
embed["description"] = description
_fire(_WEBHOOK_ADMIN, {"embeds": [embed]})
def send_security(title: str, color: int, fields: list, description: str = None, throttle_key: str = None, throttle_secs: float = 30) -> None:
if throttle_key and not _can_fire(f"sec_{throttle_key}", throttle_secs):
return
url = _WEBHOOK_ANTICHEAT or _WEBHOOK_ADMIN
if not url:
return
embed = {"title": f":warning: {title}", "color": color, "fields": fields}
if description:
embed["description"] = description
_fire(url, {"embeds": [embed]})
def avatar_url(profile_image_name) -> str | None:
if not profile_image_name:
return None
return f"{_BASE_URL}/alt/{profile_image_name}"
def check_concurrent_milestone(count: int) -> None:
global _concurrent_peak
with _concurrent_peak_lock:
if count <= _concurrent_peak:
return
crossed = sorted(m for m in _CONCURRENT_MILESTONES if _concurrent_peak < m <= count)
_concurrent_peak = count
if not crossed:
threading.Thread(target=_save_state, daemon=True).start()
return
threading.Thread(target=_save_state, daemon=True).start()
for milestone in crossed:
send_public(
title="Server Milestone!",
color=0x2ECC71,
fields=[
{"name": "Players Online", "value": str(milestone), "inline": True},
{"name": "All-Time Peak", "value": str(count), "inline": True},
],
description=f"KittyRec just hit **{milestone} players online** at the same time!",
throttle_key=f"milestone_{milestone}",
throttle_secs=0,
)
def notify_player_login(username: str, pid: int) -> None:
if not _WEBHOOK_PUBLIC:
return
send_public(
title="Player Online",
color=0x2ECC71,
fields=[
{"name": "Username", "value": username, "inline": True},
{"name": "Player ID", "value": str(pid), "inline": True},
],
description=f"**{username}** just logged in to KittyRec!",
throttle_key=f"login_{pid}",
throttle_secs=300,
)
def notify_player_logout(username: str, pid: int) -> None:
if not _WEBHOOK_PUBLIC:
return
send_public(
title="Player Offline",
color=0x95A5A6,
fields=[
{"name": "Username", "value": username, "inline": True},
{"name": "Player ID", "value": str(pid), "inline": True},
],
description=f"**{username}** logged out of KittyRec.",
throttle_key=f"logout_{pid}",
throttle_secs=300,
)
_load_state()