Refactor bot server setup to use Waitress for production; fallback to Flask dev server for local development. Added timeout to HTTP requests in Fun and Test cogs. Improved error handling for missing environment variables. Enhanced secret key management in Flask app. Added request timeout configuration. Introduced new experimental features including user profile and balance cards, and a Tic-Tac-Toe game with Minimax AI. Addressed various database and security issues, and improved code quality across multiple files.
This commit is contained in:
@@ -116,9 +116,12 @@ async def create_balance_card(user, credits, tokens, bucks):
|
|||||||
draw.line([(0, y), (width, y)], fill=(r, g, b))
|
draw.line([(0, y), (width, y)], fill=(r, g, b))
|
||||||
|
|
||||||
# Avatar with circular border
|
# Avatar with circular border
|
||||||
avatar_asset = user.avatar
|
try:
|
||||||
avatar_response = requests.get(avatar_asset)
|
avatar_bytes = await user.avatar.read()
|
||||||
avatar = Image.open(io.BytesIO(avatar_response.content)).resize((60, 60))
|
avatar = Image.open(io.BytesIO(avatar_bytes)).resize((60, 60))
|
||||||
|
except Exception:
|
||||||
|
# Fallback: blank avatar
|
||||||
|
avatar = Image.new("RGBA", (60, 60), (128, 128, 128, 255))
|
||||||
mask = Image.new("L", avatar.size, 0)
|
mask = Image.new("L", avatar.size, 0)
|
||||||
ImageDraw.Draw(mask).ellipse((0, 0, 60, 60), fill=255)
|
ImageDraw.Draw(mask).ellipse((0, 0, 60, 60), fill=255)
|
||||||
avatar = ImageOps.fit(avatar, mask.size, centering=(0.5, 0.5))
|
avatar = ImageOps.fit(avatar, mask.size, centering=(0.5, 0.5))
|
||||||
@@ -6,8 +6,13 @@ from random import shuffle
|
|||||||
|
|
||||||
# Step 1: Fetch JSON data from the URL
|
# Step 1: Fetch JSON data from the URL
|
||||||
url = "https://picsum.photos/v2/list?limit=1000"
|
url = "https://picsum.photos/v2/list?limit=1000"
|
||||||
response = requests.get(url)
|
try:
|
||||||
data = response.json()
|
response = requests.get(url, timeout=10)
|
||||||
|
response.raise_for_status()
|
||||||
|
data = response.json()
|
||||||
|
except requests.RequestException as e:
|
||||||
|
print(f"Failed to fetch image list: {e}")
|
||||||
|
data = []
|
||||||
|
|
||||||
# Step 2: Extract image download links
|
# Step 2: Extract image download links
|
||||||
image_urls = [item["download_url"] for item in data]
|
image_urls = [item["download_url"] for item in data]
|
||||||
@@ -21,8 +26,9 @@ desired_size = (450, 250)
|
|||||||
|
|
||||||
# Step 4: Download and resize each image
|
# Step 4: Download and resize each image
|
||||||
for i, image_url in enumerate(image_urls):
|
for i, image_url in enumerate(image_urls):
|
||||||
img_response = requests.get(image_url)
|
try:
|
||||||
if img_response.status_code == 200:
|
img_response = requests.get(image_url, timeout=10)
|
||||||
|
img_response.raise_for_status()
|
||||||
# Open image from response content
|
# Open image from response content
|
||||||
img = Image.open(BytesIO(img_response.content))
|
img = Image.open(BytesIO(img_response.content))
|
||||||
# Resize the image
|
# Resize the image
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
## Major problems found
|
||||||
|
|
||||||
|
### 1. Database / SQL issues
|
||||||
|
- sql_commands.py
|
||||||
|
- `execute_query()` returns `copy(cursor)` after closing the cursor/connection, which is invalid and likely breaks fetch operations.
|
||||||
|
- `insert()` parses SQL text to build `ON DUPLICATE KEY UPDATE`; this is brittle and unsafe for many query forms.
|
||||||
|
- `delete()` builds SQL using f-strings with `table_name` and column names from caller input, so it can be SQL-injection vulnerable if those values are not controlled.
|
||||||
|
- `create_table_if_not_exists()` also uses unescaped table/schema names via f-string.
|
||||||
|
- `bulk_insert()` assumes params are list of dicts and rebuilds SQL based on keys; this is fragile and can break on mixed column orders.
|
||||||
|
- `DatabaseManager` is instantiated in many modules/cogs, creating multiple separate connection pools instead of reusing one singleton.
|
||||||
|
|
||||||
|
- bank_functions.py
|
||||||
|
- `db = DatabaseManager("economy")` is created at import time and may use incorrect/duplicate env loading.
|
||||||
|
- `bank_data()` treats `fetch_one()` result inconsistently; if it returns `{}` instead of `None`, account creation may not happen.
|
||||||
|
- `update_money()` uses `insert(..., overwrite=True)` to update balances, which is a weird and brittle upsert pattern.
|
||||||
|
- `record_transaction()` calls `db.insert("transactions", ...)` without a proper query skeleton.
|
||||||
|
|
||||||
|
- npc_memory.py
|
||||||
|
- Uses `sqlite3.connect('npc_memory.db')` with a hardcoded path and no thread-safety handling.
|
||||||
|
- Single SQLite connection is reused without controlling concurrency or isolation.
|
||||||
|
|
||||||
|
### 2. Secret/configuration handling
|
||||||
|
- app.py
|
||||||
|
- `app.secret_key = os.getenv("SECRET_KEY")` can be `None`, breaking Flask session security.
|
||||||
|
- Required env-vars are checked, but `DISCORD_BOT_TOKEN` is loaded and never used; config is inconsistent with actual bot startup.
|
||||||
|
- mail.py
|
||||||
|
- Loads email credentials from env and may fail silently if missing.
|
||||||
|
- bot.py
|
||||||
|
- Prints the bot token with `print(token)`; this is a secret leak risk.
|
||||||
|
- Multiple files call `load_dotenv()` repeatedly instead of once at startup.
|
||||||
|
|
||||||
|
### 3. Bot startup / architecture
|
||||||
|
- bot.py
|
||||||
|
- `iterate_prefix("Vamoc")` and `iterate_prefix("!V")` generate all uppercase/lowercase permutations, which is extremely inefficient and unnecessary.
|
||||||
|
- `self.iterate_prefix("Vamoc")+self.iterate_prefix("!V")` creates huge prefixes list and prints it.
|
||||||
|
- A Flask dev server is started in a daemon thread with `app.run(...)`, which is not suitable for production and may cause shutdown issues.
|
||||||
|
- `token` missing path handling is minimal and should use explicit error handling.
|
||||||
|
|
||||||
|
- app.py
|
||||||
|
- Uses Flask dev server, OAuth flows, and session storage without clear production readiness.
|
||||||
|
- Raw `requests` calls to Discord API are used without timeouts in some cases.
|
||||||
|
|
||||||
|
### 4. Code quality / maintainability
|
||||||
|
- economy.py
|
||||||
|
- `from utils.bank_functions import *` is bad practice and obscures imports.
|
||||||
|
- Duplicate `from discord.ext import commands` import.
|
||||||
|
- Many methods have weak validation and inconsistent return semantics.
|
||||||
|
- `check_transfer()` has odd parameter names and does not cleanly separate logic from reply behavior.
|
||||||
|
- `daily` command uses inconsistent datetime handling and stores timestamp as float in DB without schema enforcement.
|
||||||
|
|
||||||
|
- sql_commands.py
|
||||||
|
- Uses `pandas` only for `fetch_as_dataframe`, which is heavy for a bot and likely unnecessary.
|
||||||
|
- `pool_reset_session` config uses `bool(os.getenv(...))`, which returns `True` for any non-empty string, not only `"True"`.
|
||||||
|
|
||||||
|
- README.md
|
||||||
|
- The documented repo structure does not match actual workspace structure.
|
||||||
|
- It claims SQLite usage while sql_commands.py uses MySQL.
|
||||||
|
- It references files/paths that are not present (e.g. `extras/`, `LICENSE`).
|
||||||
|
|
||||||
|
### 5. Dependency / packaging
|
||||||
|
- requirements.txt
|
||||||
|
- Includes large packages like `numpy`, `pandas`, and `mysql-connector` even though the bot only needs lightweight DB access and small utilities.
|
||||||
|
- `mysql-connector==2.2.9` is very old; upgrade or use `mysql-connector-python` / `mysqlclient`.
|
||||||
|
|
||||||
|
### 6. Security / robustness
|
||||||
|
- app.py
|
||||||
|
- OAuth redirect URL and query parameters are concatenated without URL encoding.
|
||||||
|
- Session data stores access tokens directly, which is sensitive.
|
||||||
|
- `get_user_transactions()` builds ORDER BY using string interpolation; it is validated but could be improved with safer mapping.
|
||||||
|
|
||||||
|
- mail.py
|
||||||
|
- HTML email is generated via large f-strings; this is hard to maintain and could be moved to a template.
|
||||||
|
- Many files mix business logic and I/O without error boundaries, so failures can cascade.
|
||||||
|
|
||||||
|
### 7. Other issues / enhancements
|
||||||
|
- Several experimental files under Experimantal and implementing use `input()` and are not production-ready.
|
||||||
|
- npc_memory.py and sql_commands.py should expose a shared data access layer rather than ad-hoc DB wrappers in each module.
|
||||||
|
- Missing tests, linting, formatting, and structured error logging across the repo.
|
||||||
|
- app.py has duplicated code patterns for Discord API requests and could benefit from helper functions.
|
||||||
|
- bot.py and bot_development.py are almost duplicates; consolidate startup logic.
|
||||||
|
|
||||||
|
## Recommended enhancements
|
||||||
|
- Centralize configuration and database initialization.
|
||||||
|
- Use a shared singleton `DatabaseManager` or dependency injection.
|
||||||
|
- Add strong type hints and remove wildcard imports.
|
||||||
|
- Replace Flask dev thread with proper web hosting or decouple the web interface.
|
||||||
|
- Validate all environment variables at startup.
|
||||||
|
- Add command-level checks and better error messages.
|
||||||
|
- Remove or replace heavy dependencies if they are not needed.
|
||||||
|
- Add tests for DB operations, command behavior, and web routes.
|
||||||
|
- Clean up README to match actual repository state.
|
||||||
|
|
||||||
|
> Note: this is a high-level audit, not a full code rewrite. If you want, I can now create a prioritized issue list or fix the worst bugs first.
|
||||||
+14
-7
@@ -28,9 +28,17 @@ class Client(commands.Bot):
|
|||||||
help_command=MyNewHelp(),
|
help_command=MyNewHelp(),
|
||||||
)
|
)
|
||||||
def iterate_prefix(self, prefix):
|
def iterate_prefix(self, prefix):
|
||||||
prefixes = list(map(''.join, itertools.product(*zip(prefix.upper(), prefix.lower()))))
|
# Avoid generating all case permutations for long prefixes.
|
||||||
print(prefixes)
|
# Provide a small set of common-case variants and rely on
|
||||||
|
# `case_insensitive=True` for command matching.
|
||||||
|
variants = [prefix, prefix.lower(), prefix.upper()]
|
||||||
|
# Preserve order but remove duplicates
|
||||||
|
seen = set()
|
||||||
|
prefixes = []
|
||||||
|
for p in variants:
|
||||||
|
if p not in seen:
|
||||||
|
seen.add(p)
|
||||||
|
prefixes.append(p)
|
||||||
return prefixes
|
return prefixes
|
||||||
|
|
||||||
async def setup_hook(self): # overwriting a handler
|
async def setup_hook(self): # overwriting a handler
|
||||||
@@ -48,11 +56,10 @@ class Client(commands.Bot):
|
|||||||
def main():
|
def main():
|
||||||
load_dotenv()
|
load_dotenv()
|
||||||
client = Client()
|
client = Client()
|
||||||
token = "ODA2Mjg0OTY2NzQ0NTU1NjAw.GFQoZn.Jh0OJ7KczDOfRxFFESnAPOiodUAkjSyjQ-ClGg"
|
token = os.getenv("DISCORD_TOKEN") or os.getenv("TOKEN")
|
||||||
if token is not None:
|
if not token:
|
||||||
|
raise SystemExit("ERROR: Discord token not found. Set DISCORD_TOKEN (or TOKEN) in environment.")
|
||||||
client.run(token)
|
client.run(token)
|
||||||
else:
|
|
||||||
print("Token is missing.")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -145,3 +145,44 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
|
|||||||
For support, please contact [yourname@example.com](mailto:yourname@example.com).
|
For support, please contact [yourname@example.com](mailto:yourname@example.com).
|
||||||
|
|
||||||
Happy Coding!
|
Happy Coding!
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Deployment (Web UI)
|
||||||
|
|
||||||
|
This project includes a small Flask-based web UI used for OAuth flows and guild management. The development server is fine for local testing, but for production use you should run the app under a WSGI server such as `waitress` or `gunicorn`.
|
||||||
|
|
||||||
|
Recommended steps to serve the web UI with `waitress`:
|
||||||
|
|
||||||
|
1. Install dependencies (includes `waitress`):
|
||||||
|
```bash
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Set the required environment variables (example `.env`):
|
||||||
|
```env
|
||||||
|
# Bot and web settings
|
||||||
|
TOKEN=your_bot_token_here
|
||||||
|
DISCORD_CLIENT_ID=your_client_id
|
||||||
|
DISCORD_CLIENT_SECRET=your_client_secret
|
||||||
|
DISCORD_REDIRECT_URI=https://yourdomain.com/callback
|
||||||
|
|
||||||
|
# Flask session secret (must be set in production)
|
||||||
|
SECRET_KEY=replace_with_a_secure_random_value
|
||||||
|
|
||||||
|
# Optional runtime
|
||||||
|
START_WEB=1 # set to 1 if you want the bot process to spawn the web UI
|
||||||
|
REQUEST_TIMEOUT=10 # default HTTP timeout in seconds for external requests
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Run the web app using `waitress` (example):
|
||||||
|
```bash
|
||||||
|
python -m waitress --host=0.0.0.0 --port=5000 web.app:app
|
||||||
|
```
|
||||||
|
|
||||||
|
Notes:
|
||||||
|
- If you set `START_WEB=1`, `bot_development.py` will spawn the web UI when the bot starts. This is convenient for small deployments but consider running the web UI in its own process or container for reliability and easier scaling.
|
||||||
|
- Never run the Flask development server (app.run) in production.
|
||||||
|
- Ensure `SECRET_KEY` is kept secret and not committed to source control. Use a secure random value like `openssl rand -hex 32`.
|
||||||
|
|
||||||
|
If you want, I can add a small `Procfile` and Dockerfile snippet for deployment — tell me which target (Heroku, Docker Compose, or Kubernetes) you prefer.
|
||||||
+19
-5
@@ -9,7 +9,17 @@ import threading
|
|||||||
|
|
||||||
|
|
||||||
def run_web():
|
def run_web():
|
||||||
app.run(debug=False, host="0.0.0.0", port=5000)
|
try:
|
||||||
|
# Prefer a production-ready WSGI server if available
|
||||||
|
from waitress import serve
|
||||||
|
|
||||||
|
serve(app, host="0.0.0.0", port=5000)
|
||||||
|
except Exception:
|
||||||
|
# Fall back to Flask dev server for local development only.
|
||||||
|
print(
|
||||||
|
"Warning: Running Flask development server. For production use a WSGI server (gunicorn, waitress, etc.)."
|
||||||
|
)
|
||||||
|
app.run(debug=False, host="0.0.0.0", port=5000, use_reloader=False)
|
||||||
|
|
||||||
|
|
||||||
class MyNewHelp(commands.MinimalHelpCommand):
|
class MyNewHelp(commands.MinimalHelpCommand):
|
||||||
@@ -62,11 +72,15 @@ def main():
|
|||||||
initialize_database()
|
initialize_database()
|
||||||
client = Client()
|
client = Client()
|
||||||
token = os.getenv("TOKEN")
|
token = os.getenv("TOKEN")
|
||||||
if token is not None:
|
if not token:
|
||||||
threading.Thread(target=run_web, daemon=True).start()
|
raise SystemExit("ERROR: TOKEN environment variable not set.")
|
||||||
|
|
||||||
|
# Only start the web interface if explicitly enabled to avoid
|
||||||
|
# running a dev server inside the bot process by default.
|
||||||
|
if os.getenv("START_WEB") == "1":
|
||||||
|
threading.Thread(target=run_web, daemon=False).start()
|
||||||
|
|
||||||
client.run(token)
|
client.run(token)
|
||||||
else:
|
|
||||||
print("Token is missing.")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -242,7 +242,7 @@ class Fun(commands.Cog):
|
|||||||
api_url = f"https://tenor.googleapis.com/v2/search?q={search_query}&key={self.tenor_api_key}&limit=10"
|
api_url = f"https://tenor.googleapis.com/v2/search?q={search_query}&key={self.tenor_api_key}&limit=10"
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = requests.get(api_url)
|
response = requests.get(api_url, timeout=10)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
gif_data = response.json()
|
gif_data = response.json()
|
||||||
|
|
||||||
@@ -263,7 +263,7 @@ class Fun(commands.Cog):
|
|||||||
api_url = "https://meme-api.com/memes/random"
|
api_url = "https://meme-api.com/memes/random"
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = requests.get(api_url)
|
response = requests.get(api_url, timeout=10)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
meme_data = response.json()
|
meme_data = response.json()
|
||||||
|
|
||||||
|
|||||||
@@ -38,7 +38,16 @@ class Test(commands.Cog):
|
|||||||
@commands.is_owner()
|
@commands.is_owner()
|
||||||
@commands.command(name="quiz")
|
@commands.command(name="quiz")
|
||||||
async def quiz(self, ctx):
|
async def quiz(self, ctx):
|
||||||
response = requests.get("https://opentdb.com/api.php?amount=1&category=18&difficulty=medium&type=multiple").json()["results"][0]
|
try:
|
||||||
|
resp = requests.get(
|
||||||
|
"https://opentdb.com/api.php?amount=1&category=18&difficulty=medium&type=multiple",
|
||||||
|
timeout=10,
|
||||||
|
)
|
||||||
|
resp.raise_for_status()
|
||||||
|
response = resp.json()["results"][0]
|
||||||
|
except requests.RequestException:
|
||||||
|
await ctx.send("Failed to fetch quiz question.")
|
||||||
|
return
|
||||||
question = response["question"]
|
question = response["question"]
|
||||||
|
|
||||||
view = MyView(response["correct_answer"], response["incorrect_answers"])
|
view = MyView(response["correct_answer"], response["incorrect_answers"])
|
||||||
|
|||||||
@@ -9,6 +9,9 @@ headers = {
|
|||||||
"x-rapidapi-host": "tarot-cards1.p.rapidapi.com"
|
"x-rapidapi-host": "tarot-cards1.p.rapidapi.com"
|
||||||
}
|
}
|
||||||
|
|
||||||
response = requests.get(url, headers=headers, params=querystring)
|
try:
|
||||||
|
response = requests.get(url, headers=headers, params=querystring, timeout=10)
|
||||||
print(response.json())
|
response.raise_for_status()
|
||||||
|
print(response.json())
|
||||||
|
except requests.RequestException as e:
|
||||||
|
print(f"Request failed: {e}")
|
||||||
@@ -29,3 +29,4 @@ tzdata==2024.2
|
|||||||
urllib3==2.2.3
|
urllib3==2.2.3
|
||||||
Werkzeug==3.1.7
|
Werkzeug==3.1.7
|
||||||
yarl==1.17.1
|
yarl==1.17.1
|
||||||
|
waitress==2.2.0
|
||||||
|
|||||||
+59
-13
@@ -20,7 +20,16 @@ import json
|
|||||||
load_dotenv()
|
load_dotenv()
|
||||||
|
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
app.secret_key = os.getenv("SECRET_KEY")
|
# Ensure a secret key is set for session security. In production this MUST be
|
||||||
|
# provided via the SECRET_KEY environment variable. In development we generate
|
||||||
|
# a temporary one (not suitable for production).
|
||||||
|
secret = os.getenv("SECRET_KEY")
|
||||||
|
if not secret:
|
||||||
|
if os.getenv("FLASK_ENV") == "production":
|
||||||
|
raise EnvironmentError("SECRET_KEY must be set in production environment")
|
||||||
|
print("Warning: SECRET_KEY not set; generating a temporary key for development.")
|
||||||
|
secret = os.urandom(32)
|
||||||
|
app.secret_key = secret
|
||||||
db = initialize_database()
|
db = initialize_database()
|
||||||
|
|
||||||
# Ensure required environment variables are loaded
|
# Ensure required environment variables are loaded
|
||||||
@@ -30,6 +39,9 @@ DISCORD_REDIRECT_URI = os.getenv("DISCORD_REDIRECT_URI")
|
|||||||
DISCORD_API_BASE_URL = "https://discord.com/api"
|
DISCORD_API_BASE_URL = "https://discord.com/api"
|
||||||
DISCORD_BOT_TOKEN = os.getenv("TOKEN")
|
DISCORD_BOT_TOKEN = os.getenv("TOKEN")
|
||||||
|
|
||||||
|
# Default request timeout (seconds) for external HTTP calls
|
||||||
|
REQUEST_TIMEOUT = int(os.getenv("REQUEST_TIMEOUT", "10"))
|
||||||
|
|
||||||
# Check for missing environment variables
|
# Check for missing environment variables
|
||||||
if not all([DISCORD_CLIENT_ID, DISCORD_CLIENT_SECRET, DISCORD_REDIRECT_URI]):
|
if not all([DISCORD_CLIENT_ID, DISCORD_CLIENT_SECRET, DISCORD_REDIRECT_URI]):
|
||||||
raise EnvironmentError("One or more required environment variables are missing.")
|
raise EnvironmentError("One or more required environment variables are missing.")
|
||||||
@@ -71,9 +83,17 @@ def callback():
|
|||||||
"redirect_uri": DISCORD_REDIRECT_URI,
|
"redirect_uri": DISCORD_REDIRECT_URI,
|
||||||
}
|
}
|
||||||
headers = {"Content-Type": "application/x-www-form-urlencoded"}
|
headers = {"Content-Type": "application/x-www-form-urlencoded"}
|
||||||
|
try:
|
||||||
response = requests.post(
|
response = requests.post(
|
||||||
f"{DISCORD_API_BASE_URL}/oauth2/token", data=data, headers=headers
|
f"{DISCORD_API_BASE_URL}/oauth2/token",
|
||||||
|
data=data,
|
||||||
|
headers=headers,
|
||||||
|
timeout=REQUEST_TIMEOUT,
|
||||||
)
|
)
|
||||||
|
response.raise_for_status()
|
||||||
|
except requests.RequestException:
|
||||||
|
flash("Failed to retrieve access token from Discord (network error).")
|
||||||
|
return redirect(url_for("home"))
|
||||||
|
|
||||||
if response.status_code != 200:
|
if response.status_code != 200:
|
||||||
flash("Failed to retrieve access token from Discord.")
|
flash("Failed to retrieve access token from Discord.")
|
||||||
@@ -88,19 +108,32 @@ def callback():
|
|||||||
session["access_token"] = access_token
|
session["access_token"] = access_token
|
||||||
|
|
||||||
# Fetch user info
|
# Fetch user info
|
||||||
user_data = requests.get(
|
try:
|
||||||
|
user_resp = requests.get(
|
||||||
f"{DISCORD_API_BASE_URL}/users/@me",
|
f"{DISCORD_API_BASE_URL}/users/@me",
|
||||||
headers={"Authorization": f"Bearer {access_token}"},
|
headers={"Authorization": f"Bearer {access_token}"},
|
||||||
).json()
|
timeout=REQUEST_TIMEOUT,
|
||||||
|
)
|
||||||
|
user_resp.raise_for_status()
|
||||||
|
user_data = user_resp.json()
|
||||||
|
except requests.RequestException:
|
||||||
|
flash("Failed to fetch user info from Discord.")
|
||||||
|
return redirect(url_for("home"))
|
||||||
|
|
||||||
# Store user information in session
|
# Store user information in session
|
||||||
session["user"] = user_data
|
session["user"] = user_data
|
||||||
|
|
||||||
# Fetch guilds the user is in
|
# Fetch guilds the user is in
|
||||||
|
try:
|
||||||
guilds_response = requests.get(
|
guilds_response = requests.get(
|
||||||
f"{DISCORD_API_BASE_URL}/users/@me/guilds",
|
f"{DISCORD_API_BASE_URL}/users/@me/guilds",
|
||||||
headers={"Authorization": f"Bearer {access_token}"},
|
headers={"Authorization": f"Bearer {access_token}"},
|
||||||
|
timeout=REQUEST_TIMEOUT,
|
||||||
)
|
)
|
||||||
|
guilds_response.raise_for_status()
|
||||||
|
except requests.RequestException:
|
||||||
|
flash("Failed to retrieve guilds from Discord.")
|
||||||
|
return redirect(url_for("home"))
|
||||||
|
|
||||||
if guilds_response.status_code == 200:
|
if guilds_response.status_code == 200:
|
||||||
guilds = guilds_response.json() # Store guilds in a variable
|
guilds = guilds_response.json() # Store guilds in a variable
|
||||||
@@ -109,16 +142,20 @@ def callback():
|
|||||||
# Fetch member count and permissions for each guild
|
# Fetch member count and permissions for each guild
|
||||||
for guild in guilds:
|
for guild in guilds:
|
||||||
guild_id = guild["id"]
|
guild_id = guild["id"]
|
||||||
|
try:
|
||||||
guild_info_response = requests.get(
|
guild_info_response = requests.get(
|
||||||
f"{DISCORD_API_BASE_URL}/guilds/{guild_id}",
|
f"{DISCORD_API_BASE_URL}/guilds/{guild_id}",
|
||||||
headers={"Authorization": f"Bearer {access_token}"},
|
headers={"Authorization": f"Bearer {access_token}"},
|
||||||
|
timeout=REQUEST_TIMEOUT,
|
||||||
)
|
)
|
||||||
if guild_info_response.status_code == 200:
|
guild_info_response.raise_for_status()
|
||||||
guild_info = guild_info_response.json()
|
guild_info = guild_info_response.json()
|
||||||
guild["approx_member_count"] = guild_info.get("member_count", "N/A")
|
guild["approx_member_count"] = guild_info.get("member_count", "N/A")
|
||||||
guild["permissions"] = guild_info.get(
|
guild["permissions"] = guild_info.get(
|
||||||
"permissions", 0
|
"permissions", 0
|
||||||
) # Store permissions
|
) # Store permissions
|
||||||
|
except requests.RequestException:
|
||||||
|
guild["approx_member_count"] = "N/A"
|
||||||
else:
|
else:
|
||||||
guild["approx_member_count"] = "N/A" # Fallback if unable to fetch
|
guild["approx_member_count"] = "N/A" # Fallback if unable to fetch
|
||||||
|
|
||||||
@@ -309,31 +346,38 @@ def guild_settings(guild_id):
|
|||||||
flash("You are not logged in.")
|
flash("You are not logged in.")
|
||||||
return redirect(url_for("login"))
|
return redirect(url_for("login"))
|
||||||
|
|
||||||
|
if not DISCORD_BOT_TOKEN:
|
||||||
|
flash("Bot token not configured on server; cannot fetch guild info.")
|
||||||
|
return redirect(url_for("home"))
|
||||||
|
|
||||||
bot_headers = {"Authorization": f"Bot {DISCORD_BOT_TOKEN}"}
|
bot_headers = {"Authorization": f"Bot {DISCORD_BOT_TOKEN}"}
|
||||||
|
try:
|
||||||
guild_info_response = requests.get(
|
guild_info_response = requests.get(
|
||||||
f"{DISCORD_API_BASE_URL}/guilds/{guild_id}?with_counts=true",
|
f"{DISCORD_API_BASE_URL}/guilds/{guild_id}?with_counts=true",
|
||||||
headers=bot_headers,
|
headers=bot_headers,
|
||||||
|
timeout=REQUEST_TIMEOUT,
|
||||||
)
|
)
|
||||||
|
guild_info_response.raise_for_status()
|
||||||
if guild_info_response.status_code != 200:
|
|
||||||
flash("Failed to retrieve guild information (bot may not be in this guild).")
|
|
||||||
return redirect(url_for("home"))
|
|
||||||
|
|
||||||
guild_info = guild_info_response.json()
|
guild_info = guild_info_response.json()
|
||||||
|
except requests.RequestException:
|
||||||
|
flash("Failed to retrieve guild information (bot may not be in this guild or network error).")
|
||||||
|
return redirect(url_for("home"))
|
||||||
owner_id = guild_info.get("owner_id", "N/A")
|
owner_id = guild_info.get("owner_id", "N/A")
|
||||||
member_count = guild_info.get("approximate_member_count", "N/A")
|
member_count = guild_info.get("approximate_member_count", "N/A")
|
||||||
|
|
||||||
# Fetch owner's username using the bot token
|
# Fetch owner's username using the bot token
|
||||||
owner_name = "Unknown"
|
owner_name = "Unknown"
|
||||||
if owner_id != "N/A":
|
if owner_id != "N/A":
|
||||||
|
try:
|
||||||
owner_response = requests.get(
|
owner_response = requests.get(
|
||||||
f"{DISCORD_API_BASE_URL}/users/{owner_id}",
|
f"{DISCORD_API_BASE_URL}/users/{owner_id}",
|
||||||
headers=bot_headers,
|
headers=bot_headers,
|
||||||
|
timeout=REQUEST_TIMEOUT,
|
||||||
)
|
)
|
||||||
if owner_response.status_code == 200:
|
owner_response.raise_for_status()
|
||||||
owner_data = owner_response.json()
|
owner_data = owner_response.json()
|
||||||
owner_name = f"{owner_data.get('username', 'Unknown')}#{owner_data.get('discriminator', '0000')}"
|
owner_name = f"{owner_data.get('username', 'Unknown')}#{owner_data.get('discriminator', '0000')}"
|
||||||
else:
|
except requests.RequestException:
|
||||||
owner_name = owner_id # fallback to ID if fetch fails
|
owner_name = owner_id # fallback to ID if fetch fails
|
||||||
json_formatted_str = json.dumps(guild_info, indent=2)
|
json_formatted_str = json.dumps(guild_info, indent=2)
|
||||||
|
|
||||||
@@ -360,4 +404,6 @@ def profile():
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
app.run(debug=True, port=5000, host="0.0.0.0")
|
# Running via the Flask development server for local testing.
|
||||||
|
# For production, run under a WSGI server (gunicorn, waitress, etc.).
|
||||||
|
app.run(debug=True, port=5000, host="0.0.0.0", use_reloader=False)
|
||||||
|
|||||||
Reference in New Issue
Block a user