Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,9 @@ jobs:
# Windows earns its place: the uvloop marker and update.py's chmod
# fallback never execute on Linux.
os: [ubuntu-latest, windows-latest]
python-version: ["3.13"]
include:
# The image pins 3.13, but the project documents 3.13+ support and the
# dependencies float, so this is what proves the promise still holds.
- os: ubuntu-latest
python-version: "3.14"
# Must match .python-version and the Dockerfile's minor;
# tests/test_ci_workflow.py asserts that.
python-version: ["3.15"]
runs-on: ${{ matrix.os }}
timeout-minutes: 20
steps:
Expand All @@ -43,6 +40,10 @@ jobs:
with:
python-version: ${{ matrix.python-version }}
- name: Install
# PyYAML has no cp315 wheel; without this it builds its C extension,
# which needs MSVC on Windows.
env:
PYYAML_FORCE_LIBYAML: "0"
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
Expand Down Expand Up @@ -103,7 +104,7 @@ jobs:
-e OWNER_ID=1 \
-e DATABASE_URL=mongodb://localhost:27017/smoke \
fyaz05/thunder:test python -c \
"import Thunder, Thunder.__main__, uvloop, tgcrypto, aiohttp; print('ok', Thunder.__version__)"
"import Thunder, Thunder.__main__, uvloop, warpcrypto, aiohttp; print('ok', Thunder.__version__)"
- name: Publish
# Only reached once the smoke test passed, and only for a push event: a
# pull request never receives secrets. Rebuilds from the cache the tested
Expand Down
2 changes: 1 addition & 1 deletion .python-version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
3.13
3.15
27 changes: 20 additions & 7 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# AGENTS.md — Thunder File-to-Link Bot

Python 3.13+ Telegram bot converting files to direct HTTP links. Uses Pyrofork, aiohttp, MongoDB, uvloop.
Python 3.15 Telegram bot converting files to direct HTTP links. Uses wzgram, aiohttp, MongoDB, uvloop.

## Run

Expand All @@ -15,7 +15,7 @@ python3 update.py # Update only (rolls back if the new tree is unusable

```bash
pip install -r requirements.txt
# aiohttp, cloudscraper, Jinja2, pyrofork, pymongo, psutil, python-dotenv, speedtest-cli, tgcrypto-pyrofork
# aiohttp, cloudscraper, Jinja2, wzgram, pymongo, psutil, python-dotenv, speedtest-cli
# uvloop (non-Windows/Cygwin only, requirements.txt marker); asyncio loop elsewhere
```

Expand Down Expand Up @@ -95,15 +95,26 @@ Copy `config_sample.env` → `config.env`. Required vars: `API_ID`, `API_HASH`,
## Testing

```bash
pip install -r requirements-dev.txt
PYYAML_FORCE_LIBYAML=0 pip install -r requirements-dev.txt # POSIX
python -m pytest -q # ~20s on Linux, ~45s on Windows; no credentials needed
python -m ruff check . # config lives in pyproject.toml
```

PyYAML has no `cp315` wheel, so the env var is required; on Windows set it first,
since `VAR=value cmd` is not valid there:

```powershell
$env:PYYAML_FORCE_LIBYAML = "0"; pip install -r requirements-dev.txt
```

A cached wheel from an earlier build can make a plain install appear to work — use
`--no-cache-dir` to check.

Covers request parsing, slot conservation and truncation on the streaming
routes, the import cycle, database naming, /status before startup,
update.py preconditions and rollback, plugin handler registration, the CI
workflow's invariants, and .gitignore hygiene.
workflow's invariants, .gitignore hygiene, and the interpreter and requirements
guards.

`pytest` and `ruff` both read `pyproject.toml`; there is no `pytest.ini`.

Expand All @@ -116,11 +127,13 @@ CI notices a bad upstream release. Every command below was run to confirm it wor
and leaves no lock file:

```bash
uv venv .venv --python 3.13 # ~0.15s
uv pip install --python .venv/bin/python -r requirements-dev.txt # ~3s first time
uv venv .venv --python 3.15 # ~0.15s
PYYAML_FORCE_LIBYAML=0 uv pip install --python .venv/bin/python -r requirements-dev.txt
uvx ruff check . # ~0.1s, no install needed
```

The same env var applies to `uv pip install`, which builds the same sdist.

On Windows the interpreter is `.venv\Scripts\python.exe`. `uv pip install` runs in
well under a second once anything is installed; the first install after creating
the environment takes a few seconds. Re-running it is safe.
Expand All @@ -131,7 +144,7 @@ One caveat if you deploy from this checkout: `uv venv` creates an environment
cleanest result comes from seeding pip in the first place:

