Skip to main content

Overview

The Telegram Notifier module provides a comprehensive interface for sending alerts, predictions, and trading signals via Telegram bot messages.

TelegramNotifier Class

Constructor

TelegramNotifier(bot_token: str, chat_id: str)
Initializes a new TelegramNotifier instance with bot credentials. Parameters:
  • bot_token (str): Telegram Bot API token (format: 123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11)
  • chat_id (str): Telegram chat ID where messages will be sent
Attributes:
  • bot_token (str): Stored bot token
  • chat_id (str): Stored chat ID
  • api_url (str): Constructed Telegram API base URL
Example:
from utils.telegram_notifier import TelegramNotifier

bot_token = "123456789:ABCdefGHIjklMNOpqrsTUVwxyz"
chat_id = "987654321"

notifier = TelegramNotifier(bot_token, chat_id)

Methods

send_message

send_message(message: str, parse_mode: str = 'Markdown') -> bool
Sends a text message to the configured Telegram chat. Parameters:
  • message (str): Message text to send
  • parse_mode (str, optional): Message formatting mode. Default: 'Markdown'
    • 'Markdown': Use Markdown formatting
    • 'HTML': Use HTML formatting
Returns: bool: True if message sent successfully, False otherwise Example:
from utils.telegram_notifier import TelegramNotifier

notifier = TelegramNotifier(bot_token, chat_id)

# Send simple message
success = notifier.send_message("Hello from CryptoView Pro!")

if success:
    print("✅ Message sent successfully")
else:
    print("❌ Failed to send message")

# Send formatted message
formatted_msg = """
*Bold text*
_Italic text_
`Code text`
[Link](https://example.com)
"""

notifier.send_message(formatted_msg, parse_mode='Markdown')

send_alert

send_alert(
    crypto: str,
    alert_type: str,
    current_value: float,
    threshold: float,
    condition: str
) -> bool
Sends a formatted alert notification with crypto details and trigger conditions. Parameters:
  • crypto (str): Cryptocurrency symbol (e.g., “BTC”, “ETH”, “SOL”)
  • alert_type (str): Type of alert (e.g., “Precio”, “RSI”, “Volume”)
  • current_value (float): Current value that triggered the alert
  • threshold (float): Configured threshold value
  • condition (str): Trigger condition (e.g., “Mayor que”, “Menor que”)
Returns: bool: True if alert sent successfully, False otherwise Example:
from utils.telegram_notifier import TelegramNotifier

notifier = TelegramNotifier(bot_token, chat_id)

# Price alert
notifier.send_alert(
    crypto="BTC",
    alert_type="Precio",
    current_value=52000.50,
    threshold=50000,
    condition="Mayor que"
)

# RSI alert
notifier.send_alert(
    crypto="ETH",
    alert_type="RSI",
    current_value=75.3,
    threshold=70,
    condition="Mayor que"
)
Sample Output:
🚨 ALERTA CRYPTOVIEW PRO

💰 BTC
📊 Tipo: Precio

🎯 Condición: Mayor que 50000
📈 Valor actual: 52000.50

⏰ 2026-03-07 14:30:45

Configura tus alertas en CryptoView Pro

send_prediction_alert

send_prediction_alert(
    crypto: str,
    current_price: float,
    predicted_price: float,
    hours: int,
    change_pct: float,
    confidence: float
) -> bool
Sends a machine learning prediction alert with detailed forecast information. Parameters:
  • crypto (str): Cryptocurrency symbol
  • current_price (float): Current market price
  • predicted_price (float): ML-predicted future price
  • hours (int): Prediction time horizon in hours
  • change_pct (float): Expected percentage change (can be positive or negative)
  • confidence (float): Model confidence score (0-100)
Returns: bool: True if prediction alert sent successfully, False otherwise Example:
from utils.telegram_notifier import TelegramNotifier

notifier = TelegramNotifier(bot_token, chat_id)

# Bullish prediction
notifier.send_prediction_alert(
    crypto="BTC",
    current_price=50000.00,
    predicted_price=52500.00,
    hours=24,
    change_pct=5.0,
    confidence=85.5
)

