|
1 | 1 | import os |
2 | 2 | from typing import Dict, Literal, Protocol, TypedDict, cast |
3 | 3 |
|
| 4 | +import aiohttp |
4 | 5 | from datadog_api_client.api_client import AsyncApiClient as DatadogAPI |
5 | 6 | from datadog_api_client.configuration import Configuration as DatadogConfig |
6 | 7 | from datadog_api_client.v1.api.events_api import EventsApi as DatadogEventAPI |
7 | 8 | from datadog_api_client.v1.model.event_alert_type import EventAlertType |
8 | 9 | from datadog_api_client.v1.model.event_create_request import EventCreateRequest |
| 10 | +from dotenv import load_dotenv |
9 | 11 | from loguru import logger |
10 | 12 |
|
11 | 13 | from pyth_observer.check import Check |
12 | 14 | from pyth_observer.check.publisher import PublisherCheck |
| 15 | +from pyth_observer.models import Publisher |
| 16 | + |
| 17 | +load_dotenv() |
13 | 18 |
|
14 | 19 |
|
15 | 20 | class Context(TypedDict): |
16 | 21 | network: str |
17 | | - publishers: Dict[str, str] |
| 22 | + publishers: Dict[str, Publisher] |
18 | 23 |
|
19 | 24 |
|
20 | 25 | class Event(Protocol): |
@@ -94,3 +99,47 @@ async def send(self): |
94 | 99 |
|
95 | 100 | level = cast(LogEventLevel, os.environ.get("LOG_EVENT_LEVEL", "INFO")) |
96 | 101 | logger.log(level, text.replace("\n", ". ")) |
| 102 | + |
| 103 | + |
| 104 | +class TelegramEvent(Event): |
| 105 | + def __init__(self, check: Check, context: Context): |
| 106 | + self.check = check |
| 107 | + self.context = context |
| 108 | + self.telegram_bot_token = os.environ["TELEGRAM_BOT_TOKEN"] |
| 109 | + |
| 110 | + async def send(self): |
| 111 | + if self.check.__class__.__bases__ == (PublisherCheck,): |
| 112 | + text = self.check.error_message() |
| 113 | + publisher_key = self.check.state().public_key.key |
| 114 | + publisher = self.context["publishers"].get(publisher_key, None) |
| 115 | + # Ensure publisher is not None and has contact_info before accessing telegram_chat_id |
| 116 | + chat_id = ( |
| 117 | + publisher.contact_info.telegram_chat_id |
| 118 | + if publisher is not None and publisher.contact_info is not None |
| 119 | + else None |
| 120 | + ) |
| 121 | + |
| 122 | + if chat_id is None: |
| 123 | + logger.warning( |
| 124 | + f"Telegram chat ID not found for publisher key {publisher_key}" |
| 125 | + ) |
| 126 | + return |
| 127 | + |
| 128 | + telegram_api_url = ( |
| 129 | + f"https://api.telegram.org/bot{self.telegram_bot_token}/sendMessage" |
| 130 | + ) |
| 131 | + message_data = { |
| 132 | + "chat_id": chat_id, |
| 133 | + "text": text, |
| 134 | + "parse_mode": "Markdown", |
| 135 | + } |
| 136 | + |
| 137 | + async with aiohttp.ClientSession() as session: |
| 138 | + async with session.post( |
| 139 | + telegram_api_url, json=message_data |
| 140 | + ) as response: |
| 141 | + if response.status != 200: |
| 142 | + response_text = await response.text() |
| 143 | + logger.error( |
| 144 | + f"Failed to send Telegram message: {response_text}" |
| 145 | + ) |
0 commit comments