```bash
uv venv --seed .venv --python 3.13 # includes pip
uv venv --seed .venv --python 3.15 # includes pip
```

## Debugging
Expand Down
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM python:3.13-slim
FROM python:3.15-slim

ENV PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1
Expand Down
26 changes: 17 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
<p align="center">

[![Deploy to Railyard](https://app.railyard.run/deploy/badge)](https://app.railyard.run/deploy?repo=https://github.com/fyaz05/FileToLink)
<img src="https://cdn.jsdelivr.net/gh/fyaz05/Resources@main/FileToLink/Thunder.jpg" alt="Thunder Logo" width="120">
<h1 align="center">⚡ Thunder</h1>
</p>
Expand All @@ -10,8 +8,8 @@
</p>

<p align="center">
<a href="https://www.python.org/"><img src="https://img.shields.io/badge/python-3.13%2B-blue?style=for-the-badge&logo=python" alt="Python Version"></a>
<a href="https://github.com/Mayuri-Chan/pyrofork"><img src="https://img.shields.io/badge/Pyrofork-red?style=for-the-badge" alt="Pyrofork"></a>
<a href="https://www.python.org/"><img src="https://img.shields.io/badge/python-3.15-blue?style=for-the-badge&logo=python" alt="Python Version"></a>
<a href="https://github.com/rjriajul/wzgram"><img src="https://img.shields.io/badge/wzgram-red?style=for-the-badge" alt="wzgram"></a>
<a href="LICENSE"><img src="https://img.shields.io/github/license/fyaz05/FileToLink?style=for-the-badge&color=green" alt="License"></a>
<a href="https://t.me/Thunder_Updates"><img src="https://img.shields.io/badge/Telegram-Channel-blue?style=for-the-badge&logo=telegram" alt="Telegram Channel"></a>
</p>
Expand Down Expand Up @@ -136,7 +134,7 @@ Copy `config_sample.env` to `config.env` and fill in your values.
| `MAX_BATCH_FILES` | Maximum files in batch processing | `50` |
| `CHANNEL` | Allow processing messages from channels | `False` |
| `BANNED_CHANNELS` | Blocked channel IDs | *(empty)* |
| `SLEEP_THRESHOLD` | Pyrogram flood-wait threshold | `600` |
| `SLEEP_THRESHOLD` | Flood-wait threshold in seconds | `600` |
| `WORKERS` | Async workers | `8` |
| `NAME` | Bot name; also the MongoDB database name (unsafe chars become `_`) | `ThunderF2L` |
| `BIND_ADDRESS` | Bind address | `0.0.0.0` |
Expand Down Expand Up @@ -287,7 +285,7 @@ This section covers the complete setup process for deploying Thunder, from prere

| Requirement | Description | Source |
| :--- | :--- | :--- |
| Python 3.13 | Programming language | [python.org](https://python.org) |
| Python 3.15 | Programming language | [python.org](https://python.org) |
| MongoDB | Database | [mongodb.com](https://mongodb.com) |
| Telegram API | API credentials | [my.telegram.org](https://my.telegram.org/apps) |
| Bot Token | From @BotFather | [@BotFather](https://t.me/BotFather) |
Expand Down Expand Up @@ -578,6 +576,11 @@ A: Your browser likely doesn't support the file's audio or video format (codec).
**Q: Why does the bot sometimes become unresponsive?**
A: This is likely a **Telegram Flood Wait**. To prevent spam, Telegram temporarily limits accounts that make too many requests. The bot is designed to handle this automatically by pausing and will resume on its own once the limit is lifted.

**Q: On shutdown I see `Task was destroyed but it is pending!` — is something broken?**
A: No, if `✓ Database connection closed` was printed first. The library leaves its media
sessions open on teardown; the bot still exits cleanly. Expect six after a download, none if
nothing was streamed.

#### **Performance**

**Q: How can I fix slow download and streaming speeds?**
Expand Down Expand Up @@ -605,10 +608,15 @@ Contributions are welcome! Please follow these steps:
2. Create a new feature branch (`git checkout -b feature/amazing-feature`).
3. Make your change and run the suite and linter:
```bash
pip install -r requirements-dev.txt
PYYAML_FORCE_LIBYAML=0 pip install -r requirements-dev.txt # POSIX
python -m pytest -q
python -m ruff check .
```
The env var is needed on Python 3.15 (no `cp315` wheel). On Windows, where that
assignment is not valid, set it first:
```powershell
$env:PYYAML_FORCE_LIBYAML = "0"; pip install -r requirements-dev.txt
```
4. Commit your changes (`git commit -m 'Add some amazing feature'`).
5. Push to the branch (`git push origin feature/amazing-feature`).
6. Open a Pull Request.
Expand All @@ -622,10 +630,10 @@ Licensed under the [Apache License 2.0](LICENSE). See the `LICENSE` file for det

## Acknowledgments

- [Pyrofork](https://github.com/Mayuri-Chan/pyrofork) - Telegram MTProto API Framework
- [wzgram](https://github.com/rjriajul/wzgram) - Telegram MTProto API Framework
- [aiohttp](https://github.com/aio-libs/aiohttp) - Asynchronous HTTP Client/Server
- [PyMongo](https://github.com/mongodb/mongo-python-driver) - Asynchronous MongoDB Driver
- [TgCrypto](https://github.com/wulan17/tgcrypto-pyrofork) - High-performance cryptography library
- [WarpCrypto](https://github.com/rjriajul/warpcrypto) - High-performance cryptography library (Rust)

## ⚠️ Disclaimer

Expand Down
2 changes: 1 addition & 1 deletion Thunder/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
import time

StartTime = time.time()
__version__ = "2.1.0"
__version__ = "2.5.0"
2 changes: 1 addition & 1 deletion Thunder/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

from pathlib import Path

# Pyrofork binds a client to the loop current at creation and Thunder.bot
# wzgram binds a client to the loop current at creation and Thunder.bot
# creates it on import, so the loop has to exist before these imports.
try:
from uvloop import install
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

[tool.ruff]
line-length = 120
target-version = "py313"
target-version = "py315"

[tool.ruff.lint]
# E4 stays out on purpose: __main__.py imports after creating the event loop,
Expand Down
2 changes: 2 additions & 0 deletions requirements-dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,6 @@ pytest-asyncio
# Lint gate (config in pyproject.toml), run locally and in CI.
ruff
# tests/test_ci_workflow.py parses the workflow files to check their invariants.
# No cp315 wheel: install with PYYAML_FORCE_LIBYAML=0, or the sdist build needs
# MSVC on Windows.
pyyaml
4 changes: 1 addition & 3 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@
aiohttp>=3.14
cloudscraper
Jinja2
pyrofork
wzgram
pymongo
psutil
python-dotenv
speedtest-cli
# Fork provides cp313/cp314 wheels (avoids C toolchain at build time) and imports as "tgcrypto".
tgcrypto-pyrofork
# uvloop is Unix-only; bot falls back to standard asyncio on Windows.
uvloop>=0.22.1; sys_platform != "win32" and sys_platform != "cygwin"
112 changes: 105 additions & 7 deletions tests/test_ci_workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@
PINNED_ACTION = re.compile(r"^[^@\s]+@[0-9a-f]{40}$")
PUSH_EVENT = "github.event_name == 'push'"

# The interpreter the project ships, read from .python-version rather than written
# twice, so a version bump has one place to change.
PRIMARY_PYTHON = (REPO / ".python-version").read_text(encoding="utf-8").strip()


def load(path: Path):
return yaml.safe_load(path.read_text(encoding="utf-8"))
Expand Down Expand Up @@ -123,18 +127,32 @@ def test_the_suite_runs_on_both_operating_systems():
assert any(os_name.startswith("windows") for os_name in matrix["os"]), (
"the uvloop marker and update.py's chmod fallback only run on Windows"
)
assert "3.13" in [str(value) for value in matrix["python-version"]]
assert PRIMARY_PYTHON in [str(value) for value in matrix["python-version"]]


def test_the_tested_python_is_the_one_the_project_ships():
"""`.python-version`, the Dockerfile and CI must name one version.

def test_the_documented_python_range_is_actually_tested():
"""README says 3.13+; a floating dependency can quietly drop the newer one."""
Three files describe the interpreter and can drift apart silently.
"""
matrix = workflow()["jobs"]["test"]["strategy"]["matrix"]
tested = {str(value) for value in matrix["python-version"]}
tested |= {str(entry["python-version"]) for entry in matrix.get("include", [])}
assert "3.14" in tested, (
"3.14 was deferred only until uvloop shipped cp314 wheels, which it now "
"does; the range is documented, so it is tested"
)

stated = (REPO / ".python-version").read_text(encoding="utf-8").strip()

assert stated in tested, \
f".python-version says {stated!r} but CI tests {sorted(tested)}"

# Parse FROM rather than reading line 0: a `# syntax=` directive would break
# that, and a substring test would accept a version named only in a comment.
base_images = re.findall(r"^FROM\s+(\S+)", (REPO / "Dockerfile").read_text(encoding="utf-8"),
flags=re.MULTILINE | re.IGNORECASE)
assert base_images, "the Dockerfile has no FROM line"
minor = ".".join(stated.split(".")[:2])
assert any(re.fullmatch(rf"python:{re.escape(minor)}(\.\d+)?-\w+", image)
for image in base_images), \
f"the Dockerfile builds from {base_images}, not {minor}"


def test_a_weekly_run_guards_the_floating_dependencies():
Expand Down Expand Up @@ -256,3 +274,83 @@ def test_dependabot_only_tracks_actions():
assert ecosystems == {"github-actions"}, (
"app dependencies float by policy, so only the pinned actions need updates"
)


def test_the_archived_library_stays_out_of_the_requirements():
"""The retired distributions must not return, and wzgram must stay named.

Nothing else in the tree mentions the old names, so a revert of this file
would be silent until a deployment broke.
"""
def package_name(entry: str) -> str:
# PEP 503: case-insensitive, and -/_/. are interchangeable, so `Pyrofork`
# must not slip past a check for `pyrofork`.
raw = re.split(r"[<>=!~;\[ (]", entry.strip(), maxsplit=1)[0]
return re.sub(r"[-_.]+", "-", raw).lower()

entries = [
line.strip() for line in
(REPO / "requirements.txt").read_text(encoding="utf-8").splitlines()
if line.strip() and not line.lstrip().startswith("#")
]
names = {package_name(entry) for entry in entries}

for retired in ("pyrofork", "tgcrypto-pyrofork"):
assert retired not in names, f"{retired} is retired; wzgram replaces it"

assert "wzgram" in names, "wzgram is what the `pyrogram` imports resolve through"


def test_the_crypto_backend_is_checked_in_the_image():
"""The smoke test must prove the crypto backend shipped.

The import list is the only place asserting the backend is present in the
built image, so a stale name there surfaces only when the image fails to start.
"""
steps = workflow()["jobs"]["build"]["steps"]
runs = [step for step in steps if "docker run" in str(step.get("run", ""))]
assert runs, "the image is never run, so nothing proves it starts"

# Read the parsed `run` values: a commented-out smoke test still matches a
# text search while executing nothing.
commands = " ".join(str(step["run"]) for step in runs)
imports = [line for line in commands.splitlines() if "import Thunder" in line]
assert imports, "the smoke test no longer imports the app"

assert any("warpcrypto" in line for line in imports), \
"the smoke test does not import warpcrypto, so nothing proves the backend shipped"
assert not any("tgcrypto" in line for line in imports), \
"tgcrypto is no longer a dependency; importing it would fail the gate"


def test_the_dev_install_is_documented_the_way_ci_does_it():
"""The documented dev installs must match what CI does.

PyYAML has no cp315 wheel, so the documented install needs the env var or it
fails locally while CI passes. Either spelling counts: `VAR=0 cmd` on POSIX,
`$env:VAR = "0"; cmd` in PowerShell.
"""
# Matches both `PYYAML_FORCE_LIBYAML=0` and `$env:PYYAML_FORCE_LIBYAML = "0"`.
sets_the_var = re.compile(r"PYYAML_FORCE_LIBYAML\s*=\s*[\"']?0")

for relative in ("requirements-dev.txt", "AGENTS.md", "README.md"):
text = (REPO / relative).read_text(encoding="utf-8")
assert sets_the_var.search(text), (
f"{relative} no longer tells the reader to set PYYAML_FORCE_LIBYAML=0, "
"so a dev install on 3.15 fails where CI succeeds"
)
commands = [line.strip() for line in text.splitlines()
if "install" in line and "requirements-dev" in line
and not line.lstrip().startswith("#")]
for command in commands:
assert sets_the_var.search(command), (
f"{relative} documents `{command}` without setting the env var, "
"which fails on 3.15; both the pip and uv forms need it"
)

install = next(step for step in workflow()["jobs"]["test"]["steps"]
if step.get("name") == "Install")
assert (install.get("env") or {}).get("PYYAML_FORCE_LIBYAML") == "0", (
"the CI install step dropped the env var, so the job would fail on the "
"sdist build it is documented to avoid"
)
3 changes: 2 additions & 1 deletion tests/test_deployment_entrypoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,6 @@ def test_platform_files_consumed_at_deploy_time_still_exist():
target = REPO / name
assert target.is_file(), f"{name} is read by the deploy platform, not by our code"

# Local tooling and buildpack deploys read this; the Docker image does not.
assert (REPO / ".python-version").read_text(encoding="utf-8").strip(), \
"Heroku reads this to pick the interpreter"
"uv and buildpack-based deploys read this to pick the interpreter"
Loading
Loading