from fastapi import FastAPI import threading import requests import time app = FastAPI() def bot_run(): import os # 檢查 Status.txt 是否存在,如果不存在則創建並設置初始值為 0 if not os.path.exists("Status.txt"): with open("Status.txt", "w") as status_file: status_file.write("0") # 讀取 Status.txt 的值 with open("Status.txt", "r") as status_file: status = status_file.read().strip() # 如果 Status.txt 的值是 "1",則運行 bot_main.py if status == "0": with open("Status.txt", "w") as status_file: status_file.write("1") os.system("python bot_main.py") def keep_alive(): while True: try: response = requests.get(SPACE_URL) print(f"Ping Status: {response.status_code}") # 確保請求成功 except Exception as e: print(f"Error: {e}") time.sleep(86400/4) # 每 5 分鐘執行一次 SPACE_URL = "https://mke0108-discordbot.hf.space/" threading.Thread(target=keep_alive, daemon=True).start() @app.get("/") def greet_json(): threading.Thread(target=bot_run).start() return {"Hello": "World!"}