Spaces:
Runtime error
Runtime error
Commit ·
f05ff3f
0
Parent(s):
Initial Deploy: Restructured root files and configured Git LFS
Browse files- .gitattributes +1 -0
- .gitignore +159 -0
- Dockerfile +15 -0
- Procfile +1 -0
- README.md +20 -0
- bot.py +696 -0
- bot_main.py +27 -0
- card_generator.py +163 -0
- commmands.txt +32 -0
- core.py +105 -0
- discloud.config +7 -0
- friendly_launcher.py +77 -0
- give_role_command.py +104 -0
- index.html +89 -0
- invite_bot.html +50 -0
- lineup_manager.py +245 -0
- login.html +22 -0
- logo.png +3 -0
- manual_lineup.py +59 -0
- network_fix.py +107 -0
- requirements.txt +11 -0
- server.py +198 -0
- servers.html +40 -0
- storage_manager.py +120 -0
- style.css +245 -0
.gitattributes
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
*.png filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Byte-compiled / optimized / DLL files
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.py[cod]
|
| 4 |
+
*$py.class
|
| 5 |
+
|
| 6 |
+
# C extensions
|
| 7 |
+
*.so
|
| 8 |
+
|
| 9 |
+
# Distribution / packaging
|
| 10 |
+
.Python
|
| 11 |
+
build/
|
| 12 |
+
develop-eggs/
|
| 13 |
+
dist/
|
| 14 |
+
downloads/
|
| 15 |
+
eggs/
|
| 16 |
+
.eggs/
|
| 17 |
+
lib/
|
| 18 |
+
lib64/
|
| 19 |
+
parts/
|
| 20 |
+
sdist/
|
| 21 |
+
var/
|
| 22 |
+
wheels/
|
| 23 |
+
share/python-wheels/
|
| 24 |
+
*.egg-info/
|
| 25 |
+
.installed.cfg
|
| 26 |
+
*.egg
|
| 27 |
+
MANIFEST
|
| 28 |
+
|
| 29 |
+
# PyInstaller
|
| 30 |
+
# Usually these files are written by a python script from a template
|
| 31 |
+
# before PyInstaller builds the exe, so may be deleted after.
|
| 32 |
+
*.manifest
|
| 33 |
+
*.spec
|
| 34 |
+
|
| 35 |
+
# Installer logs
|
| 36 |
+
pip-log.txt
|
| 37 |
+
pip-delete-this-directory.txt
|
| 38 |
+
|
| 39 |
+
# Unit test / coverage reports
|
| 40 |
+
htmlcov/
|
| 41 |
+
.tox/
|
| 42 |
+
.nox/
|
| 43 |
+
.coverage
|
| 44 |
+
.coverage.*
|
| 45 |
+
.cache
|
| 46 |
+
nosetests.xml
|
| 47 |
+
coverage.xml
|
| 48 |
+
*.cover
|
| 49 |
+
*.py,cover
|
| 50 |
+
.hypothesis/
|
| 51 |
+
.pytest_cache/
|
| 52 |
+
pytestdebuglog.txt
|
| 53 |
+
|
| 54 |
+
# Translations
|
| 55 |
+
*.mo
|
| 56 |
+
*.pot
|
| 57 |
+
|
| 58 |
+
# Django stuff:
|
| 59 |
+
*.log
|
| 60 |
+
local_settings.py
|
| 61 |
+
db.sqlite3
|
| 62 |
+
db.sqlite3-journal
|
| 63 |
+
|
| 64 |
+
# Flask stuff:
|
| 65 |
+
instance/
|
| 66 |
+
.webassets-cache
|
| 67 |
+
|
| 68 |
+
# Scrapy stuff:
|
| 69 |
+
.scrapy
|
| 70 |
+
|
| 71 |
+
# Sphinx documentation
|
| 72 |
+
docs/_build/
|
| 73 |
+
|
| 74 |
+
# PyBuilder
|
| 75 |
+
.pybuilder/
|
| 76 |
+
target/
|
| 77 |
+
|
| 78 |
+
# Jupyter Notebook
|
| 79 |
+
.ipynb_checkpoints
|
| 80 |
+
|
| 81 |
+
# IPython
|
| 82 |
+
profile_default/
|
| 83 |
+
ipython_config.py
|
| 84 |
+
|
| 85 |
+
# pyenv
|
| 86 |
+
# For a library or binary, you shouldn't ignore these files, but for a specific project, it's fine.
|
| 87 |
+
# .python-version
|
| 88 |
+
|
| 89 |
+
# pipenv
|
| 90 |
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
| 91 |
+
# However, in case of collaboration, if having platform-specific dependencies or experience issues with locking,
|
| 92 |
+
# then it is better to ignore Pipfile.lock
|
| 93 |
+
# Pipfile.lock
|
| 94 |
+
|
| 95 |
+
# poetry
|
| 96 |
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
| 97 |
+
# poetry.lock
|
| 98 |
+
|
| 99 |
+
# pdm
|
| 100 |
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
| 101 |
+
# .pdm-python.json
|
| 102 |
+
# pdm.lock
|
| 103 |
+
# .pdm-build/
|
| 104 |
+
|
| 105 |
+
# PEP 582; used by e.g. github.com/pdm-project/pdm
|
| 106 |
+
__pypackages__/
|
| 107 |
+
|
| 108 |
+
# Celery stuff
|
| 109 |
+
celerybeat-schedule
|
| 110 |
+
celerybeat.pid
|
| 111 |
+
|
| 112 |
+
# SageMath parsed files
|
| 113 |
+
*.sage.py
|
| 114 |
+
|
| 115 |
+
# Environments
|
| 116 |
+
.env
|
| 117 |
+
.venv
|
| 118 |
+
env/
|
| 119 |
+
venv/
|
| 120 |
+
ENV/
|
| 121 |
+
env.bak/
|
| 122 |
+
venv.bak/
|
| 123 |
+
|
| 124 |
+
# Spyder project settings
|
| 125 |
+
.spyderproject
|
| 126 |
+
.spyder-py3
|
| 127 |
+
|
| 128 |
+
# Rope project settings
|
| 129 |
+
.ropeproject
|
| 130 |
+
|
| 131 |
+
# mkdocs documentation
|
| 132 |
+
/site
|
| 133 |
+
|
| 134 |
+
# mypy
|
| 135 |
+
.mypy_cache/
|
| 136 |
+
.dmypy.json
|
| 137 |
+
dmypy.json
|
| 138 |
+
|
| 139 |
+
# Pyre type checker
|
| 140 |
+
.pyre/
|
| 141 |
+
|
| 142 |
+
# pytype static type analyzer
|
| 143 |
+
.pytype/
|
| 144 |
+
|
| 145 |
+
# Cython debug symbols
|
| 146 |
+
cython_debug/
|
| 147 |
+
|
| 148 |
+
# PyCharm
|
| 149 |
+
.idea/
|
| 150 |
+
|
| 151 |
+
# VS Code
|
| 152 |
+
.vscode/
|
| 153 |
+
|
| 154 |
+
# Project Specific
|
| 155 |
+
data/
|
| 156 |
+
*.lock
|
| 157 |
+
logs/
|
| 158 |
+
temp/
|
| 159 |
+
scratch/
|
Dockerfile
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.9
|
| 2 |
+
|
| 3 |
+
RUN useradd -m -u 1000 user
|
| 4 |
+
USER user
|
| 5 |
+
ENV PATH="/home/user/.local/bin:${PATH}"
|
| 6 |
+
|
| 7 |
+
WORKDIR /app
|
| 8 |
+
|
| 9 |
+
COPY --chown=user requirements.txt .
|
| 10 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 11 |
+
|
| 12 |
+
COPY --chown=user . .
|
| 13 |
+
|
| 14 |
+
ENV PORT=7860
|
| 15 |
+
CMD ["python", "server.py"]
|
Procfile
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
web: gunicorn -w 1 server:app
|
README.md
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: SentryNode / Lineup Bot
|
| 3 |
+
emoji: 🤖
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: green
|
| 6 |
+
sdk: docker
|
| 7 |
+
pinned: false
|
| 8 |
+
---
|
| 9 |
+
|
| 10 |
+
This repository contains a Flask wrapper and Discord bot for use with a Docker-based Hugging Face Space.
|
| 11 |
+
|
| 12 |
+
The Discord bot startup is now isolated in `bot_runner.py`, so the bot runtime is kept separate from the web app and other code.
|
| 13 |
+
|
| 14 |
+
A dedicated supervisor is now included in `bot_supervisor.py`, which keeps the bot running and automatically restarts it whenever the code changes or the bot process stops.
|
| 15 |
+
|
| 16 |
+
When `server.py` is launched as the application entrypoint, it starts `bot_supervisor.py` automatically, so the bot will come online without manual startup.
|
| 17 |
+
|
| 18 |
+
If you want to run the bot directly in a standalone environment, use `python bot_supervisor.py`.
|
| 19 |
+
|
| 20 |
+
Use the root `server.py` as the app entrypoint. If you want to deploy the new bot instead, place its files at the repository root or use a separate Space repository.
|
bot.py
ADDED
|
@@ -0,0 +1,696 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
from collections import deque
|
| 3 |
+
import datetime
|
| 4 |
+
import io
|
| 5 |
+
import os
|
| 6 |
+
import asyncio
|
| 7 |
+
import discord
|
| 8 |
+
from discord.ext import commands
|
| 9 |
+
|
| 10 |
+
# Import from core first!
|
| 11 |
+
import core
|
| 12 |
+
from core import bot, BOT_TOKEN, user_has_lineup_access, respond_or_send, reset_async_state
|
| 13 |
+
|
| 14 |
+
# Other modules
|
| 15 |
+
from storage_manager import StorageManager
|
| 16 |
+
from lineup_manager import (
|
| 17 |
+
LineupView, FORMATIONS, format_lineup,
|
| 18 |
+
managerlineup, ManagerLineupView
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
import manual_lineup
|
| 22 |
+
import give_role_command
|
| 23 |
+
|
| 24 |
+
from core import (
|
| 25 |
+
guild_lineup_queues, guild_selected_formation,
|
| 26 |
+
lineup_lock, counted_stats_per_message
|
| 27 |
+
)
|
| 28 |
+
from card_generator import CardGenerator, LineupGenerator
|
| 29 |
+
|
| 30 |
+
# --- CUSTOMIZATION ---
|
| 31 |
+
TIME_OFFSET = 3
|
| 32 |
+
LOG_CHANNEL_ID = 1495044946107961364
|
| 33 |
+
# ---------------------
|
| 34 |
+
|
| 35 |
+
# --- Duplicate Instance Prevention ---
|
| 36 |
+
LOCK_FILE = "data/bot.lock"
|
| 37 |
+
def acquire_lock():
|
| 38 |
+
if os.path.exists(LOCK_FILE):
|
| 39 |
+
try:
|
| 40 |
+
with open(LOCK_FILE, "r") as f:
|
| 41 |
+
old_pid = int(f.read().strip())
|
| 42 |
+
if old_pid == os.getpid(): return
|
| 43 |
+
os.kill(old_pid, 0)
|
| 44 |
+
except (OSError, ValueError, ProcessLookupError): pass
|
| 45 |
+
try:
|
| 46 |
+
with open(LOCK_FILE, "w") as f: f.write(str(os.getpid()))
|
| 47 |
+
except Exception: pass
|
| 48 |
+
acquire_lock()
|
| 49 |
+
|
| 50 |
+
# Initialize storage and link back to core
|
| 51 |
+
storage = StorageManager(bot)
|
| 52 |
+
storage.load_all_local()
|
| 53 |
+
core.storage = storage
|
| 54 |
+
|
| 55 |
+
# Global cooldown removed for better responsiveness
|
| 56 |
+
|
| 57 |
+
# --- Utilities ---
|
| 58 |
+
def parse_time_to_timestamp(time_str: str) -> int:
|
| 59 |
+
now_utc = datetime.datetime.now(datetime.timezone.utc)
|
| 60 |
+
match = re.match(r"(\d{1,2})\s*(am|pm|AM|PM)", time_str)
|
| 61 |
+
if match:
|
| 62 |
+
h = int(match.group(1))
|
| 63 |
+
if match.group(2).lower() == "pm" and h != 12: h += 12
|
| 64 |
+
elif match.group(2).lower() == "am" and h == 12: h = 0
|
| 65 |
+
dt = now_utc.replace(hour=h, minute=0, second=0, microsecond=0)
|
| 66 |
+
if (h < (now_utc.hour + TIME_OFFSET) % 24): dt += datetime.timedelta(days=1)
|
| 67 |
+
return int((dt - datetime.timedelta(hours=TIME_OFFSET)).timestamp())
|
| 68 |
+
return None
|
| 69 |
+
|
| 70 |
+
# State
|
| 71 |
+
# --- State Management (Persistent) ---
|
| 72 |
+
# Transitioned to storage.processed_messages and storage.active_polls
|
| 73 |
+
|
| 74 |
+
# --- UI Components ---
|
| 75 |
+
class SettingsDropdown(discord.ui.Select):
|
| 76 |
+
def __init__(self, guild_id):
|
| 77 |
+
s = storage.guild_settings.get(guild_id, {})
|
| 78 |
+
options = [
|
| 79 |
+
discord.SelectOption(label="Welcome Messages", value="toggle_welcome", emoji="👋"),
|
| 80 |
+
discord.SelectOption(label="Goodbye Messages", value="toggle_goodbye", emoji="🚪"),
|
| 81 |
+
discord.SelectOption(label="Disable Automation", value="disable", emoji="❌")
|
| 82 |
+
]
|
| 83 |
+
super().__init__(placeholder="Configure automation...", options=options)
|
| 84 |
+
async def callback(self, interaction: discord.Interaction):
|
| 85 |
+
gid = interaction.guild.id
|
| 86 |
+
s = storage.guild_settings.setdefault(gid, {"welcome_enabled": False, "goodbye_enabled": False})
|
| 87 |
+
val = self.values[0]
|
| 88 |
+
if val == "toggle_welcome": s["welcome_enabled"] = not s["welcome_enabled"]; s["welcome_channel"] = interaction.channel_id
|
| 89 |
+
elif val == "toggle_goodbye": s["goodbye_enabled"] = not s["goodbye_enabled"]; s["goodbye_channel"] = interaction.channel_id
|
| 90 |
+
else: s["welcome_enabled"] = s["goodbye_enabled"] = False
|
| 91 |
+
storage.save_settings(); await storage.backup_to_discord(); await interaction.response.send_message("✅ Updated!", ephemeral=True)
|
| 92 |
+
|
| 93 |
+
# --- Commands ---
|
| 94 |
+
@bot.bridge_command(name="lineup")
|
| 95 |
+
async def lineup(ctx):
|
| 96 |
+
"""Admin/Staff: Create a new interactive lineup form."""
|
| 97 |
+
if not user_has_lineup_access(ctx.author): return await respond_or_send(ctx, "❌ Access Denied")
|
| 98 |
+
for q in guild_lineup_queues[ctx.guild.id].values(): q.clear()
|
| 99 |
+
await respond_or_send(ctx, f"@everyone\n**Lineup ({guild_selected_formation[ctx.guild.id]})**\n\n{format_lineup(ctx.guild.id)}", view=LineupView(ctx.guild.id), allowed_mentions=discord.AllowedMentions(everyone=True))
|
| 100 |
+
|
| 101 |
+
@bot.bridge_command(name="addrole")
|
| 102 |
+
@commands.has_permissions(administrator=True)
|
| 103 |
+
async def addrole(ctx, role: discord.Role):
|
| 104 |
+
"""Admin Only: Add a role that is allowed to use bot commands."""
|
| 105 |
+
storage.lineup_roles.setdefault(ctx.guild.id, set()).add(role.id)
|
| 106 |
+
storage.save_roles(); await storage.backup_to_discord(); await respond_or_send(ctx, f"✅ Added {role.mention}")
|
| 107 |
+
|
| 108 |
+
@bot.bridge_command(name="removerole")
|
| 109 |
+
@commands.has_permissions(administrator=True)
|
| 110 |
+
async def removerole(ctx, role: discord.Role):
|
| 111 |
+
"""Admin Only: Revoke a role's bot permission."""
|
| 112 |
+
if ctx.guild.id in storage.lineup_roles: storage.lineup_roles[ctx.guild.id].discard(role.id)
|
| 113 |
+
storage.save_roles(); await storage.backup_to_discord(); await respond_or_send(ctx, f"❌ Removed {role.mention}")
|
| 114 |
+
|
| 115 |
+
@bot.bridge_command(name="profile")
|
| 116 |
+
async def profile(ctx, member: discord.Member = None):
|
| 117 |
+
"""View a player's visual FIFA-style profile card."""
|
| 118 |
+
t = member or ctx.author
|
| 119 |
+
s = storage.player_stats.get(t.id, {"matches": 0, "positions": {}})
|
| 120 |
+
m = s["matches"]
|
| 121 |
+
f_pos = max(s["positions"], key=s["positions"].get) if s["positions"] else "None"
|
| 122 |
+
wait_msg = await respond_or_send(ctx, f"🎨 **Generating {t.display_name}'s Card...**")
|
| 123 |
+
card_bytes = await CardGenerator.create_profile_card(t.display_name, m, f_pos, t.display_avatar.url)
|
| 124 |
+
await respond_or_send(ctx, file=discord.File(fp=card_bytes, filename=f"card_{t.id}.png"))
|
| 125 |
+
await wait_msg.delete()
|
| 126 |
+
|
| 127 |
+
@bot.bridge_command(name="friendly")
|
| 128 |
+
async def friendly(ctx, reactions_needed: int = 7):
|
| 129 |
+
"""Admin/Staff: Start a Friendly Match session."""
|
| 130 |
+
if not user_has_lineup_access(ctx.author): return await respond_or_send(ctx, "❌ No permission")
|
| 131 |
+
content = f"⭐▬▬▬▬▬ **FRIENDLY** ▬▬▬▬▬⭐\n🤝 Session\n🟩 I'm In\n🟥 Busy\n⭐▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬⭐\n🗳️ Needed: {reactions_needed}\n@everyone"
|
| 132 |
+
msg = await respond_or_send(ctx, content, allowed_mentions=discord.AllowedMentions(everyone=True))
|
| 133 |
+
if msg:
|
| 134 |
+
storage.active_polls[ctx.guild.id] = msg.id
|
| 135 |
+
storage.save_state()
|
| 136 |
+
await msg.add_reaction("🟩"); await msg.add_reaction("🟥")
|
| 137 |
+
|
| 138 |
+
@bot.bridge_command(name="leaguematch")
|
| 139 |
+
async def leaguematch(ctx, home: str, away: str, link: str, time: str = None):
|
| 140 |
+
"""Schedule a professional league match."""
|
| 141 |
+
if not user_has_lineup_access(ctx.author): return await respond_or_send(ctx, "❌ No permission")
|
| 142 |
+
t = parse_time_to_timestamp(time)
|
| 143 |
+
ts = f"\n🕒 **Time**: <t:{t}:F> (<t:{t}:R>)" if t else ""
|
| 144 |
+
content = f"⭐▬▬ 🏆 **LEAGUE MATCH** 🏆 ▬▬⭐\n🏟️ {home} vs {away}\n🔗 {link}\n🤝 Session{ts}\n⭐▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬⭐\n@everyone"
|
| 145 |
+
if ctx.message:
|
| 146 |
+
try: await ctx.message.add_reaction("🏆")
|
| 147 |
+
except: pass
|
| 148 |
+
msg = await respond_or_send(ctx, content, allowed_mentions=discord.AllowedMentions(everyone=True))
|
| 149 |
+
if msg:
|
| 150 |
+
storage.active_polls[ctx.guild.id] = msg.id
|
| 151 |
+
storage.save_state()
|
| 152 |
+
await msg.add_reaction("🟩"); await msg.add_reaction("🟥")
|
| 153 |
+
|
| 154 |
+
@bot.bridge_command(name="sendlink")
|
| 155 |
+
async def sendlink(ctx, *, link: str):
|
| 156 |
+
"""Send a link publicly in the current channel."""
|
| 157 |
+
if not user_has_lineup_access(ctx.author):
|
| 158 |
+
return await respond_or_send(ctx, "❌ No permission")
|
| 159 |
+
await respond_or_send(ctx, f"Link : {link}")
|
| 160 |
+
|
| 161 |
+
@bot.bridge_command(name="setup")
|
| 162 |
+
@commands.has_permissions(administrator=True)
|
| 163 |
+
async def setup(ctx):
|
| 164 |
+
"""Admin Only: Configure server settings."""
|
| 165 |
+
view = discord.ui.View()
|
| 166 |
+
view.add_item(SettingsDropdown(ctx.guild.id))
|
| 167 |
+
await respond_or_send(ctx, "⚙️ **Settings**", view=view)
|
| 168 |
+
|
| 169 |
+
@bot.bridge_command(name="friendlybotsettings")
|
| 170 |
+
async def friendlybotsettings(ctx):
|
| 171 |
+
"""Owner/Staff: Check status and allowed roles."""
|
| 172 |
+
if not user_has_lineup_access(ctx.author):
|
| 173 |
+
return await respond_or_send(ctx, "❌ No permission")
|
| 174 |
+
roles = storage.lineup_roles.get(ctx.guild.id, set())
|
| 175 |
+
r_info = ", ".join([f"<@&{r}>" for r in roles]) if roles else "Only owner."
|
| 176 |
+
await respond_or_send(ctx, f"🟢 **Online**\nAllowed: {r_info}")
|
| 177 |
+
|
| 178 |
+
@bot.bridge_command(name="reboot")
|
| 179 |
+
@commands.is_owner()
|
| 180 |
+
async def reboot(ctx):
|
| 181 |
+
"""Owner Only: Restart the bot."""
|
| 182 |
+
await respond_or_send(ctx, "🔄 Rebooting..."); import os; os._exit(0)
|
| 183 |
+
|
| 184 |
+
@bot.bridge_command(name="sync")
|
| 185 |
+
async def sync(ctx):
|
| 186 |
+
"""Admin Only: Manually sync slash commands with Discord."""
|
| 187 |
+
if not user_has_lineup_access(ctx.author): return await respond_or_send(ctx, "❌ No permission")
|
| 188 |
+
msg = await respond_or_send(ctx, "🔄 **Syncing commands...** (This can take up to 30 seconds)")
|
| 189 |
+
try:
|
| 190 |
+
await bot.sync_commands()
|
| 191 |
+
if msg: await msg.edit(content="✅ **Commands Synced Successfully!**")
|
| 192 |
+
else: await respond_or_send(ctx, "✅ **Commands Synced Successfully!**")
|
| 193 |
+
except Exception as e:
|
| 194 |
+
err_msg = f"❌ **Sync Failed**: {e}"
|
| 195 |
+
if msg: await msg.edit(content=err_msg)
|
| 196 |
+
else: await respond_or_send(ctx, err_msg)
|
| 197 |
+
|
| 198 |
+
@bot.bridge_command(name="ping")
|
| 199 |
+
async def ping(ctx): await respond_or_send(ctx, f"🏓 {round(bot.latency * 1000)}ms")
|
| 200 |
+
|
| 201 |
+
@bot.bridge_command(name="uptime")
|
| 202 |
+
async def uptime(ctx):
|
| 203 |
+
delta = datetime.datetime.now(datetime.timezone.utc) - bot.start_time
|
| 204 |
+
s = int(delta.total_seconds())
|
| 205 |
+
m, s = divmod(s, 60); h, m = divmod(m, 60); d, h = divmod(h, 24)
|
| 206 |
+
await respond_or_send(ctx, f"⏱️ **Uptime**: {d}d {h}h {m}m {s}s")
|
| 207 |
+
|
| 208 |
+
async def get_guild_invite_link(guild):
|
| 209 |
+
"""Helper to get or create a join link for a guild."""
|
| 210 |
+
try:
|
| 211 |
+
invites = await guild.invites()
|
| 212 |
+
if invites:
|
| 213 |
+
return invites[0].url
|
| 214 |
+
# Find a suitable text channel to create an invite from
|
| 215 |
+
channel = guild.system_channel or next((c for c in guild.text_channels if c.permissions_for(guild.me).create_instant_invite), None)
|
| 216 |
+
if channel:
|
| 217 |
+
invite = await channel.create_invite(max_age=0, max_uses=0, reason="FriendlyBot Utility Link")
|
| 218 |
+
return invite.url
|
| 219 |
+
except:
|
| 220 |
+
pass
|
| 221 |
+
return None
|
| 222 |
+
|
| 223 |
+
@bot.bridge_command(name="servers")
|
| 224 |
+
@commands.is_owner()
|
| 225 |
+
async def servers(ctx):
|
| 226 |
+
"""Owner Only: Show how many servers the bot is in with join links."""
|
| 227 |
+
# Sort guilds by member count (most to least)
|
| 228 |
+
guild_list = sorted(bot.guilds, key=lambda g: g.member_count or 0, reverse=True)
|
| 229 |
+
count = len(guild_list)
|
| 230 |
+
lines = []
|
| 231 |
+
|
| 232 |
+
# Optional message for wait if there are many servers
|
| 233 |
+
wait_msg = None
|
| 234 |
+
if count > 5:
|
| 235 |
+
wait_msg = await respond_or_send(ctx, "⏳ *Sorting and fetching links for all servers...*")
|
| 236 |
+
|
| 237 |
+
for i, g in enumerate(guild_list, 1):
|
| 238 |
+
members = g.member_count or len(g.members) or 0
|
| 239 |
+
invite_url = await get_guild_invite_link(g)
|
| 240 |
+
guild_display = f"[{g.name}]({invite_url})" if invite_url else g.name
|
| 241 |
+
lines.append(f"**{i}.** {guild_display} — `{members}` members")
|
| 242 |
+
|
| 243 |
+
description = "\n".join(lines) if lines else "No servers."
|
| 244 |
+
embed = discord.Embed(
|
| 245 |
+
title=f"🌐 Serving {count} Server{'s' if count != 1 else ''}",
|
| 246 |
+
description=description,
|
| 247 |
+
color=0x5865F2
|
| 248 |
+
)
|
| 249 |
+
embed.set_footer(text=f"Total servers: {count}")
|
| 250 |
+
|
| 251 |
+
if wait_msg:
|
| 252 |
+
await wait_msg.edit(content=None, embed=embed)
|
| 253 |
+
else:
|
| 254 |
+
await respond_or_send(ctx, embed=embed)
|
| 255 |
+
|
| 256 |
+
@bot.bridge_command(name="post")
|
| 257 |
+
@commands.is_owner()
|
| 258 |
+
async def post(ctx, *, message: str):
|
| 259 |
+
"""Owner Only: Broadcast a message to all servers the bot is in."""
|
| 260 |
+
await respond_or_send(ctx, f"⏳ **Broadcasting to {len(bot.guilds)} servers...**")
|
| 261 |
+
|
| 262 |
+
success = 0
|
| 263 |
+
failed = 0
|
| 264 |
+
|
| 265 |
+
for guild in bot.guilds:
|
| 266 |
+
# 1. Try to find the best channel
|
| 267 |
+
target_channel = None
|
| 268 |
+
|
| 269 |
+
# High priority: System channel (usually the #general or welcome channel)
|
| 270 |
+
if guild.system_channel and guild.system_channel.permissions_for(guild.me).send_messages:
|
| 271 |
+
target_channel = guild.system_channel
|
| 272 |
+
|
| 273 |
+
# Medium priority: Public updates channel
|
| 274 |
+
if not target_channel and guild.public_updates_channel and guild.public_updates_channel.permissions_for(guild.me).send_messages:
|
| 275 |
+
target_channel = guild.public_updates_channel
|
| 276 |
+
|
| 277 |
+
# Low priority: First text channel we can talk in
|
| 278 |
+
if not target_channel:
|
| 279 |
+
target_channel = next((c for c in guild.text_channels if c.permissions_for(guild.me).send_messages), None)
|
| 280 |
+
|
| 281 |
+
if target_channel:
|
| 282 |
+
try:
|
| 283 |
+
await target_channel.send(message)
|
| 284 |
+
success += 1
|
| 285 |
+
# Small delay to prevent hitting global rate limits if in hundreds of servers
|
| 286 |
+
await asyncio.sleep(0.1)
|
| 287 |
+
except Exception:
|
| 288 |
+
failed += 1
|
| 289 |
+
else:
|
| 290 |
+
failed += 1
|
| 291 |
+
|
| 292 |
+
await respond_or_send(ctx, f"✅ **Broadcast Complete!**\n📦 **Success**: {success}\n❌ **Failed**: {failed}")
|
| 293 |
+
|
| 294 |
+
# --- COMPETITIVE STATS ---
|
| 295 |
+
@bot.bridge_command(name="top")
|
| 296 |
+
async def top(ctx):
|
| 297 |
+
"""View the Top 10 most active players in the server."""
|
| 298 |
+
stats = storage.player_stats
|
| 299 |
+
if not stats: return await respond_or_send(ctx, "❌ No match data recorded yet.")
|
| 300 |
+
|
| 301 |
+
# Sort members by match count
|
| 302 |
+
sorted_players = sorted(stats.items(), key=lambda x: x[1].get("matches", 0), reverse=True)[:10]
|
| 303 |
+
|
| 304 |
+
embed = discord.Embed(title="🏆 Most Active Players", color=0xFFD700)
|
| 305 |
+
lines = []
|
| 306 |
+
for i, (user_id, data) in enumerate(sorted_players, 1):
|
| 307 |
+
member = ctx.guild.get_member(user_id)
|
| 308 |
+
name = member.display_name if member else f"ID: {user_id}"
|
| 309 |
+
lines.append(f"**#{i}** {name} — `{data.get('matches', 0)}` matches | ⚽ `{data.get('goals', 0)}` goals")
|
| 310 |
+
|
| 311 |
+
embed.description = "\n".join(lines)
|
| 312 |
+
await respond_or_send(ctx, embed=embed)
|
| 313 |
+
|
| 314 |
+
@bot.bridge_command(name="record")
|
| 315 |
+
async def record(ctx):
|
| 316 |
+
"""View the global server Win/Loss/Draw record."""
|
| 317 |
+
settings = storage.guild_settings.setdefault(ctx.guild.id, {})
|
| 318 |
+
wins = settings.get("wins", 0)
|
| 319 |
+
losses = settings.get("losses", 0)
|
| 320 |
+
draws = settings.get("draws", 0)
|
| 321 |
+
|
| 322 |
+
embed = discord.Embed(title="📊 Server Record", color=0x5865F2)
|
| 323 |
+
embed.add_field(name="✅ Wins", value=f"`{wins}`")
|
| 324 |
+
embed.add_field(name="🟥 Losses", value=f"`{losses}`")
|
| 325 |
+
embed.add_field(name="🤝 Draws", value=f"`{draws}`")
|
| 326 |
+
|
| 327 |
+
total = wins + losses + draws
|
| 328 |
+
win_rate = (wins / total * 100) if total > 0 else 0
|
| 329 |
+
embed.set_footer(text=f"Total Matches: {total} | Win Rate: {win_rate:.1f}%")
|
| 330 |
+
await respond_or_send(ctx, embed=embed)
|
| 331 |
+
|
| 332 |
+
def process_scorers(scorers_str):
|
| 333 |
+
"""Parses 'User 1 Goal, User2 2 Goals' and returns (clean_text, goal_map)."""
|
| 334 |
+
if not scorers_str:
|
| 335 |
+
return "None", {}
|
| 336 |
+
|
| 337 |
+
parts = [p.strip() for p in scorers_str.split(',')]
|
| 338 |
+
clean_lines = []
|
| 339 |
+
goal_map = {}
|
| 340 |
+
|
| 341 |
+
for p in parts:
|
| 342 |
+
if not p: continue
|
| 343 |
+
# Find mention
|
| 344 |
+
match = re.search(r'<@!?(\d+)>', p)
|
| 345 |
+
if match:
|
| 346 |
+
uid = int(match.group(1))
|
| 347 |
+
# Find first number in the remainder
|
| 348 |
+
remainder = p.replace(match.group(0), '')
|
| 349 |
+
num_match = re.search(r'(\d+)', remainder)
|
| 350 |
+
goals = int(num_match.group(1)) if num_match else 1
|
| 351 |
+
goal_map[uid] = goals
|
| 352 |
+
clean_lines.append(p)
|
| 353 |
+
|
| 354 |
+
return "\n".join(clean_lines), goal_map
|
| 355 |
+
|
| 356 |
+
@bot.bridge_command(name="win")
|
| 357 |
+
async def win(ctx, result: str, *, scorers: str = ""):
|
| 358 |
+
"""Record a match victory with result and scorers."""
|
| 359 |
+
if not user_has_lineup_access(ctx.author): return
|
| 360 |
+
settings = storage.guild_settings.setdefault(ctx.guild.id, {})
|
| 361 |
+
settings["wins"] = settings.get("wins", 0) + 1
|
| 362 |
+
|
| 363 |
+
clean_scorers, goal_map = process_scorers(scorers)
|
| 364 |
+
for uid, count in goal_map.items():
|
| 365 |
+
stats = storage.player_stats.setdefault(uid, {"matches": 0, "positions": {}, "goals": 0})
|
| 366 |
+
stats["goals"] = stats.get("goals", 0) + count
|
| 367 |
+
|
| 368 |
+
storage.save_settings(); storage.save_stats()
|
| 369 |
+
|
| 370 |
+
content = f"⭐▬▬▬▬▬ **VICTORY RECORDED** ▬▬▬▬▬⭐\n🏟️ **Result**: {result}\n\n⚽ **Scorers**:\n{clean_scorers}\n\n⭐▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬⭐\n@everyone"
|
| 371 |
+
await respond_or_send(ctx, content, allowed_mentions=discord.AllowedMentions(everyone=True))
|
| 372 |
+
|
| 373 |
+
@bot.bridge_command(name="loss")
|
| 374 |
+
async def loss(ctx, result: str, *, scorers: str = ""):
|
| 375 |
+
"""Record a match defeat."""
|
| 376 |
+
if not user_has_lineup_access(ctx.author): return
|
| 377 |
+
settings = storage.guild_settings.setdefault(ctx.guild.id, {})
|
| 378 |
+
settings["losses"] = settings.get("losses", 0) + 1
|
| 379 |
+
|
| 380 |
+
clean_scorers, goal_map = process_scorers(scorers)
|
| 381 |
+
for uid, count in goal_map.items():
|
| 382 |
+
stats = storage.player_stats.setdefault(uid, {"matches": 0, "positions": {}, "goals": 0})
|
| 383 |
+
stats["goals"] = stats.get("goals", 0) + count
|
| 384 |
+
|
| 385 |
+
storage.save_settings(); storage.save_stats()
|
| 386 |
+
|
| 387 |
+
content = f"⭐▬▬▬▬▬ **LOSS RECORDED** ▬▬▬▬▬⭐\n🏟️ **Result**: {result}\n\n⚽ **Scorers**:\n{clean_scorers}\n\n⭐▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬⭐\n@everyone"
|
| 388 |
+
await respond_or_send(ctx, content, allowed_mentions=discord.AllowedMentions(everyone=True))
|
| 389 |
+
|
| 390 |
+
@bot.bridge_command(name="draw")
|
| 391 |
+
async def draw(ctx, result: str, *, scorers: str = ""):
|
| 392 |
+
"""Record a draw."""
|
| 393 |
+
if not user_has_lineup_access(ctx.author): return
|
| 394 |
+
settings = storage.guild_settings.setdefault(ctx.guild.id, {})
|
| 395 |
+
settings["draws"] = settings.get("draws", 0) + 1
|
| 396 |
+
|
| 397 |
+
clean_scorers, goal_map = process_scorers(scorers)
|
| 398 |
+
for uid, count in goal_map.items():
|
| 399 |
+
stats = storage.player_stats.setdefault(uid, {"matches": 0, "positions": {}, "goals": 0})
|
| 400 |
+
stats["goals"] = stats.get("goals", 0) + count
|
| 401 |
+
|
| 402 |
+
storage.save_settings(); storage.save_stats()
|
| 403 |
+
|
| 404 |
+
content = f"⭐▬▬▬▬▬ **DRAW RECORDED** ▬▬▬▬▬⭐\n🏟️ **Result**: {result}\n\n⚽ **Scorers**:\n{clean_scorers}\n\n⭐▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬⭐\n@everyone"
|
| 405 |
+
await respond_or_send(ctx, content, allowed_mentions=discord.AllowedMentions(everyone=True))
|
| 406 |
+
|
| 407 |
+
# --- Logging & Events ---
|
| 408 |
+
async def log_command(ctx_or_inter, command_name, status="Success"):
|
| 409 |
+
user = getattr(ctx_or_inter, "author", getattr(ctx_or_inter, "user", "Unknown"))
|
| 410 |
+
guild = getattr(ctx_or_inter, "guild", None)
|
| 411 |
+
|
| 412 |
+
# Immediate console print as requested
|
| 413 |
+
if status == "Invoked":
|
| 414 |
+
print(f"🏃 Command Call: {command_name} | User: {user} | Server: {guild.name if guild else 'DM'}")
|
| 415 |
+
elif status == "Error":
|
| 416 |
+
print(f"❌ Command Error: {command_name} | User: {user} | Server: {guild.name if guild else 'DM'}")
|
| 417 |
+
|
| 418 |
+
# We only send to the Discord Log Channel on Success/Error (to keep it clean)
|
| 419 |
+
if status == "Invoked": return
|
| 420 |
+
|
| 421 |
+
try:
|
| 422 |
+
log_channel = bot.get_channel(LOG_CHANNEL_ID)
|
| 423 |
+
if not log_channel: return
|
| 424 |
+
|
| 425 |
+
embed = discord.Embed(
|
| 426 |
+
title=f"📜 Log ({status})",
|
| 427 |
+
color=0x5865F2 if status == "Success" else 0xE74C3C,
|
| 428 |
+
timestamp=datetime.datetime.now()
|
| 429 |
+
)
|
| 430 |
+
embed.add_field(name="Cmd", value=f"`/{command_name}`")
|
| 431 |
+
embed.add_field(name="User", value=f"{user}")
|
| 432 |
+
|
| 433 |
+
# Show server name with invite link
|
| 434 |
+
if not guild:
|
| 435 |
+
guild_id = getattr(ctx_or_inter, "guild_id", None)
|
| 436 |
+
if guild_id:
|
| 437 |
+
guild = bot.get_guild(guild_id) or await bot.fetch_guild(guild_id)
|
| 438 |
+
|
| 439 |
+
if guild:
|
| 440 |
+
name = getattr(guild, "name", f"Server ID: {guild.id}")
|
| 441 |
+
invite_url = await get_guild_invite_link(guild)
|
| 442 |
+
guild_value = f"[{name}]({invite_url})" if invite_url else name
|
| 443 |
+
else:
|
| 444 |
+
guild_value = "DM"
|
| 445 |
+
|
| 446 |
+
embed.add_field(name="Server", value=guild_value)
|
| 447 |
+
await log_channel.send(embed=embed)
|
| 448 |
+
except Exception as e:
|
| 449 |
+
print(f"DEBUG: Logging error: {e}", flush=True)
|
| 450 |
+
|
| 451 |
+
@bot.event
|
| 452 |
+
async def on_command(ctx):
|
| 453 |
+
# Print when a prefix command is typed
|
| 454 |
+
await log_command(ctx, ctx.command.name, "Invoked")
|
| 455 |
+
|
| 456 |
+
@bot.event
|
| 457 |
+
async def on_application_command(ctx):
|
| 458 |
+
# Print when a slash command is used
|
| 459 |
+
await log_command(ctx, ctx.command.name, "Invoked")
|
| 460 |
+
|
| 461 |
+
@bot.event
|
| 462 |
+
async def on_command_completion(ctx):
|
| 463 |
+
await log_command(ctx, ctx.command.name, "Success")
|
| 464 |
+
|
| 465 |
+
@bot.event
|
| 466 |
+
async def on_application_command_completion(ctx):
|
| 467 |
+
await log_command(ctx, ctx.command.name, "Success")
|
| 468 |
+
|
| 469 |
+
@bot.event
|
| 470 |
+
async def on_command_error(ctx, error):
|
| 471 |
+
if isinstance(error, commands.CommandNotFound):
|
| 472 |
+
return
|
| 473 |
+
|
| 474 |
+
# Print what's wrong to console
|
| 475 |
+
print(f"⚠️ Command Error ({ctx.command}): {error}")
|
| 476 |
+
await log_command(ctx, str(ctx.command), "Error")
|
| 477 |
+
|
| 478 |
+
# Show user what's wrong in Discord
|
| 479 |
+
error_msg = str(error)
|
| 480 |
+
if isinstance(error, commands.CommandInvokeError):
|
| 481 |
+
error_msg = str(error.original)
|
| 482 |
+
|
| 483 |
+
try:
|
| 484 |
+
await respond_or_send(ctx, f"❌ **Error**: `{error_msg}`", ephemeral=True)
|
| 485 |
+
except:
|
| 486 |
+
pass
|
| 487 |
+
|
| 488 |
+
@bot.event
|
| 489 |
+
async def on_application_command_error(ctx, error):
|
| 490 |
+
# Handle slash command errors specifically
|
| 491 |
+
print(f"⚠️ Slash Error ({ctx.command}): {error}")
|
| 492 |
+
await log_command(ctx, str(ctx.command), "Error")
|
| 493 |
+
|
| 494 |
+
error_msg = str(error)
|
| 495 |
+
if hasattr(error, "original"):
|
| 496 |
+
error_msg = str(error.original)
|
| 497 |
+
|
| 498 |
+
try:
|
| 499 |
+
await respond_or_send(ctx, f"❌ **Slash Error**: `{error_msg}`", ephemeral=True)
|
| 500 |
+
except:
|
| 501 |
+
pass
|
| 502 |
+
|
| 503 |
+
@bot.bridge_command(name="lineupimage")
|
| 504 |
+
async def lineupimage(ctx):
|
| 505 |
+
"""Generate a high-quality visual of the current starting lineup."""
|
| 506 |
+
gid = ctx.guild.id
|
| 507 |
+
form_key = guild_selected_formation[gid]
|
| 508 |
+
formation = FORMATIONS.get(form_key, FORMATIONS["default"])
|
| 509 |
+
qs = guild_lineup_queues[gid]
|
| 510 |
+
|
| 511 |
+
items = [] # (pos_id, label, name, avatar_url)
|
| 512 |
+
for pos_id, label in formation:
|
| 513 |
+
q = qs.get(pos_id, deque())
|
| 514 |
+
if q:
|
| 515 |
+
# Handle both Member objects and typed names
|
| 516 |
+
m = q[0]
|
| 517 |
+
name = m.display_name if hasattr(m, "display_name") else str(m)
|
| 518 |
+
avatar_url = m.display_avatar.url if hasattr(m, "display_avatar") else None
|
| 519 |
+
items.append((pos_id, label, name, avatar_url))
|
| 520 |
+
|
| 521 |
+
if not items:
|
| 522 |
+
return await respond_or_send(ctx, "❌ The lineup is empty! People need to join first.")
|
| 523 |
+
|
| 524 |
+
async with ctx.typing():
|
| 525 |
+
img_data = LineupGenerator.create_lineup_image(form_key, items)
|
| 526 |
+
file = discord.File(fp=img_data, filename="matchday.png")
|
| 527 |
+
await respond_or_send(ctx, "📸 **MATCH DAY!** Here is our starting lineup:", file=file)
|
| 528 |
+
|
| 529 |
+
@bot.event
|
| 530 |
+
async def on_message(message):
|
| 531 |
+
# LOUD DEBUG
|
| 532 |
+
print(f"📩 [MESSAGE] From: {message.author} | Content: '{message.content}'", flush=True)
|
| 533 |
+
if message.author.bot: return
|
| 534 |
+
# Process commands normally
|
| 535 |
+
await bot.process_commands(message)
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
# Removed premature defer handler — py-cord handles slash command acknowledgment automatically.
|
| 539 |
+
# Manual deferring here was racing with respond_or_send() and causing double-defer conflicts.
|
| 540 |
+
|
| 541 |
+
@bot.event
|
| 542 |
+
async def on_connect():
|
| 543 |
+
print(f"📡 Gateway: Connected to Discord! Authenticating...", flush=True)
|
| 544 |
+
|
| 545 |
+
@bot.event
|
| 546 |
+
async def on_ready():
|
| 547 |
+
# Force state reset for the current loop
|
| 548 |
+
reset_async_state()
|
| 549 |
+
|
| 550 |
+
print(f"--- BOT IS ONLINE ---", flush=True)
|
| 551 |
+
print(f"🤖 User: {bot.user} ({bot.user.id})", flush=True)
|
| 552 |
+
print(f"📋 Commands Loaded ({len(bot.commands)}): {', '.join(c.name for c in bot.commands)}", flush=True)
|
| 553 |
+
print(f"📶 Latency: {round(bot.latency * 1000)}ms", flush=True)
|
| 554 |
+
print(f"📝 Intents: MsgContent={bot.intents.message_content}", flush=True)
|
| 555 |
+
print(f"----------------------", flush=True)
|
| 556 |
+
|
| 557 |
+
# Background startup tasks (Non-blocking)
|
| 558 |
+
async def post_ready_tasks():
|
| 559 |
+
# 1. REGISTER VIEWS IMMEDIATELY
|
| 560 |
+
for guild in bot.guilds:
|
| 561 |
+
try:
|
| 562 |
+
bot.add_view(LineupView(guild.id))
|
| 563 |
+
bot.add_view(ManagerLineupView(guild.id))
|
| 564 |
+
except: pass
|
| 565 |
+
|
| 566 |
+
# 2. Heavy data tasks in background
|
| 567 |
+
print("🚚 Loading data in background...", flush=True)
|
| 568 |
+
try: await storage.restore_from_discord()
|
| 569 |
+
except Exception as e: print(f"⚠️ Storage restore failed: {e}", flush=True)
|
| 570 |
+
|
| 571 |
+
# 3. BACKGROUND COMMAND SYNC (ALWAYS SYNC)
|
| 572 |
+
print("🔄 Background Sync: Updating commands...", flush=True)
|
| 573 |
+
try:
|
| 574 |
+
await bot.sync_commands()
|
| 575 |
+
print("✅ Background Sync: Commands updated.", flush=True)
|
| 576 |
+
except Exception as e:
|
| 577 |
+
print(f"⚠️ Background Sync: Failed ({e})", flush=True)
|
| 578 |
+
|
| 579 |
+
try: storage.save_guilds()
|
| 580 |
+
except: pass
|
| 581 |
+
print("🚀 Ready. Listening for events...", flush=True)
|
| 582 |
+
await auto_scan_lineups()
|
| 583 |
+
|
| 584 |
+
# Start tasks immediately
|
| 585 |
+
asyncio.create_task(post_ready_tasks())
|
| 586 |
+
|
| 587 |
+
async def auto_scan_lineups():
|
| 588 |
+
# 3. AUTO-SCAN FOR PENDING LINEUPS: Check if any active polls reached their goal while offline
|
| 589 |
+
print("🔍 Auto-Scan: Checking for completed friendly matches...")
|
| 590 |
+
for gid, mid in list(storage.active_polls.items()):
|
| 591 |
+
if (gid, mid) in storage.processed_messages: continue
|
| 592 |
+
try:
|
| 593 |
+
guild = bot.get_guild(gid)
|
| 594 |
+
if not guild: continue
|
| 595 |
+
for channel in guild.text_channels:
|
| 596 |
+
try:
|
| 597 |
+
m = await channel.fetch_message(mid)
|
| 598 |
+
if m:
|
| 599 |
+
# Extract requirement
|
| 600 |
+
if "Needed:" in m.content:
|
| 601 |
+
req = int(m.content.split("Needed: ")[1].split("\n")[0])
|
| 602 |
+
current_count = 0
|
| 603 |
+
for react in m.reactions:
|
| 604 |
+
if str(react.emoji) == "🟩":
|
| 605 |
+
current_count = react.count - (1 if react.me else 0)
|
| 606 |
+
break
|
| 607 |
+
if current_count >= req:
|
| 608 |
+
print(f"✅ AUTO-PICKUP: Found completed match {mid} in {guild.name}")
|
| 609 |
+
# Trigger the reaction handler logic manually
|
| 610 |
+
p = discord.RawReactionActionEvent(
|
| 611 |
+
data={"message_id": mid, "channel_id": m.channel.id, "guild_id": gid, "user_id": bot.user.id, "emoji": {"name": "🟩"}},
|
| 612 |
+
member=None,
|
| 613 |
+
event_type="REACTION_ADD"
|
| 614 |
+
)
|
| 615 |
+
await on_raw_reaction_add(p)
|
| 616 |
+
break
|
| 617 |
+
except: continue
|
| 618 |
+
except: continue
|
| 619 |
+
|
| 620 |
+
@bot.event
|
| 621 |
+
async def on_guild_join(guild):
|
| 622 |
+
storage.save_guilds()
|
| 623 |
+
|
| 624 |
+
@bot.event
|
| 625 |
+
async def on_guild_remove(guild):
|
| 626 |
+
storage.save_guilds()
|
| 627 |
+
|
| 628 |
+
@bot.event
|
| 629 |
+
async def on_voice_state_update(member, before, after):
|
| 630 |
+
# Bot stays in voice channel until explicitly told to leave via !leavevc
|
| 631 |
+
# This event is kept for potential future monitoring
|
| 632 |
+
pass
|
| 633 |
+
|
| 634 |
+
@bot.event
|
| 635 |
+
async def on_raw_reaction_add(payload):
|
| 636 |
+
print(f"📦 REACT DEBUG: Recv reaction {payload.emoji} on {payload.message_id}")
|
| 637 |
+
if payload.member and payload.member.bot: return
|
| 638 |
+
|
| 639 |
+
gid = payload.guild_id
|
| 640 |
+
if not gid: return
|
| 641 |
+
|
| 642 |
+
# Check if we already processed this message
|
| 643 |
+
if (gid, payload.message_id) in storage.processed_messages:
|
| 644 |
+
return
|
| 645 |
+
|
| 646 |
+
# Fetch channel and message objects
|
| 647 |
+
try:
|
| 648 |
+
channel = bot.get_channel(payload.channel_id) or await bot.fetch_channel(payload.channel_id)
|
| 649 |
+
m = await channel.fetch_message(payload.message_id)
|
| 650 |
+
except Exception:
|
| 651 |
+
return
|
| 652 |
+
|
| 653 |
+
if "FRIENDLY" not in m.content and "LEAGUE MATCH" not in m.content:
|
| 654 |
+
return
|
| 655 |
+
|
| 656 |
+
if "Needed:" in m.content:
|
| 657 |
+
try:
|
| 658 |
+
req = int(m.content.split("Needed: ")[1].split("\n")[0])
|
| 659 |
+
except Exception:
|
| 660 |
+
return
|
| 661 |
+
|
| 662 |
+
current_count = 0
|
| 663 |
+
for react in m.reactions:
|
| 664 |
+
if str(react.emoji) == "🟩":
|
| 665 |
+
# Use current count minus bot's own reaction (if any)
|
| 666 |
+
current_count = react.count - (1 if react.me else 0)
|
| 667 |
+
break
|
| 668 |
+
|
| 669 |
+
print(f"📦 DEBUG: Reaction check on {m.id} | Needed: {req} | Current: {current_count}")
|
| 670 |
+
|
| 671 |
+
if current_count >= req:
|
| 672 |
+
async with lineup_lock:
|
| 673 |
+
# Double check to prevent race conditions
|
| 674 |
+
if (gid, m.id) in storage.processed_messages: return
|
| 675 |
+
storage.processed_messages.add((gid, m.id))
|
| 676 |
+
storage.save_state()
|
| 677 |
+
|
| 678 |
+
print(f"✅ AUTO-LINEUP: Target reached ({current_count}/{req}). Sending lineup...")
|
| 679 |
+
|
| 680 |
+
for q in guild_lineup_queues[gid].values(): q.clear()
|
| 681 |
+
|
| 682 |
+
content = f"@everyone\n**Lineup ({guild_selected_formation[gid]})**\n\n{format_lineup(gid)}"
|
| 683 |
+
await m.channel.send(
|
| 684 |
+
content,
|
| 685 |
+
view=LineupView(gid),
|
| 686 |
+
allowed_mentions=discord.AllowedMentions(everyone=True)
|
| 687 |
+
)
|
| 688 |
+
|
| 689 |
+
# Voice transcription commands removed.
|
| 690 |
+
|
| 691 |
+
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
# Bot startup is managed by bot_runner.py to keep runtime separate from the bot code.
|
| 696 |
+
|
bot_main.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import subprocess
|
| 4 |
+
import time
|
| 5 |
+
|
| 6 |
+
def start_bot():
|
| 7 |
+
"""Starts the bot using the clean launcher system."""
|
| 8 |
+
# We use a subprocess to keep the Flask server and Bot separated cleanly
|
| 9 |
+
def runner():
|
| 10 |
+
while True:
|
| 11 |
+
try:
|
| 12 |
+
# Run the new optimized launcher
|
| 13 |
+
process = subprocess.Popen([sys.executable, "friendly_launcher.py"])
|
| 14 |
+
process.wait()
|
| 15 |
+
except Exception:
|
| 16 |
+
pass
|
| 17 |
+
time.sleep(5) # Brief pause before quiet restart
|
| 18 |
+
|
| 19 |
+
import threading
|
| 20 |
+
threading.Thread(target=runner, daemon=True).start()
|
| 21 |
+
print("[*] Unified Startup: Bot and Server are initializing...")
|
| 22 |
+
|
| 23 |
+
if __name__ == "__main__":
|
| 24 |
+
start_bot()
|
| 25 |
+
# Keep main thread alive
|
| 26 |
+
while True:
|
| 27 |
+
time.sleep(3600)
|
card_generator.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from PIL import Image, ImageDraw, ImageFont, ImageFilter
|
| 2 |
+
import io
|
| 3 |
+
import requests
|
| 4 |
+
|
| 5 |
+
class CardGenerator:
|
| 6 |
+
@staticmethod
|
| 7 |
+
def get_rank_theme(matches):
|
| 8 |
+
if matches >= 50: # Legend
|
| 9 |
+
return {"bg": (30, 30, 30), "border": (255, 215, 0), "text": (255, 215, 0), "label": "GOLD LEGEND"}
|
| 10 |
+
elif matches >= 25: # Veteran
|
| 11 |
+
return {"bg": (30, 30, 30), "border": (192, 192, 192), "text": (211, 211, 211), "label": "SILVER VET"}
|
| 12 |
+
elif matches >= 10: # Pro
|
| 13 |
+
return {"bg": (30, 30, 30), "border": (0, 150, 255), "text": (255, 255, 255), "label": "ELITE PRO"}
|
| 14 |
+
else: # Rookie
|
| 15 |
+
return {"bg": (20, 20, 20), "border": (80, 80, 80), "text": (200, 200, 200), "label": "ROOKIE"}
|
| 16 |
+
|
| 17 |
+
@staticmethod
|
| 18 |
+
async def create_profile_card(name, matches, fav_pos, avatar_url):
|
| 19 |
+
# Card settings
|
| 20 |
+
width, height = 400, 600
|
| 21 |
+
theme = CardGenerator.get_rank_theme(matches)
|
| 22 |
+
|
| 23 |
+
# Create base image
|
| 24 |
+
card = Image.new("RGBA", (width, height), (0,0,0,0))
|
| 25 |
+
draw = ImageDraw.Draw(card)
|
| 26 |
+
|
| 27 |
+
# Draw Card Shape (Rounded Rectangle)
|
| 28 |
+
draw.rounded_rectangle([10, 10, 390, 590], radius=40, fill=theme["bg"], outline=theme["border"], width=5)
|
| 29 |
+
|
| 30 |
+
# Top Header Area
|
| 31 |
+
draw.rounded_rectangle([30, 30, 370, 80], radius=20, fill=(40, 40, 40))
|
| 32 |
+
|
| 33 |
+
# Load Fonts (Using default if OS fonts missing, but usually arial is safe on many systems)
|
| 34 |
+
try: font_large = ImageFont.truetype("arial.ttf", 40)
|
| 35 |
+
except: font_large = ImageFont.load_default()
|
| 36 |
+
|
| 37 |
+
try: font_small = ImageFont.truetype("arial.ttf", 25)
|
| 38 |
+
except: font_small = ImageFont.load_default()
|
| 39 |
+
|
| 40 |
+
# Draw Label
|
| 41 |
+
draw.text((width//2, 55), theme["label"], fill=theme["text"], font=font_small, anchor="mm")
|
| 42 |
+
|
| 43 |
+
# Handle Avatar
|
| 44 |
+
try:
|
| 45 |
+
response = requests.get(avatar_url)
|
| 46 |
+
avatar_img = Image.open(io.BytesIO(response.content)).convert("RGBA")
|
| 47 |
+
avatar_img = avatar_img.resize((180, 180))
|
| 48 |
+
|
| 49 |
+
# Create Circular Mask for Avatar
|
| 50 |
+
mask = Image.new("L", (180, 180), 0)
|
| 51 |
+
mask_draw = ImageDraw.Draw(mask)
|
| 52 |
+
mask_draw.ellipse((0, 0, 180, 180), fill=255)
|
| 53 |
+
|
| 54 |
+
card.paste(avatar_img, (110, 110), mask)
|
| 55 |
+
|
| 56 |
+
# Avatar Border
|
| 57 |
+
draw.ellipse((110, 110, 290, 290), outline=theme["border"], width=3)
|
| 58 |
+
except:
|
| 59 |
+
pass
|
| 60 |
+
|
| 61 |
+
# Name
|
| 62 |
+
draw.text((width//2, 340), name, fill=(255, 255, 255), font=font_large, anchor="mm")
|
| 63 |
+
|
| 64 |
+
# Separator line
|
| 65 |
+
draw.line([100, 380, 300, 380], fill=theme["border"], width=2)
|
| 66 |
+
|
| 67 |
+
# Stats Area
|
| 68 |
+
draw.text((width//2, 430), f"MATCHES: {matches}", fill=theme["text"], font=font_small, anchor="mm")
|
| 69 |
+
draw.text((width//2, 480), f"POS: {fav_pos}", fill=(255, 255, 255), font=font_small, anchor="mm")
|
| 70 |
+
|
| 71 |
+
# Badge / Footer
|
| 72 |
+
draw.text((width//2, 550), "⚽ FRIENDLY BOT OFFICIAL", fill=(100, 100, 100), font=font_small, anchor="mm")
|
| 73 |
+
|
| 74 |
+
# Save to bytes
|
| 75 |
+
img_byte_arr = io.BytesIO()
|
| 76 |
+
card.save(img_byte_arr, format='PNG')
|
| 77 |
+
img_byte_arr.seek(0)
|
| 78 |
+
return img_byte_arr
|
| 79 |
+
|
| 80 |
+
class LineupGenerator:
|
| 81 |
+
# X/Y Coords for positions on an 800x1200 pitch (Top-Down)
|
| 82 |
+
# 0 = Top (Strikers), 1200 = Bottom (GK)
|
| 83 |
+
POSITIONS = {
|
| 84 |
+
"GK": (400, 1050),
|
| 85 |
+
"CB": (400, 850), "LCB": (250, 850), "RCB": (550, 850), "CB1": (300, 850), "CB2": (500, 850),
|
| 86 |
+
"LB": (100, 800), "RB": (700, 800),
|
| 87 |
+
"CDM": (400, 650), "LCM": (200, 600), "RCM": (600, 600), "CM": (400, 550), "CM1": (300, 550), "CM2": (500, 550),
|
| 88 |
+
"LM": (100, 450), "RM": (700, 450), "CAM": (400, 350),
|
| 89 |
+
"LW": (150, 200), "RW": (650, 200), "ST": (400, 150), "ST1": (300, 150), "ST2": (500, 150)
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
@staticmethod
|
| 93 |
+
def create_lineup_image(formation_name, items):
|
| 94 |
+
"""
|
| 95 |
+
items: List of (pos_id, label, member_name, avatar_url)
|
| 96 |
+
"""
|
| 97 |
+
width, height = 800, 1200
|
| 98 |
+
img = Image.new("RGB", (width, height), (34, 139, 34)) # Grass Green
|
| 99 |
+
draw = ImageDraw.Draw(img)
|
| 100 |
+
|
| 101 |
+
# --- Draw Pitch Lines ---
|
| 102 |
+
white = (255, 255, 255)
|
| 103 |
+
draw.rectangle([20, 20, 780, 1180], outline=white, width=5) # Border
|
| 104 |
+
draw.line([20, 600, 780, 600], fill=white, width=5) # Halfway
|
| 105 |
+
draw.ellipse([300, 500, 500, 700], outline=white, width=5) # Center Circle
|
| 106 |
+
|
| 107 |
+
# Penalty areas
|
| 108 |
+
draw.rectangle([150, 20, 650, 200], outline=white, width=5) # Top Box
|
| 109 |
+
draw.rectangle([150, 1000, 650, 1180], outline=white, width=5) # Bottom Box
|
| 110 |
+
|
| 111 |
+
# Fonts
|
| 112 |
+
try:
|
| 113 |
+
font_name = ImageFont.truetype("arial.ttf", 24)
|
| 114 |
+
font_label = ImageFont.truetype("arial.ttf", 20)
|
| 115 |
+
font_title = ImageFont.truetype("arial.ttf", 46)
|
| 116 |
+
except:
|
| 117 |
+
font_name = ImageFont.load_default()
|
| 118 |
+
font_label = ImageFont.load_default()
|
| 119 |
+
font_title = ImageFont.load_default()
|
| 120 |
+
|
| 121 |
+
# Title - Manual Centering
|
| 122 |
+
title_text = f"FORMATION: {formation_name}"
|
| 123 |
+
t_w = len(title_text) * 10
|
| 124 |
+
draw.text(((width - t_w)//2, 40), title_text, fill=white, font=font_title)
|
| 125 |
+
|
| 126 |
+
# Draw Players
|
| 127 |
+
for pos_id, label, name, avatar_url in items:
|
| 128 |
+
coords = LineupGenerator.POSITIONS.get(pos_id, (400, 600))
|
| 129 |
+
x, y = coords
|
| 130 |
+
|
| 131 |
+
# Draw Avatar
|
| 132 |
+
if avatar_url:
|
| 133 |
+
try:
|
| 134 |
+
resp = requests.get(avatar_url)
|
| 135 |
+
pfp = Image.open(io.BytesIO(resp.content)).convert("RGBA").resize((80, 80))
|
| 136 |
+
|
| 137 |
+
mask = Image.new("L", (80, 80), 0)
|
| 138 |
+
draw_mask = ImageDraw.Draw(mask)
|
| 139 |
+
draw_mask.ellipse((0, 0, 80, 80), fill=255)
|
| 140 |
+
|
| 141 |
+
img.paste(pfp, (x-40, y-40), mask)
|
| 142 |
+
draw.ellipse([x-42, y-42, x+42, y+42], outline=white, width=3)
|
| 143 |
+
except:
|
| 144 |
+
draw.ellipse([x-30, y-30, x+30, y+30], fill=white, outline=(0,0,0), width=2)
|
| 145 |
+
else:
|
| 146 |
+
draw.ellipse([x-30, y-30, x+30, y+30], fill=white, outline=(0,0,0), width=2)
|
| 147 |
+
|
| 148 |
+
# Position Label
|
| 149 |
+
l_w = len(label) * 6
|
| 150 |
+
draw.rectangle([x-(l_w//2)-5, y+45, x+(l_w//2)+5, y+65], fill=(0,0,0), outline=white)
|
| 151 |
+
draw.text((x-(l_w//2), y+47), label, fill=white, font=font_label)
|
| 152 |
+
|
| 153 |
+
# Player Name
|
| 154 |
+
n_w = len(name) * 6
|
| 155 |
+
# Shadow
|
| 156 |
+
draw.text((x-(n_w//2)+1, y+71), name, fill=(0,0,0), font=font_name)
|
| 157 |
+
draw.text((x-(n_w//2), y+70), name, fill=white, font=font_name)
|
| 158 |
+
|
| 159 |
+
# Save
|
| 160 |
+
img_byte_arr = io.BytesIO()
|
| 161 |
+
img.save(img_byte_arr, format='PNG')
|
| 162 |
+
img_byte_arr.seek(0)
|
| 163 |
+
return img_byte_arr
|
commmands.txt
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
⭐ FRIENDLYBOT OFFICIAL COMMANDS ⭐
|
| 2 |
+
|
| 3 |
+
--- ⚽ MATCH & LINEUP MANAGEMENT ---
|
| 4 |
+
!friendly /friendly - Start a standard lineup vote for players to join.
|
| 5 |
+
!leaguematch /leaguematch - Schedule a professional league match with an opponent, link, and optional time.
|
| 6 |
+
!lineup /lineup - (Admin/Staff) Generate the standard interactive lineup board.
|
| 7 |
+
!managerlineup /managerlineup - (Admin/Staff) Open the GUI editor to draft players interactively.
|
| 8 |
+
!lineupimage /lineupimage - Generate a high-quality visual representation of the current starting lineup.
|
| 9 |
+
!sendlink /sendlink - Send a link publicly in the current channel as `Link : [link]`.
|
| 10 |
+
|
| 11 |
+
--- 📈 COMPETITION & STATS ---
|
| 12 |
+
!top /top - 🏆 Show the Top 10 most active players in the server.
|
| 13 |
+
!profile /profile - 🎴 Generate a custom FIFA-style profile card with player stats.
|
| 14 |
+
!record /record - 📊 View the server's global Win/Loss/Draw record.
|
| 15 |
+
!win /win - (Admin/Staff) Record a victory into the server record.
|
| 16 |
+
!loss /loss - (Admin/Staff) Record a defeat into the server record.
|
| 17 |
+
!draw /draw - (Admin/Staff) Record a draw into the server record.
|
| 18 |
+
|
| 19 |
+
--- ⚙️ SYSTEM & STAFF SETUP ---
|
| 20 |
+
!setup /setup - (Admin Only) Opens the interactive settings dropdown panel.
|
| 21 |
+
!addrole /addrole - (Admin Only) Add a role to the bot staff whitelist.
|
| 22 |
+
!removerole /removerole - (Admin Only) Remove a role from the bot staff whitelist.
|
| 23 |
+
!giverole /giverole - (Admin Only) Give a role to every member who already has the required roles.
|
| 24 |
+
!friendlybotsettings /friendlybotsettings - View bot status and permitted roles.
|
| 25 |
+
!sync /sync - (Admin Only) Synchronize slash commands.
|
| 26 |
+
!sync_cmds /sync_cmds - Alias for /sync.
|
| 27 |
+
!reboot /reboot - (Owner Only) Restart the bot.
|
| 28 |
+
!ping /ping - Check bot latency.
|
| 29 |
+
!uptime /uptime - Show how long the bot has been online.
|
| 30 |
+
|
| 31 |
+
⭐▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬⭐
|
| 32 |
+
Tip: All commands listed here completely support Discord Slash Commands (/) due to the Bridge Network upgrade!
|
core.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import socket
|
| 2 |
+
|
| 3 |
+
# Force IPv4 to prevent ClientConnectorError on HuggingFace/Docker
|
| 4 |
+
if not hasattr(socket, "_friendly_patched"):
|
| 5 |
+
socket._friendly_patched = True
|
| 6 |
+
_old_getaddrinfo = socket.getaddrinfo
|
| 7 |
+
def _new_getaddrinfo(*args, **kwargs):
|
| 8 |
+
try:
|
| 9 |
+
responses = _old_getaddrinfo(*args, **kwargs)
|
| 10 |
+
ipv4_responses = [r for r in responses if r[0] == socket.AF_INET]
|
| 11 |
+
return ipv4_responses if ipv4_responses else responses
|
| 12 |
+
except Exception:
|
| 13 |
+
return _old_getaddrinfo(*args, **kwargs)
|
| 14 |
+
socket.getaddrinfo = _new_getaddrinfo
|
| 15 |
+
|
| 16 |
+
import discord
|
| 17 |
+
from discord.ext import commands, bridge
|
| 18 |
+
import os
|
| 19 |
+
from dotenv import load_dotenv
|
| 20 |
+
from collections import deque, defaultdict
|
| 21 |
+
import asyncio
|
| 22 |
+
|
| 23 |
+
# Shared basic state
|
| 24 |
+
load_dotenv()
|
| 25 |
+
BOT_TOKEN = os.getenv("BOT_TOKEN") or os.getenv("BOTTOKEN")
|
| 26 |
+
|
| 27 |
+
INTENTS = discord.Intents.default()
|
| 28 |
+
INTENTS.message_content = True
|
| 29 |
+
INTENTS.reactions = True
|
| 30 |
+
INTENTS.members = True
|
| 31 |
+
INTENTS.voice_states = True
|
| 32 |
+
|
| 33 |
+
bot = bridge.Bot(command_prefix="!", intents=INTENTS, help_command=None, case_insensitive=True)
|
| 34 |
+
|
| 35 |
+
# RE-LOCATED SHARED STATE
|
| 36 |
+
storage = None
|
| 37 |
+
# Late-initialized state to avoid loop mismatch
|
| 38 |
+
lineup_lock = None
|
| 39 |
+
guild_selected_formation = defaultdict(lambda: "default")
|
| 40 |
+
guild_lineup_queues = defaultdict(lambda: defaultdict(deque))
|
| 41 |
+
counted_stats_per_message = defaultdict(set)
|
| 42 |
+
guild_voice_channels = defaultdict(lambda: None)
|
| 43 |
+
|
| 44 |
+
def reset_async_state():
|
| 45 |
+
"""Call this after creating a new event loop to ensure Locks work."""
|
| 46 |
+
global lineup_lock
|
| 47 |
+
lineup_lock = asyncio.Lock()
|
| 48 |
+
print("🔄 Core: Async state (Locks) reset for new loop.")
|
| 49 |
+
|
| 50 |
+
def user_has_lineup_access(member: discord.Member) -> bool:
|
| 51 |
+
# Owner always has access
|
| 52 |
+
try:
|
| 53 |
+
if member.id == member.guild.owner_id:
|
| 54 |
+
return True
|
| 55 |
+
except Exception:
|
| 56 |
+
pass
|
| 57 |
+
|
| 58 |
+
# Check admin permissions safely
|
| 59 |
+
try:
|
| 60 |
+
if member.guild_permissions.administrator:
|
| 61 |
+
return True
|
| 62 |
+
except Exception:
|
| 63 |
+
try:
|
| 64 |
+
for role in member.roles:
|
| 65 |
+
if role is not None and role.permissions.administrator:
|
| 66 |
+
return True
|
| 67 |
+
except Exception:
|
| 68 |
+
pass
|
| 69 |
+
|
| 70 |
+
# Check lineup roles from storage
|
| 71 |
+
if not storage:
|
| 72 |
+
return False
|
| 73 |
+
allowed_roles = storage.lineup_roles.get(member.guild.id, set())
|
| 74 |
+
try:
|
| 75 |
+
return any(r is not None and r.id in allowed_roles for r in member.roles)
|
| 76 |
+
except Exception:
|
| 77 |
+
return False
|
| 78 |
+
|
| 79 |
+
async def respond_or_send(ctx, *args, ephemeral=False, **kwargs):
|
| 80 |
+
"""Respond to a slash interaction if available, otherwise send normally.
|
| 81 |
+
Works with py-cord's bridge commands (both slash and prefix)."""
|
| 82 |
+
try:
|
| 83 |
+
# Bridge commands: ctx.respond() handles both slash and prefix automatically
|
| 84 |
+
if hasattr(ctx, "respond"):
|
| 85 |
+
return await ctx.respond(*args, ephemeral=ephemeral, **kwargs)
|
| 86 |
+
except Exception as e:
|
| 87 |
+
print(f"⚠️ [SEND] ctx.respond failed: {e}", flush=True)
|
| 88 |
+
|
| 89 |
+
# Fallback: try channel.send for raw contexts (e.g. from reaction handlers)
|
| 90 |
+
try:
|
| 91 |
+
if hasattr(ctx, "channel"):
|
| 92 |
+
return await ctx.channel.send(*args, **kwargs)
|
| 93 |
+
except Exception as e:
|
| 94 |
+
print(f"⚠️ [SEND] channel.send failed: {e}", flush=True)
|
| 95 |
+
|
| 96 |
+
# Last resort: try send (prefix-style)
|
| 97 |
+
try:
|
| 98 |
+
if hasattr(ctx, "send"):
|
| 99 |
+
return await ctx.send(*args, **kwargs)
|
| 100 |
+
except Exception as e:
|
| 101 |
+
print(f"⚠️ [SEND] ctx.send failed: {e}", flush=True)
|
| 102 |
+
|
| 103 |
+
return None
|
| 104 |
+
|
| 105 |
+
print("✅ Core: Module loaded successfully.")
|
discloud.config
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
ID=my-cool-bot
|
| 2 |
+
TYPE=bot
|
| 3 |
+
MAIN=server.py
|
| 4 |
+
NAME=MessageMonitor
|
| 5 |
+
RAM=512
|
| 6 |
+
VERSION=latest
|
| 7 |
+
AUTORESTART=true
|
friendly_launcher.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import asyncio
|
| 4 |
+
import discord
|
| 5 |
+
import socket
|
| 6 |
+
import logging
|
| 7 |
+
import time
|
| 8 |
+
import threading
|
| 9 |
+
from discord.ext import bridge
|
| 10 |
+
from aiohttp import TCPConnector, ClientSession, ClientTimeout
|
| 11 |
+
|
| 12 |
+
# --- 1. SILENT LOGGING ---
|
| 13 |
+
logging.basicConfig(level=logging.WARNING)
|
| 14 |
+
for logger in ["discord", "aiohttp", "urllib3"]:
|
| 15 |
+
logging.getLogger(logger).setLevel(logging.CRITICAL)
|
| 16 |
+
|
| 17 |
+
def clean_print(msg):
|
| 18 |
+
print(f"[*] {msg}", flush=True)
|
| 19 |
+
|
| 20 |
+
# --- 2. CLEAN NETWORK PATCH (IPv4 only, no domain hijacking) ---
|
| 21 |
+
def patch_network():
|
| 22 |
+
"""Force IPv4 connections only. This fixes connectivity on HuggingFace/Docker."""
|
| 23 |
+
_old_getaddrinfo = socket.getaddrinfo
|
| 24 |
+
def _new_getaddrinfo(*args, **kwargs):
|
| 25 |
+
try:
|
| 26 |
+
responses = _old_getaddrinfo(*args, **kwargs)
|
| 27 |
+
ipv4 = [r for r in responses if r[0] == socket.AF_INET]
|
| 28 |
+
return ipv4 if ipv4 else responses
|
| 29 |
+
except Exception:
|
| 30 |
+
return _old_getaddrinfo(*args, **kwargs)
|
| 31 |
+
socket.getaddrinfo = _new_getaddrinfo
|
| 32 |
+
|
| 33 |
+
# Patch aiohttp's TCPConnector to default to IPv4
|
| 34 |
+
_old_tcp_init = TCPConnector.__init__
|
| 35 |
+
def _new_tcp_init(self, *args, **kwargs):
|
| 36 |
+
kwargs['family'] = socket.AF_INET
|
| 37 |
+
_old_tcp_init(self, *args, **kwargs)
|
| 38 |
+
TCPConnector.__init__ = _new_tcp_init
|
| 39 |
+
|
| 40 |
+
# --- 3. THE CLEAN RUNNER ---
|
| 41 |
+
def run_bot():
|
| 42 |
+
# 1. Create the loop FIRST before any imports
|
| 43 |
+
loop = asyncio.new_event_loop()
|
| 44 |
+
asyncio.set_event_loop(loop)
|
| 45 |
+
|
| 46 |
+
patch_network()
|
| 47 |
+
|
| 48 |
+
try:
|
| 49 |
+
import core
|
| 50 |
+
from core import bot, BOT_TOKEN
|
| 51 |
+
# Re-bind the bot to the new event loop
|
| 52 |
+
bot._connection._loop = loop
|
| 53 |
+
import bot as bot_logic
|
| 54 |
+
|
| 55 |
+
# Reset async primitives for the new loop
|
| 56 |
+
core.lineup_lock = asyncio.Lock()
|
| 57 |
+
core.storage.bot = bot
|
| 58 |
+
except Exception as e:
|
| 59 |
+
clean_print(f"Config Error: {e}")
|
| 60 |
+
return
|
| 61 |
+
|
| 62 |
+
clean_print("System Initialized. Establishing Connection...")
|
| 63 |
+
|
| 64 |
+
# on_ready is handled inside bot.py to prevent event handler conflicts
|
| 65 |
+
|
| 66 |
+
while True:
|
| 67 |
+
try:
|
| 68 |
+
loop.run_until_complete(bot.start(BOT_TOKEN.strip()))
|
| 69 |
+
except KeyboardInterrupt:
|
| 70 |
+
clean_print("Shutting down...")
|
| 71 |
+
break
|
| 72 |
+
except Exception as e:
|
| 73 |
+
clean_print(f"Connection lost: {e}. Reconnecting in 5s...")
|
| 74 |
+
time.sleep(5)
|
| 75 |
+
|
| 76 |
+
if __name__ == "__main__":
|
| 77 |
+
run_bot()
|
give_role_command.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import shlex
|
| 2 |
+
|
| 3 |
+
from core import respond_or_send
|
| 4 |
+
import discord
|
| 5 |
+
from discord.ext import commands
|
| 6 |
+
|
| 7 |
+
from core import bot
|
| 8 |
+
|
| 9 |
+
async def _resolve_role_from_tokens(ctx, tokens):
|
| 10 |
+
converter = commands.RoleConverter()
|
| 11 |
+
for size in range(len(tokens), 0, -1):
|
| 12 |
+
candidate = " ".join(tokens[:size])
|
| 13 |
+
try:
|
| 14 |
+
return await converter.convert(ctx, candidate), size
|
| 15 |
+
except commands.BadArgument:
|
| 16 |
+
continue
|
| 17 |
+
return None, 0
|
| 18 |
+
|
| 19 |
+
async def _parse_giverole_args(ctx, raw_args: str):
|
| 20 |
+
if not raw_args:
|
| 21 |
+
return None, None, "❌ Usage: `!giverole [required roles] [role to give]`"
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
tokens = shlex.split(raw_args)
|
| 25 |
+
except ValueError:
|
| 26 |
+
tokens = raw_args.split()
|
| 27 |
+
|
| 28 |
+
if len(tokens) < 2:
|
| 29 |
+
return None, None, "❌ You must specify at least one required role and one role to give."
|
| 30 |
+
|
| 31 |
+
target_role = None
|
| 32 |
+
target_index = 0
|
| 33 |
+
for start in range(len(tokens) - 1, -1, -1):
|
| 34 |
+
candidate = " ".join(tokens[start:])
|
| 35 |
+
try:
|
| 36 |
+
role = await commands.RoleConverter().convert(ctx, candidate)
|
| 37 |
+
target_role = role
|
| 38 |
+
target_index = start
|
| 39 |
+
break
|
| 40 |
+
except commands.BadArgument:
|
| 41 |
+
continue
|
| 42 |
+
|
| 43 |
+
if not target_role:
|
| 44 |
+
return None, None, "❌ Could not resolve the target role to give. Please mention it or use the exact role name."
|
| 45 |
+
|
| 46 |
+
required_roles = []
|
| 47 |
+
remaining = tokens[:target_index]
|
| 48 |
+
while remaining:
|
| 49 |
+
role, used = await _resolve_role_from_tokens(ctx, remaining)
|
| 50 |
+
if not role:
|
| 51 |
+
token_sample = " ".join(remaining[:min(3, len(remaining))])
|
| 52 |
+
return None, None, f"❌ Could not resolve required role from: `{token_sample}`. Use mentions or exact role names."
|
| 53 |
+
required_roles.append(role)
|
| 54 |
+
remaining = remaining[used:]
|
| 55 |
+
|
| 56 |
+
if not required_roles:
|
| 57 |
+
return None, None, "❌ You must specify at least one required role before the role to give."
|
| 58 |
+
|
| 59 |
+
return required_roles, target_role, None
|
| 60 |
+
|
| 61 |
+
async def _giverole_impl(ctx, raw_args: str):
|
| 62 |
+
"""Give a role to every member who already has all required roles."""
|
| 63 |
+
required_roles, target_role, error = await _parse_giverole_args(ctx, raw_args)
|
| 64 |
+
if error:
|
| 65 |
+
return await respond_or_send(ctx, error)
|
| 66 |
+
|
| 67 |
+
if target_role.managed:
|
| 68 |
+
return await respond_or_send(ctx, "❌ I cannot assign a managed role.")
|
| 69 |
+
|
| 70 |
+
me = ctx.guild.me or ctx.guild.get_member(bot.user.id)
|
| 71 |
+
if me and target_role >= me.top_role:
|
| 72 |
+
return await respond_or_send(ctx, "❌ I cannot assign that role because it is higher than or equal to my top role.")
|
| 73 |
+
|
| 74 |
+
members_to_update = [member for member in ctx.guild.members
|
| 75 |
+
if all(req in member.roles for req in required_roles)]
|
| 76 |
+
|
| 77 |
+
if not members_to_update:
|
| 78 |
+
required_names = ", ".join([r.name for r in required_roles])
|
| 79 |
+
return await respond_or_send(ctx, f"❌ No members found with all required roles: {required_names}.")
|
| 80 |
+
|
| 81 |
+
assigned = 0
|
| 82 |
+
failed = []
|
| 83 |
+
for member in members_to_update:
|
| 84 |
+
if target_role in member.roles:
|
| 85 |
+
continue
|
| 86 |
+
try:
|
| 87 |
+
await member.add_roles(target_role, reason=f"giverole command used by {ctx.author}")
|
| 88 |
+
assigned += 1
|
| 89 |
+
except discord.Forbidden:
|
| 90 |
+
failed.append(member.display_name)
|
| 91 |
+
except discord.HTTPException:
|
| 92 |
+
failed.append(member.display_name)
|
| 93 |
+
|
| 94 |
+
required_list = ", ".join([r.mention for r in required_roles])
|
| 95 |
+
result_message = f"✅ Assigned {target_role.mention} to {assigned} member(s) who had {required_list}."
|
| 96 |
+
if failed:
|
| 97 |
+
result_message += f"\n⚠️ Failed to assign the role to {len(failed)} member(s)."
|
| 98 |
+
await respond_or_send(ctx, result_message)
|
| 99 |
+
|
| 100 |
+
@bot.bridge_command(name="giverole")
|
| 101 |
+
@commands.has_permissions(manage_roles=True)
|
| 102 |
+
async def giverole(ctx, *, args: str):
|
| 103 |
+
return await _giverole_impl(ctx, args)
|
| 104 |
+
|
index.html
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 6 |
+
<title>FriendlyBot | {{ guild_name }}</title>
|
| 7 |
+
<link rel="stylesheet" href="/style.css">
|
| 8 |
+
<link rel="preconnect" href="https://fonts.googleapis.com">
|
| 9 |
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
| 10 |
+
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&family=Fira+Code:wght@400;600&display=swap" rel="stylesheet">
|
| 11 |
+
</head>
|
| 12 |
+
<body>
|
| 13 |
+
<div class="sidebar">
|
| 14 |
+
<div class="sidebar-header">
|
| 15 |
+
<img src="/logo.png" class="logo">
|
| 16 |
+
<h1>FriendlyBot</h1>
|
| 17 |
+
</div>
|
| 18 |
+
|
| 19 |
+
<a href="/" class="back-btn">← Back to servers</a>
|
| 20 |
+
|
| 21 |
+
<div class="nav-menu">
|
| 22 |
+
<a href="#" class="nav-item active"><span>👋 Arrivals/Departures</span></a>
|
| 23 |
+
</div>
|
| 24 |
+
|
| 25 |
+
<div class="sidebar-footer">
|
| 26 |
+
<a href="#" class="nav-item"><span>📚 Documentation</span></a>
|
| 27 |
+
<a href="/logout" class="nav-item"><span>🚪 Logout</span></a>
|
| 28 |
+
</div>
|
| 29 |
+
</div>
|
| 30 |
+
|
| 31 |
+
<div class="main-content">
|
| 32 |
+
<header>
|
| 33 |
+
<h2>Automation: {{ guild_name }}</h2>
|
| 34 |
+
<p>Customize how FriendlyBot greets and interacts with your server members.</p>
|
| 35 |
+
</header>
|
| 36 |
+
|
| 37 |
+
<div class="card">
|
| 38 |
+
<h3>Arrival & Departure Messages</h3>
|
| 39 |
+
<div class="settings-form">
|
| 40 |
+
<div class="input-group">
|
| 41 |
+
<label>👋 Welcome Message Content</label>
|
| 42 |
+
<textarea id="welcome_msg">{{ settings.welcome_msg }}</textarea>
|
| 43 |
+
<div class="hint">Variable: {user} mentions the member.</div>
|
| 44 |
+
</div>
|
| 45 |
+
<div class="input-group">
|
| 46 |
+
<label>🚪 Goodbye Message Content</label>
|
| 47 |
+
<textarea id="goodbye_msg">{{ settings.goodbye_msg }}</textarea>
|
| 48 |
+
<div class="hint">Variable: {user} shows the member's name.</div>
|
| 49 |
+
</div>
|
| 50 |
+
<button onclick="saveSettings()" class="btn-primary" id="save-btn">Save Content</button>
|
| 51 |
+
</div>
|
| 52 |
+
</div>
|
| 53 |
+
</div>
|
| 54 |
+
|
| 55 |
+
<script>
|
| 56 |
+
async function saveSettings() {
|
| 57 |
+
const btn = document.getElementById('save-btn');
|
| 58 |
+
const welcome = document.getElementById('welcome_msg').value;
|
| 59 |
+
const goodbye = document.getElementById('goodbye_msg').value;
|
| 60 |
+
const guildId = "{{ guild_id }}";
|
| 61 |
+
|
| 62 |
+
btn.textContent = 'Saving...';
|
| 63 |
+
btn.disabled = true;
|
| 64 |
+
|
| 65 |
+
try {
|
| 66 |
+
const response = await fetch('/api/settings/' + guildId, {
|
| 67 |
+
method: 'POST',
|
| 68 |
+
headers: { 'Content-Type': 'application/json' },
|
| 69 |
+
body: JSON.stringify({ welcome_msg: welcome, goodbye_msg: goodbye })
|
| 70 |
+
});
|
| 71 |
+
|
| 72 |
+
if (response.ok) {
|
| 73 |
+
btn.textContent = '✅ Content Saved!';
|
| 74 |
+
setTimeout(() => {
|
| 75 |
+
btn.textContent = 'Save Content';
|
| 76 |
+
btn.disabled = false;
|
| 77 |
+
}, 2000);
|
| 78 |
+
} else {
|
| 79 |
+
throw new Error('Failed to save');
|
| 80 |
+
}
|
| 81 |
+
} catch (err) {
|
| 82 |
+
alert('Error saving settings: ' + err.message);
|
| 83 |
+
btn.textContent = 'Save Content';
|
| 84 |
+
btn.disabled = false;
|
| 85 |
+
}
|
| 86 |
+
}
|
| 87 |
+
</script>
|
| 88 |
+
</body>
|
| 89 |
+
</html>
|
invite_bot.html
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 6 |
+
<title>Invite FriendlyBot</title>
|
| 7 |
+
<style>
|
| 8 |
+
body { font-family: 'Inter', sans-serif; background-color: #36393f; color: #fff; display: flex; flex-direction: column; align-items: center; padding-top: 100px; }
|
| 9 |
+
h1 { font-size: 2rem; margin-bottom: 10px; }
|
| 10 |
+
p { color: #b9bbbe; margin-bottom: 30px; text-align: center; max-width: 500px;}
|
| 11 |
+
input { padding: 10px; font-size: 1rem; border-radius: 5px; border: none; width: 300px; margin-bottom: 20px; text-align: center; }
|
| 12 |
+
button { background-color: #5865F2; color: white; border: none; padding: 12px 24px; font-size: 1rem; border-radius: 5px; cursor: pointer; font-weight: bold; transition: background-color 0.2s;}
|
| 13 |
+
button:hover { background-color: #4752C4; }
|
| 14 |
+
.instructions { background: #2f3136; padding: 20px; border-radius: 8px; margin-top: 40px; }
|
| 15 |
+
.instructions h3 { margin-top: 0; color: #5865F2; }
|
| 16 |
+
</style>
|
| 17 |
+
</head>
|
| 18 |
+
<body>
|
| 19 |
+
<h1>Fix FriendlyBot Invite</h1>
|
| 20 |
+
<p>Use this tool to generate the correct invite link for your bot with all the required slash command permissions.</p>
|
| 21 |
+
|
| 22 |
+
<input type="text" id="clientId" placeholder="Paste your Application ID here">
|
| 23 |
+
<button onclick="generateLink()">Invite Bot to Server</button>
|
| 24 |
+
|
| 25 |
+
<div class="instructions">
|
| 26 |
+
<h3>How to fix the "Add App" button on Discord Profile:</h3>
|
| 27 |
+
<ul style="color: #dcddde; line-height: 1.6;">
|
| 28 |
+
<li>Go to the <a href="https://discord.com/developers/applications" style="color: #00aff4;" target="_blank">Discord Developer Portal</a></li>
|
| 29 |
+
<li>Select your bot → Click <b>Installation</b> on the left menu.</li>
|
| 30 |
+
<li>Scroll down to <b>Install Link</b>.</li>
|
| 31 |
+
<li>Change it to <b>Discord Provided Link</b>.</li>
|
| 32 |
+
<li>Under Default Parameters, set <b>scopes</b> to: <code>bot</code> AND <code>applications.commands</code></li>
|
| 33 |
+
<li>Set <b>permissions</b> to full Administrator (or 8).</li>
|
| 34 |
+
<li>Save changes! Now the Add App button will work perfectly.</li>
|
| 35 |
+
</ul>
|
| 36 |
+
</div>
|
| 37 |
+
|
| 38 |
+
<script>
|
| 39 |
+
function generateLink() {
|
| 40 |
+
const clientId = document.getElementById('clientId').value.trim();
|
| 41 |
+
if (!clientId || isNaN(clientId)) {
|
| 42 |
+
alert("Please enter a valid numeric Application ID / Client ID!");
|
| 43 |
+
return;
|
| 44 |
+
}
|
| 45 |
+
const link = `https://discord.com/oauth2/authorize?client_id=${clientId}&permissions=8&integration_type=0&scope=bot%20applications.commands`;
|
| 46 |
+
window.open(link, '_blank');
|
| 47 |
+
}
|
| 48 |
+
</script>
|
| 49 |
+
</body>
|
| 50 |
+
</html>
|
lineup_manager.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import discord
|
| 2 |
+
from collections import deque
|
| 3 |
+
from core import (
|
| 4 |
+
bot, user_has_lineup_access, guild_selected_formation,
|
| 5 |
+
guild_lineup_queues, lineup_lock, counted_stats_per_message, respond_or_send
|
| 6 |
+
)
|
| 7 |
+
|
| 8 |
+
FORMATIONS = {
|
| 9 |
+
"default": [("GK", "GK"), ("CB", "CB"), ("LB", "LB"), ("RB", "RB"), ("CM", "CM"), ("RW", "RW"), ("LW", "LW")],
|
| 10 |
+
"3-1-2": [("GK", "GK"), ("CB", "CB"), ("LB", "LB"), ("RB", "RB"), ("CM", "CM"), ("ST1", "ST"), ("ST2", "ST")],
|
| 11 |
+
"3-0-3": [("GK", "GK"), ("CB", "CB"), ("LB", "LB"), ("RB", "RB"), ("LW", "LW"), ("ST", "ST"), ("RW", "RW")],
|
| 12 |
+
"3-2-1": [("GK", "GK"), ("CB", "CB"), ("LB", "LB"), ("RB", "RB"), ("CM1", "CM"), ("CM2", "CM"), ("ST", "ST")],
|
| 13 |
+
"2-3-1": [("GK", "GK"), ("CB1", "CB"), ("CB2", "CB"), ("LCM", "LCM"), ("CM", "CM"), ("RCM", "RCM"), ("ST", "ST")],
|
| 14 |
+
"2-2-2": [("GK", "GK"), ("CB1", "CB"), ("CB2", "CB"), ("CM1", "CM"), ("CM2", "CM"), ("ST1", "ST"), ("ST2", "ST")],
|
| 15 |
+
"4-1-1": [("GK", "GK"), ("LCB", "LCB"), ("RCB", "RCB"), ("LB", "LB"), ("RB", "RB"), ("CDM", "CDM"), ("ST", "ST")],
|
| 16 |
+
"3-3-0": [("GK", "GK"), ("CB", "CB"), ("LB", "LB"), ("RB", "RB"), ("LCM", "LCM"), ("CM", "CM"), ("RCM", "RCM")],
|
| 17 |
+
"2-1-3": [("GK", "GK"), ("CB1", "CB"), ("CB2", "CB"), ("CM", "CM"), ("LW", "LW"), ("ST", "ST"), ("RW", "RW")],
|
| 18 |
+
"1-4-1": [("GK", "GK"), ("CB", "CB"), ("LM", "LM"), ("LCM", "LCM"), ("RCM", "RCM"), ("RM", "RM"), ("ST", "ST")],
|
| 19 |
+
"4-2-0": [("GK", "GK"), ("LCB", "LCB"), ("RCB", "RCB"), ("LB", "LB"), ("RB", "RB"), ("LCM", "LCM"), ("RCM", "RCM")],
|
| 20 |
+
"3-1-3": [("GK", "GK"), ("CB", "CB"), ("LW", "LW"), ("ST", "ST"), ("RW", "RW"), ("ST1", "ST"), ("ST2", "ST")],
|
| 21 |
+
"5-0-1": [("GK", "GK"), ("LCB", "LCB"), ("CB", "CB"), ("RCB", "RCB"), ("LB", "LB"), ("RB", "RB"), ("ST", "ST")],
|
| 22 |
+
"3-1-1-1": [("GK", "GK"), ("CB", "CB"), ("LB", "LB"), ("RB", "RB"), ("CDM", "CDM"), ("CAM", "CAM"), ("ST", "ST")],
|
| 23 |
+
"2-2-1-1": [("GK", "GK"), ("CB1", "CB"), ("CB2", "CB"), ("LCM", "LCM"), ("RCM", "RCM"), ("CAM", "CAM"), ("ST", "ST")],
|
| 24 |
+
"4-1-2": [("GK", "GK"), ("LCB", "LCB"), ("RCB", "RCB"), ("CDM", "CDM"), ("LB", "LB"), ("RB", "RB"), ("ST", "ST")],
|
| 25 |
+
"2-3-2": [("GK", "GK"), ("CB1", "CB"), ("CB2", "CB"), ("CM", "CM"), ("CAM", "CAM"), ("ST1", "ST"), ("ST2", "ST")],
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
def format_lineup(guild_id) -> str:
|
| 29 |
+
lines = []
|
| 30 |
+
qs = guild_lineup_queues[guild_id]
|
| 31 |
+
form_key = guild_selected_formation[guild_id]
|
| 32 |
+
formation = FORMATIONS.get(form_key, FORMATIONS["default"])
|
| 33 |
+
for pos, label in formation:
|
| 34 |
+
q = qs.get(pos, deque())
|
| 35 |
+
if q:
|
| 36 |
+
m = q[0]
|
| 37 |
+
display = m.mention if hasattr(m, 'mention') else str(m)
|
| 38 |
+
# Check for waiting list (players after the first one)
|
| 39 |
+
if len(q) > 1:
|
| 40 |
+
waiters = []
|
| 41 |
+
for i in range(1, len(q)):
|
| 42 |
+
w = q[i]
|
| 43 |
+
waiters.append(w.mention if hasattr(w, 'mention') else str(w))
|
| 44 |
+
line = f"{label} — {display} [waiting : {', '.join(waiters)}]"
|
| 45 |
+
else:
|
| 46 |
+
line = f"{label} — {display}"
|
| 47 |
+
else: line = f"{label}"
|
| 48 |
+
lines.append(line)
|
| 49 |
+
return "\n".join(lines)
|
| 50 |
+
|
| 51 |
+
class LineupButton(discord.ui.Button):
|
| 52 |
+
def __init__(self, pos, label, guild_id):
|
| 53 |
+
super().__init__(style=discord.ButtonStyle.secondary, label=label, emoji="✅", custom_id=f"ln_{guild_id}_{pos}")
|
| 54 |
+
self.pos, self.guild_id = pos, guild_id
|
| 55 |
+
|
| 56 |
+
async def callback(self, interaction: discord.Interaction):
|
| 57 |
+
# 1. IMMEDIATE DEFER TO STOP "INTERACTION FAILED"
|
| 58 |
+
try: await interaction.response.defer()
|
| 59 |
+
except: pass
|
| 60 |
+
|
| 61 |
+
import core
|
| 62 |
+
import asyncio
|
| 63 |
+
try:
|
| 64 |
+
async with asyncio.timeout(12):
|
| 65 |
+
async with lineup_lock:
|
| 66 |
+
qs = guild_lineup_queues[self.guild_id]
|
| 67 |
+
|
| 68 |
+
for p, q_other in qs.items():
|
| 69 |
+
if interaction.user in q_other and p != self.pos:
|
| 70 |
+
qs[p] = deque(m for m in q_other if m.id != interaction.user.id)
|
| 71 |
+
|
| 72 |
+
q = qs[self.pos] # Re-fetch just in case
|
| 73 |
+
if interaction.user in q:
|
| 74 |
+
qs[self.pos] = deque(m for m in q if m.id != interaction.user.id)
|
| 75 |
+
else:
|
| 76 |
+
q.append(interaction.user)
|
| 77 |
+
stats = core.storage.player_stats.setdefault(interaction.user.id, {"matches": 0, "positions": {}})
|
| 78 |
+
if interaction.user.id not in counted_stats_per_message[interaction.message.id]:
|
| 79 |
+
stats["matches"] += 1
|
| 80 |
+
stats["positions"][self.pos] = stats["positions"].get(self.pos, 0) + 1
|
| 81 |
+
counted_stats_per_message[interaction.message.id].add(interaction.user.id)
|
| 82 |
+
core.storage.save_stats()
|
| 83 |
+
|
| 84 |
+
# 2. USE edit_original_response (supported after defer)
|
| 85 |
+
await interaction.edit_original_response(
|
| 86 |
+
content=f"@everyone\n**Lineup ({guild_selected_formation[self.guild_id]})**\n\n{format_lineup(self.guild_id)}",
|
| 87 |
+
view=LineupView(self.guild_id)
|
| 88 |
+
)
|
| 89 |
+
except asyncio.TimeoutError:
|
| 90 |
+
await interaction.followup.send("⚠️ The action took too long. Please try again.", ephemeral=True)
|
| 91 |
+
except Exception as e:
|
| 92 |
+
print(f"DEBUG: Lineup error: {e}", flush=True)
|
| 93 |
+
|
| 94 |
+
class FormationSelect(discord.ui.Select):
|
| 95 |
+
def __init__(self, guild_id):
|
| 96 |
+
options = [discord.SelectOption(label=k, value=k) for k in list(FORMATIONS.keys())[:25]]
|
| 97 |
+
super().__init__(placeholder="Select formation...", options=options, custom_id=f"sel_{guild_id}")
|
| 98 |
+
self.guild_id = guild_id
|
| 99 |
+
|
| 100 |
+
async def callback(self, interaction: discord.Interaction):
|
| 101 |
+
if not user_has_lineup_access(interaction.user): return await interaction.response.send_message("❌ No permission", ephemeral=True)
|
| 102 |
+
|
| 103 |
+
# 1. IMMEDIATE DEFER TO STOP "INTERACTION FAILED"
|
| 104 |
+
try: await interaction.response.defer()
|
| 105 |
+
except: pass
|
| 106 |
+
|
| 107 |
+
import asyncio
|
| 108 |
+
try:
|
| 109 |
+
async with asyncio.timeout(12):
|
| 110 |
+
async with lineup_lock:
|
| 111 |
+
gid = self.guild_id
|
| 112 |
+
guild_selected_formation[gid] = self.values[0]
|
| 113 |
+
for q in guild_lineup_queues[gid].values(): q.clear()
|
| 114 |
+
|
| 115 |
+
if "manager" in interaction.message.content.lower() or "Step 1" in interaction.message.content:
|
| 116 |
+
# Delete the setup message and send a FRESH PUBLIC board
|
| 117 |
+
await interaction.message.delete()
|
| 118 |
+
await interaction.channel.send(content=format_manager_header(gid), view=ManagerLineupView(gid))
|
| 119 |
+
else:
|
| 120 |
+
await interaction.edit_original_response(
|
| 121 |
+
content=f"@everyone\n**Lineup ({self.values[0]})**\n\n{format_lineup(gid)}",
|
| 122 |
+
view=LineupView(gid)
|
| 123 |
+
)
|
| 124 |
+
except asyncio.TimeoutError:
|
| 125 |
+
await interaction.followup.send("⚠️ Formation change timed out.", ephemeral=True)
|
| 126 |
+
|
| 127 |
+
class LineupView(discord.ui.View):
|
| 128 |
+
def __init__(self, guild_id):
|
| 129 |
+
super().__init__(timeout=None)
|
| 130 |
+
self.add_item(FormationSelect(guild_id))
|
| 131 |
+
cur_formation = guild_selected_formation[guild_id]
|
| 132 |
+
for pos, label in FORMATIONS.get(cur_formation, FORMATIONS["default"]):
|
| 133 |
+
self.add_item(LineupButton(pos, label, guild_id))
|
| 134 |
+
|
| 135 |
+
# --- MANAGER MODE ---
|
| 136 |
+
class ManagerPlayerPicker(discord.ui.View):
|
| 137 |
+
def __init__(self, pos_key, pos_label, guild_id, original_interaction):
|
| 138 |
+
super().__init__(timeout=60)
|
| 139 |
+
self.pos_key, self.guild_id = pos_key, guild_id
|
| 140 |
+
self.original_interaction = original_interaction
|
| 141 |
+
self.add_item(ManagerUserSelect())
|
| 142 |
+
|
| 143 |
+
class ManagerUserSelect(discord.ui.Select):
|
| 144 |
+
def __init__(self):
|
| 145 |
+
super().__init__(
|
| 146 |
+
select_type=discord.ComponentType.user_select,
|
| 147 |
+
placeholder="Select the player...",
|
| 148 |
+
min_values=1,
|
| 149 |
+
max_values=1
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
async def callback(self, interaction: discord.Interaction):
|
| 153 |
+
# 1. IMMEDIATE DEFER TO STOP "INTERACTION FAILED"
|
| 154 |
+
try: await interaction.response.defer(ephemeral=True)
|
| 155 |
+
except: pass
|
| 156 |
+
|
| 157 |
+
view: ManagerPlayerPicker = self.view
|
| 158 |
+
target_user = self.values[0]
|
| 159 |
+
|
| 160 |
+
import asyncio
|
| 161 |
+
try:
|
| 162 |
+
async with asyncio.timeout(12):
|
| 163 |
+
async with lineup_lock:
|
| 164 |
+
qs = guild_lineup_queues[view.guild_id]
|
| 165 |
+
# Replace current occupant with the picked user
|
| 166 |
+
qs[view.pos_key] = deque([target_user])
|
| 167 |
+
|
| 168 |
+
# Update the main lineup GUI DIRECTLY for instant refresh
|
| 169 |
+
try:
|
| 170 |
+
await view.original_interaction.message.edit(
|
| 171 |
+
content=format_manager_header(view.guild_id),
|
| 172 |
+
view=ManagerLineupView(view.guild_id)
|
| 173 |
+
)
|
| 174 |
+
except:
|
| 175 |
+
# Fallback for edge cases
|
| 176 |
+
await view.original_interaction.edit_original_response(
|
| 177 |
+
content=format_manager_header(view.guild_id),
|
| 178 |
+
view=ManagerLineupView(view.guild_id)
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
await interaction.edit_original_response(content=f"✅ Assigned {target_user.mention} to **{view.pos_key}**")
|
| 182 |
+
except asyncio.TimeoutError:
|
| 183 |
+
await interaction.followup.send("⚠️ Picker timed out.", ephemeral=True)
|
| 184 |
+
except Exception as e:
|
| 185 |
+
print(f"DEBUG: Picker error: {e}", flush=True)
|
| 186 |
+
|
| 187 |
+
def format_manager_header(guild_id):
|
| 188 |
+
lines = ["🛠️ **LINEUP GUI EDITOR**", "▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬"]
|
| 189 |
+
form_key = guild_selected_formation[guild_id]
|
| 190 |
+
formation = FORMATIONS.get(form_key, FORMATIONS["default"])
|
| 191 |
+
qs = guild_lineup_queues[guild_id]
|
| 192 |
+
for pos, label in formation:
|
| 193 |
+
q = qs.get(pos, deque())
|
| 194 |
+
val = q[0] if q else "---"
|
| 195 |
+
display = val.mention if hasattr(val, "mention") else f"`{str(val)}`"
|
| 196 |
+
lines.append(f"📦 **{label}**: {display}")
|
| 197 |
+
lines.append("▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\n*Click a box below to edit a position!*")
|
| 198 |
+
return "\n".join(lines)
|
| 199 |
+
|
| 200 |
+
class ManagerPositionButton(discord.ui.Button):
|
| 201 |
+
def __init__(self, pos, label, guild_id, row):
|
| 202 |
+
qs = guild_lineup_queues[guild_id]
|
| 203 |
+
q = qs.get(pos, deque())
|
| 204 |
+
|
| 205 |
+
# SAFE NAME CHECK: Check if q has players first!
|
| 206 |
+
if q:
|
| 207 |
+
m = q[0]
|
| 208 |
+
val = m.display_name if hasattr(m, "display_name") else str(m)
|
| 209 |
+
else:
|
| 210 |
+
val = "---"
|
| 211 |
+
|
| 212 |
+
# Use a distinctive emoji so we know it's the right button
|
| 213 |
+
super().__init__(
|
| 214 |
+
style=discord.ButtonStyle.secondary,
|
| 215 |
+
label=f"{label}: {val}",
|
| 216 |
+
emoji="🛠️",
|
| 217 |
+
row=row,
|
| 218 |
+
custom_id=f"man_edit_{guild_id}_{pos}"
|
| 219 |
+
)
|
| 220 |
+
self.pos, self.label, self.guild_id = pos, label, guild_id
|
| 221 |
+
|
| 222 |
+
async def callback(self, interaction: discord.Interaction):
|
| 223 |
+
if not user_has_lineup_access(interaction.user):
|
| 224 |
+
return await interaction.response.send_message("❌ No permission to modify the lineup.", ephemeral=True)
|
| 225 |
+
# Pass the current interaction so the picker can update the main message
|
| 226 |
+
view = ManagerPlayerPicker(self.pos, self.label, self.guild_id, interaction)
|
| 227 |
+
await interaction.response.send_message(f"👤 Pick a player for **{self.label}**", view=view, ephemeral=True)
|
| 228 |
+
|
| 229 |
+
class ManagerLineupView(discord.ui.View):
|
| 230 |
+
def __init__(self, guild_id):
|
| 231 |
+
super().__init__(timeout=None)
|
| 232 |
+
form_key = guild_selected_formation[guild_id]
|
| 233 |
+
formation = FORMATIONS.get(form_key, FORMATIONS["default"])
|
| 234 |
+
for i, (pos, label) in enumerate(formation):
|
| 235 |
+
row = 0 if "GK" in pos else 1 if i < 5 else 2 if i < 8 else 3
|
| 236 |
+
self.add_item(ManagerPositionButton(pos, label, guild_id, row))
|
| 237 |
+
|
| 238 |
+
@bot.bridge_command(name="managerlineup", aliases=["managelineup"])
|
| 239 |
+
async def managerlineup(ctx):
|
| 240 |
+
"""Owner Only: Pick formation first, then fill positions manually."""
|
| 241 |
+
if not user_has_lineup_access(ctx.author): return await respond_or_send(ctx, "❌ No permission")
|
| 242 |
+
view = discord.ui.View()
|
| 243 |
+
view.add_item(FormationSelect(ctx.guild.id))
|
| 244 |
+
# Explicitly public
|
| 245 |
+
await respond_or_send(ctx, "📋 **Step 1: Choose Formation**", view=view)
|
login.html
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 6 |
+
<title>FriendlyBot | Login</title>
|
| 7 |
+
<link rel="stylesheet" href="style.css">
|
| 8 |
+
<link rel="preconnect" href="https://fonts.googleapis.com">
|
| 9 |
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
| 10 |
+
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap" rel="stylesheet">
|
| 11 |
+
</head>
|
| 12 |
+
<body style="display: flex; align-items: center; justify-content: center; height: 100vh;">
|
| 13 |
+
<div class="card" style="text-align: center; max-width: 400px; padding: 40px;">
|
| 14 |
+
<div style="background: #5865f2; width: 64px; height: 64px; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 20px;">
|
| 15 |
+
<img src="logo.png" style="width: 32px; border-radius: 50%;">
|
| 16 |
+
</div>
|
| 17 |
+
<h1 style="font-size: 1.5rem; margin-bottom: 10px;">Welcome Back</h1>
|
| 18 |
+
<p style="color: #72767d; margin-bottom: 30px;">Please login with Discord to manage your servers and session settings.</p>
|
| 19 |
+
<a href="/login" class="btn-primary" style="display: inline-block; text-decoration: none;">Login with Discord</a>
|
| 20 |
+
</div>
|
| 21 |
+
</body>
|
| 22 |
+
</html>
|
logo.png
ADDED
|
Git LFS Details
|
manual_lineup.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import discord
|
| 2 |
+
from collections import deque
|
| 3 |
+
from core import (
|
| 4 |
+
bot, user_has_lineup_access, guild_lineup_queues,
|
| 5 |
+
guild_selected_formation, lineup_lock, respond_or_send
|
| 6 |
+
)
|
| 7 |
+
from lineup_manager import FORMATIONS, format_lineup, LineupView
|
| 8 |
+
|
| 9 |
+
class ManualAssignSelect(discord.ui.Select):
|
| 10 |
+
def __init__(self, pos_key, pos_label, guild_id):
|
| 11 |
+
super().__init__(
|
| 12 |
+
select_type=discord.ComponentType.user_select,
|
| 13 |
+
placeholder=f"Assign {pos_label}...",
|
| 14 |
+
custom_id=f"man_{guild_id}_{pos_key}",
|
| 15 |
+
min_values=1,
|
| 16 |
+
max_values=1,
|
| 17 |
+
)
|
| 18 |
+
self.pos_key = pos_key
|
| 19 |
+
self.guild_id = guild_id
|
| 20 |
+
|
| 21 |
+
async def callback(self, interaction: discord.Interaction):
|
| 22 |
+
if not user_has_lineup_access(interaction.user):
|
| 23 |
+
return await interaction.response.send_message("❌ No permission", ephemeral=True)
|
| 24 |
+
|
| 25 |
+
target_user = self.values[0]
|
| 26 |
+
async with lineup_lock:
|
| 27 |
+
qs = guild_lineup_queues[self.guild_id]
|
| 28 |
+
for p, q in qs.items():
|
| 29 |
+
qs[p] = deque(m for m in q if m.id != target_user.id)
|
| 30 |
+
qs[self.pos_key].appendleft(target_user)
|
| 31 |
+
|
| 32 |
+
await interaction.response.send_message(f"✅ Assigned {target_user.mention} to **{self.pos_key}**", ephemeral=True)
|
| 33 |
+
|
| 34 |
+
class ManualPositionSelect(discord.ui.Select):
|
| 35 |
+
def __init__(self, guild_id):
|
| 36 |
+
cur_form = guild_selected_formation[guild_id]
|
| 37 |
+
options = [discord.SelectOption(label=f"Assign {label}", value=pos) for pos, label in FORMATIONS[cur_form]]
|
| 38 |
+
super().__init__(placeholder="Step 1: Choose Position to Edit", options=options, custom_id=f"p_sel_{guild_id}")
|
| 39 |
+
self.guild_id = guild_id
|
| 40 |
+
|
| 41 |
+
async def callback(self, interaction: discord.Interaction):
|
| 42 |
+
pos_key = self.values[0]
|
| 43 |
+
pos_label = next(l for p, l in FORMATIONS[guild_selected_formation[self.guild_id]] if p == pos_key)
|
| 44 |
+
view = discord.ui.View()
|
| 45 |
+
view.add_item(ManualAssignSelect(pos_key, pos_label, self.guild_id))
|
| 46 |
+
await interaction.response.send_message(f"👤 Step 2: Select the player for **{pos_label}**", view=view, ephemeral=True)
|
| 47 |
+
|
| 48 |
+
class ManualLineupView(discord.ui.View):
|
| 49 |
+
def __init__(self, guild_id):
|
| 50 |
+
super().__init__(timeout=None)
|
| 51 |
+
self.add_item(ManualPositionSelect(guild_id))
|
| 52 |
+
|
| 53 |
+
@bot.bridge_command(name="editlineup")
|
| 54 |
+
async def editlineup(ctx):
|
| 55 |
+
"""Admin Only: Manually assign players to specific lineup positions."""
|
| 56 |
+
if not user_has_lineup_access(ctx.author):
|
| 57 |
+
return await respond_or_send(ctx, "❌ No permission to use Manual Draft.")
|
| 58 |
+
embed = discord.Embed(title="📝 Manual Lineup Editor", description="Force-assign players to positions.", color=0x5865F2)
|
| 59 |
+
await respond_or_send(ctx, embed=embed, view=ManualLineupView(ctx.guild.id), ephemeral=True)
|
network_fix.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import aiohttp
|
| 2 |
+
import socket
|
| 3 |
+
import os
|
| 4 |
+
import ssl
|
| 5 |
+
import discord
|
| 6 |
+
import functools
|
| 7 |
+
import sys
|
| 8 |
+
import asyncio
|
| 9 |
+
from aiohttp.client import ClientSession
|
| 10 |
+
from yarl import URL
|
| 11 |
+
|
| 12 |
+
# Force real-time logs
|
| 13 |
+
print = functools.partial(print, flush=True)
|
| 14 |
+
|
| 15 |
+
# Advanced Networking Strategy
|
| 16 |
+
DOMAINS = [
|
| 17 |
+
"ptb.discord.com",
|
| 18 |
+
"canary.discord.com",
|
| 19 |
+
"discord.com"
|
| 20 |
+
]
|
| 21 |
+
# Persist index across module re-imports via environment variable
|
| 22 |
+
_env_idx = os.getenv("FRIENDLY_NET_IDX", "0")
|
| 23 |
+
try:
|
| 24 |
+
current_index = int(_env_idx) % len(DOMAINS)
|
| 25 |
+
except:
|
| 26 |
+
current_index = 0
|
| 27 |
+
|
| 28 |
+
def get_current_domain():
|
| 29 |
+
return DOMAINS[current_index]
|
| 30 |
+
|
| 31 |
+
def rotate_endpoint():
|
| 32 |
+
global current_index
|
| 33 |
+
current_index = (current_index + 1) % len(DOMAINS)
|
| 34 |
+
os.environ["FRIENDLY_NET_IDX"] = str(current_index)
|
| 35 |
+
print(f"🔄 Network: Rotating domain to {get_current_domain()}")
|
| 36 |
+
|
| 37 |
+
def apply_advanced_fixes():
|
| 38 |
+
if hasattr(sys, "_discord_network_fix_applied_v3"): return
|
| 39 |
+
sys._discord_network_fix_applied_v3 = True
|
| 40 |
+
|
| 41 |
+
print("📡 Network: Initializing Absolute Domain Bridge...")
|
| 42 |
+
|
| 43 |
+
# 1. TCP Family Hardening (Force IPv4)
|
| 44 |
+
try:
|
| 45 |
+
_old_connector_init = aiohttp.TCPConnector.__init__
|
| 46 |
+
def _new_connector_init(self, *args, **kwargs):
|
| 47 |
+
kwargs['family'] = socket.AF_INET
|
| 48 |
+
_old_connector_init(self, *args, **kwargs)
|
| 49 |
+
aiohttp.TCPConnector.__init__ = _new_connector_init
|
| 50 |
+
except: pass
|
| 51 |
+
|
| 52 |
+
# 2. ULTIMATE DOMAIN HIJACKER: Intercept the HOST
|
| 53 |
+
try:
|
| 54 |
+
if not hasattr(ClientSession, "_friendly_patched_request"):
|
| 55 |
+
ClientSession._friendly_patched_request = True
|
| 56 |
+
_old_request = ClientSession._request
|
| 57 |
+
async def _new_request(self, method, str_or_url, *args, **kwargs):
|
| 58 |
+
url = URL(str_or_url)
|
| 59 |
+
if url.host == "discord.com":
|
| 60 |
+
target_domain = get_current_domain()
|
| 61 |
+
if target_domain != "discord.com":
|
| 62 |
+
url = url.with_host(target_domain)
|
| 63 |
+
print(f"🔗 HIJACK: {method} {url}")
|
| 64 |
+
|
| 65 |
+
# Extended retry logic for throttled networks
|
| 66 |
+
attempt = 0
|
| 67 |
+
while attempt < 3:
|
| 68 |
+
try:
|
| 69 |
+
return await _old_request(self, method, url, *args, **kwargs)
|
| 70 |
+
except (aiohttp.ClientError, asyncio.TimeoutError, asyncio.exceptions.TimeoutError):
|
| 71 |
+
attempt += 1
|
| 72 |
+
if attempt >= 3: raise
|
| 73 |
+
print(f"⚠️ Network: Request failed (Attempt {attempt}/3). Retrying in 2s...")
|
| 74 |
+
await asyncio.sleep(2.0)
|
| 75 |
+
ClientSession._request = _new_request
|
| 76 |
+
print(f"🔧 Network: Domain Hijacker Active (Targeting {get_current_domain()}).")
|
| 77 |
+
except: pass
|
| 78 |
+
|
| 79 |
+
# 3. Session Hardening (Heroic Timeouts)
|
| 80 |
+
try:
|
| 81 |
+
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
|
| 82 |
+
if not hasattr(ClientSession, "_friendly_patched_init"):
|
| 83 |
+
ClientSession._friendly_patched_init = True
|
| 84 |
+
_old_init = ClientSession.__init__
|
| 85 |
+
def _new_init(self, *args, **kwargs):
|
| 86 |
+
if 'headers' not in kwargs or kwargs['headers'] is None: kwargs['headers'] = {}
|
| 87 |
+
kwargs['headers']['User-Agent'] = UA
|
| 88 |
+
kwargs['trust_env'] = True
|
| 89 |
+
if 'timeout' not in kwargs:
|
| 90 |
+
# Extended timeouts for heavily throttled networks
|
| 91 |
+
kwargs['timeout'] = aiohttp.ClientTimeout(total=60, connect=15, sock_read=30)
|
| 92 |
+
_old_init(self, *args, **kwargs)
|
| 93 |
+
ClientSession.__init__ = _new_init
|
| 94 |
+
except: pass
|
| 95 |
+
|
| 96 |
+
def run_diagnostic():
|
| 97 |
+
import requests
|
| 98 |
+
print("📡 Network Diagnostic: Starting...")
|
| 99 |
+
for domain in DOMAINS:
|
| 100 |
+
try:
|
| 101 |
+
url = f"https://{domain}/api/v10/gateway"
|
| 102 |
+
r = requests.get(url, timeout=10)
|
| 103 |
+
print(f"✅ {domain} reached! Status: {r.status_code}")
|
| 104 |
+
return True
|
| 105 |
+
except Exception as e:
|
| 106 |
+
print(f"❌ {domain} failed: {e}")
|
| 107 |
+
return False
|
requirements.txt
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
py-cord[voice]
|
| 2 |
+
flask
|
| 3 |
+
requests
|
| 4 |
+
python-dotenv
|
| 5 |
+
tzlocal
|
| 6 |
+
Pillow
|
| 7 |
+
SpeechRecognition
|
| 8 |
+
pydub
|
| 9 |
+
aiodns
|
| 10 |
+
cchardet
|
| 11 |
+
gunicorn
|
server.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, render_template, request, jsonify, redirect, url_for, session
|
| 2 |
+
import os
|
| 3 |
+
import json
|
| 4 |
+
import requests
|
| 5 |
+
import urllib.parse
|
| 6 |
+
import sys
|
| 7 |
+
import functools
|
| 8 |
+
|
| 9 |
+
# Force real-time logs (disable buffering)
|
| 10 |
+
print = functools.partial(print, flush=True)
|
| 11 |
+
if hasattr(sys.stdout, "reconfigure"):
|
| 12 |
+
try: sys.stdout.reconfigure(line_buffering=True)
|
| 13 |
+
except: pass
|
| 14 |
+
os.environ["PYTHONUNBUFFERED"] = "1"
|
| 15 |
+
|
| 16 |
+
app = Flask(__name__, template_folder='.', static_folder='.', static_url_path='')
|
| 17 |
+
app.secret_key = "friendlybot_ultra_secure_secret_key_fixed"
|
| 18 |
+
|
| 19 |
+
# Start the Bot 24/7 (Clean Version)
|
| 20 |
+
def start_unified_bot():
|
| 21 |
+
try:
|
| 22 |
+
import friendly_launcher
|
| 23 |
+
import threading
|
| 24 |
+
threading.Thread(target=friendly_launcher.run_bot, daemon=True).start()
|
| 25 |
+
except Exception as e:
|
| 26 |
+
print(f"[*] Launcher Error: {e}")
|
| 27 |
+
|
| 28 |
+
start_unified_bot()
|
| 29 |
+
|
| 30 |
+
# OAuth2 Config
|
| 31 |
+
CLIENT_ID = os.getenv("DISCORD_CLIENT_ID") or os.getenv("CLIENT_ID")
|
| 32 |
+
CLIENT_SECRET = os.getenv("DISCORD_CLIENT_SECRET") or os.getenv("CLIENT_SECRET")
|
| 33 |
+
REDIRECT_URI = os.getenv("DISCORD_REDIRECT_URL") or os.getenv("DISCORD_REDIRECT") or os.getenv("REDIRECT_URL")
|
| 34 |
+
API_ENDPOINT = 'https://discord.com/api/v10'
|
| 35 |
+
|
| 36 |
+
# Path to the shared settings file
|
| 37 |
+
PERSISTENT_DIR = "data"
|
| 38 |
+
GUILD_SETTINGS_FILE = os.path.join(PERSISTENT_DIR, "guild_settings.json")
|
| 39 |
+
GUILDS_FILE = os.path.join(PERSISTENT_DIR, "guilds.json")
|
| 40 |
+
|
| 41 |
+
def get_settings():
|
| 42 |
+
if os.path.exists(GUILD_SETTINGS_FILE):
|
| 43 |
+
try:
|
| 44 |
+
with open(GUILD_SETTINGS_FILE, "r", encoding="utf-8") as f:
|
| 45 |
+
return json.load(f)
|
| 46 |
+
except Exception:
|
| 47 |
+
return {}
|
| 48 |
+
return {}
|
| 49 |
+
|
| 50 |
+
def save_settings(data):
|
| 51 |
+
os.makedirs(PERSISTENT_DIR, exist_ok=True)
|
| 52 |
+
with open(GUILD_SETTINGS_FILE, "w", encoding="utf-8") as f:
|
| 53 |
+
json.dump(data, f)
|
| 54 |
+
|
| 55 |
+
def get_bot_guilds():
|
| 56 |
+
if os.path.exists(GUILDS_FILE):
|
| 57 |
+
try:
|
| 58 |
+
with open(GUILDS_FILE, "r", encoding="utf-8") as f:
|
| 59 |
+
return json.load(f)
|
| 60 |
+
except Exception:
|
| 61 |
+
return []
|
| 62 |
+
return []
|
| 63 |
+
|
| 64 |
+
@app.route('/login')
|
| 65 |
+
def login():
|
| 66 |
+
if not CLIENT_ID or not REDIRECT_URI:
|
| 67 |
+
return "❌ OAuth2 Config Missing: Set DISCORD_CLIENT_ID and DISCORD_REDIRECT_URL in environment variables."
|
| 68 |
+
|
| 69 |
+
encoded_redirect = urllib.parse.quote(REDIRECT_URI)
|
| 70 |
+
return redirect(f"https://discord.com/api/oauth2/authorize?client_id={CLIENT_ID}&redirect_uri={encoded_redirect}&response_type=code&scope=identify%20guilds")
|
| 71 |
+
|
| 72 |
+
@app.route('/callback')
|
| 73 |
+
def callback():
|
| 74 |
+
error = request.args.get('error')
|
| 75 |
+
if error:
|
| 76 |
+
# User cancelled or another error occurred
|
| 77 |
+
return redirect(url_for('home'))
|
| 78 |
+
|
| 79 |
+
code = request.args.get('code')
|
| 80 |
+
data = {
|
| 81 |
+
'client_id': CLIENT_ID,
|
| 82 |
+
'client_secret': CLIENT_SECRET,
|
| 83 |
+
'grant_type': 'authorization_code',
|
| 84 |
+
'code': code,
|
| 85 |
+
'redirect_uri': REDIRECT_URI
|
| 86 |
+
}
|
| 87 |
+
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
|
| 88 |
+
r = requests.post(f'{API_ENDPOINT}/oauth2/token', data=data, headers=headers)
|
| 89 |
+
token_response = r.json()
|
| 90 |
+
|
| 91 |
+
if 'access_token' in token_response:
|
| 92 |
+
session['access_token'] = token_response['access_token']
|
| 93 |
+
return redirect(url_for('home'))
|
| 94 |
+
return "Failed to login: " + str(token_response)
|
| 95 |
+
|
| 96 |
+
@app.route('/')
|
| 97 |
+
def home():
|
| 98 |
+
if 'access_token' not in session:
|
| 99 |
+
return render_template('login.html')
|
| 100 |
+
|
| 101 |
+
headers = {'Authorization': f"Bearer {session['access_token']}"}
|
| 102 |
+
user_guilds = requests.get(f'{API_ENDPOINT}/users/@me/guilds', headers=headers).json()
|
| 103 |
+
|
| 104 |
+
if not isinstance(user_guilds, list):
|
| 105 |
+
session.pop('access_token', None)
|
| 106 |
+
return redirect(url_for('login'))
|
| 107 |
+
|
| 108 |
+
bot_guilds = get_bot_guilds()
|
| 109 |
+
bot_guild_ids = {str(g['id']) for g in bot_guilds}
|
| 110 |
+
|
| 111 |
+
# Filter guilds where user has ADMIN (0x8)
|
| 112 |
+
managed_guilds = []
|
| 113 |
+
for g in user_guilds:
|
| 114 |
+
is_admin = int(g['permissions']) & 0x8
|
| 115 |
+
if is_admin and str(g['id']) in bot_guild_ids:
|
| 116 |
+
# Find matching bot data for the icon/name
|
| 117 |
+
bot_data = next((bg for bg in bot_guilds if str(bg['id']) == str(g['id'])), g)
|
| 118 |
+
managed_guilds.append(bot_data)
|
| 119 |
+
|
| 120 |
+
return render_template('servers.html', guilds=managed_guilds, client_id=CLIENT_ID)
|
| 121 |
+
|
| 122 |
+
@app.route('/guild/<guild_id>')
|
| 123 |
+
def guild_settings(guild_id):
|
| 124 |
+
if 'access_token' not in session:
|
| 125 |
+
return redirect(url_for('login'))
|
| 126 |
+
|
| 127 |
+
# Security check: Does the user HAVE admin in this specific guild?
|
| 128 |
+
headers = {'Authorization': f"Bearer {session['access_token']}"}
|
| 129 |
+
user_guilds = requests.get(f'{API_ENDPOINT}/users/@me/guilds', headers=headers).json()
|
| 130 |
+
|
| 131 |
+
can_manage = False
|
| 132 |
+
for g in user_guilds:
|
| 133 |
+
if str(g['id']) == str(guild_id) and (int(g['permissions']) & 0x8):
|
| 134 |
+
can_manage = True
|
| 135 |
+
break
|
| 136 |
+
|
| 137 |
+
if not can_manage:
|
| 138 |
+
return "❌ Access Denied: You do not have Administrator permissions in this server.", 403
|
| 139 |
+
|
| 140 |
+
settings = get_settings()
|
| 141 |
+
current_settings = settings.get(str(guild_id), {
|
| 142 |
+
"welcome_msg": "Welcome {user} to the server!",
|
| 143 |
+
"goodbye_msg": "Goodbye {user}, we will miss you."
|
| 144 |
+
})
|
| 145 |
+
|
| 146 |
+
bot_guilds = get_bot_guilds()
|
| 147 |
+
guild_name = "Selected Server"
|
| 148 |
+
for g in bot_guilds:
|
| 149 |
+
if str(g['id']) == str(guild_id):
|
| 150 |
+
guild_name = g['name']
|
| 151 |
+
break
|
| 152 |
+
|
| 153 |
+
return render_template('index.html', settings=current_settings, guild_id=guild_id, guild_name=guild_name)
|
| 154 |
+
|
| 155 |
+
@app.route('/api/settings/<guild_id>', methods=['POST'])
|
| 156 |
+
def update_settings(guild_id):
|
| 157 |
+
if 'access_token' not in session:
|
| 158 |
+
return jsonify({"status": "error", "message": "Unauthorized"}), 401
|
| 159 |
+
|
| 160 |
+
# (Same security check as GET)
|
| 161 |
+
headers = {'Authorization': f"Bearer {session['access_token']}"}
|
| 162 |
+
user_guilds = requests.get(f'{API_ENDPOINT}/users/@me/guilds', headers=headers).json()
|
| 163 |
+
can_manage = False
|
| 164 |
+
for g in user_guilds:
|
| 165 |
+
if str(g['id']) == str(guild_id) and (int(g['permissions']) & 0x8):
|
| 166 |
+
can_manage = True
|
| 167 |
+
break
|
| 168 |
+
if not can_manage:
|
| 169 |
+
return jsonify({"status": "error", "message": "Forbidden"}), 403
|
| 170 |
+
|
| 171 |
+
data = request.json
|
| 172 |
+
all_settings = get_settings()
|
| 173 |
+
if str(guild_id) not in all_settings:
|
| 174 |
+
all_settings[str(guild_id)] = {}
|
| 175 |
+
all_settings[str(guild_id)]["welcome_msg"] = data.get("welcome_msg")
|
| 176 |
+
all_settings[str(guild_id)]["goodbye_msg"] = data.get("goodbye_msg")
|
| 177 |
+
save_settings(all_settings)
|
| 178 |
+
return jsonify({"status": "success"})
|
| 179 |
+
|
| 180 |
+
@app.route('/style.css')
|
| 181 |
+
def serve_css():
|
| 182 |
+
return app.send_static_file('style.css')
|
| 183 |
+
|
| 184 |
+
@app.route('/logo.png')
|
| 185 |
+
def serve_logo():
|
| 186 |
+
return app.send_static_file('logo.png')
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
# UptimeRobot route removed
|
| 190 |
+
|
| 191 |
+
@app.route('/logout')
|
| 192 |
+
def logout():
|
| 193 |
+
session.pop('access_token', None)
|
| 194 |
+
return redirect(url_for('home'))
|
| 195 |
+
|
| 196 |
+
if __name__ == '__main__':
|
| 197 |
+
port = int(os.environ.get('PORT', 7860))
|
| 198 |
+
app.run(host='0.0.0.0', port=port)
|
servers.html
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 6 |
+
<title>FriendlyBot | Select Server</title>
|
| 7 |
+
<link rel="stylesheet" href="/style.css">
|
| 8 |
+
<link rel="preconnect" href="https://fonts.googleapis.com">
|
| 9 |
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
| 10 |
+
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap" rel="stylesheet">
|
| 11 |
+
</head>
|
| 12 |
+
<body style="display: block; overflow-y: auto;">
|
| 13 |
+
<div class="container" style="max-width: 1200px; padding: 60px 40px;">
|
| 14 |
+
<h1 style="font-size: 2.2rem; font-weight: 800; margin-bottom: 40px;">Servers</h1>
|
| 15 |
+
|
| 16 |
+
<h2 style="font-size: 1.4rem; color: #b9bbbe; margin-bottom: 20px;">Your Servers</h2>
|
| 17 |
+
<div class="server-grid">
|
| 18 |
+
<a href="https://discord.com/oauth2/authorize?client_id={{ client_id }}&permissions=8&integration_type=0&scope=bot%20applications.commands" target="_blank" class="server-card add-server">
|
| 19 |
+
<div class="add-icon">+</div>
|
| 20 |
+
<div class="server-info">
|
| 21 |
+
<span class="server-name">Invite to your server</span>
|
| 22 |
+
</div>
|
| 23 |
+
</a>
|
| 24 |
+
|
| 25 |
+
{% for guild in guilds %}
|
| 26 |
+
<a href="/guild/{{ guild.id }}" class="server-card">
|
| 27 |
+
{% if guild.icon %}
|
| 28 |
+
<img src="{{ guild.icon }}" class="server-icon">
|
| 29 |
+
{% else %}
|
| 30 |
+
<div class="server-icon-placeholder">{{ guild.name[0] }}</div>
|
| 31 |
+
{% endif %}
|
| 32 |
+
<div class="server-info">
|
| 33 |
+
<span class="server-name">{{ guild.name }}</span>
|
| 34 |
+
</div>
|
| 35 |
+
</a>
|
| 36 |
+
{% endfor %}
|
| 37 |
+
</div>
|
| 38 |
+
</div>
|
| 39 |
+
</body>
|
| 40 |
+
</html>
|
storage_manager.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import datetime
|
| 4 |
+
import discord
|
| 5 |
+
from collections import deque
|
| 6 |
+
|
| 7 |
+
# --- File Paths ---
|
| 8 |
+
PERSISTENT_DIR = "data"
|
| 9 |
+
os.makedirs(PERSISTENT_DIR, exist_ok=True)
|
| 10 |
+
|
| 11 |
+
GUILD_SETTINGS_FILE = os.path.join(PERSISTENT_DIR, "guild_settings.json")
|
| 12 |
+
CONFIG_FILE = os.path.join(PERSISTENT_DIR, "lineup_access.json")
|
| 13 |
+
PLAYER_STATS_FILE = os.path.join(PERSISTENT_DIR, "player_stats.json")
|
| 14 |
+
GUILDS_FILE = os.path.join(PERSISTENT_DIR, "guilds.json")
|
| 15 |
+
|
| 16 |
+
def load_json(path, default):
|
| 17 |
+
if os.path.exists(path):
|
| 18 |
+
try:
|
| 19 |
+
with open(path, "r", encoding="utf-8") as f:
|
| 20 |
+
return json.load(f)
|
| 21 |
+
except: pass
|
| 22 |
+
return default
|
| 23 |
+
|
| 24 |
+
def save_json(path, data):
|
| 25 |
+
try:
|
| 26 |
+
with open(path, "w", encoding="utf-8") as f:
|
| 27 |
+
json.dump(data, f)
|
| 28 |
+
except: pass
|
| 29 |
+
|
| 30 |
+
class StorageManager:
|
| 31 |
+
def __init__(self, bot):
|
| 32 |
+
self.bot = bot
|
| 33 |
+
self.guild_settings = {}
|
| 34 |
+
self.lineup_roles = {}
|
| 35 |
+
self.player_stats = {}
|
| 36 |
+
self.active_polls = {} # {guild_id: message_id}
|
| 37 |
+
self.processed_messages = set() # {(guild_id, message_id)}
|
| 38 |
+
|
| 39 |
+
def load_all_local(self):
|
| 40 |
+
# Load Guild Settings
|
| 41 |
+
data = load_json(GUILD_SETTINGS_FILE, {})
|
| 42 |
+
self.guild_settings = {int(k): v for k, v in data.items()}
|
| 43 |
+
|
| 44 |
+
# Load Roles
|
| 45 |
+
data = load_json(CONFIG_FILE, {})
|
| 46 |
+
self.lineup_roles = {int(k): set(v) for k, v in data.items()}
|
| 47 |
+
|
| 48 |
+
# Load Stats
|
| 49 |
+
data = load_json(PLAYER_STATS_FILE, {})
|
| 50 |
+
self.player_stats = {int(k): v for k, v in data.items()}
|
| 51 |
+
|
| 52 |
+
# Load State
|
| 53 |
+
state = load_json(os.path.join(PERSISTENT_DIR, "state.json"), {})
|
| 54 |
+
self.active_polls = {int(k): v for k, v in state.get("polls", {}).items()}
|
| 55 |
+
self.processed_messages = {tuple(x) for x in state.get("processed", [])}
|
| 56 |
+
|
| 57 |
+
def save_state(self):
|
| 58 |
+
save_json(os.path.join(PERSISTENT_DIR, "state.json"), {
|
| 59 |
+
"polls": {str(k): v for k, v in self.active_polls.items()},
|
| 60 |
+
"processed": [list(x) for x in self.processed_messages]
|
| 61 |
+
})
|
| 62 |
+
|
| 63 |
+
def save_settings(self):
|
| 64 |
+
save_json(GUILD_SETTINGS_FILE, {str(k): v for k, v in self.guild_settings.items()})
|
| 65 |
+
|
| 66 |
+
def save_roles(self):
|
| 67 |
+
save_json(CONFIG_FILE, {str(k): list(v) for k, v in self.lineup_roles.items()})
|
| 68 |
+
|
| 69 |
+
def save_stats(self):
|
| 70 |
+
save_json(PLAYER_STATS_FILE, {str(k): v for k, v in self.player_stats.items()})
|
| 71 |
+
|
| 72 |
+
def save_guilds(self):
|
| 73 |
+
guilds_data = []
|
| 74 |
+
for guild in self.bot.guilds:
|
| 75 |
+
guilds_data.append({
|
| 76 |
+
"id": str(guild.id),
|
| 77 |
+
"name": guild.name,
|
| 78 |
+
"icon": str(guild.icon.url) if guild.icon else None
|
| 79 |
+
})
|
| 80 |
+
save_json(GUILDS_FILE, guilds_data)
|
| 81 |
+
|
| 82 |
+
async def backup_to_discord(self):
|
| 83 |
+
"""Hidden cloud backup to private channel."""
|
| 84 |
+
guild = self.bot.guilds[0] if self.bot.guilds else None
|
| 85 |
+
if not guild: return
|
| 86 |
+
|
| 87 |
+
channel = discord.utils.get(guild.text_channels, name="friendlybot-storage")
|
| 88 |
+
if not channel:
|
| 89 |
+
overwrites = {guild.default_role: discord.PermissionOverwrite(read_messages=False), guild.me: discord.PermissionOverwrite(read_messages=True)}
|
| 90 |
+
channel = await guild.create_text_channel("friendlybot-storage", overwrites=overwrites)
|
| 91 |
+
|
| 92 |
+
from core import guild_voice_channels
|
| 93 |
+
backup = {
|
| 94 |
+
"roles": {str(k): list(v) for k, v in self.lineup_roles.items()},
|
| 95 |
+
"settings": {str(k): v for k, v in self.guild_settings.items()},
|
| 96 |
+
"voice_channels": {str(k): v for k, v in guild_voice_channels.items()},
|
| 97 |
+
"time": str(datetime.datetime.now())
|
| 98 |
+
}
|
| 99 |
+
await channel.send(f"BACKUP_DATA\n```json\n{json.dumps(backup)}\n```")
|
| 100 |
+
|
| 101 |
+
async def restore_from_discord(self):
|
| 102 |
+
"""Restore memory from the cloud."""
|
| 103 |
+
from core import guild_voice_channels
|
| 104 |
+
for guild in self.bot.guilds:
|
| 105 |
+
channel = discord.utils.get(guild.text_channels, name="friendlybot-storage")
|
| 106 |
+
if channel:
|
| 107 |
+
async_hist = channel.history(limit=5)
|
| 108 |
+
async for message in async_hist:
|
| 109 |
+
if message.author == self.bot.user and message.content.startswith("BACKUP_DATA"):
|
| 110 |
+
try:
|
| 111 |
+
raw = message.content.split("```json\n")[1].split("\n```")[0]
|
| 112 |
+
data = json.loads(raw)
|
| 113 |
+
self.lineup_roles.update({int(k): set(v) for k, v in data.get("roles", {}).items()})
|
| 114 |
+
self.guild_settings.update({int(k): v for k, v in data.get("settings", {}).items()})
|
| 115 |
+
guild_voice_channels.update({int(k): v for k, v in data.get("voice_channels", {}).items()})
|
| 116 |
+
self.save_roles()
|
| 117 |
+
self.save_settings()
|
| 118 |
+
return True
|
| 119 |
+
except: pass
|
| 120 |
+
return False
|
style.css
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
* {
|
| 2 |
+
margin: 0;
|
| 3 |
+
padding: 0;
|
| 4 |
+
box-sizing: border-box;
|
| 5 |
+
}
|
| 6 |
+
|
| 7 |
+
body {
|
| 8 |
+
font-family: 'Inter', sans-serif;
|
| 9 |
+
background-color: #0f1014;
|
| 10 |
+
color: #ffffff;
|
| 11 |
+
height: 100vh;
|
| 12 |
+
display: flex;
|
| 13 |
+
overflow: hidden;
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
/* Sidebar */
|
| 17 |
+
.sidebar {
|
| 18 |
+
width: 260px;
|
| 19 |
+
background-color: #1a1b21;
|
| 20 |
+
border-right: 1px solid #2a2b32;
|
| 21 |
+
display: flex;
|
| 22 |
+
flex-direction: column;
|
| 23 |
+
padding: 20px;
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
.sidebar-header {
|
| 27 |
+
display: flex;
|
| 28 |
+
align-items: center;
|
| 29 |
+
padding: 10px;
|
| 30 |
+
margin-bottom: 20px;
|
| 31 |
+
background: #5865f2;
|
| 32 |
+
border-radius: 8px;
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
.logo {
|
| 36 |
+
width: 32px;
|
| 37 |
+
height: 32px;
|
| 38 |
+
border-radius: 50%;
|
| 39 |
+
margin-right: 10px;
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
.sidebar-header h1 {
|
| 43 |
+
font-size: 1.1rem;
|
| 44 |
+
font-weight: 700;
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
.back-btn {
|
| 48 |
+
background: #2a2b32;
|
| 49 |
+
color: #b9bbbe;
|
| 50 |
+
padding: 10px;
|
| 51 |
+
border-radius: 6px;
|
| 52 |
+
text-decoration: none;
|
| 53 |
+
font-size: 0.85rem;
|
| 54 |
+
text-align: center;
|
| 55 |
+
margin-bottom: 20px;
|
| 56 |
+
display: block;
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
.nav-menu {
|
| 60 |
+
flex-grow: 1;
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
.nav-item {
|
| 64 |
+
display: flex;
|
| 65 |
+
align-items: center;
|
| 66 |
+
padding: 12px;
|
| 67 |
+
color: #b9bbbe;
|
| 68 |
+
text-decoration: none;
|
| 69 |
+
border-radius: 6px;
|
| 70 |
+
margin-bottom: 5px;
|
| 71 |
+
font-size: 0.9rem;
|
| 72 |
+
transition: all 0.2s;
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
.nav-item:hover, .nav-item.active {
|
| 76 |
+
background-color: #2a2b32;
|
| 77 |
+
color: white;
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
.nav-item i {
|
| 81 |
+
width: 20px;
|
| 82 |
+
margin-right: 12px;
|
| 83 |
+
font-size: 1rem;
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
.sidebar-footer {
|
| 87 |
+
border-top: 1px solid #2a2b32;
|
| 88 |
+
padding-top: 20px;
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
/* Main Content */
|
| 92 |
+
.main-content {
|
| 93 |
+
flex-grow: 1;
|
| 94 |
+
padding: 40px;
|
| 95 |
+
overflow-y: auto;
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
header {
|
| 99 |
+
margin-bottom: 30px;
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
header h2 {
|
| 103 |
+
font-size: 1.8rem;
|
| 104 |
+
font-weight: 800;
|
| 105 |
+
margin-bottom: 10px;
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
header p {
|
| 109 |
+
color: #72767d;
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
.card {
|
| 113 |
+
background-color: #1a1b21;
|
| 114 |
+
border: 1px solid #2a2b32;
|
| 115 |
+
border-radius: 12px;
|
| 116 |
+
padding: 30px;
|
| 117 |
+
max-width: 800px;
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
.card h3 {
|
| 121 |
+
font-size: 1.2rem;
|
| 122 |
+
margin-bottom: 25px;
|
| 123 |
+
color: #5865f2;
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
.input-group {
|
| 127 |
+
margin-bottom: 20px;
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
label {
|
| 131 |
+
display: block;
|
| 132 |
+
margin-bottom: 8px;
|
| 133 |
+
font-size: 0.85rem;
|
| 134 |
+
font-weight: 600;
|
| 135 |
+
color: #b9bbbe;
|
| 136 |
+
text-transform: uppercase;
|
| 137 |
+
letter-spacing: 0.5px;
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
textarea {
|
| 141 |
+
width: 100%;
|
| 142 |
+
background-color: #0f1014;
|
| 143 |
+
border: 1px solid #2a2b32;
|
| 144 |
+
border-radius: 8px;
|
| 145 |
+
color: white;
|
| 146 |
+
padding: 15px;
|
| 147 |
+
font-family: 'Fira Code', monospace;
|
| 148 |
+
font-size: 0.9rem;
|
| 149 |
+
resize: vertical;
|
| 150 |
+
min-height: 100px;
|
| 151 |
+
outline: none;
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
textarea:focus {
|
| 155 |
+
border-color: #5865f2;
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
.hint {
|
| 159 |
+
font-size: 0.8rem;
|
| 160 |
+
color: #5d5f66;
|
| 161 |
+
margin-top: 8px;
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
.btn-primary {
|
| 165 |
+
background-color: #5865f2;
|
| 166 |
+
color: white;
|
| 167 |
+
border: none;
|
| 168 |
+
padding: 12px 25px;
|
| 169 |
+
border-radius: 6px;
|
| 170 |
+
font-weight: 700;
|
| 171 |
+
cursor: pointer;
|
| 172 |
+
transition: opacity 0.2s;
|
| 173 |
+
display: block;
|
| 174 |
+
margin-left: auto;
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
/* Server Selection Grid */
|
| 178 |
+
.server-grid {
|
| 179 |
+
display: grid;
|
| 180 |
+
grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
|
| 181 |
+
gap: 20px;
|
| 182 |
+
margin-bottom: 40px;
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
.server-card {
|
| 186 |
+
background-color: #1a1b21;
|
| 187 |
+
border: 1px solid #2a2b32;
|
| 188 |
+
border-radius: 12px;
|
| 189 |
+
padding: 20px;
|
| 190 |
+
display: flex;
|
| 191 |
+
align-items: center;
|
| 192 |
+
text-decoration: none;
|
| 193 |
+
color: white;
|
| 194 |
+
transition: transform 0.2s, background-color 0.2s;
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
.server-card:hover {
|
| 198 |
+
background-color: #2a2b32;
|
| 199 |
+
transform: translateY(-2px);
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
.server-icon, .server-icon-placeholder {
|
| 203 |
+
width: 64px;
|
| 204 |
+
height: 64px;
|
| 205 |
+
border-radius: 12px;
|
| 206 |
+
margin-right: 15px;
|
| 207 |
+
background-color: #2f3136;
|
| 208 |
+
display: flex;
|
| 209 |
+
align-items: center;
|
| 210 |
+
justify-content: center;
|
| 211 |
+
font-size: 1.5rem;
|
| 212 |
+
font-weight: 700;
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
.add-server {
|
| 216 |
+
border: 1px dashed #5865f2;
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
.add-icon {
|
| 220 |
+
width: 64px;
|
| 221 |
+
height: 64px;
|
| 222 |
+
border-radius: 12px;
|
| 223 |
+
background-color: #2f3136;
|
| 224 |
+
color: #5865f2;
|
| 225 |
+
display: flex;
|
| 226 |
+
align-items: center;
|
| 227 |
+
justify-content: center;
|
| 228 |
+
font-size: 2.5rem;
|
| 229 |
+
font-weight: 300;
|
| 230 |
+
margin-right: 15px;
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
.server-name {
|
| 234 |
+
font-weight: 700;
|
| 235 |
+
font-size: 1rem;
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
.btn-primary:hover {
|
| 239 |
+
opacity: 0.9;
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
.btn-primary:disabled {
|
| 243 |
+
opacity: 0.5;
|
| 244 |
+
cursor: not-allowed;
|
| 245 |
+
}
|