⚡ Zero runtime dependencies · Python 3.10+ · MIT License

Analytics for
Telegram Bots

Lightweight, privacy-first analytics for Telegram (and other) chatbots. Track users, messages, events, funnels, and ratings. Get beautiful Markdown reports and an optional Flask web dashboard.

Python 3.10+ 254 tests Zero dependencies mypy clean MIT License
0
Core Dependencies
0
Metric Functions
0
Tests Passing
0+
Data Tables
Why this library

Everything you need to understand your bot

From day-one analytics to privacy-compliant data retention. Built for production Telegram bots.

Non-blocking Writes

All track_update, event, rating calls enqueue instantly. A background writer thread batches and commits. Never block your bot's event loop.

🔒

Privacy by Default

Usernames off, raw JSON off, text truncated, optional HMAC-SHA256 user ID hashing with per-DB salt. Configurable at every level.

📊

22 Metric Functions

DAU/WAU/MAU/YAU, new users, accumulation, hourly activity heatmap, message analysis, funnels, ratings, reviews, and more.

🛡️

SQL Injection Proof

Every query uses bound parameters. Read-only mode=ro connections for all reads. Custom sql_query only allows SELECT/WITH.

🎨

Flask Dashboard

Optional web dashboard with a card-grid UI, client-side Chart.js graphs, hashed-password auth, and a read-only JSON API.

🗑️

GDPR-ready Retention

Automatic data purging with configurable retention_days. Cross-surface consistency: metrics, reports, and dashboard all see the same trimmed dataset.

🤖

Multi-Bot Isolation

Multiple Analytics instances with different bot_id write to one DB. Each metric is scoped per-bot. Dashboard auto-detects or pins via CLI.

📝

Markdown Reports

Five report categories (total, users, messages, events, ratings) deliver rich Markdown directly in chat. Admin-gated allowlist access.

📦

Zero Dependencies

The core library uses only Python stdlib. Install with pip install . and you're done. Dashboard is an optional Flask extra.

Developer Experience

Start tracking in 5 lines

Works with telebot, aiogram, python-telegram-bot, or any framework that gives you a dict.

# pip install analytics-for-telegram-bot
from analytics_for_telegram_bot import Analytics, Config

config = Config(
    db_path="analytics.db",
    bot_id="my_bot",
    admin_ids=[123456789],
)
ana = Analytics(config)

# In your /start handler
ana.track_update(update)

# Track custom events
ana.event("purchase", event_type="shop", user_id=user_id)
ana.rating(5, user_id)
ana.review("Great bot!", user_id)

ana.close()  # flushes all pending writes
Full Metric API

22 metrics out of the box

Every metric opens a read-only connection, works after close(), and returns safe empty values on DB errors.

analyze_totalTotals + averages
analyze_dauDaily active
analyze_wauWeekly active
analyze_mauMonthly active
analyze_yauYearly active
analyze_new_userNew users/day
analyze_user_accumulationCumulative
analyze_hour_activity24×7 heatmap
analyze_messages_numberMsgs/day
analyze_messages_typeType dist
analyze_update_typeUpdate dist
analyze_chat_typeChat dist
analyze_languageLanguages
analyze_eventsEvent counts
analyze_events_typeEvent types
analyze_events_funnelEvent funnel
analyze_funnelUser funnel
analyze_assessmentRatings 1-5
analyze_reviewText reviews
analyze_messagesTop messages
analyze_bots_usersMulti-bot
sql_queryCustom SQL
Privacy & Security

Collect less by default

Every privacy setting defaults to the most restrictive option. Opt in only to what you need.

SettingDefaultDescription
collect_usernameFalseTelegram usernames are not collected
collect_rawFalseFull update JSON is not stored
hash_user_idFalseWhen True: HMAC-SHA256 with per-DB random salt
collect_textTrueMessage text stored, truncated to text_max_len
text_max_len200Max characters of message text retained
collect_languageTruelanguage_code from Telegram user object
Under the Hood

Non-blocking, thread-safe architecture

A single writer thread owns the only write connection. All reads use independent read-only connections.

  ┌──────────────────────────────────────────────────────────────┐
  │                     Your Telegram Bot                         │
  │            (telebot / aiogram / python-telegram-bot)          │
  └──────────┬───────────────────┬────────────────────┬──────────┘
             │                   │                    │
        track_update()      event()              rating()
        funnel_step()       review()
             │                   │                    │
             ▼                   ▼                    ▼
  ┌──────────────────────────────────────────────────────────────┐
  │                    In-Memory Queue                            │
  │            (non-blocking, thread-safe enqueue)                │
  └──────────────────────────┬───────────────────────────────────┘
                             │ batch + flush_interval
                             ▼
  ┌──────────────────────────────────────────────────────────────┐
  │               Background Writer Thread                        │
  │     (single daemon thread, sole write connection)             │
  │     INSERT OR IGNORE dedup · error rollback · no data loss    │
  └──────────────────────────┬───────────────────────────────────┘
                             │
                             ▼
  ┌──────────────────────────────────────────────────────────────┐
  │                     SQLite Database                           │
  │  ┌─────────┐ ┌────────┐ ┌─────────┐ ┌────────────┐          │
  │  │ updates │ │ events │ │ ratings │ │ funnel_step│  + users  │
  │  └─────────┘ └────────┘ └─────────┘ └────────────┘          │
  └──────┬───────────────────────────────────────────┬──────────┘
         │ mode=ro (read-only)                        │ mode=ro
         ▼                                            ▼
  ┌──────────────┐    ┌───────────────────┐    ┌─────────────────┐
  │  Metrics API │    │  Markdown Reports │    │  Flask Dashboard │
  │  (22 funcs)  │    │  (5 categories)   │    │  (Chart.js + API)│
  └──────────────┘    └───────────────────┘    └─────────────────┘

Ready to add analytics to your bot?

Install in seconds. Zero dependencies. Production-ready.