# Bearish prediction
notifier.send_prediction_alert(
    crypto="ETH",
    current_price=3000.00,
    predicted_price=2850.00,
    hours=48,
    change_pct=-5.0,
    confidence=78.2
)
Sample Output (Bullish):
🔮 PREDICCIÓN ML - CRYPTOVIEW PRO

💰 BTC

📊 Precio Actual: $50,000.00
📈 Predicción (24h): $52,500.00
📈 Cambio Esperado: +5.00%
🎯 Confianza: 85.5%

⏰ 2026-03-07 14:30:45

Generado por modelos híbridos XGBoost + Prophet

send_signal

send_signal(
    crypto: str,
    signal: str,
    current_price: float,
    rsi: float,
    macd_signal: str
) -> bool
Sends a trading signal notification with technical indicators. Parameters:
  • crypto (str): Cryptocurrency symbol
  • signal (str): Trading signal - must be one of:
    • "COMPRA": Buy signal
    • "VENTA": Sell signal
    • "NEUTRAL": Neutral/hold signal
  • current_price (float): Current market price
  • rsi (float): RSI (Relative Strength Index) value
  • macd_signal (str): MACD signal description (e.g., “Bullish”, “Bearish”)
Returns: bool: True if signal sent successfully, False otherwise Example:
from utils.telegram_notifier import TelegramNotifier

notifier = TelegramNotifier(bot_token, chat_id)

# Buy signal
notifier.send_signal(
    crypto="BTC",
    signal="COMPRA",
    current_price=50000.00,
    rsi=35.5,
    macd_signal="Bullish Crossover"
)

# Sell signal
notifier.send_signal(
    crypto="ETH",
    signal="VENTA",
    current_price=3200.00,
    rsi=78.2,
    macd_signal="Bearish Divergence"
)

# Neutral signal
notifier.send_signal(
    crypto="SOL",
    signal="NEUTRAL",
    current_price=100.00,
    rsi=50.0,
    macd_signal="Consolidating"
)
Sample Output (Buy Signal):
🟢 SEÑAL DE TRADING

💰 BTC
💵 Precio: $50,000.00

🎲 Señal: COMPRA

📊 Indicadores:
• RSI: 35.5
• MACD: Bullish Crossover

⏰ 2026-03-07 14:30:45

⚠️ No es asesoría financiera. Investiga antes de operar.

test_connection

test_connection() -> bool
Tests the Telegram bot connection by sending a test message. Parameters: None Returns: bool: True if connection successful, False otherwise Example:
from utils.telegram_notifier import TelegramNotifier

notifier = TelegramNotifier(bot_token, chat_id)

# Test connection before sending alerts
if notifier.test_connection():
    print("✅ Telegram bot connected successfully")
    # Proceed with sending alerts
else:
    print("❌ Failed to connect to Telegram")
    print("Check your bot_token and chat_id")
Test Message Output:
✅ Conexión exitosa con CryptoView Pro

¡Tu bot de alertas está activo!

Helper Functions

create_telegram_bot_url

create_telegram_bot_url(bot_token: str) -> str
Generates a Telegram deep link URL to open the bot. Parameters:
  • bot_token (str): Telegram bot token
