import os, sys # 현재 파일 기준으로 프로젝트 루트 경로를 sys.path 에 추가 sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) import requests import logging from lib.config import Config def send_message_to_mattermost(message: str) -> bool: """ 설정된 방식에 따라 Mattermost로 메시지를 전송합니다. - 웹훅 URL이 있으면 웹훅으로 전송 - 봇 토큰과 채널 ID가 있으면 API로 전송 - 둘 다 있으면 두 방식 모두 시도 """ success = True if Config.MATTERMOST_WEBHOOK_URL: result = _send_via_webhook(message) if not result: logging.error("웹훅 전송 실패") success = False if Config.MATTERMOST_BOT_TOKEN and Config.MATTERMOST_CH_ID: result = _send_via_bot_api(message) if not result: logging.error("봇 API 전송 실패") success = False if not Config.MATTERMOST_WEBHOOK_URL and not (Config.MATTERMOST_BOT_TOKEN and Config.MATTERMOST_CH_ID): logging.error("Mattermost 전송 실패: 환경변수 설정이 없음") success = False return success def _send_via_webhook(message: str) -> bool: try: resp = requests.post( Config.MATTERMOST_WEBHOOK_URL, json={"text": message}, timeout=5 ) if resp.status_code == 200: return True logging.error(f"[WEBHOOK ERROR] {resp.status_code}: {resp.text}") return False except Exception as e: logging.exception("[WEBHOOK EXCEPTION]") return False def _send_via_bot_api(message: str) -> bool: url = Config.mattermost_post_api_url() if not url: logging.error("MATTERMOST_SERVER_URL 설정이 필요합니다.") return False headers = { "Authorization": f"Bearer {Config.MATTERMOST_BOT_TOKEN}", "Content-Type": "application/json", } payload = { "channel_id": Config.MATTERMOST_CH_ID, "message": message, } try: resp = requests.post(url, headers=headers, json=payload, timeout=5) if resp.status_code == 201: return True logging.error(f"[BOT API ERROR] {resp.status_code}: {resp.text}") return False except Exception as e: logging.exception("[BOT API EXCEPTION]") return False if __name__ == "__main__": test_msg = "✅ 테스트 메시지입니다: 시스템 점검 완료" success = send_message_to_mattermost(test_msg) print("[RESULT]", "전송 성공" if success else "전송 실패")