notifications

Module Path: pt_dev_utility.notifications


Description

Notification utilities for sending messages via various platforms. This module provides functions for sending notifications through different services like Telegram for Python 3.8+.


Functions

send_telegram_message(token: str, message: str, chat_id: str) -> Tuple[bool, Union[Dict[str, Any], str]]

Description: Send a message via Telegram Bot API.

Sends a text message to a specified Telegram chat using the Telegram Bot API. Supports HTML formatting and returns detailed response information.

Parameters:

  • token (str) - Telegram bot token for authentication

  • message (str) - Text message to send (supports HTML formatting)

  • chat_id (str) - Target chat ID or username to send message to

Returns: - Tuple[bool, Union[Dict[str, Any], str]] - Tuple containing success status and response data - On success: (True, response_dict) - On failure: (False, error_text)

Features: - HTML message formatting support - Comprehensive error handling - Detailed response information - Simple boolean success indicator - Works with chat IDs and usernames

Example Usage:

import pt_dev_utility as pdu

# Example 1: Basic message
success, response = pdu.send_telegram_message(
    token='1234567890:ABCdefGHIjklMNOpqrsTUVwxyz',
    message='Hello from Python!',
    chat_id='@my_channel'
)

if success:
    print("✅ Message sent successfully!")
    print(f"Message ID: {response['result']['message_id']}")
else:
    print("❌ Failed to send message:")
    print(response)

# Example 2: HTML formatted message
success, response = pdu.send_telegram_message(
    token='your_bot_token',
    message='<b>Alert!</b>\n<i>System status:</i> <code>ONLINE</code>',
    chat_id='-1001234567890'  # Group chat ID
)

# Example 3: Error handling
try:
    success, response = pdu.send_telegram_message(
        token='invalid_token',
        message='Test message',
        chat_id='@test_channel'
    )

    if not success:
        print(f"Error: {response}")
        # Handle the error appropriately

except Exception as e:
    print(f"Network error: {e}")

# Example 4: Notification system
def send_alert(alert_type, message, chat_id):
    """Send formatted alert via Telegram."""

    # Format message based on alert type
    if alert_type == 'error':
        formatted_message = f'🚨 <b>ERROR</b>\n{message}'
    elif alert_type == 'warning':
        formatted_message = f'âš ī¸ <b>WARNING</b>\n{message}'
    elif alert_type == 'info':
        formatted_message = f'â„šī¸ <b>INFO</b>\n{message}'
    else:
        formatted_message = message

    success, response = pdu.send_telegram_message(
        token='your_bot_token',
        message=formatted_message,
        chat_id=chat_id
    )

    return success, response

# Usage
send_alert('error', 'Database connection failed!', '@alerts_channel')
send_alert('info', 'Backup completed successfully', '@status_channel')

# Example 5: Batch notifications
def notify_multiple_chats(token, message, chat_ids):
    """Send message to multiple chats."""
    results = []

    for chat_id in chat_ids:
        success, response = pdu.send_telegram_message(token, message, chat_id)
        results.append({
            'chat_id': chat_id,
            'success': success,
            'response': response
        })

    return results

# Send to multiple channels
chat_list = ['@channel1', '@channel2', '-1001234567890']
results = notify_multiple_chats(
    'your_bot_token',
    'System maintenance scheduled for tonight',
    chat_list
)

for result in results:
    status = "✅" if result['success'] else "❌"
    print(f"{status} {result['chat_id']}: {result['success']}")

HTML Formatting Support

The Telegram Bot API supports the following HTML tags:

  • <b>bold text</b> - Bold text
  • <i>italic text</i> - Italic text
  • <code>monospace</code> - Monospace text
  • <pre>preformatted</pre> - Preformatted text block
  • <a href="URL">link text</a> - Hyperlinks

Example:

message = '''
<b>System Report</b>

<i>Status:</i> <code>HEALTHY</code>
<i>Uptime:</i> <code>99.9%</code>

<a href="https://status.example.com">View Details</a>
'''

Use Cases

  • System Monitoring - Send alerts and status updates
  • CI/CD Notifications - Notify about build and deployment status
  • Error Reporting - Send error notifications to development teams
  • User Notifications - Send updates to users via Telegram channels
  • Automated Reports - Send scheduled reports and summaries
  • Bot Integration - Integrate with existing Telegram bots

Setup Requirements

  1. Create a Telegram Bot:
  2. Message @BotFather on Telegram
  3. Use /newbot command
  4. Get your bot token

  5. Get Chat ID:

  6. For channels: Use @channel_username
  7. For groups: Use the group chat ID (negative number)
  8. For private chats: Use the user's chat ID

  9. Bot Permissions:

  10. Add bot to your channel/group
  11. Give appropriate permissions to send messages

Notes

  • Bot token should be kept secure and not exposed in code
  • Chat IDs for groups are negative numbers
  • Channel usernames start with @
  • HTML formatting is enabled by default
  • Network timeouts and errors are handled gracefully
  • Response includes full Telegram API response data