Commit 1c5302e2 authored by porramet's avatar porramet

first commit

parents
Pipeline #1696 canceled with stages
DEFAULT_GMAIL_APP_EMAIL=porrametict@gmail.com
DEFAULT_GMAIL_APP_PASS=glzrazzeanduismm
DEFAULT_SMTP_SERVER=smtp.gmail.com
DEFAULT_SMTP_PORT=465
TG_CHAT_ID=7737553843
TG_BOT_TOKEN=7733296788:AAGMG8jaPVK80XKGHPWnFZ5OcKvGmzFNgBk
\ No newline at end of file
.idea
.ipynb_checkpoints
.mypy_cache
.vscode
__pycache__
.pytest_cache
htmlcov
dist
site
.coverage*
coverage.xml
.netlify
test.db
log.txt
Pipfile.lock
env3.*
env
docs_build
site_build
venv
docs.zip
archive.zip
# vim temporary files
*~
.*.sw?
.cache
# macOS
.DS_Store
.env
\ No newline at end of file
How to Use
1. Configure the Notification Service
You need to create a configuration dictionary for both Gmail and/or Telegram. The configuration should look like this:
```python
config = {
"gmail": {
"smtp_server": "smtp.gmail.com", # SMTP server
"smtp_port": "587", # SMTP port
"sender_email": "your_email@gmail.com", # Gmail sender email
"sender_password": "your_password", # Gmail sender password
},
"telegram": {
"bot_token": "your_bot_token", # Telegram bot token
"chat_id": "your_chat_id", # The chat ID to send messages to
}
}
```
2. Initialize the Notification Service
```python
from notification_service import NotificationService
notification_service = NotificationService(config)
```
3. Send a Notification
To send a notification, pass the method ("gmail" or "telegram") and the parameters related to the respective method.
Example:
Sending a Gmail Notification:
```python
from src.strategies.gmail import MessageParams
gmail_params:MessageParams = {
"to" : ["poramet.tan@nectec.or.th"],
"subject" : "Test Notification",
"body" : f"""
Hello World
""",
"cc" : ["poramet.tan@nectec.or.th"]
}
notification_params = {
"method": "gmail",
"params": gmail_params
}
notification_service.send_notification(notification_params)
```
Sending a Telegram Notification:
```python
from src.strategies.telegram import MessageParams
telegram_params:MessageParams = {
"text" :f"""Hello World"""
}
notification_params = {
"method": "telegram",
"params": telegram_params
}
notification_service.send_notification(notification_params)
```
from setuptools import setup, find_packages
setup(
name='nc_service',
version='1.0.0',
packages=find_packages(where='src'),
package_dir={'': 'src'},
install_requires=[
"requests",
],
author='Poramet Tangon',
author_email='poramet.tan@nectec.or.th',
description='Notification Service',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
classifiers=[
'Programming Language :: Python :: 3',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
],
)
import strategies.gmail as gmail
import strategies.telegram as telegram
from notification_service import *
\ No newline at end of file
import os
from dotenv import load_dotenv
load_dotenv() # take environment variables
DEFAULT_GMAIL_APP_EMAIL = os.environ.get("DEFAULT_GMAIL_APP_EMAIL")
DEFAULT_GMAIL_APP_PASS = os.environ.get("DEFAULT_GMAIL_APP_PASS")
DEFAULT_SMTP_SERVER = os.environ.get("DEFAULT_SMTP_SERVER")
DEFAULT_SMTP_PORT = int(os.environ.get("DEFAULT_SMTP_PORT"))
TG_CHAT_ID = str(os.environ.get("TG_CHAT_ID"))
TG_BOT_TOKEN = str(os.environ.get("TG_BOT_TOKEN"))
\ No newline at end of file
from typing import Union
from strategies.gmail import MessageParams as GmailMessageParams
from strategies.telegram import MessageParams as TelegramMessageParams
from strategies.notification_strategy import NotificationStrategy
class NotificationSender:
def set_strategy(self,strategy:NotificationStrategy):
self._strategy = strategy
def send_notification(self,params:Union[GmailMessageParams,TelegramMessageParams],raise_error:bool=False):
if raise_error:
self._strategy.send(params)
else :
try:
self._strategy.send(params)
except Exception as e :
pass # do nothing
from typing import TypedDict,Union,Literal,Optional
from src.strategies.gmail import Gmail,MessageParams as GmailMessageParams
from src.strategies.telegram import Telegram, MessageParams as TelegramMessageParams
from src.notification_sender import NotificationSender
class GmailConfig(TypedDict):
smtp_server:str
smtp_port:str
sender_email : str
sender_password:str
class TelegramConfig(TypedDict):
bot_token:str
chat_id : str
class NotificationConfig(TypedDict):
gmail : Optional[GmailConfig]
telegram : Optional[TelegramConfig]
class NotificationMessageParams(TypedDict):
method: Literal['gmail', 'telegram']
params: Union[GmailMessageParams, TelegramMessageParams]
class NotificationService:
_config : NotificationConfig
_gmail_strategy : Optional[Gmail] = None
_telegram_strategy : Optional[Telegram] = None
_sender : NotificationSender
def __init__(self,config:NotificationConfig):
self._config = config
self._sender = NotificationSender()
if config.get("gmail") :
self._gmail_strategy = Gmail(
smtp_server=config["gmail"]["smtp_server"],
smtp_port=config["gmail"]["smtp_port"]
)
self._gmail_strategy.set_sender(
mail=config["gmail"]['sender_email'],
password=config["gmail"]['sender_password']
)
if config.get("telegram"):
self._telegram_strategy = Telegram(
bot_token=config["telegram"]["bot_token"],
chat_id=config["telegram"]["chat_id"],
)
def send_notification(self,params:NotificationMessageParams,raise_error:Optional[bool]=False):
method = params.get("method")
if method == "gmail" and self._gmail_strategy :
self._sender.set_strategy(self._gmail_strategy)
elif method == "telegram" and self._telegram_strategy :
self._sender.set_strategy(self._telegram_strategy)
else :
raise ValueError(f"Unsupported method: {method}")
self._sender.send_notification(params["params"],raise_error)
\ No newline at end of file
import smtplib
from typing import Optional,TypedDict
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import src.config as _config
from .notification_strategy import NotificationStrategy
class MessageParams(TypedDict):
to : list[str]
cc : Optional[list[str]]
subject : str
body : str
class Gmail(NotificationStrategy):
_smtp_server : str
_smtp_port :str
_sender_mail : str
_sender_pass : str
def __init__(self,smtp_server:str,smtp_port:str):
self._smtp_server = smtp_server
self._smtp_port = smtp_port
def set_sender(self,mail:str,password:str):
self._sender_mail = mail
self._sender_pass = password
def send(self,params:MessageParams):
with smtplib.SMTP_SSL(self._smtp_server,self._smtp_port) as smtp:
smtp.login(self._sender_mail,self._sender_pass)
_to = params['to']
_cc = params['cc'] if 'cc' in params else []
msg = MIMEMultipart()
msg['From'] = self._sender_mail
msg['To'] = ",".join(_to)
msg['Subject'] = params['subject']
if len(_cc):
msg["CC"] = ",".join(_cc)
msg.attach(MIMEText(params['body'],'plain'))
text = msg.as_string()
toaddrs = _to + _cc
smtp.sendmail(self._sender_mail,toaddrs,text)
if __name__ == '__main__':
params = {
"to" : ["poramet.tan@nectec.or.th"],
"subject" : "Test Notification",
"body" : f"""
Hello World
""",
"cc" : ["poramet.tan@nectec.or.th"]
}
gmail = Gmail(_config.DEFAULT_SMTP_SERVER,_config.DEFAULT_SMTP_PORT)
gmail.set_sender(_config.DEFAULT_GMAIL_APP_EMAIL,_config.DEFAULT_GMAIL_APP_PASS)
gmail.send(params)
\ No newline at end of file
from abc import ABC,abstractmethod
class NotificationStrategy(ABC):
@abstractmethod
def send(self,params:str):
pass
\ No newline at end of file
import requests
from typing import TypedDict
from .notification_strategy import NotificationStrategy
class MessageParams(TypedDict):
text : str
class Telegram(NotificationStrategy):
_bot_token :str
_chat_id :str
def __init__(self,bot_token:str,chat_id:str):
self._bot_token = bot_token
self._chat_id = chat_id
def send(self,params:MessageParams):
request_params = {
"chat_id": self._chat_id,
"text" : params['text']
}
url = f"https://api.telegram.org/bot{self._bot_token}/sendMessage"
requests.get(url,params=request_params)
if __name__ == '__main__':
import src.config as _config
params = {
"text" :f"""
Hello World
""",
}
tg = Telegram(_config.TG_BOT_TOKEN,_config.TG_CHAT_ID)
tg.send(params)
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment