refactor code - #9
Open
NimaQu wants to merge 2 commits into
Open
Conversation
There was a problem hiding this comment.
Pull request overview
This PR is a full refactor from the legacy monolithic Pyrogram + Flask implementation into a packaged FastAPI application with typed configuration, async PostgreSQL persistence, and a new CLI/CI + pytest suite.
Changes:
- Replace Flask web entrypoints with FastAPI routes (
/,/healthz,/recaptcha) plus a structured async app lifespan that owns DB/HTTP/Telegram resources. - Introduce a typed TOML configuration model with legacy INI/JSON migration and a new
captcha-botCLI. - Add substantial unit/integration test coverage and a GitHub Actions quality workflow (format/lint/typecheck/tests/alembic/audit).
Reviewed changes
Copilot reviewed 59 out of 62 changed files in this pull request and generated 9 comments.
Show a summary per file
| File | Description |
|---|---|
| web.py | Removed legacy Flask web server implementation. |
| Timer/init.py | Removed legacy asyncio timer helper. |
| test.py | Removed standalone test script. |
| templates/index.html | Updated template to use Starlette/FastAPI static URL generation. |
| templates/recaptcha.html | Updated template to accept explicit error context instead of Flask flash messages. |
| templates/result.html | Updated template to accept explicit notice/category context instead of Flask flash messages. |
| src/captcha_bot/web.py | Added FastAPI web routes, middleware headers, and Turnstile verification flow. |
| src/captcha_bot/services.py | Added policy + Turnstile service layer. |
| src/captcha_bot/handlers/common.py | Added shared handler utilities (permissions, scheduling, logging helpers). |
| src/captcha_bot/handlers/challenge.py | Added challenge/join flow handlers and timeout processing. |
| src/captcha_bot/handlers/admin.py | Added admin command handlers (reload/leave/config/log/ip tools). |
| src/captcha_bot/handlers/init.py | Added handler registration exports. |
| src/captcha_bot/challenges.py | Added in-memory concurrent-safe challenge registry + math challenge/turnstile helpers. |
| src/captcha_bot/db/models.py | Added SQLAlchemy models for async PostgreSQL schema. |
| src/captcha_bot/db/repository.py | Added async repository with upserts, logging, and query helpers. |
| src/captcha_bot/db/importer.py | Added CSV importer for legacy DB data. |
| src/captcha_bot/db/init.py | Added DB module exports. |
| src/captcha_bot/context.py | Added AppContext container for shared app dependencies. |
| src/captcha_bot/config.py | Added strict TOML settings model, reload semantics, and legacy config migration. |
| src/captcha_bot/app.py | Added FastAPI app factory + lifespan wiring for DB/HTTP/Telegram client. |
| src/captcha_bot/cli.py | Added CLI entrypoint for run/migrate-config/import-csv workflows. |
| src/captcha_bot/main.py | Added python -m captcha_bot entrypoint. |
| src/captcha_bot/init.py | Added package metadata. |
| main.py | Replaced legacy monolith with backward-compatible wrapper invoking the new CLI. |
| README.md | Updated documentation to match new architecture, config format, and tooling. |
| pyproject.toml | Updated packaging metadata, dependencies, dev tooling, and pytest/ruff config. |
| config.example.toml | Added new example TOML config. |
| config.example.json | Removed legacy JSON config example. |
| config.example.ini | Removed legacy INI config example. |
| model.py | Removed legacy SQLAlchemy models module. |
| dbhelper.py | Removed legacy sync DB helper layer. |
| db.py | Removed legacy DB bootstrap/CSV import script. |
| challengedata.py | Removed legacy threaded challenge store. |
| challenge/recaptcha.py | Removed legacy reCAPTCHA/Turnstile wrapper. |
| challenge/math.py | Removed legacy math challenge generator. |
| challenge/autokickcache.py | Removed legacy auto-kick cache placeholder. |
| ai.py | Removed legacy OpenAI-based spam detection module. |
| example.service | Added updated systemd service unit for the new CLI runner. |
| exapmle.service | Removed misspelled legacy systemd example. |
| Dockerfile | Removed legacy Docker build. |
| docker-run.sh | Removed legacy Docker run script. |
| alembic/env.py | Updated Alembic env to read DB URL from CAPTCHA_BOT_CONFIG TOML settings. |
| alembic.ini | Updated Alembic config path separator handling. |
| alembic/versions/13a9421b19d9_add_challenge_id.py | Reformatted/modernized Alembic migration typing/strings. |
| alembic/versions/c945fe00daeb_change_ip_length.py | Cleaned migration operations and typing. |
| alembic/versions/b841fd90a794_remove.py | Cleaned migration operations and typing. |
| alembic/versions/7f4c2a9d5e10_async_schema_cleanup.py | Added new migration to clean schema, add constraints/indexes, and drop legacy column/constraints. |
| .gitignore | Updated ignores for TOML config + modern Python tooling caches. |
| .github/workflows/quality.yml | Added CI workflow running formatting, linting, type checks, tests, Alembic checks, and dependency audit. |
| tests/conftest.py | Added settings fixture loading config.example.toml. |
| tests/test_web.py | Added FastAPI web route tests (headers, health, Turnstile flow, proxy IP trust). |
| tests/test_services.py | Added PolicyService + TurnstileService tests. |
| tests/test_repository_unit.py | Added repository unit tests with mocked async sessions. |
| tests/test_importer.py | Added CSV importer unit tests. |
| tests/test_handlers.py | Added broad handler behavior tests (admin + challenge flows). |
| tests/test_database_integration.py | Added PostgreSQL integration tests for Alembic and concurrent repository writes. |
| tests/test_config.py | Added settings validation and legacy migration tests. |
| tests/test_common.py | Added common utility tests. |
| tests/test_cli_app.py | Added CLI and app lifespan tests. |
| tests/test_challenges.py | Added challenge registry and math challenge tests. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| chat_id = int(arguments[1]) | ||
| await client.send_message(chat_id, context.config.settings.messages.leave_message) | ||
| await client.leave_chat(chat_id, delete=True) | ||
| except ValueError, RPCError: |
| for user_id in user_ids: | ||
| try: | ||
| user = await client.get_users(user_id) | ||
| except BadRequest, IndexError: |
| except BadRequest: | ||
| await message.reply("Bot 不在该群组中") | ||
| return | ||
| except ValueError, IndexError: |
Comment on lines
+63
to
+71
| async def runner() -> None: | ||
| try: | ||
| if delay: | ||
| await asyncio.sleep(delay) | ||
| await coroutine | ||
| except asyncio.CancelledError: | ||
| raise | ||
| except RPCError: | ||
| logger.exception("background Telegram operation failed", extra={"task": name}) |
Comment on lines
+129
to
+130
| except ChatAdminRequired: | ||
| logger.warning("bot lacks permission to approve challenge", extra={"challenge_id": challenge_id}) |
Comment on lines
+87
to
+94
| await context.repository.log_recaptcha( | ||
| challenge_id, | ||
| session.user_id, | ||
| session.chat_id, | ||
| remote_ip, | ||
| user_agent, | ||
| RecaptchaLogAction.PAGE_VISIT, | ||
| ) |
Comment on lines
+104
to
+111
| await context.repository.log_recaptcha( | ||
| challenge_id, | ||
| session.user_id, | ||
| session.chat_id, | ||
| remote_ip, | ||
| user_agent, | ||
| RecaptchaLogAction.FAILED, | ||
| ) |
Comment on lines
+131
to
+138
| await context.repository.log_recaptcha( | ||
| challenge_id, | ||
| session.user_id, | ||
| session.chat_id, | ||
| remote_ip, | ||
| user_agent, | ||
| RecaptchaLogAction.PASSED, | ||
| ) |
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
No description provided.