332 lines
12 KiB
Python
332 lines
12 KiB
Python
# ===================================================================
|
|
# core/message_sender.py
|
|
# FGTools 다중 플랫폼 메시지 발송 모듈
|
|
# ===================================================================
|
|
# Mattermost, Telegram, Synology Chat 등 다양한 플랫폼으로
|
|
# 메시지를 발송하는 통합 클래스를 제공합니다.
|
|
# ===================================================================
|
|
"""
|
|
다중 플랫폼 메시지 발송 모듈
|
|
|
|
Mattermost, Telegram, Synology Chat 등 다양한 메시징 플랫폼으로
|
|
메시지를 발송하는 기능을 제공합니다.
|
|
|
|
사용 예시:
|
|
from core.message_sender import MessageSender, send_notification
|
|
|
|
# 클래스 직접 사용
|
|
sender = MessageSender.from_config()
|
|
sender.send("알림 메시지", platforms=['mattermost', 'telegram'])
|
|
|
|
# 간편 함수 사용
|
|
send_notification("알림 메시지", platforms=['mattermost'])
|
|
"""
|
|
|
|
import logging
|
|
from typing import List, Optional, Union
|
|
|
|
import requests
|
|
|
|
from .config import get_config
|
|
from .logging_utils import get_logger
|
|
|
|
logger = get_logger(__name__)
|
|
|
|
|
|
class MessageSender:
|
|
"""
|
|
다중 플랫폼 메시지 발송 클래스
|
|
|
|
Mattermost, Telegram, Synology Chat 등 여러 플랫폼으로
|
|
동시에 메시지를 발송할 수 있습니다.
|
|
|
|
Attributes:
|
|
mattermost_url: Mattermost 서버 URL
|
|
mattermost_token: Mattermost Bot 토큰
|
|
mattermost_channel_id: Mattermost 채널 ID
|
|
mattermost_webhook_url: Mattermost 웹훅 URL (선택)
|
|
telegram_bot_token: Telegram Bot 토큰
|
|
telegram_chat_id: Telegram 채팅 ID
|
|
synology_webhook_url: Synology Chat 웹훅 URL
|
|
"""
|
|
|
|
def __init__(
|
|
self,
|
|
mattermost_url: str = "",
|
|
mattermost_token: str = "",
|
|
mattermost_channel_id: str = "",
|
|
mattermost_webhook_url: str = "",
|
|
telegram_bot_token: str = "",
|
|
telegram_chat_id: str = "",
|
|
synology_webhook_url: str = ""
|
|
):
|
|
"""
|
|
메시지 발송자 초기화
|
|
|
|
Args:
|
|
mattermost_url: Mattermost 서버 URL (예: https://mattermost.example.com)
|
|
mattermost_token: Mattermost Bot 인증 토큰
|
|
mattermost_channel_id: 메시지를 보낼 채널 ID
|
|
mattermost_webhook_url: 웹훅 URL (웹훅 방식 사용 시)
|
|
telegram_bot_token: Telegram Bot API 토큰
|
|
telegram_chat_id: Telegram 채팅방 ID
|
|
synology_webhook_url: Synology Chat 웹훅 URL
|
|
"""
|
|
# Mattermost 설정
|
|
self.mattermost_url = mattermost_url.rstrip('/') if mattermost_url else ""
|
|
self.mattermost_token = mattermost_token
|
|
self.mattermost_channel_id = mattermost_channel_id
|
|
self.mattermost_webhook_url = mattermost_webhook_url
|
|
|
|
# Telegram 설정
|
|
self.telegram_bot_token = telegram_bot_token
|
|
self.telegram_chat_id = telegram_chat_id
|
|
|
|
# Synology Chat 설정
|
|
self.synology_webhook_url = synology_webhook_url
|
|
|
|
@classmethod
|
|
def from_config(cls) -> 'MessageSender':
|
|
"""
|
|
설정 파일에서 메시지 발송자 생성
|
|
|
|
환경변수에서 모든 메시징 설정을 로드하여 인스턴스를 생성합니다.
|
|
|
|
Returns:
|
|
설정이 적용된 MessageSender 인스턴스
|
|
"""
|
|
config = get_config()
|
|
|
|
return cls(
|
|
mattermost_url=config.mattermost.get('url', ''),
|
|
mattermost_token=config.mattermost.get('token', ''),
|
|
mattermost_channel_id=config.mattermost.get('channel_id', ''),
|
|
mattermost_webhook_url=config.mattermost.get('webhook_url', ''),
|
|
telegram_bot_token=config.telegram.get('bot_token', ''),
|
|
telegram_chat_id=config.telegram.get('chat_id', ''),
|
|
synology_webhook_url=config.synology.get('chat_url', ''),
|
|
)
|
|
|
|
def send(
|
|
self,
|
|
message: str,
|
|
platforms: Optional[Union[str, List[str]]] = None,
|
|
use_webhook: bool = False
|
|
) -> bool:
|
|
"""
|
|
지정된 플랫폼으로 메시지 발송
|
|
|
|
여러 플랫폼에 동시에 메시지를 보낼 수 있습니다.
|
|
|
|
Args:
|
|
message: 발송할 메시지 내용
|
|
platforms: 발송할 플랫폼 목록 (['mattermost', 'telegram', 'synology'])
|
|
None이면 모든 설정된 플랫폼으로 발송
|
|
use_webhook: Mattermost 웹훅 사용 여부 (API 대신)
|
|
|
|
Returns:
|
|
모든 발송 성공 시 True, 하나라도 실패 시 False
|
|
"""
|
|
# 플랫폼이 지정되지 않으면 설정된 모든 플랫폼으로 발송
|
|
if platforms is None:
|
|
platforms = self._get_configured_platforms()
|
|
|
|
if not platforms:
|
|
logger.warning("전송할 플랫폼이 지정되지 않았습니다.")
|
|
return False
|
|
|
|
# 문자열이면 리스트로 변환
|
|
if isinstance(platforms, str):
|
|
platforms = [platforms]
|
|
|
|
success = True
|
|
for platform in platforms:
|
|
platform_lower = platform.lower()
|
|
|
|
if platform_lower == "mattermost":
|
|
result = self._send_to_mattermost(message, use_webhook)
|
|
elif platform_lower == "telegram":
|
|
result = self._send_to_telegram(message)
|
|
elif platform_lower == "synology":
|
|
result = self._send_to_synology(message)
|
|
else:
|
|
logger.error(f"지원하지 않는 플랫폼: {platform}")
|
|
result = False
|
|
|
|
if not result:
|
|
success = False
|
|
|
|
return success
|
|
|
|
def _get_configured_platforms(self) -> List[str]:
|
|
"""설정된 플랫폼 목록 반환"""
|
|
platforms = []
|
|
|
|
if self.mattermost_url and (self.mattermost_token or self.mattermost_webhook_url):
|
|
platforms.append('mattermost')
|
|
if self.telegram_bot_token and self.telegram_chat_id:
|
|
platforms.append('telegram')
|
|
if self.synology_webhook_url:
|
|
platforms.append('synology')
|
|
|
|
return platforms
|
|
|
|
def _send_to_mattermost(self, message: str, use_webhook: bool = False) -> bool:
|
|
"""
|
|
Mattermost로 메시지 발송
|
|
|
|
웹훅 또는 API 방식으로 메시지를 발송합니다.
|
|
|
|
Args:
|
|
message: 발송할 메시지
|
|
use_webhook: 웹훅 사용 여부 (False면 API 사용)
|
|
|
|
Returns:
|
|
발송 성공 여부
|
|
"""
|
|
try:
|
|
if use_webhook and self.mattermost_webhook_url:
|
|
# 웹훅 방식
|
|
response = requests.post(
|
|
self.mattermost_webhook_url,
|
|
json={"text": message},
|
|
headers={"Content-Type": "application/json"},
|
|
timeout=10
|
|
)
|
|
else:
|
|
# API 방식
|
|
if not self._validate_mattermost_config():
|
|
return False
|
|
|
|
url = f"{self.mattermost_url}/api/v4/posts"
|
|
headers = {
|
|
"Authorization": f"Bearer {self.mattermost_token}",
|
|
"Content-Type": "application/json"
|
|
}
|
|
payload = {
|
|
"channel_id": self.mattermost_channel_id,
|
|
"message": message
|
|
}
|
|
response = requests.post(url, json=payload, headers=headers, timeout=10)
|
|
|
|
if response.status_code in [200, 201]:
|
|
logger.info("Mattermost 메시지 전송 완료")
|
|
return True
|
|
else:
|
|
logger.error(f"Mattermost 전송 실패: {response.status_code} - {response.text}")
|
|
return False
|
|
|
|
except requests.exceptions.Timeout:
|
|
logger.error("Mattermost 전송 타임아웃")
|
|
return False
|
|
except requests.exceptions.RequestException as e:
|
|
logger.error(f"Mattermost 전송 예외: {e}")
|
|
return False
|
|
|
|
def _validate_mattermost_config(self) -> bool:
|
|
"""Mattermost API 설정 검증"""
|
|
if not self.mattermost_url or not self.mattermost_url.startswith(('http://', 'https://')):
|
|
logger.error(f"Mattermost URL이 유효하지 않습니다: {self.mattermost_url}")
|
|
return False
|
|
if not self.mattermost_token:
|
|
logger.error("Mattermost 토큰이 설정되지 않았습니다.")
|
|
return False
|
|
if not self.mattermost_channel_id:
|
|
logger.error("Mattermost 채널 ID가 설정되지 않았습니다.")
|
|
return False
|
|
return True
|
|
|
|
def _send_to_telegram(self, message: str) -> bool:
|
|
"""
|
|
Telegram으로 메시지 발송
|
|
|
|
Args:
|
|
message: 발송할 메시지
|
|
|
|
Returns:
|
|
발송 성공 여부
|
|
"""
|
|
if not self.telegram_bot_token or not self.telegram_chat_id:
|
|
logger.error("Telegram 설정이 완료되지 않았습니다.")
|
|
return False
|
|
|
|
try:
|
|
url = f"https://api.telegram.org/bot{self.telegram_bot_token}/sendMessage"
|
|
payload = {
|
|
"chat_id": self.telegram_chat_id,
|
|
"text": message,
|
|
"parse_mode": "Markdown"
|
|
}
|
|
response = requests.post(url, data=payload, timeout=10)
|
|
|
|
if response.status_code == 200:
|
|
logger.info("Telegram 메시지 전송 완료")
|
|
return True
|
|
else:
|
|
logger.error(f"Telegram 전송 실패: {response.status_code} - {response.text}")
|
|
return False
|
|
|
|
except requests.exceptions.RequestException as e:
|
|
logger.error(f"Telegram 전송 예외: {e}")
|
|
return False
|
|
|
|
def _send_to_synology(self, message: str) -> bool:
|
|
"""
|
|
Synology Chat으로 메시지 발송
|
|
|
|
Args:
|
|
message: 발송할 메시지
|
|
|
|
Returns:
|
|
발송 성공 여부
|
|
"""
|
|
if not self.synology_webhook_url:
|
|
logger.error("Synology Chat 웹훅 URL이 설정되지 않았습니다.")
|
|
return False
|
|
|
|
try:
|
|
payload = {"text": message}
|
|
headers = {"Content-Type": "application/json"}
|
|
response = requests.post(
|
|
self.synology_webhook_url,
|
|
json=payload,
|
|
headers=headers,
|
|
timeout=10
|
|
)
|
|
|
|
if response.status_code == 200:
|
|
logger.info("Synology Chat 메시지 전송 완료")
|
|
return True
|
|
else:
|
|
logger.error(f"Synology Chat 전송 실패: {response.status_code} - {response.text}")
|
|
return False
|
|
|
|
except requests.exceptions.RequestException as e:
|
|
logger.error(f"Synology Chat 전송 예외: {e}")
|
|
return False
|
|
|
|
|
|
def send_notification(
|
|
message: str,
|
|
platforms: Optional[Union[str, List[str]]] = None,
|
|
use_webhook: bool = False
|
|
) -> bool:
|
|
"""
|
|
알림 메시지 발송 간편 함수
|
|
|
|
설정 파일에서 자동으로 설정을 로드하여 메시지를 발송합니다.
|
|
|
|
Args:
|
|
message: 발송할 메시지
|
|
platforms: 발송할 플랫폼 목록 (None이면 모든 설정된 플랫폼)
|
|
use_webhook: Mattermost 웹훅 사용 여부
|
|
|
|
Returns:
|
|
발송 성공 여부
|
|
|
|
사용 예시:
|
|
send_notification("서버 점검 알림", platforms=['mattermost'])
|
|
"""
|
|
sender = MessageSender.from_config()
|
|
return sender.send(message, platforms=platforms, use_webhook=use_webhook)
|