Skip to content
This repository has been archived by the owner on Jan 18, 2025. It is now read-only.

Commit

Permalink
feat!: send messages to telegram
Browse files Browse the repository at this point in the history
  • Loading branch information
NTGNguyen committed Dec 26, 2024
1 parent 0bc5174 commit d53bc09
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
48 changes: 48 additions & 0 deletions src/check_phat_nguoi/modules/notify/telegram.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from typing import LiteralString
from check_phat_nguoi.models.notify.telegram_notify import TelegramNotifyModel
from check_phat_nguoi.utils.constants import SEND_MESSAGE_API_URL_TELEGRAM as API_URL
import requests
from logging import getLogger
from threading import Thread

logger = getLogger(__name__)


class Telegram:
def __init__(
self,
telegram_notify_object: TelegramNotifyModel,
message_dict: dict[str, LiteralString],
):
self._telegram_notify_object: TelegramNotifyModel = telegram_notify_object
self._message_dict: dict[str, LiteralString] = message_dict

def _send_message(self, message: LiteralString, timeout=10) -> None:
url = API_URL.format(bot_token=self._telegram_notify_object.telegram.bot_token)
payload = {
"chat_id": self._telegram_notify_object.telegram.chat_id,
"text": message,
"parse_mode": "Markdown",
}
try:
response = requests.post(url, json=payload)
response.raise_for_status()
logger.info(f"Request successful: {response.status_code}")
except requests.exceptions.ConnectionError:
logger.error(f"Unable to connect to {url}")
except requests.exceptions.Timeout:
logger.error(f"Time out of {timeout} seconds from URL {url}")

def mutithread_send_message(self) -> None:
threads: list[Thread] = []
for _, message in self._message_dict.items():
thread = Thread(target=self._send_message, args=(message))
threads.append(thread)
thread.start()
for idx, thread in enumerate(threads, start=1):
try:
thread.join()
except Exception:
logger.error(
f"An error occurs while sending message in thread number {idx}"
)
3 changes: 3 additions & 0 deletions src/check_phat_nguoi/utils/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@

# API from checkphatnguoi.vn
GET_DATA_API_URL_CHECKPHATNGUOI: str = "https://api.checkphatnguoi.vn/phatnguoi"
SEND_MESSAGE_API_URL_TELEGRAM: str = (
"https://api.telegram.org/bot{bot_token}/sendMessage"
)
DATETIME_FORMAT_CHECKPHATNGUOI: str = "%H:%M, %d/%m/%Y"

OFFICE_NAME_PATTERN = r"^\d+\."
Expand Down

0 comments on commit d53bc09

Please sign in to comment.