from fastapi import FastAPI import subprocess import asyncio from contextlib import asynccontextmanager import json # ================= 关键配置 ================= # 在这里配置两个机器人的房间号和对应的独立账号 ID! # 注意:第二个账号必须换成您拥有的另一个有效天凤 ID。 BOT_CONFIGS = [ {"changci": "153", "id": "ID10CC3AA2-ZVHZe4Ae"}, {"changci": "153", "id": "ID2FA84D3D-2F36ADaG"} ] # ============================================ bots = [None, None] async def run_bot(index, config): global bots while True: changci = config["changci"] bot_id = config["id"] print(f"========== 正在启动机器人 {index + 1} (账号 {bot_id}) ==========") # 启动脚本,不仅传房间号,还把专属 ID 传进去 bots[index] = subprocess.Popen(["python", "-u", "core.py", bot_id, changci]) print('Calling for bots') while bots[index].poll() is None: await asyncio.sleep(1) print(f"========== 机器人 {index + 1} 已退出,5秒后自动重连 ==========") await asyncio.sleep(5) @asynccontextmanager async def lifespan(app: FastAPI): tasks = [] for i, config in enumerate(BOT_CONFIGS): tasks.append(asyncio.create_task(run_bot(i, config))) yield for bot in bots: if bot: bot.terminate() for t in tasks: t.cancel() app = FastAPI(lifespan=lifespan) @app.get("/") def health_check(id: int = None): status = [] if id is not None: try: return json.load(open(BOT_CONFIGS[id]['id'] + '_paiju.txt', 'r')) except Exception as e: return {'error': f'{e}'} for i, bot in enumerate(bots): state = "运行中" if bot and bot.poll() is None else "重启中" status.append(f"Bot {i+1}: {state}") return {"status": "alive", "bots": status}