Update configuration and README for improved setup and security; disable default API and emoji sync, and enhance Discord permission checks in API routes.
This commit is contained in:
@@ -1,53 +1,43 @@
|
||||
TOKEN = TOKEN_HERE
|
||||
TOKEN=TOKEN_HERE
|
||||
brand_name='ZyroX'
|
||||
NEXT_PUBLIC_BRAND_NAME='ZyroX'
|
||||
|
||||
# ── Owner / Staff IDs (comma-separated Discord user IDs) ──────────────────────
|
||||
# Edit this list — no code changes needed anywhere else
|
||||
OWNER_IDS=870179991462236170,767979794411028491,1432771000629596225,1382744437049790495,1263404140965396555
|
||||
# ── Owner / Staff IDs (REQUIRED — comma-separated Discord user IDs) ───────────
|
||||
# Set your own Discord user ID(s). No foreign IDs are used as fallback.
|
||||
OWNER_IDS=YOUR_DISCORD_USER_ID_HERE
|
||||
|
||||
# ── Optional: debug REPL for owners (disabled by default) ─────────────────────
|
||||
JISHAKU_ENABLED=false
|
||||
|
||||
# ── Optional: Discord log / stats channels (leave empty to disable) ───────────
|
||||
# LOG_CHANNEL_ID=
|
||||
# SERVER_COUNT_CHANNEL_ID=
|
||||
# USER_COUNT_CHANNEL_ID=
|
||||
|
||||
# ── Lavalink ──────────────────────────────────────────────────────────────────
|
||||
LAVALINK_HOST="lavalink.jirayu.net"
|
||||
LAVALINK_PASSWORD="youshallnotpass"
|
||||
|
||||
# Set to true if the node uses HTTPS/WSS (secure), false for HTTP/WS
|
||||
LAVALINK_SECURE="false"
|
||||
|
||||
# Only needed when LAVALINK_SECURE is false (e.g. 2333)
|
||||
LAVALINK_PORT="13592"
|
||||
|
||||
# ── Emoji Sync ────────────────────────────────────────────────────────────────
|
||||
# Set to true to enable automatic application emoji sync on startup
|
||||
EMOJI_SYNC="false"
|
||||
|
||||
# ── API / Dashboard Backend ───────────────────────────────────────────────────
|
||||
# Set to true to enable the dashboard API server
|
||||
API_ENABLED="false"
|
||||
# Port the API server listens on
|
||||
API_HOST="127.0.0.1"
|
||||
API_PORT="8000"
|
||||
DASHBOARD_API_KEY="ZYROX_SECURE_API_KEY_12345_CHANGE_THIS_ASAP_BY_CODEX_DEVS"
|
||||
# Extra CORS-allowed origins, comma-separated (optional)
|
||||
DASHBOARD_API_KEY="generate_a_long_random_secret_here"
|
||||
# Discord user IDs allowed to use /api/v1/admin (comma-separated; falls back to OWNER_IDS)
|
||||
DASHBOARD_ADMIN_IDS=YOUR_DISCORD_USER_ID_HERE
|
||||
CORS_ORIGINS=""
|
||||
|
||||
# CODEX DEVS
|
||||
# ── Webhooks (leave empty or unset to disable command logging) ────────────────
|
||||
# CMD_WEBHOOK_URL must be a full Discord webhook URL to enable logging.
|
||||
# CMD_WEBHOOK_URL=
|
||||
|
||||
# ── Webhooks ──────────────────────────────────────────────────────────────────
|
||||
WEBHOOK_URL="https://discord.com/api/webhooks/"
|
||||
CMD_WEBHOOK_URL="https://discord.com/api/webhooks/"
|
||||
|
||||
|
||||
# ── Cloudflare Tunnel For API Server ─────────────────────────────────────────────────────────
|
||||
#
|
||||
# How to get CF_TUNNEL_TOKEN (browser only, no CLI):
|
||||
# 1. Go to https://one.dash.cloudflare.com
|
||||
# 2. Networks → Tunnels → Create a tunnel → Choose "Cloudflared"
|
||||
# 3. Give it a name (e.g. zyrox-api) and save
|
||||
# 4. On the "Install connector" step, copy the token from the shown command:
|
||||
# cloudflared tunnel run --token <COPY_THIS_TOKEN>
|
||||
# 5. Go to "Published Application Routes" tab → Add a Published Application Routes:
|
||||
# Subdomain: zyrox-api Domain: yourdomain.com Service: http://localhost:8000
|
||||
# 6. Paste the token below — that's it. Permanent URL, unlimited traffic.
|
||||
#
|
||||
TUNNEL_ENABLED="true"
|
||||
CF_TUNNEL_TOKEN="xxx_xxxx"
|
||||
CF_TUNNEL_URL="https://zyrox-api.yourdomain.com"
|
||||
# ── Cloudflare Tunnel (disabled by default) ───────────────────────────────────
|
||||
TUNNEL_ENABLED="false"
|
||||
TUNNEL_ALLOW_BINARY_DOWNLOAD="false"
|
||||
# CF_TUNNEL_TOKEN=
|
||||
# CF_TUNNEL_URL=
|
||||
|
||||
115
bot/CodeX.py
115
bot/CodeX.py
@@ -35,51 +35,50 @@ from utils.config import *
|
||||
from utils.emoji import SUCCESS, ERROR, TICK, CROSS, REACTION_TEST_EMOJIS
|
||||
from utils.sync_emojis import run_sync
|
||||
|
||||
import jishaku
|
||||
import cogs
|
||||
|
||||
|
||||
os.environ["JISHAKU_NO_DM_TRACEBACK"] = "False"
|
||||
os.environ["JISHAKU_HIDE"] = "True"
|
||||
os.environ["JISHAKU_NO_UNDERSCORE"] = "True"
|
||||
os.environ["JISHAKU_FORCE_PAGINATOR"] = "True"
|
||||
|
||||
from dotenv import load_dotenv
|
||||
load_dotenv()
|
||||
TOKEN = os.getenv("TOKEN")
|
||||
|
||||
# --- Configuration ---
|
||||
# IMPORTANT: Replace these with your actual channel IDs.
|
||||
SERVER_COUNT_CHANNEL_ID = 1419729255977189467 # Replace with your server count channel ID
|
||||
USER_COUNT_CHANNEL_ID = 1419729283861184632 # Replace with your user count channel ID
|
||||
LOG_CHANNEL_ID = 1396794297386532978 # Replace with the channel ID for join/leave logs
|
||||
if JISHAKU_ENABLED:
|
||||
os.environ["JISHAKU_NO_DM_TRACEBACK"] = "False"
|
||||
os.environ["JISHAKU_HIDE"] = "True"
|
||||
os.environ["JISHAKU_NO_UNDERSCORE"] = "True"
|
||||
os.environ["JISHAKU_FORCE_PAGINATOR"] = "True"
|
||||
|
||||
if not OWNER_IDS:
|
||||
print("\033[33m⚠ OWNER_IDS is not set in .env — no bot owners configured.\033[0m")
|
||||
print("\033[33m Set OWNER_IDS=YOUR_DISCORD_USER_ID before running in production.\033[0m")
|
||||
|
||||
client = zyrox()
|
||||
tree = client.tree
|
||||
|
||||
# --- Background Task for Stats ---
|
||||
async def update_stats():
|
||||
"""A background task to update server and user stats in channel names."""
|
||||
"""Update server/user counts in channel names when channel IDs are configured."""
|
||||
if not SERVER_COUNT_CHANNEL_ID and not USER_COUNT_CHANNEL_ID:
|
||||
return
|
||||
await client.wait_until_ready()
|
||||
while not client.is_closed():
|
||||
try:
|
||||
servers = len(client.guilds)
|
||||
users = sum(guild.member_count for guild in client.guilds if guild.member_count is not None)
|
||||
|
||||
server_channel = client.get_channel(SERVER_COUNT_CHANNEL_ID)
|
||||
user_channel = client.get_channel(USER_COUNT_CHANNEL_ID)
|
||||
|
||||
if server_channel:
|
||||
await server_channel.edit(name=f"Servers: {servers}")
|
||||
|
||||
if user_channel:
|
||||
await user_channel.edit(name=f"Users: {users}")
|
||||
|
||||
|
||||
if SERVER_COUNT_CHANNEL_ID:
|
||||
server_channel = client.get_channel(SERVER_COUNT_CHANNEL_ID)
|
||||
if server_channel:
|
||||
await server_channel.edit(name=f"Servers: {servers}")
|
||||
|
||||
if USER_COUNT_CHANNEL_ID:
|
||||
user_channel = client.get_channel(USER_COUNT_CHANNEL_ID)
|
||||
if user_channel:
|
||||
await user_channel.edit(name=f"Users: {users}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error updating stats: {e}")
|
||||
|
||||
await asyncio.sleep(600) # Update every 10 minutes
|
||||
|
||||
await asyncio.sleep(600)
|
||||
|
||||
# --- Event Handlers ---
|
||||
@client.event
|
||||
@@ -113,49 +112,50 @@ async def on_ready():
|
||||
print(f"Error syncing command tree: {e}")
|
||||
|
||||
client.loop.create_task(sync_commands())
|
||||
client.loop.create_task(update_stats())
|
||||
if SERVER_COUNT_CHANNEL_ID or USER_COUNT_CHANNEL_ID:
|
||||
client.loop.create_task(update_stats())
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_guild_join(guild: discord.Guild):
|
||||
# Log when the bot joins a server
|
||||
if not LOG_CHANNEL_ID:
|
||||
return
|
||||
log_channel = client.get_channel(LOG_CHANNEL_ID)
|
||||
if log_channel:
|
||||
await log_channel.send(f"{BRAND_NAME} has been added to the server: **{guild.name}** (ID: `{guild.id}`)")
|
||||
|
||||
@client.event
|
||||
async def on_command_completion(context: commands.Context) -> None:
|
||||
if context.author.id in OWNER_IDS:
|
||||
if not CMD_WEBHOOK_URL or context.command is None or context.author.id in OWNER_IDS:
|
||||
return
|
||||
|
||||
full_command_name = context.command.qualified_name
|
||||
split = full_command_name.split("\n")
|
||||
executed_command = str(split[0])
|
||||
webhook_url = CMD_WEBHOOK_URL
|
||||
async with aiohttp.ClientSession() as session:
|
||||
webhook = discord.Webhook.from_url(webhook_url, session=session)
|
||||
|
||||
embed_color = 0xFF0000
|
||||
embed = discord.Embed(color=embed_color)
|
||||
avatar_url = context.author.display_avatar.url
|
||||
embed_color = 0xFF0000
|
||||
embed = discord.Embed(color=embed_color)
|
||||
avatar_url = context.author.display_avatar.url
|
||||
|
||||
embed.set_author(name=f"Cmd Executed: {executed_command}", icon_url=avatar_url)
|
||||
embed.set_thumbnail(url=avatar_url)
|
||||
embed.set_author(name=f"Cmd Executed: {executed_command}", icon_url=avatar_url)
|
||||
embed.set_thumbnail(url=avatar_url)
|
||||
|
||||
if context.guild is not None:
|
||||
embed.add_field(name="User", value=f"{context.author.mention} (`{context.author.id}`)", inline=False)
|
||||
embed.add_field(name="Server", value=f"{context.guild.name} (`{context.guild.id}`)", inline=False)
|
||||
embed.add_field(name="Channel", value=f"{context.channel.mention} (`{context.channel.id}`)", inline=False)
|
||||
else:
|
||||
embed.add_field(name="User (DM)", value=f"{context.author.mention} (`{context.author.id}`)", inline=False)
|
||||
|
||||
embed.timestamp = discord.utils.utcnow()
|
||||
embed.set_footer(text=f"{BRAND_NAME} Development™ ❤️", icon_url=client.user.display_avatar.url)
|
||||
|
||||
try:
|
||||
if context.guild is not None:
|
||||
embed.add_field(name="User", value=f"{context.author.mention} (`{context.author.id}`)", inline=False)
|
||||
embed.add_field(name="Server", value=f"{context.guild.name} (`{context.guild.id}`)", inline=False)
|
||||
embed.add_field(name="Channel", value=f"{context.channel.mention} (`{context.channel.id}`)", inline=False)
|
||||
else:
|
||||
embed.add_field(name="User (DM)", value=f"{context.author.mention} (`{context.author.id}`)", inline=False)
|
||||
|
||||
embed.timestamp = discord.utils.utcnow()
|
||||
embed.set_footer(text=f"{BRAND_NAME} Development™ ❤️", icon_url=client.user.display_avatar.url)
|
||||
|
||||
try:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
webhook = discord.Webhook.from_url(CMD_WEBHOOK_URL, session=session)
|
||||
await webhook.send(embed=embed)
|
||||
except Exception as e:
|
||||
print(f'Command log webhook failed: {e}')
|
||||
except Exception as e:
|
||||
print(f'Command log webhook failed: {e}')
|
||||
|
||||
|
||||
# --- Utility Commands ---
|
||||
@@ -318,23 +318,22 @@ fastapi_app = create_app()
|
||||
fastapi_app.state.bot = client
|
||||
set_bot(client)
|
||||
|
||||
API_ENABLED = os.getenv("API_ENABLED", "true").strip().lower() == "true"
|
||||
API_PORT = int(os.getenv("API_PORT", "8000"))
|
||||
|
||||
def run_api():
|
||||
uvicorn.run(fastapi_app, host='0.0.0.0', port=API_PORT, log_level="warning")
|
||||
uvicorn.run(fastapi_app, host=API_HOST, port=API_PORT, log_level="warning")
|
||||
|
||||
def keep_alive():
|
||||
if not API_ENABLED:
|
||||
print(f"\033[33m◈ API Server: Disabled via API_ENABLED=false\033[0m")
|
||||
return
|
||||
print(f"\033[32m◈ API Server: Starting on port {API_PORT}\033[0m")
|
||||
print(f"\033[32m◈ API Server: Starting on {API_HOST}:{API_PORT}\033[0m")
|
||||
if API_HOST in ("0.0.0.0", "::"):
|
||||
print("\033[33m ⚠ API bound to all interfaces — use API_HOST=127.0.0.1 unless behind a reverse proxy.\033[0m")
|
||||
server = Thread(target=run_api, daemon=True)
|
||||
server.start()
|
||||
|
||||
keep_alive()
|
||||
|
||||
# --- Cloudflare Tunnel (HTTPS for API) ---
|
||||
# --- Cloudflare Tunnel (HTTPS for API) — only when explicitly enabled ---
|
||||
from utils.tunnel import start_tunnel
|
||||
start_tunnel()
|
||||
|
||||
@@ -342,7 +341,11 @@ start_tunnel()
|
||||
async def main():
|
||||
async with client:
|
||||
os.system("clear")
|
||||
await client.load_extension("jishaku")
|
||||
if JISHAKU_ENABLED:
|
||||
await client.load_extension("jishaku")
|
||||
print("\033[33m◈ Jishaku: enabled (owner-only debug REPL)\033[0m")
|
||||
else:
|
||||
print("\033[32m◈ Jishaku: disabled (set JISHAKU_ENABLED=true to enable)\033[0m")
|
||||
|
||||
max_retries = 5
|
||||
for attempt in range(max_retries):
|
||||
|
||||
@@ -180,8 +180,8 @@ Create a `.env` file (copy from `.env.example`):
|
||||
TOKEN = your_discord_bot_token
|
||||
brand_name = 'ZyroX'
|
||||
|
||||
# ── Owner IDs (comma-separated — no code changes needed) ──────────
|
||||
OWNER_IDS = 870179991462236170,767979794411028491
|
||||
# ── Owner IDs (REQUIRED — your Discord user ID) ───────────────────
|
||||
OWNER_IDS = YOUR_DISCORD_USER_ID_HERE
|
||||
|
||||
# ── Lavalink ──────────────────────────────────────────────────────
|
||||
LAVALINK_HOST = "your-lavalink-host"
|
||||
@@ -190,21 +190,23 @@ LAVALINK_SECURE = "true"
|
||||
LAVALINK_PORT = ""
|
||||
|
||||
# ── Emoji Sync ────────────────────────────────────────────────────
|
||||
EMOJI_SYNC = "true"
|
||||
EMOJI_SYNC = "false"
|
||||
|
||||
# ── API / Dashboard Backend ───────────────────────────────────────
|
||||
API_ENABLED = "true"
|
||||
API_ENABLED = "false"
|
||||
API_HOST = "127.0.0.1"
|
||||
API_PORT = "8000"
|
||||
DASHBOARD_API_KEY = "change_this_to_a_strong_secret"
|
||||
DASHBOARD_ADMIN_IDS = YOUR_DISCORD_USER_ID_HERE
|
||||
CORS_ORIGINS = ""
|
||||
|
||||
# ── Cloudflare Tunnel ─────────────────────────────────────────────
|
||||
TUNNEL_ENABLED = "true"
|
||||
# ── Cloudflare Tunnel (optional) ──────────────────────────────────
|
||||
TUNNEL_ENABLED = "false"
|
||||
CF_TUNNEL_TOKEN = "your_tunnel_token"
|
||||
CF_TUNNEL_URL = "https://api.yourdomain.com"
|
||||
|
||||
# ── Webhooks ──────────────────────────────────────────────────────
|
||||
WEBHOOK_URL = "https://discord.com/api/webhooks/..."
|
||||
# ── Webhooks (optional) ─────────────────────────────────────────────
|
||||
# CMD_WEBHOOK_URL = "https://discord.com/api/webhooks/ID/TOKEN"
|
||||
```
|
||||
|
||||
### 3 — Run
|
||||
@@ -220,20 +222,26 @@ python CodeX.py
|
||||
| Variable | Default | Description |
|
||||
|---|---|---|
|
||||
| `TOKEN` | — | Discord bot token |
|
||||
| `OWNER_IDS` | — | Comma-separated owner Discord user IDs |
|
||||
| `OWNER_IDS` | _(required)_ | Comma-separated owner Discord user IDs — **your own ID only** |
|
||||
| `LAVALINK_HOST` | — | Lavalink server hostname (no protocol) |
|
||||
| `LAVALINK_PASSWORD` | — | Lavalink password |
|
||||
| `LAVALINK_SECURE` | `true` | `true` = HTTPS, `false` = HTTP |
|
||||
| `LAVALINK_PORT` | _(empty)_ | Port — only when `LAVALINK_SECURE=false` |
|
||||
| `EMOJI_SYNC` | `true` | Auto-sync application emojis on startup |
|
||||
| `API_ENABLED` | `true` | Start the FastAPI dashboard backend |
|
||||
| `EMOJI_SYNC` | `false` | Auto-sync application emojis on startup |
|
||||
| `JISHAKU_ENABLED` | `false` | Enable owner debug REPL (disable in production) |
|
||||
| `API_ENABLED` | `false` | Start the FastAPI dashboard backend |
|
||||
| `API_HOST` | `127.0.0.1` | Bind address for the API server |
|
||||
| `API_PORT` | `8000` | Port the backend listens on |
|
||||
| `DASHBOARD_API_KEY` | — | Shared secret between bot API and dashboard |
|
||||
| `DASHBOARD_API_KEY` | — | Shared secret with dashboard (server-side only) |
|
||||
| `DASHBOARD_ADMIN_IDS` | — | Discord user IDs for admin API routes |
|
||||
| `CORS_ORIGINS` | _(empty)_ | Extra CORS-allowed origins, comma-separated |
|
||||
| `WEBHOOK_URL` | — | Discord webhook for command logs |
|
||||
| `TUNNEL_ENABLED` | `true` | Expose API over HTTPS via Cloudflare Tunnel |
|
||||
| `CMD_WEBHOOK_URL` | _(empty)_ | Optional webhook for command logging |
|
||||
| `TUNNEL_ENABLED` | `false` | Expose API over HTTPS via Cloudflare Tunnel |
|
||||
| `CF_TUNNEL_TOKEN` | — | Token from Cloudflare Zero Trust dashboard |
|
||||
| `CF_TUNNEL_URL` | — | Your permanent public URL |
|
||||
| `LOG_CHANNEL_ID` | _(empty)_ | Optional channel for join/leave logs |
|
||||
|
||||
> **API security:** All `/api/v1/guilds/*` routes verify Discord Manage Server permission via `X-Discord-Access-Token` header.
|
||||
|
||||
---
|
||||
|
||||
@@ -271,7 +279,7 @@ On every startup the console prints:
|
||||
```
|
||||
◈ Tunnel: cloudflared binary ready — starting tunnel on port 8000…
|
||||
◈ Tunnel: API is live at https://api.yourdomain.com
|
||||
↳ NEXT_PUBLIC_API_URL = https://api.yourdomain.com/api/v1
|
||||
↳ DASHBOARD_API_URL = https://api.yourdomain.com/api/v1
|
||||
```
|
||||
|
||||
Set `TUNNEL_ENABLED=false` to disable.
|
||||
@@ -313,7 +321,7 @@ python CodeX.py
|
||||
|---|---|
|
||||
| Bot fails to start | Check `TOKEN` and gateway intents in Developer Portal |
|
||||
| Music not working | Verify `LAVALINK_HOST`, `LAVALINK_SECURE`, `LAVALINK_PORT` |
|
||||
| Dashboard can't reach API | Check `API_ENABLED=true` and `NEXT_PUBLIC_API_URL` in dashboard |
|
||||
| Dashboard can't reach API | Check `API_ENABLED=true`, `DASHBOARD_API_URL` in dashboard, and Discord login |
|
||||
| CORS errors | Add your Vercel URL to `CORS_ORIGINS` in `.env` |
|
||||
| Emojis showing as plain text | Run once with `EMOJI_SYNC=true` to upload and patch IDs |
|
||||
| Tunnel not starting | Check `CF_TUNNEL_TOKEN` is valid and `pycloudflared` is installed |
|
||||
|
||||
130
bot/api/discord_auth.py
Normal file
130
bot/api/discord_auth.py
Normal file
@@ -0,0 +1,130 @@
|
||||
# ╔══════════════════════════════════════════════════════════════════╗
|
||||
# ║ Discord OAuth permission checks for dashboard API requests ║
|
||||
# ╚══════════════════════════════════════════════════════════════════╝
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
import aiohttp
|
||||
from fastapi import HTTPException, Request
|
||||
|
||||
from utils.config import OWNER_IDS_STR
|
||||
|
||||
MANAGE_GUILD = 0x20
|
||||
ADMINISTRATOR = 0x8
|
||||
|
||||
GUILD_PATH_RE = re.compile(r"^/api/v1/guilds/(\d+)(?:/|$)")
|
||||
|
||||
|
||||
def _parse_admin_ids() -> list[str]:
|
||||
import os
|
||||
|
||||
raw = os.getenv("DASHBOARD_ADMIN_IDS", "").strip()
|
||||
if raw:
|
||||
return [p.strip() for p in raw.split(",") if p.strip().isdigit()]
|
||||
return list(OWNER_IDS_STR)
|
||||
|
||||
|
||||
def can_manage_guild(guild: dict[str, Any]) -> bool:
|
||||
if guild.get("owner"):
|
||||
return True
|
||||
try:
|
||||
perms = int(guild.get("permissions", "0"))
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
return bool(perms & ADMINISTRATOR) or bool(perms & MANAGE_GUILD)
|
||||
|
||||
|
||||
async def fetch_user_guilds(access_token: str) -> list[dict[str, Any]]:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(
|
||||
"https://discord.com/api/users/@me/guilds",
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
) as resp:
|
||||
if resp.status != 200:
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Invalid or expired Discord access token.",
|
||||
)
|
||||
data = await resp.json()
|
||||
return data if isinstance(data, list) else []
|
||||
|
||||
|
||||
async def verify_discord_token(access_token: str) -> dict[str, Any]:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(
|
||||
"https://discord.com/api/users/@me",
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
) as resp:
|
||||
if resp.status != 200:
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Invalid or expired Discord access token.",
|
||||
)
|
||||
return await resp.json()
|
||||
|
||||
|
||||
async def user_can_manage_guild(access_token: str, guild_id: int) -> bool:
|
||||
guilds = await fetch_user_guilds(access_token)
|
||||
for guild in guilds:
|
||||
if str(guild.get("id")) == str(guild_id):
|
||||
return can_manage_guild(guild)
|
||||
return False
|
||||
|
||||
|
||||
async def get_manageable_guild_ids(access_token: str) -> set[str]:
|
||||
guilds = await fetch_user_guilds(access_token)
|
||||
return {str(g["id"]) for g in guilds if can_manage_guild(g)}
|
||||
|
||||
|
||||
def get_discord_headers(request: Request) -> tuple[str | None, str | None]:
|
||||
token = request.headers.get("X-Discord-Access-Token")
|
||||
user_id = request.headers.get("X-Discord-User-Id")
|
||||
return token, user_id
|
||||
|
||||
|
||||
async def require_discord_session(request: Request) -> tuple[str, str]:
|
||||
token, user_id = get_discord_headers(request)
|
||||
if not token:
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="X-Discord-Access-Token header is required.",
|
||||
)
|
||||
|
||||
user = await verify_discord_token(token)
|
||||
resolved_id = str(user.get("id", ""))
|
||||
if not resolved_id:
|
||||
raise HTTPException(status_code=403, detail="Could not resolve Discord user.")
|
||||
|
||||
if user_id and user_id != resolved_id:
|
||||
raise HTTPException(status_code=403, detail="Discord user ID mismatch.")
|
||||
|
||||
return token, resolved_id
|
||||
|
||||
|
||||
async def require_guild_access(request: Request, guild_id: int) -> None:
|
||||
token, _ = await require_discord_session(request)
|
||||
if not await user_can_manage_guild(token, guild_id):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="You do not have permission to manage this guild.",
|
||||
)
|
||||
|
||||
|
||||
async def require_dashboard_admin(request: Request) -> None:
|
||||
token, user_id = await require_discord_session(request)
|
||||
admin_ids = _parse_admin_ids()
|
||||
if user_id not in admin_ids:
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Dashboard admin access required.",
|
||||
)
|
||||
|
||||
|
||||
def extract_guild_id_from_path(path: str) -> int | None:
|
||||
match = GUILD_PATH_RE.match(path)
|
||||
if not match:
|
||||
return None
|
||||
return int(match.group(1))
|
||||
@@ -14,6 +14,7 @@
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from api.dependencies import get_bot, limiter
|
||||
from api.discord_auth import require_discord_session, get_manageable_guild_ids
|
||||
from api.db_manager import db_manager
|
||||
from api.schemas import (
|
||||
GuildSummary, GuildDetails, PrefixConfig, AutomodConfig,
|
||||
@@ -41,13 +42,18 @@ if TYPE_CHECKING:
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/", response_model=List[GuildSummary], summary="List all guilds", description="Returns a summary of all guilds the bot is currently in.")
|
||||
async def list_guilds(bot: "zyrox" = Depends(get_bot)):
|
||||
@router.get("/", response_model=List[GuildSummary], summary="List all guilds", description="Returns guilds the authenticated user can manage that the bot is in.")
|
||||
async def list_guilds(request: Request, bot: "zyrox" = Depends(get_bot)):
|
||||
"""
|
||||
Lists detailed information about all guilds the bot is currently in.
|
||||
Lists guilds the bot is in, filtered to those the caller can manage on Discord.
|
||||
"""
|
||||
token, _ = await require_discord_session(request)
|
||||
manageable_ids = await get_manageable_guild_ids(token)
|
||||
|
||||
guilds_list = []
|
||||
for guild in bot.guilds:
|
||||
if str(guild.id) not in manageable_ids:
|
||||
continue
|
||||
guilds_list.append(GuildSummary(
|
||||
id=str(guild.id),
|
||||
name=guild.name,
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
# ║ ║
|
||||
# ╚══════════════════════════════════════════════════════════════════╝
|
||||
|
||||
from fastapi import FastAPI, Depends, Request
|
||||
from fastapi import FastAPI, Depends, Request, HTTPException
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from contextlib import asynccontextmanager
|
||||
import os
|
||||
@@ -28,6 +28,13 @@ from utils.config import *
|
||||
from api.routes import bot, guilds, admin
|
||||
from api.dependencies import verify_api_key, limiter
|
||||
from api.db_manager import db_manager
|
||||
from api.discord_auth import (
|
||||
require_dashboard_admin,
|
||||
require_discord_session,
|
||||
require_guild_access,
|
||||
extract_guild_id_from_path,
|
||||
)
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
# Configure logging
|
||||
logger = logging.getLogger("api_request_logs")
|
||||
@@ -57,6 +64,29 @@ def create_app() -> FastAPI:
|
||||
lifespan=lifespan
|
||||
)
|
||||
|
||||
# Discord permission checks for dashboard API routes
|
||||
@app.middleware("http")
|
||||
async def discord_permission_middleware(request: Request, call_next):
|
||||
if request.method == "OPTIONS":
|
||||
return await call_next(request)
|
||||
|
||||
path = request.url.path
|
||||
try:
|
||||
if path.startswith("/api/v1/admin"):
|
||||
await require_dashboard_admin(request)
|
||||
elif path.startswith("/api/v1/bot"):
|
||||
await require_discord_session(request)
|
||||
elif path.startswith("/api/v1/guilds"):
|
||||
guild_id = extract_guild_id_from_path(path)
|
||||
if guild_id is not None:
|
||||
await require_guild_access(request, guild_id)
|
||||
else:
|
||||
await require_discord_session(request)
|
||||
except HTTPException as exc:
|
||||
return JSONResponse(status_code=exc.status_code, content={"detail": exc.detail})
|
||||
|
||||
return await call_next(request)
|
||||
|
||||
# Structured Logging Middleware
|
||||
@app.middleware("http")
|
||||
async def log_requests(request: Request, call_next):
|
||||
|
||||
@@ -23,6 +23,7 @@ from discord.ui import LayoutView, TextDisplay, Separator, Container
|
||||
from utils.Tools import *
|
||||
from utils.cv2 import CV2, build_container
|
||||
from utils.config import OWNER_IDS
|
||||
from utils.safe_parse import parse_role_id_list, dump_role_id_list
|
||||
|
||||
|
||||
|
||||
@@ -232,7 +233,7 @@ class AutoRole(commands.Cog):
|
||||
data = await cursor.fetchone()
|
||||
|
||||
if data:
|
||||
humans = eval(data[0])
|
||||
humans = parse_role_id_list(data[0])
|
||||
if role.id in humans:
|
||||
view = CV2(f"{ICONS_WARNING} Access Denied", f"{role.mention} is already in human autoroles.")
|
||||
elif len(humans) >= 10:
|
||||
@@ -240,13 +241,13 @@ class AutoRole(commands.Cog):
|
||||
else:
|
||||
humans.append(role.id)
|
||||
async with aiosqlite.connect(DATABASE_PATH) as db:
|
||||
await db.execute("UPDATE autorole SET humans = ? WHERE guild_id = ?", (str(humans), ctx.guild.id))
|
||||
await db.execute("UPDATE autorole SET humans = ? WHERE guild_id = ?", (dump_role_id_list(humans), ctx.guild.id))
|
||||
await db.commit()
|
||||
view = CV2(f"{TICK} Success", f"{role.mention} has been added to human autoroles.")
|
||||
else:
|
||||
humans = [role.id]
|
||||
async with aiosqlite.connect(DATABASE_PATH) as db:
|
||||
await db.execute("INSERT INTO autorole (guild_id, humans, bots) VALUES (?, ?, ?)", (ctx.guild.id, str(humans), '[]'))
|
||||
await db.execute("INSERT INTO autorole (guild_id, humans, bots) VALUES (?, ?, ?)", (ctx.guild.id, dump_role_id_list(humans), '[]'))
|
||||
await db.commit()
|
||||
view = CV2(f"{TICK} Success", f"{role.mention} has been added to human autoroles.")
|
||||
|
||||
@@ -265,13 +266,13 @@ class AutoRole(commands.Cog):
|
||||
data = await cursor.fetchone()
|
||||
|
||||
if data:
|
||||
humans = eval(data[0])
|
||||
humans = parse_role_id_list(data[0])
|
||||
if role.id not in humans:
|
||||
view = CV2(f"{CROSS} Error", f"{role.mention} is not in human autoroles.")
|
||||
else:
|
||||
humans.remove(role.id)
|
||||
async with aiosqlite.connect(DATABASE_PATH) as db:
|
||||
await db.execute("UPDATE autorole SET humans = ? WHERE guild_id = ?", (str(humans), ctx.guild.id))
|
||||
await db.execute("UPDATE autorole SET humans = ? WHERE guild_id = ?", (dump_role_id_list(humans), ctx.guild.id))
|
||||
await db.commit()
|
||||
view = CV2(f"{TICK} Success", f"{role.mention} has been removed from human autoroles.")
|
||||
else:
|
||||
@@ -303,7 +304,7 @@ class AutoRole(commands.Cog):
|
||||
data = await cursor.fetchone()
|
||||
|
||||
if data:
|
||||
bots = eval(data[0])
|
||||
bots = parse_role_id_list(data[0])
|
||||
if role.id in bots:
|
||||
view = CV2(f"{ICONS_WARNING} Access Denied", f"{role.mention} is already in bot autoroles.")
|
||||
elif len(bots) >= 10:
|
||||
@@ -311,13 +312,13 @@ class AutoRole(commands.Cog):
|
||||
else:
|
||||
bots.append(role.id)
|
||||
async with aiosqlite.connect(DATABASE_PATH) as db:
|
||||
await db.execute("UPDATE autorole SET bots = ? WHERE guild_id = ?", (str(bots), ctx.guild.id))
|
||||
await db.execute("UPDATE autorole SET bots = ? WHERE guild_id = ?", (dump_role_id_list(bots), ctx.guild.id))
|
||||
await db.commit()
|
||||
view = CV2(f"{TICK} Success", f"{role.mention} has been added to bot autoroles.")
|
||||
else:
|
||||
bots = [role.id]
|
||||
async with aiosqlite.connect(DATABASE_PATH) as db:
|
||||
await db.execute("INSERT INTO autorole (guild_id, humans, bots) VALUES (?, ?, ?)", (ctx.guild.id, '[]', str(bots)))
|
||||
await db.execute("INSERT INTO autorole (guild_id, humans, bots) VALUES (?, ?, ?)", (ctx.guild.id, '[]', dump_role_id_list(bots)))
|
||||
await db.commit()
|
||||
view = CV2(f"{TICK} Success", f"{role.mention} has been added to bot autoroles.")
|
||||
|
||||
@@ -336,13 +337,13 @@ class AutoRole(commands.Cog):
|
||||
data = await cursor.fetchone()
|
||||
|
||||
if data:
|
||||
bots = eval(data[0])
|
||||
bots = parse_role_id_list(data[0])
|
||||
if role.id not in bots:
|
||||
view = CV2(f"{CROSS} Error", f"{role.mention} is not in bot autoroles.")
|
||||
else:
|
||||
bots.remove(role.id)
|
||||
async with aiosqlite.connect(DATABASE_PATH) as db:
|
||||
await db.execute("UPDATE autorole SET bots = ? WHERE guild_id = ?", (str(bots), ctx.guild.id))
|
||||
await db.execute("UPDATE autorole SET bots = ? WHERE guild_id = ?", (dump_role_id_list(bots), ctx.guild.id))
|
||||
await db.commit()
|
||||
view = CV2(f"{TICK} Success", f"{role.mention} has been removed from bot autoroles.")
|
||||
else:
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
from discord.ext import commands
|
||||
from discord.ui import View, Button, button
|
||||
import discord
|
||||
from utils.safe_parse import safe_math_eval
|
||||
|
||||
|
||||
class CalculatorView(View):
|
||||
@@ -89,7 +90,7 @@ class CalculatorView(View):
|
||||
)
|
||||
try:
|
||||
expression = self.value.strip().replace("\n", "")
|
||||
result = str(eval(expression))
|
||||
result = safe_math_eval(expression)
|
||||
await self.update_embed(interaction, result)
|
||||
self.value = result # Store the result for possible further calculations
|
||||
except:
|
||||
|
||||
@@ -38,11 +38,6 @@ from typing import *
|
||||
import string
|
||||
from utils.cv2 import CV2, build_container
|
||||
|
||||
lawda = [
|
||||
'8', '3821', '23', '21', '313', '43', '29', '76', '11', '9',
|
||||
'44', '470', '318' , '26', '69'
|
||||
]
|
||||
|
||||
|
||||
class AvatarView(View):
|
||||
def __init__(self, user, member, author_id, banner_url):
|
||||
@@ -214,55 +209,6 @@ class General(commands.Cog):
|
||||
await msg.add_reaction(CROSS)
|
||||
|
||||
|
||||
@commands.command(name="hack",
|
||||
help="hack someone's discord account",
|
||||
usage="Hack <member>")
|
||||
@blacklist_check()
|
||||
@ignore_check()
|
||||
@commands.cooldown(1, 3, commands.BucketType.user)
|
||||
async def hack(self, ctx: commands.Context, member: discord.Member):
|
||||
stringi = member.name
|
||||
min_length = 2
|
||||
max_length = 12
|
||||
length = random.randint(min_length, max_length)
|
||||
stringg = member.name
|
||||
remaining_length = length - len(stringg)
|
||||
all_chars = string.ascii_letters + string.digits + string.punctuation
|
||||
random_chars = random.choices(all_chars, k=remaining_length)
|
||||
|
||||
password = stringg + ''.join(random_chars)
|
||||
|
||||
lund = await ctx.send(f"Processing to Hack {member.mention}...")
|
||||
await asyncio.sleep(2)
|
||||
random_pass = random.choice(lawda)
|
||||
|
||||
random_pass2 = ''.join(random.choices(string.ascii_letters + string.digits, k=3))
|
||||
hack_text = (
|
||||
f"**User:** {member.mention}\n"
|
||||
f"**E-Mail:** {''.join(c for c in stringi if c.isalnum())}{random_pass}@gmail.com\n"
|
||||
f"**Account Password:** {member.name}@{random_pass2}"
|
||||
)
|
||||
await ctx.send(view=CV2(f"Hacked {member.display_name}!", hack_text))
|
||||
await lund.delete()
|
||||
|
||||
|
||||
@commands.command(name="token", usage="Token <member>")
|
||||
@blacklist_check()
|
||||
@ignore_check()
|
||||
@commands.cooldown(1, 2, commands.BucketType.user)
|
||||
async def token(self, ctx: commands.Context, user: discord.Member = None):
|
||||
list = [
|
||||
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
|
||||
"O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "_"
|
||||
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
|
||||
'ñ', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0',
|
||||
'1', '2', '3', '4', '5', '6', '7', '8', '9'
|
||||
]
|
||||
token = random.choices(list, k=59)
|
||||
if user is None:
|
||||
user = ctx.author
|
||||
await ctx.send(view=CV2("🔐 Token", f"{user.mention}'s token: `{''.join(token)}`"))
|
||||
|
||||
@commands.command(name="users", help=f"checks total users of {BotName}.")
|
||||
@blacklist_check()
|
||||
@ignore_check()
|
||||
@@ -274,34 +220,6 @@ class General(commands.Cog):
|
||||
await ctx.send(view=CV2(f"{BotName} Users", f"❯ Total of __**{users}**__ Users in **{guilds}** Guilds"))
|
||||
|
||||
|
||||
@commands.command(name="wizz", usage="Wizz")
|
||||
@blacklist_check()
|
||||
@ignore_check()
|
||||
@commands.cooldown(1, 3, commands.BucketType.user)
|
||||
async def wizz(self, ctx: commands.Context):
|
||||
message6 = await ctx.send(
|
||||
f"`Wizzing {ctx.guild.name}, will take 22 seconds to complete`")
|
||||
message7 = await ctx.send(f"Changing all guild settings...")
|
||||
message5 = await ctx.send(f"Deleting **{len(ctx.guild.roles)}** Roles...")
|
||||
await asyncio.sleep(1)
|
||||
message4 = await ctx.send(
|
||||
f"Deleting **{len(ctx.guild.channels)}** Channels...")
|
||||
await asyncio.sleep(1)
|
||||
message3 = await ctx.send(f"Deleting Webhooks...")
|
||||
message2 = await ctx.send(f"Deleting emojis")
|
||||
await asyncio.sleep(1)
|
||||
message1 = await ctx.send(f"Installing Ban Wave..")
|
||||
await asyncio.sleep(1)
|
||||
await message6.delete()
|
||||
await message7.delete()
|
||||
await message5.delete()
|
||||
await message4.delete()
|
||||
await message3.delete()
|
||||
await message2.delete()
|
||||
await message1.delete()
|
||||
await ctx.send(view=CV2(f"{self.bot.user.name}", f"**{ZWARNING} Successfully Wizzed {ctx.guild.name}**"))
|
||||
|
||||
|
||||
@commands.hybrid_command(
|
||||
name="urban",
|
||||
description="Searches for specified phrase on urbandictionary",
|
||||
|
||||
@@ -128,7 +128,7 @@ class TimeSelect(Select):
|
||||
if role:
|
||||
await member.add_roles(role, reason="No prefix added")
|
||||
|
||||
log_channel = interaction.client.get_channel(1396794297386532978)
|
||||
log_channel = interaction.client.get_channel(LOG_CHANNEL_ID) if LOG_CHANNEL_ID else None
|
||||
if log_channel:
|
||||
embed = CV2Embed(
|
||||
title="User Added to No Prefix",
|
||||
@@ -140,7 +140,7 @@ class TimeSelect(Select):
|
||||
if self.user.avatar
|
||||
else self.user.default_avatar.url
|
||||
)
|
||||
await log_channel.send("<#1396794297386532978>", view=embed)
|
||||
await log_channel.send(view=embed)
|
||||
|
||||
embed = CV2Embed(
|
||||
description=f"**Added Global No Prefix**:\n{ZHUMAN} User: **{self.user.mention}**\n{MENTION} User Mention: {self.user.mention}\n{ZYROXSYS} User ID: {self.user.id}\n\n__**Additional Info**__:\n{ZYROXHAMMER} Added By: **{self.author.display_name}**\n{TIME} Expiry Time: {expiry_text}\n{BOOST} Timestamp: {expiry_timestamp}",
|
||||
@@ -233,7 +233,7 @@ class NoPrefix(commands.Cog):
|
||||
for user_id in expired_users:
|
||||
user = self.client.get_user(user_id)
|
||||
if user:
|
||||
log_channel = self.client.get_channel(1396794297386532978)
|
||||
log_channel = self.client.get_channel(LOG_CHANNEL_ID) if LOG_CHANNEL_ID else None
|
||||
if log_channel:
|
||||
embed_log = CV2Embed(
|
||||
title="No Prefix Expired",
|
||||
@@ -251,9 +251,7 @@ class NoPrefix(commands.Cog):
|
||||
else user.default_avatar.url
|
||||
)
|
||||
embed_log.set_footer(text="No Prefix Removal Log")
|
||||
await log_channel.send(
|
||||
"<#1396794297386532978>", view=embed_log
|
||||
)
|
||||
await log_channel.send(view=embed_log)
|
||||
bot = self.client
|
||||
guild = bot.get_guild(1401125905677553716)
|
||||
if guild:
|
||||
@@ -402,7 +400,7 @@ class NoPrefix(commands.Cog):
|
||||
embed.set_author(name="Removed No Prefix")
|
||||
await ctx.reply(view=embed)
|
||||
|
||||
log_channel = ctx.bot.get_channel(1396794297386532978)
|
||||
log_channel = ctx.bot.get_channel(LOG_CHANNEL_ID) if LOG_CHANNEL_ID else None
|
||||
if log_channel:
|
||||
embed_log = CV2Embed(
|
||||
title="No Prefix Removed",
|
||||
@@ -694,7 +692,7 @@ class NoPrefix(commands.Cog):
|
||||
await interaction.response.edit_message(view=success_embed)
|
||||
|
||||
# Log the action
|
||||
log_channel = self.client.get_channel(1396794297386532978)
|
||||
log_channel = self.client.get_channel(LOG_CHANNEL_ID) if LOG_CHANNEL_ID else None
|
||||
if log_channel:
|
||||
log_embed = CV2Embed(
|
||||
title="No-Prefix List Reset",
|
||||
@@ -702,7 +700,7 @@ class NoPrefix(commands.Cog):
|
||||
color=0xFF0000,
|
||||
)
|
||||
log_embed.set_footer(text="No Prefix Reset Log")
|
||||
await log_channel.send("<#1396794297386532978>", view=log_embed)
|
||||
await log_channel.send(view=log_embed)
|
||||
|
||||
async def no_callback(interaction):
|
||||
if interaction.user != ctx.author:
|
||||
|
||||
@@ -44,7 +44,9 @@ class Guild(Cog):
|
||||
for inv in await guild.invites()
|
||||
if inv.max_age == 0 and inv.max_uses == 0
|
||||
]
|
||||
ch = 1396794297386532978
|
||||
ch = LOG_CHANNEL_ID
|
||||
if not ch:
|
||||
return
|
||||
me = self.client.get_channel(ch)
|
||||
if me is None:
|
||||
logging.error(f"Channel with ID {ch} not found.")
|
||||
@@ -159,7 +161,9 @@ Threads : {len(guild.threads)}
|
||||
self.recently_removed_guilds.clear()
|
||||
|
||||
try:
|
||||
ch = 1396794297386532978
|
||||
ch = LOG_CHANNEL_ID
|
||||
if not ch:
|
||||
return
|
||||
idk = self.client.get_channel(ch)
|
||||
if idk is None:
|
||||
logging.error(f"Channel with ID {ch} not found.")
|
||||
|
||||
@@ -31,4 +31,4 @@ class _general(commands.Cog):
|
||||
|
||||
@commands.group()
|
||||
async def __General__(self, ctx: commands.Context):
|
||||
"""`status` , `afk` , `avatar` , `banner` , `servericon` , `membercount` , `poll` , `hack` , `token` , `users` , `wizz` , `urban` , `rickroll` , `hash` , `snipe` , `users` , `list boosters` , `list inrole` , `list emojis` , `list bots` , `list admins` , `list invoice` , `list mods` , `list early` , `list activedeveloper` , `list createpos` , `list roles` , `calculator`"""
|
||||
"""`status` , `afk` , `avatar` , `banner` , `servericon` , `membercount` , `poll` , `users` , `urban` , `rickroll` , `hash` , `snipe` , `users` , `list boosters` , `list inrole` , `list emojis` , `list bots` , `list admins` , `list invoice` , `list mods` , `list early` , `list activedeveloper` , `list createpos` , `list roles` , `calculator`"""
|
||||
@@ -16,9 +16,6 @@ from __future__ import annotations
|
||||
from discord.ext import commands, tasks
|
||||
import discord
|
||||
import aiohttp
|
||||
import json
|
||||
import jishaku
|
||||
import asyncio
|
||||
import typing
|
||||
from typing import List
|
||||
import aiosqlite
|
||||
|
||||
@@ -26,24 +26,61 @@ server = "https://discord.gg/codexdev"
|
||||
serverLink = "https://discord.gg/codexdev"
|
||||
ch = "https://discord.com/channels/699587669059174461/1271825678710476911"
|
||||
|
||||
CMD_WEBHOOK_URL = os.getenv("CMD_WEBHOOK_URL")
|
||||
# ── Security / feature toggles ────────────────────────────────────────────────
|
||||
|
||||
def _env_bool(key: str, default: bool = False) -> bool:
|
||||
raw = os.getenv(key, str(default)).strip().lower()
|
||||
return raw in ("1", "true", "yes", "on")
|
||||
|
||||
|
||||
JISHAKU_ENABLED = _env_bool("JISHAKU_ENABLED", False)
|
||||
API_ENABLED = _env_bool("API_ENABLED", False)
|
||||
TUNNEL_ENABLED = _env_bool("TUNNEL_ENABLED", False)
|
||||
TUNNEL_ALLOW_BINARY_DOWNLOAD = _env_bool("TUNNEL_ALLOW_BINARY_DOWNLOAD", False)
|
||||
|
||||
API_HOST = os.getenv("API_HOST", "127.0.0.1").strip() or "127.0.0.1"
|
||||
API_PORT = int(os.getenv("API_PORT", "8000"))
|
||||
|
||||
# ── Webhooks (only active when explicitly configured) ─────────────────────────
|
||||
|
||||
def _valid_webhook_url(url: str | None) -> str | None:
|
||||
if not url:
|
||||
return None
|
||||
url = url.strip()
|
||||
if not url or url == "https://discord.com/api/webhooks/":
|
||||
return None
|
||||
if "discord.com/api/webhooks/" not in url and "discordapp.com/api/webhooks/" not in url:
|
||||
return None
|
||||
return url
|
||||
|
||||
CMD_WEBHOOK_URL = _valid_webhook_url(os.getenv("CMD_WEBHOOK_URL"))
|
||||
|
||||
# ── Optional Discord log / stats channels (unset = disabled) ──────────────────
|
||||
|
||||
def _parse_optional_id(env_key: str) -> int | None:
|
||||
raw = os.getenv(env_key, "").strip()
|
||||
if not raw or not raw.isdigit():
|
||||
return None
|
||||
return int(raw)
|
||||
|
||||
LOG_CHANNEL_ID = _parse_optional_id("LOG_CHANNEL_ID")
|
||||
SERVER_COUNT_CHANNEL_ID = _parse_optional_id("SERVER_COUNT_CHANNEL_ID")
|
||||
USER_COUNT_CHANNEL_ID = _parse_optional_id("USER_COUNT_CHANNEL_ID")
|
||||
|
||||
# ── Owner / Staff IDs ─────────────────────────────────────────────────────────
|
||||
# Edit OWNER_IDS in .env — comma-separated, no spaces needed.
|
||||
# Example: OWNER_IDS = 870179991462236170,767979794411028491,1432771000629596225
|
||||
# REQUIRED: set OWNER_IDS in .env — no hardcoded fallback IDs.
|
||||
|
||||
def _parse_ids(env_key: str, defaults: list[int]) -> list[int]:
|
||||
def _parse_ids(env_key: str) -> list[int]:
|
||||
raw = os.getenv(env_key, "").strip()
|
||||
if not raw:
|
||||
return defaults
|
||||
ids = [int(p.strip()) for p in raw.split(",") if p.strip().isdigit()]
|
||||
return ids or defaults
|
||||
return []
|
||||
return [int(p.strip()) for p in raw.split(",") if p.strip().isdigit()]
|
||||
|
||||
OWNER_IDS: list[int] = _parse_ids("OWNER_IDS", [870179991462236170])
|
||||
OWNER_IDS: list[int] = _parse_ids("OWNER_IDS")
|
||||
OWNER_IDS_STR: list[str] = [str(i) for i in OWNER_IDS]
|
||||
|
||||
# Aliases kept for backwards compatibility with files that import these names
|
||||
BOT_OWNER_IDS = OWNER_IDS
|
||||
BOT_OWNER_IDS_STR = OWNER_IDS_STR
|
||||
STAFF_IDS = OWNER_IDS
|
||||
STAFF_IDS_STR = OWNER_IDS_STR
|
||||
STAFF_IDS_STR = OWNER_IDS_STR
|
||||
|
||||
@@ -13,14 +13,15 @@
|
||||
# ╚══════════════════════════════════════════════════════════════════╝
|
||||
|
||||
from __future__ import annotations
|
||||
import os
|
||||
import discord
|
||||
from utils.config import BotName
|
||||
try:
|
||||
from discord.ext import menus
|
||||
from discord.ext import commands
|
||||
except ModuleNotFoundError:
|
||||
os.system("pip install git+https://github.com/Rapptz/discord-ext-menus")
|
||||
except ModuleNotFoundError as exc:
|
||||
raise ImportError(
|
||||
"discord-ext-menus is required. Install it with: pip install git+https://github.com/Rapptz/discord-ext-menus"
|
||||
) from exc
|
||||
|
||||
from .paginator import Paginator as EmbedPaginator
|
||||
from discord.ext.commands import Context, Paginator as CmdPaginator
|
||||
|
||||
66
bot/utils/safe_parse.py
Normal file
66
bot/utils/safe_parse.py
Normal file
@@ -0,0 +1,66 @@
|
||||
# ╔══════════════════════════════════════════════════════════════════╗
|
||||
# ║ Safe parsing helpers — no eval() on untrusted data ║
|
||||
# ╚══════════════════════════════════════════════════════════════════╝
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import json
|
||||
import operator
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
|
||||
def parse_role_id_list(raw: str | None) -> list[int]:
|
||||
"""Parse a stored role-ID list (JSON or legacy Python repr)."""
|
||||
if not raw:
|
||||
return []
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
try:
|
||||
parsed = ast.literal_eval(raw)
|
||||
except (ValueError, SyntaxError):
|
||||
return []
|
||||
if not isinstance(parsed, list):
|
||||
return []
|
||||
return [int(x) for x in parsed if str(x).isdigit()]
|
||||
|
||||
|
||||
def dump_role_id_list(ids: list[int]) -> str:
|
||||
return json.dumps(ids)
|
||||
|
||||
|
||||
_MATH_ALLOWED = re.compile(r"^[\d+\-*/().\s]+$")
|
||||
|
||||
|
||||
def _eval_math_node(node: ast.AST) -> float:
|
||||
if isinstance(node, ast.Expression):
|
||||
return _eval_math_node(node.body)
|
||||
if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
|
||||
return float(node.value)
|
||||
if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.UAdd, ast.USub)):
|
||||
value = _eval_math_node(node.operand)
|
||||
return value if isinstance(node.op, ast.UAdd) else -value
|
||||
if isinstance(node, ast.BinOp) and isinstance(node.op, (ast.Add, ast.Sub, ast.Mult, ast.Div)):
|
||||
left = _eval_math_node(node.left)
|
||||
right = _eval_math_node(node.right)
|
||||
ops = {
|
||||
ast.Add: operator.add,
|
||||
ast.Sub: operator.sub,
|
||||
ast.Mult: operator.mul,
|
||||
ast.Div: operator.truediv,
|
||||
}
|
||||
if isinstance(node.op, ast.Div) and right == 0:
|
||||
raise ZeroDivisionError("division by zero")
|
||||
return ops[type(node.op)](left, right)
|
||||
raise ValueError("unsupported expression")
|
||||
|
||||
|
||||
def safe_math_eval(expression: str) -> str:
|
||||
"""Evaluate basic arithmetic safely (digits, +, -, *, /, parentheses)."""
|
||||
expr = expression.strip()
|
||||
if not expr or not _MATH_ALLOWED.match(expr):
|
||||
raise ValueError("invalid characters in expression")
|
||||
tree = ast.parse(expr, mode="eval")
|
||||
return str(_eval_math_node(tree))
|
||||
@@ -50,10 +50,10 @@ import threading
|
||||
import subprocess
|
||||
|
||||
# ── env vars ──────────────────────────────────────────────────────────────────
|
||||
TUNNEL_ENABLED = os.getenv("TUNNEL_ENABLED", "true").strip().lower() == "true"
|
||||
from utils.config import TUNNEL_ENABLED, TUNNEL_ALLOW_BINARY_DOWNLOAD, API_PORT
|
||||
|
||||
CF_TUNNEL_TOKEN = os.getenv("CF_TUNNEL_TOKEN", "").strip() # token from Cloudflare dashboard
|
||||
CF_TUNNEL_URL = os.getenv("CF_TUNNEL_URL", "").strip() # e.g. https://api.yourdomain.com
|
||||
API_PORT = int(os.getenv("API_PORT", "8000"))
|
||||
|
||||
# ── colours ───────────────────────────────────────────────────────────────────
|
||||
_CYAN = "\033[36m"
|
||||
@@ -64,30 +64,15 @@ _RESET = "\033[0m"
|
||||
|
||||
|
||||
def _ensure_pycloudflared() -> bool:
|
||||
"""Install pycloudflared via pip if it's not available. Returns True on success."""
|
||||
"""Return True if pycloudflared is installed (no automatic pip install)."""
|
||||
try:
|
||||
import pycloudflared # noqa: F401
|
||||
return True
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
print(f"{_YELLOW}◈ Tunnel: pycloudflared not found — installing via pip…{_RESET}")
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[__import__("sys").executable, "-m", "pip", "install", "pycloudflared"],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
timeout=120,
|
||||
text=True,
|
||||
print(
|
||||
f"{_RED}◈ Tunnel: pycloudflared is not installed.\n"
|
||||
f" Install manually: pip install pycloudflared{_RESET}"
|
||||
)
|
||||
if result.returncode == 0:
|
||||
print(f"{_GREEN}◈ Tunnel: pycloudflared installed successfully.{_RESET}")
|
||||
return True
|
||||
else:
|
||||
print(f"{_RED}◈ Tunnel: pip install failed:\n{result.stdout}{_RESET}")
|
||||
return False
|
||||
except Exception as exc:
|
||||
print(f"{_RED}◈ Tunnel: could not install pycloudflared — {exc}{_RESET}")
|
||||
return False
|
||||
|
||||
|
||||
@@ -157,8 +142,9 @@ def _get_binary() -> str | None:
|
||||
import shutil
|
||||
import stat
|
||||
|
||||
# ── Step 0: make sure pycloudflared is installed ──────────────────────────
|
||||
_ensure_pycloudflared()
|
||||
# ── Step 0: check pycloudflared is installed ─────────────────────────────
|
||||
if not _ensure_pycloudflared():
|
||||
return None
|
||||
|
||||
candidates: list[str] = []
|
||||
|
||||
@@ -222,7 +208,15 @@ def _get_binary() -> str | None:
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
continue
|
||||
|
||||
# ── Step 4: direct GitHub download as last resort ─────────────────────────
|
||||
# ── Step 4: direct GitHub download (opt-in only) ─────────────────────────
|
||||
if not TUNNEL_ALLOW_BINARY_DOWNLOAD:
|
||||
print(
|
||||
f"{_YELLOW}◈ Tunnel: no working binary found.\n"
|
||||
f" Install pycloudflared manually, or set TUNNEL_ALLOW_BINARY_DOWNLOAD=true "
|
||||
f"to allow downloading cloudflared from GitHub.{_RESET}"
|
||||
)
|
||||
return None
|
||||
|
||||
print(f"{_YELLOW}◈ Tunnel: no working binary found — attempting direct download…{_RESET}")
|
||||
direct = _download_cloudflared_direct()
|
||||
if direct and os.path.isfile(direct):
|
||||
@@ -288,7 +282,7 @@ def _run_tunnel(binary: str, token: str, port: int, public_url: str) -> None:
|
||||
announced = True
|
||||
if public_url:
|
||||
print(f"{_GREEN}◈ Tunnel: API is live at {public_url}{_RESET}")
|
||||
print(f"{_CYAN} ↳ NEXT_PUBLIC_API_URL = {public_url}/api/v1{_RESET}")
|
||||
print(f"{_CYAN} ↳ DASHBOARD_API_URL = {public_url}/api/v1{_RESET}")
|
||||
else:
|
||||
print(f"{_GREEN}◈ Tunnel: connected — check CF_TUNNEL_URL in .env for your public URL{_RESET}")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user