126 lines
3.2 KiB
Python
126 lines
3.2 KiB
Python
#!/usr/bin/env python3
|
|
"""TG 群管机器人 v2 — FastAPI + Tortoise ORM + python-telegram-bot"""
|
|
import os
|
|
import asyncio
|
|
import logging
|
|
|
|
# 代理(必须在其他 import 之前)
|
|
PROXY_URL = os.getenv("PROXY_URL", "http://192.168.123.10:11055")
|
|
os.environ["HTTPS_PROXY"] = PROXY_URL
|
|
os.environ["HTTP_PROXY"] = PROXY_URL
|
|
os.environ["NO_PROXY"] = os.getenv("NO_PROXY", "127.0.0.1,localhost")
|
|
|
|
import uvicorn
|
|
from fastapi import FastAPI
|
|
from telegram import BotCommand, BotCommandScopeChat
|
|
from telegram.ext import Application
|
|
|
|
import config
|
|
from db import init_db, close_db
|
|
from handlers import register_all
|
|
|
|
# ============ 日志 ============
|
|
|
|
log_fmt = "%(asctime)s [%(levelname)s] %(message)s"
|
|
log_datefmt = "%Y-%m-%d %H:%M:%S"
|
|
|
|
logging.basicConfig(level=logging.INFO, format=log_fmt, datefmt=log_datefmt)
|
|
logger = logging.getLogger("spam_guard")
|
|
|
|
# 阻止 httpx 刷屏
|
|
logging.getLogger("httpx").setLevel(logging.WARNING)
|
|
logging.getLogger("httpcore").setLevel(logging.WARNING)
|
|
|
|
# ============ Telegram Bot ============
|
|
|
|
tg_app: Application = None
|
|
|
|
|
|
async def start_tg_bot():
|
|
global tg_app
|
|
|
|
from telegram.request import HTTPXRequest
|
|
|
|
proxy_request = HTTPXRequest(proxy=PROXY_URL)
|
|
tg_app = (
|
|
Application.builder()
|
|
.token(config.TG_BOT_TOKEN)
|
|
.request(proxy_request)
|
|
.build()
|
|
)
|
|
|
|
register_all(tg_app)
|
|
|
|
await tg_app.initialize()
|
|
await tg_app.start()
|
|
await tg_app.updater.start_polling(drop_pending_updates=False)
|
|
|
|
# 菜单
|
|
commands = [
|
|
BotCommand("ask", "🤖 向知识库提问"),
|
|
BotCommand("stats", "📊 今日统计"),
|
|
BotCommand("checkin", "✅ 每日签到"),
|
|
BotCommand("trivia", "🎮 知识答题"),
|
|
BotCommand("bind", "🔗 绑定账号"),
|
|
BotCommand("help", "📖 帮助"),
|
|
]
|
|
await tg_app.bot.delete_my_commands()
|
|
await tg_app.bot.set_my_commands(commands, scope=BotCommandScopeChat(chat_id=config.TG_CHAT_ID))
|
|
logger.info(f"✅ TG Bot 已启动,菜单命令已设置 (群组: {config.TG_CHAT_ID})")
|
|
|
|
|
|
async def stop_tg_bot():
|
|
global tg_app
|
|
if tg_app:
|
|
await tg_app.updater.stop()
|
|
await tg_app.stop()
|
|
await tg_app.shutdown()
|
|
logger.info("🛑 TG Bot 已停止")
|
|
|
|
|
|
# ============ FastAPI ============
|
|
|
|
from web.api import app as web_app
|
|
|
|
|
|
async def start_tg_bot_safe():
|
|
"""启动 TG Bot,并确保异常能进日志。"""
|
|
try:
|
|
await start_tg_bot()
|
|
except Exception:
|
|
logger.exception("❌ TG Bot 启动失败")
|
|
raise
|
|
|
|
|
|
@web_app.on_event("startup")
|
|
async def on_startup():
|
|
# 初始化数据库
|
|
await init_db()
|
|
# 启动 TG Bot
|
|
task = asyncio.create_task(start_tg_bot_safe())
|
|
|
|
def log_task_result(t: asyncio.Task):
|
|
if t.cancelled():
|
|
return
|
|
exc = t.exception()
|
|
if exc:
|
|
logger.error("❌ TG Bot 任务异常结束", exc_info=exc)
|
|
|
|
task.add_done_callback(log_task_result)
|
|
logger.info("🚀 服务启动完成")
|
|
|
|
|
|
@web_app.on_event("shutdown")
|
|
async def on_shutdown():
|
|
await stop_tg_bot()
|
|
await close_db()
|
|
logger.info("🛑 服务已关闭")
|
|
|
|
|
|
def run():
|
|
uvicorn.run(web_app, host="0.0.0.0", port=config.WEB_PORT, log_level="info")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
run()
|