HomePhase 1: Python FoundationsLesson 5
Lesson 5 of 24Phase 1: Python FoundationsBeginner

Teaching Your Bot to Keep a Diary & Message You

Give your trading bot a permanent logbook on disk and instant Telegram alerts so you always know what it did, why it acted, and when something breaks.

Bitfoster Team
December 3, 2026
8 Min Read
lesson-05-logging-telegram-alerts/
Teaching Your Bot to Keep a Diary & Message You

Hands-On Deliverable

A helper module that saves trade logs to disk and sends messages straight to your Telegram app.

Why print() Is Not Enough for a Real Bot

When you first start coding, print("Bought BTC!") feels great. The problem shows up the moment you leave your bot running overnight or close your terminal window: everything printed to the screen disappears forever.

If your bot makes a surprising Testnet trade at 3:14 AM—or crashes because your Wi-Fi blipped—you need two things:

  1. A permanent diary on disk (logging): Every signal, order, and error is saved to a timestamped file (logs/bot.log) with automatic file rotation so it never fills up your hard drive.
  2. Instant push notifications (Telegram): Instead of staring at a terminal all day, your bot sends a short message straight to your phone whenever a trade fills or an error needs your attention.

In this lesson, you will build a reusable bot_notifier.py module that you can import into every bot you build in Phases 2, 3, and 4.


Prerequisites & Safe .env Setup

Activate your .venv and make sure requests and python-dotenv are installed:

pip install requests python-dotenv

Add two placeholder lines to your .env file (remember: .env stays in .gitignore and never gets shared):

TELEGRAM_BOT_TOKEN=your_telegram_bot_token_here
TELEGRAM_CHAT_ID=your_telegram_chat_id_here

How to get your own free Telegram credentials later (takes 60 seconds):

  1. Open Telegram, search for @BotFather, send /newbot, and follow the prompts to copy your TELEGRAM_BOT_TOKEN.
  2. Send one message to your new bot, then open https://api.telegram.org/bot<YOUR_TOKEN>/getUpdates in your browser to find your numeric chat.id.

Until you paste real values into .env, our script safely runs in dry-run preview mode so you can test everything immediately without errors.

Common Beginner Mistake: Letting a bot write to a single log file forever without rotation, or letting a Telegram network error crash the trading loop. Always use RotatingFileHandler to cap log file sizes, and wrap Telegram calls in a try / except block with a short timeout so a slow notification never stalls a trade.


Checkpoint Script: bot_notifier.py

Save this file as bot_notifier.py. You can run it directly to test your diary and alerts, or import setup_logger and send_telegram_alert into future strategies.

"""
Lesson 5 Checkpoint: Bot Diary (Rotating Logs) & Telegram Notifier
Reusable helper module that records timestamped events to disk
and sends non-blocking alerts to your Telegram app.
"""

import logging
import os
from logging.handlers import RotatingFileHandler
from pathlib import Path
import requests
from dotenv import load_dotenv

load_dotenv()

LOG_DIR = Path("logs")
LOG_FILE = LOG_DIR / "bot.log"


def setup_logger(name: str = "bitfoster_bot") -> logging.Logger:
    """Create a logger that writes to both the terminal and a rotating file."""
    LOG_DIR.mkdir(parents=True, exist_ok=True)
    logger = logging.getLogger(name)
    logger.setLevel(logging.INFO)

    # Avoid duplicate log lines if setup_logger() is called more than once
    if logger.handlers:
        return logger

    formatter = logging.Formatter(
        fmt="%(asctime)s | %(levelname)-8s | %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
    )

    # 1. File handler: keeps up to 3 backup files, 1 MB each
    file_handler = RotatingFileHandler(
        LOG_FILE, maxBytes=1_000_000, backupCount=3, encoding="utf-8"
    )
    file_handler.setFormatter(formatter)

    # 2. Console handler: still shows messages in your terminal
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(formatter)

    logger.addHandler(file_handler)
    logger.addHandler(console_handler)
    return logger


def send_telegram_alert(message: str, logger: logging.Logger) -> bool:
    """Send a Telegram message using credentials stored in .env."""
    token = os.getenv("TELEGRAM_BOT_TOKEN", "")
    chat_id = os.getenv("TELEGRAM_CHAT_ID", "")

    # Safe educational fallback when placeholders are still in .env
    if not token or not chat_id or token.startswith("your_"):
        logger.warning(
            "[TELEGRAM DRY-RUN] Add real keys to .env to send live alerts. Preview: %s",
            message,
        )
        return False

    url = f"https://api.telegram.org/bot{token}/sendMessage"
    payload = {"chat_id": chat_id, "text": message}

    try:
        response = requests.post(url, json=payload, timeout=5)
        response.raise_for_status()
        logger.info("[TELEGRAM SENT] %s", message)
        return True
    except requests.RequestException as err:
        # Never let a notification failure crash the trading bot
        logger.error("[TELEGRAM FAILED] %s", err)
        return False


def main() -> None:
    logger = setup_logger()
    logger.info("Bot started in TESTNET mode.")

    # Simulate a Testnet trade signal and notification
    trade_msg = "[TESTNET] BUY 0.01 BTC @ $94,200.00 | Reason: Price crossed above 20-SMA"
    logger.info(trade_msg)
    send_telegram_alert(trade_msg, logger)

    # Simulate a handled warning so you can see log levels in action
    logger.warning("Exchange latency slightly elevated (420ms). Monitoring...")
    logger.info("Log file saved at: %s", LOG_FILE.resolve())


if __name__ == "__main__":
    main()

Run it from your terminal:

python bot_notifier.py

Expected Terminal Output

2026-12-03 14:35:10 | INFO     | Bot started in TESTNET mode.
2026-12-03 14:35:10 | INFO     | [TESTNET] BUY 0.01 BTC @ $94,200.00 | Reason: Price crossed above 20-SMA
2026-12-03 14:35:10 | WARNING  | [TELEGRAM DRY-RUN] Add real keys to .env to send live alerts. Preview: [TESTNET] BUY 0.01 BTC @ $94,200.00 | Reason: Price crossed above 20-SMA
2026-12-03 14:35:10 | WARNING  | Exchange latency slightly elevated (420ms). Monitoring...
2026-12-03 14:35:10 | INFO     | Log file saved at: /path/to/my-crypto-bot/logs/bot.log

Open logs/bot.log afterward—every single line is permanently recorded with its exact timestamp and severity level, and once you add your Telegram token to .env, that same alert will buzz on your phone within a second.


Study & Practice Recap

  • Logs outlive your terminal: Python's logging module with RotatingFileHandler gives your bot a searchable, self-cleaning diary on disk.
  • Notifications should never crash your bot: Always set a network timeout and catch RequestException around Telegram API calls.
  • Build reusable helpers early: Keeping setup_logger and send_telegram_alert in one clean module means every strategy you write next gets monitoring in two lines of code.

Tiny Hands-On Exercise: Create a second file called test_import.py that imports setup_logger and send_telegram_alert from bot_notifier, logs a simulated [TESTNET] SELL trade, and confirms the new entry is appended to logs/bot.log.

Topics:#Python#Logging#Telegram Bot#Alerts#Monitoring