inpaintServer/app/utils/discord_notifier.py

79 lines
2.7 KiB
Python
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
Discord 웹훅 알림 유틸리티
"""
import logging
import requests
import socket
from datetime import datetime
from pathlib import Path
from ..core.config import settings
logger = logging.getLogger(__name__)
WEBHOOK_URL_FILE = Path(settings.PROJECT_ROOT) / "webhook_url.txt"
def get_webhook_url() -> str:
"""환경 변수 또는 파일에서 웹훅 URL을 가져옵니다."""
# 1. 환경 변수 확인
if settings.DISCORD_WEBHOOK_URL:
return settings.DISCORD_WEBHOOK_URL
# 2. 파일 확인
if WEBHOOK_URL_FILE.exists():
return WEBHOOK_URL_FILE.read_text().strip()
return ""
def send_discord_notification(message: str, level: str = "info"):
"""Discord 웹훅으로 알림을 보냅니다."""
webhook_url = get_webhook_url()
if not webhook_url:
if "시작" in message or "종료" in message:
logger.warning("Discord 웹훅 URL이 설정되지 않아 알림을 보낼 수 없습니다.")
return
hostname = socket.gethostname()
color_map = {
"info": 3447003, # Blue
"warning": 16776960, # Yellow
"error": 15158332, # Red
"success": 3066993 # Green
}
color = color_map.get(level.lower(), 3447003)
payload = {
"embeds": [
{
"title": f"🚨 서버 알림 ({level.upper()})",
"description": message,
"color": color,
"footer": {
"text": f"Host: {hostname} | {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
}
}
]
}
try:
response = requests.post(webhook_url, json=payload, timeout=5)
response.raise_for_status()
logger.info("Discord로 알림을 성공적으로 보냈습니다.")
except requests.RequestException as e:
logger.error(f"Discord 알림 전송 실패: {e}")
if __name__ == '__main__':
# 테스트용
settings.DISCORD_WEBHOOK_URL = "YOUR_TEST_WEBHOOK_URL" # 여기에 테스트용 웹훅 URL을 입력하세요.
if settings.DISCORD_WEBHOOK_URL == "YOUR_TEST_WEBHOOK_URL":
print("Please replace 'YOUR_TEST_WEBHOOK_URL' with your actual Discord webhook URL to test.")
else:
send_discord_notification("✅ 테스트: 서버가 성공적으로 시작되었습니다.", level="success")
send_discord_notification(" 정보: 모델 캐시를 업데이트하고 있습니다.", level="info")
send_discord_notification("⚠️ 경고: GPU 온도가 85°C를 초과했습니다.", level="warning")
send_discord_notification("❌ 오류: 메인 서버가 응답하지 않습니다. 재시작을 시도합니다.", level="error")