Returns: str: Telegram bot URL (format: https://t.me/bot_username) Example:
from utils.telegram_notifier import create_telegram_bot_url

bot_token = "123456789:ABCdefGHIjklMNOpqrsTUVwxyz"
bot_url = create_telegram_bot_url(bot_token)

print(f"Open your bot: {bot_url}")
# Output: Open your bot: https://t.me/123456789

Complete Usage Example

import time
from utils.telegram_notifier import TelegramNotifier, create_telegram_bot_url
from utils.alerts import AlertSystem

# Configuration
BOT_TOKEN = "your_bot_token_here"
CHAT_ID = "your_chat_id_here"

# Initialize notifier
notifier = TelegramNotifier(BOT_TOKEN, CHAT_ID)

# Test connection first
if not notifier.test_connection():
    print("Failed to connect to Telegram")
    exit(1)

print("✅ Connected to Telegram")

# Send various notifications

# 1. Price alert
notifier.send_alert(
    crypto="BTC",
    alert_type="Precio",
    current_value=51500.00,
    threshold=50000.00,
    condition="Mayor que"
)

time.sleep(1)  # Rate limiting

# 2. ML Prediction
notifier.send_prediction_alert(
    crypto="BTC",
    current_price=51500.00,
    predicted_price=53000.00,
    hours=24,
    change_pct=2.91,
    confidence=87.5
)

time.sleep(1)

# 3. Trading signal
notifier.send_signal(
    crypto="BTC",
    signal="COMPRA",
    current_price=51500.00,
    rsi=42.5,
    macd_signal="Bullish Crossover"
)

# 4. Custom message
notifier.send_message("""
📊 *Daily Market Summary*

✅ BTC: $51,500 (+2.5%)
✅ ETH: $3,200 (+3.1%)
✅ SOL: $105 (+1.8%)

_CryptoView Pro Analytics_
""")

print("\n✅ All notifications sent successfully")
print(f"\nBot URL: {create_telegram_bot_url(BOT_TOKEN)}")

Integration with Alert System

from utils.alerts import AlertSystem
from utils.telegram_notifier import TelegramNotifier

# Initialize both systems
alert_system = AlertSystem()
notifier = TelegramNotifier(bot_token, chat_id)

# Configure alert with Telegram notification
alert_config = {
    'type': 'Precio',
    'crypto': 'BTC',
    'condition': 'Mayor que',
    'threshold': 50000,
    'methods': ['App', 'Telegram']
}

alert_system.add_alert(alert_config)

# Check alerts and send Telegram notification
current_data = {'precio': 52000}
triggered = alert_system.check_alerts(current_data)

for alert in triggered:
    if 'Telegram' in alert.get('methods', []):
        notifier.send_alert(
            crypto=alert['crypto'],
            alert_type=alert['type'],
            current_value=current_data.get(alert['type'].lower()),
            threshold=alert['threshold'],
            condition=alert['condition']
        )

Error Handling

from utils.telegram_notifier import TelegramNotifier
import requests

notifier = TelegramNotifier(bot_token, chat_id)

try:
    success = notifier.send_message("Test message")
    
    if success:
        print("✅ Message sent")
    else:
        print("❌ Failed to send message")
        print("Possible issues:")
        print("- Invalid bot token")
        print("- Invalid chat ID")
        print("- Network connectivity problems")
        print("- Bot not started by user")
        
except requests.exceptions.Timeout:
    print("⏱️ Request timed out")
except requests.exceptions.RequestException as e:
    print(f"🌐 Network error: {e}")
except Exception as e:
    print(f"❌ Unexpected error: {e}")

Setting Up Your Telegram Bot

Step 1: Create Bot

  1. Open Telegram and search for @BotFather
  2. Send /newbot command
  3. Follow prompts to name your bot
  4. Copy the bot token provided

Step 2: Get Chat ID

  1. Start a chat with your bot
  2. Send any message to the bot
  3. Visit: https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getUpdates
  4. Find the chat.id value in the JSON response

Step 3: Test Configuration

from utils.telegram_notifier import TelegramNotifier

BOT_TOKEN = "paste_your_token_here"
CHAT_ID = "paste_your_chat_id_here"

notifier = TelegramNotifier(BOT_TOKEN, CHAT_ID)

if notifier.test_connection():
    print("✅ Setup complete!")
else:
    print("❌ Setup failed - check credentials")

Best Practices

  1. Rate Limiting: Add delays between messages to avoid Telegram API limits
    import time
    notifier.send_message("Message 1")
    time.sleep(1)
    notifier.send_message("Message 2")
    
  2. Error Handling: Always check return values
    if not notifier.send_alert(...):
        # Log error or retry
        pass
    
  3. Test Connection: Verify connection before critical operations
    if notifier.test_connection():
        # Proceed with notifications
        pass
    
  4. Secure Credentials: Store tokens in environment variables
    import os
    BOT_TOKEN = os.getenv('TELEGRAM_BOT_TOKEN')
    CHAT_ID = os.getenv('TELEGRAM_CHAT_ID')
    
  5. Message Length: Keep messages under 4096 characters (Telegram limit)

See Also

Build docs developers (and LLMs) love