| from fastapi import FastAPI |
| import subprocess |
| import asyncio |
| from contextlib import asynccontextmanager |
| import json |
|
|
| |
| |
| |
| 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}) ==========") |
| |
| |
| 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} |