Events-Recovery / main.py
Archy-Bots's picture
Update main.py
25eec6f verified
Raw History Blame Contribute Delete
14.6 kB
import os
import sys
import json
import time
import asyncio
import threading
import http.server
from datetime import datetime
from curl_cffi.requests import AsyncSession
from huggingface_hub import list_bucket_tree, download_bucket_files, batch_bucket_files
# Secrets Loaded (Add Your Own before using) Totally not AI.
HF_TOKEN = os.getenv("HF_TOKEN")
HF_BUCKET_NAME = os.getenv("HF_BUCKET_NAME")
SERVICES_URL = os.getenv("SERVICES_URL")
API_SECRET = os.getenv("API_SECRET")
DISCORD_BOT_TOKEN = os.getenv("DISCORD_BOT_TOKEN")
PROXY_API_KEY = os.getenv("PROXY_API_KEY")
tunnel_url = None
tunnel_lock = threading.Lock()
# You Sure need uptime script to keep it alive and an endpoint to ping right this is the endpoint
class HealthHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/health':
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({"status": "ok", "timestamp": time.time()}).encode())
else:
self.send_response(404)
self.end_headers()
def do_POST(self):
global tunnel_url
if self.path == '/internal/update-proxy':
if self.headers.get('x-api-secret') != API_SECRET:
self.send_response(401)
self.end_headers()
return
try:
content_length = int(self.headers.get('Content-Length', 0))
body = json.loads(self.rfile.read(content_length))
with tunnel_lock:
tunnel_url = body.get('url')
print(f'[recovery] tunnel updated: {tunnel_url}')
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({"status": "ok", "url": tunnel_url}).encode())
except Exception as e:
print(f'[recovery] update-proxy error: {e}')
self.send_response(500)
self.end_headers()
else:
self.send_response(404)
self.end_headers()
def log_message(self, format, *args):
return
def run_health_server():
server = http.server.HTTPServer(('0.0.0.0', 7860), HealthHandler)
print('[recovery] health server on port 7860')
server.serve_forever()
# SO HF Buckets does not work like normal things so they have their own way.
# list_bucket_tree / download_bucket_files / batch_bucket_files are the only api things i think i know about.
def list_guild_ids():
"""Every guild has a config.json, so that's what we look for.
list_bucket_tree returns BucketFile/BucketFolder objects, not dicts —
access via .path and .type, not subscripting. So you do understand right? who ever is looking at this code."""
try:
guilds = set()
for item in list_bucket_tree(HF_BUCKET_NAME, prefix="guilds/", recursive=True, token=HF_TOKEN):
if item.type == "file" and item.path.endswith("/config.json"):
parts = item.path.split("/")
if len(parts) >= 2:
guilds.add(parts[1])
return list(guilds)
except Exception as e:
print(f'[recovery] list_guild_ids failed: {e}')
return []
def read_member(guild_id, user_id):
remote_path = f"guilds/{guild_id}/members/{user_id}.json"
local_path = f"/tmp/member_{guild_id}_{user_id}.json"
try:
download_bucket_files(HF_BUCKET_NAME, files=[(remote_path, local_path)], token=HF_TOKEN)
with open(local_path, 'r') as f:
data = json.load(f)
os.remove(local_path)
return data
except Exception:
return None
def write_member(guild_id, member_data):
try:
content = json.dumps(member_data, indent=2).encode('utf-8')
remote_path = f"guilds/{guild_id}/members/{member_data['userId']}.json"
batch_bucket_files(HF_BUCKET_NAME, add=[(content, remote_path)], token=HF_TOKEN)
except Exception as e:
print(f'[recovery] write_member failed: {e}')
def read_config(guild_id):
remote_path = f"guilds/{guild_id}/config.json"
local_path = f"/tmp/config_{guild_id}.json"
try:
download_bucket_files(HF_BUCKET_NAME, files=[(remote_path, local_path)], token=HF_TOKEN)
with open(local_path, 'r') as f:
data = json.load(f)
os.remove(local_path)
return data
except Exception:
return None
# Now I Mostly use Fallback because i do not trust free services that much so you know just do whatever you like
async def fetch_members(guild_id, session):
path = f'/guilds/{guild_id}/members?limit=1000'
# Github Backend the one whose code is provided in the repo also make sure to add repo secrets in both hf and github.
with tunnel_lock:
t_url = tunnel_url
if t_url:
print(f'[recovery] trying tunnel for {guild_id}')
try:
r = await session.get(f"{t_url}{path}", headers={"x-api-key": PROXY_API_KEY}, timeout=10)
if r.status_code == 429:
wait = r.json().get('retry_after', 5)
await asyncio.sleep(wait)
r = await session.get(f"{t_url}{path}", headers={"x-api-key": PROXY_API_KEY}, timeout=10)
if r.status_code == 200:
members = r.json()
print(f'[recovery] got {len(members)} members via tunnel')
return members
print(f'[recovery] tunnel returned {r.status_code}')
except Exception as e:
print(f'[recovery] tunnel failed: {e}')
else:
print('[recovery] tunnel not set, skipping')
# Webshare as we know it provides 1gb of free monthly traffic why not we put it to use
proxy = os.getenv('WEBSHARE_PROXY_URL')
if not proxy:
print('[recovery] webshare not configured, skipping')
else:
try:
r = await session.get(
f"https://discord.com/api/v10{path}",
proxy=proxy,
headers={"Authorization": f"Bot {DISCORD_BOT_TOKEN}"},
timeout=10
)
if r.status_code == 429:
wait = r.json().get('retry_after', 5)
await asyncio.sleep(wait)
r = await session.get(
f"https://discord.com/api/v10{path}",
proxy=proxy,
headers={"Authorization": f"Bot {DISCORD_BOT_TOKEN}"},
timeout=10
)
if r.status_code == 200:
members = r.json()
print(f'[recovery] got {len(members)} members via webshare')
return members
except Exception as e:
print(f'[recovery] webshare failed: {e}')
# Wispbyte a free server why would i not use it
proxy = os.getenv('WISPBYTE_PROXY_URL')
if not proxy:
print('[recovery] wispbyte not configured, skipping')
else:
try:
payload = {
"url": f"https://discord.com/api/v10{path}",
"method": "GET",
"headers": {"Authorization": f"Bot {DISCORD_BOT_TOKEN}"},
"proxy_timeout": 10
}
r = await session.post(f"{proxy}/fetch", json=payload, timeout=12)
if r.status_code == 200:
members = r.json()
if isinstance(members, list):
print(f'[recovery] got {len(members)} members via wispbyte')
return members
except Exception as e:
print(f'[recovery] wispbyte failed: {e}')
# Oxylabs i think its the parent company of webshare but whatever as long as it provides 5gb of bandwidth i am happy
proxy = os.getenv('OXYLABS_PROXY_URL')
if not proxy:
print('[recovery] oxylabs not configured, skipping')
else:
try:
r = await session.get(
f"https://discord.com/api/v10{path}",
proxy=proxy,
headers={"Authorization": f"Bot {DISCORD_BOT_TOKEN}"},
timeout=10
)
if r.status_code == 429:
wait = r.json().get('retry_after', 5)
await asyncio.sleep(wait)
r = await session.get(
f"https://discord.com/api/v10{path}",
proxy=proxy,
headers={"Authorization": f"Bot {DISCORD_BOT_TOKEN}"},
timeout=10
)
if r.status_code == 200:
members = r.json()
print(f'[recovery] got {len(members)} members via oxylabs')
return members
except Exception as e:
print(f'[recovery] oxylabs failed: {e}')
print(f'[recovery] all proxies failed for guild {guild_id}, skipping this cycle')
return []
async def send_late_welcome(guild_id, member, session):
user = member['user']
avatar = user.get('avatar')
payload = {
"event": "join",
"guildId": guild_id,
"userId": str(user['id']),
"username": user['username'],
"globalName": user.get('global_name'),
"avatarUrl": f"https://cdn.discordapp.com/avatars/{user['id']}/{avatar}.png?size=256" if avatar else None,
"memberCount": 0,
"late": True
}
try:
r = await session.post(
f"{SERVICES_URL}/internal/member-event",
json=payload,
headers={"Content-Type": "application/json", "x-api-secret": API_SECRET},
timeout=15
)
if r.status_code == 200:
print(f"[recovery] late welcome sent for {user['username']} in {guild_id}")
return True
print(f"[recovery] member-event returned {r.status_code}")
return False
except Exception as e:
print(f'[recovery] send_late_welcome failed: {e}')
return False
# Now this is the Main Logic do not mess with any of the code unless you do not know about it ok any not just this
async def recovery_loop():
async with AsyncSession(impersonate="chrome110") as session:
while True:
try:
guild_ids = list_guild_ids()
if not guild_ids:
print('[recovery] no guilds found, sleeping')
for guild_id in guild_ids:
try:
config = read_config(guild_id)
if config is None:
print(f'[recovery] no config for {guild_id}, skipping')
continue
members = await fetch_members(guild_id, session)
if not members:
continue
for member in members:
user_id = None
try:
user = member['user']
user_id = str(user['id'])
if user.get('bot'):
continue
if read_member(guild_id, user_id) is not None:
continue
# Giving our last chances for the Discloud bot to handle it 5 seconds are enough i think.
await asyncio.sleep(5)
if read_member(guild_id, user_id) is not None:
continue
success = await send_late_welcome(guild_id, member, session)
write_member(guild_id, {
'userId': user_id,
'username': user['username'],
'guildId': guild_id,
'joinedAt': member.get('joined_at') or datetime.utcnow().isoformat(),
'cardSent': success
})
await asyncio.sleep(0.5)
except Exception as e:
print(f'[recovery] member error {user_id}: {e}')
continue
await asyncio.sleep(2)
except Exception as e:
print(f'[recovery] guild error {guild_id}: {e}')
continue
except Exception as e:
print(f'[recovery] loop error: {e}')
await asyncio.sleep(120)
def run_diagnostics():
print('=' * 50) # Just to make it pretty not everything is AI
print('[diagnostics] checking environment...')
required = {
'HF_TOKEN': HF_TOKEN,
'HF_BUCKET_NAME': HF_BUCKET_NAME,
'SERVICES_URL': SERVICES_URL,
'API_SECRET': API_SECRET,
'DISCORD_BOT_TOKEN': DISCORD_BOT_TOKEN,
'PROXY_API_KEY' : PROXY_API_KEY,
}
optional = {
'WEBSHARE_PROXY_URL': os.getenv('WEBSHARE_PROXY_URL'),
'OXYLABS_PROXY_URL': os.getenv('OXYLABS_PROXY_URL'),
'WISPBYTE_PROXY_URL': os.getenv('WISPBYTE_PROXY_URL'),
}
failures = 0
for key, value in required.items():
if not value:
print(f'[diagnostics] MISSING {key}')
failures += 1
else:
display = f'{value[:4]}...{value[-4:]}' if len(value) > 8 else '***'
print(f'[diagnostics] OK {key} -> {display}')
for key, value in optional.items():
if not value:
print(f'[diagnostics] NOT SET {key} (fallback will be skipped)')
else:
print(f'[diagnostics] OK {key} -> configured')
print('=' * 50)
return failures == 0
def main():
if not run_diagnostics():
print('[recovery] missing required env vars, exiting')
sys.exit(1)
threading.Thread(target=run_health_server, daemon=True).start()
print('[recovery] starting recovery loop')
asyncio.run(recovery_loop())
if __name__ == '__main__':
main()