Skip to content

refactor code - #9

Open
NimaQu wants to merge 2 commits into
masterfrom
code-refactor-by-5.6sol
Open

refactor code#9
NimaQu wants to merge 2 commits into
masterfrom
code-refactor-by-5.6sol

Conversation

@NimaQu

@NimaQu NimaQu commented Jul 14, 2026

Copy link
Copy Markdown
Owner

No description provided.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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-bot CLI.
  • 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.

Comment thread src/captcha_bot/services.py Outdated
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 thread src/captcha_bot/web.py
Comment on lines +129 to +130
except ChatAdminRequired:
logger.warning("bot lacks permission to approve challenge", extra={"challenge_id": challenge_id})
Comment thread src/captcha_bot/web.py
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 thread src/captcha_bot/web.py
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 thread src/captcha_bot/web.py
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants