Update main.py
Browse files
main.py
CHANGED
|
@@ -1,48 +1,53 @@
|
|
| 1 |
-
from fastapi import FastAPI
|
| 2 |
-
import subprocess
|
| 3 |
-
import asyncio
|
| 4 |
-
from contextlib import asynccontextmanager
|
| 5 |
-
|
| 6 |
-
#
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
print(f"========== 机器人 {index + 1}
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
for
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
return {"status": "alive", "bots": status}
|
|
|
|
| 1 |
+
from fastapi import FastAPI
|
| 2 |
+
import subprocess
|
| 3 |
+
import asyncio
|
| 4 |
+
from contextlib import asynccontextmanager
|
| 5 |
+
|
| 6 |
+
# ================= 关键配置 =================
|
| 7 |
+
# 在这里配置两个机器人的房间号和对应的独立账号 ID!
|
| 8 |
+
# 注意:第二个账号必须换成您拥有的另一个有效天凤 ID。
|
| 9 |
+
BOT_CONFIGS = [
|
| 10 |
+
{"room": "4441", "id": "ID215416DE-EJPGCHM8"},
|
| 11 |
+
{"room": "4441", "id": "ID27101B05-nRUZ8Xgg"}
|
| 12 |
+
]
|
| 13 |
+
# ============================================
|
| 14 |
+
|
| 15 |
+
bots = [None, None]
|
| 16 |
+
|
| 17 |
+
async def run_bot(index, config):
|
| 18 |
+
global bots
|
| 19 |
+
while True:
|
| 20 |
+
room_id = config["room"]
|
| 21 |
+
bot_id = config["id"]
|
| 22 |
+
print(f"========== 正在启动机器人 {index + 1} (房间 {room_id} | 账号 {bot_id}) ==========")
|
| 23 |
+
|
| 24 |
+
# 启动脚本,不仅传房间号,还把专属 ID 传进去
|
| 25 |
+
bots[index] = subprocess.Popen(["python", "-u", "core_for_test_3.py", room_id, bot_id])
|
| 26 |
+
|
| 27 |
+
while bots[index].poll() is None:
|
| 28 |
+
await asyncio.sleep(1)
|
| 29 |
+
|
| 30 |
+
print(f"========== 机器人 {index + 1} 已退出,5秒后自动重连 ==========")
|
| 31 |
+
await asyncio.sleep(5)
|
| 32 |
+
|
| 33 |
+
@asynccontextmanager
|
| 34 |
+
async def lifespan(app: FastAPI):
|
| 35 |
+
tasks = []
|
| 36 |
+
for i, config in enumerate(BOT_CONFIGS):
|
| 37 |
+
tasks.append(asyncio.create_task(run_bot(i, config)))
|
| 38 |
+
yield
|
| 39 |
+
for bot in bots:
|
| 40 |
+
if bot:
|
| 41 |
+
bot.terminate()
|
| 42 |
+
for t in tasks:
|
| 43 |
+
t.cancel()
|
| 44 |
+
|
| 45 |
+
app = FastAPI(lifespan=lifespan)
|
| 46 |
+
|
| 47 |
+
@app.get("/")
|
| 48 |
+
def health_check():
|
| 49 |
+
status = []
|
| 50 |
+
for i, bot in enumerate(bots):
|
| 51 |
+
state = "运行中" if bot and bot.poll() is None else "重启中"
|
| 52 |
+
status.append(f"Bot {i+1}: {state}")
|
| 53 |
return {"status": "alive", "bots": status}
|