Skip to content

Instantly share code, notes, and snippets.

@raminfp
Forked from mthri/exception.py
Created November 10, 2024 13:50
Show Gist options
  • Save raminfp/b43601cf2a8356413f3972b5656218b4 to your computer and use it in GitHub Desktop.
Save raminfp/b43601cf2a8356413f3972b5656218b4 to your computer and use it in GitHub Desktop.
Python Decorator for Exception Logging and Telegram Notifications
from functools import wraps
import logging
import time
import requests
logger = logging.getLogger(__name__)
TELEGRAM_NOTIFICATION_BOT = 'YOUR_TELEGRAM_NOTIFICATION_BOT'
TELEGRAM_NOTIFICATION_CHANNEL_ID = 'YOUR_TELEGRAM_NOTIFICATION_CHANNEL_ID'
def send_message_to_telegram_channel(message: str) -> None:
try:
response = requests.post(
f'https://api.telegram.org/bot{TELEGRAM_NOTIFICATION_BOT}/'
f'sendMessage?chat_id={TELEGRAM_NOTIFICATION_CHANNEL_ID}&text={message}',
timeout=10
)
response.raise_for_status()
except requests.exceptions.HTTPError as ex:
logger.exception(ex)
time.sleep(1)
return send_message_to_telegram_channel(message)
except Exception as ex:
logger.exception(ex)
def exception_wrap(func):
@wraps(func)
def wrapped(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as ex:
logger.exception(ex)
send_message_to_telegram_channel(str(ex) + f' | {ex.__class__.__name__}')
return wrapped
@exception_wrap
def example():
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment