import time import requests from msg_send_save import send_feishu # 服务状态检查间隔(秒) CHECK_INTERVAL = 120 # 2分钟 # 心跳超时时间(秒) HEARTBEAT_TIMEOUT = 120 # 2分钟 # 服务状态跟踪变量 is_service_online = True # 初始假设服务在线 last_status_change_time = time.time() # 上次状态变更时间 def check_service_status(): """ 检查服务状态 Returns: bool: True表示服务在线,False表示服务离线 """ try: response = requests.get('http://127.0.0.1:3100/stat', timeout=10) if response.status_code == 200: data = response.json() last_heartbeat = data.get('heartbeat', 0) # 检查最近一次心跳时间是否在超时范围内 if time.time() - last_heartbeat <= HEARTBEAT_TIMEOUT: return True else: return False else: return False except Exception as e: print(f"检查服务状态时出错: {e}") return False def notify_status_change(online): """ 通知服务状态变更 Args: online (bool): True表示服务上线,False表示服务下线 """ if online: message = "【服务状态通知】QQ机器人服务已重新上线" else: message = "【服务状态通知】QQ机器人服务已下线,请及时处理" send_feishu(message) print(message) def main(): """ 主循环,定时检查服务状态 """ global is_service_online, last_status_change_time print("开始监控服务状态...") while True: try: # 检查当前服务状态 current_status = check_service_status() # 如果状态发生变化 if current_status != is_service_online: # 更新状态和变更时间 is_service_online = current_status last_status_change_time = time.time() # 通知状态变更 notify_status_change(current_status) else: # 状态未变化,打印当前状态 status_text = "在线" if is_service_online else "离线" print(f"服务状态: {status_text}") # 等待下次检查 time.sleep(CHECK_INTERVAL) except KeyboardInterrupt: print("监控程序已退出") break except Exception as e: print(f"监控过程中发生错误: {e}") time.sleep(CHECK_INTERVAL) if __name__ == "__main__": main()