File size: 14,575 Bytes
4910b4c 36691ce 4910b4c 36691ce 4910b4c 36691ce 663ff47 42d3eac 4910b4c fe36d05 4910b4c 36691ce 4910b4c 36691ce 7e1601f b0caf94 36691ce 4910b4c 42d3eac 7e1601f 36691ce 4910b4c 36691ce 42d3eac 36691ce 663ff47 36691ce 42d3eac 36691ce 42d3eac 36691ce 42d3eac 4910b4c 42d3eac 7e1601f 42d3eac 36691ce 6f49330 7e1601f 36691ce 6f49330 42d3eac 36691ce 42d3eac 920d15e 36691ce 42d3eac 4910b4c 6f49330 42d3eac 4910b4c 36691ce 4910b4c 36691ce 42d3eac 4910b4c 36691ce 42d3eac 36691ce 6f49330 42d3eac b65fb58 7e1601f 663ff47 36691ce 42d3eac 7e1601f 42d3eac 663ff47 7e1601f 663ff47 42d3eac 7e1601f 42d3eac 663ff47 7e1601f 663ff47 42d3eac 663ff47 42d3eac 663ff47 7e1601f 663ff47 42d3eac 663ff47 42d3eac 663ff47 42d3eac 663ff47 7e1601f 663ff47 42d3eac 663ff47 42d3eac 663ff47 42d3eac 36691ce 42d3eac 36691ce 42d3eac 36691ce 42d3eac 36691ce 42d3eac 36691ce 7e1601f 36691ce 663ff47 36691ce 42d3eac 7e1601f 42d3eac 25eec6f 36691ce 42d3eac 7e1601f 42d3eac 7e1601f 42d3eac 36691ce 42d3eac 36691ce 4910b4c 42d3eac 36691ce | 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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 | 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() |