Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

TGtrigger

A self-hosted Telegram chat-monitoring system that watches many group chats for keyword/regex triggers, scores matching messages with an AI lead-scorer, and forwards qualified leads to people, channels, and webhooks.

TGtrigger connects one or more Telegram accounts through a Telethon userbot and listens to the groups you choose. When a message matches one of your triggers, it is scored, filtered, deduplicated, and — if it qualifies — delivered in real time, complete with a link back to the original message. A single-page dashboard lets you manage accounts, triggers, filters, schedules, webhooks, logs, and analytics.


Features

  • AI lead scoring (highlight). Every matching message is passed through an AI lead-scorer powered by OpenRouter (Llama 3.2). Each message is classified as spam, hot, warm, or cold, with a short human-readable reason. Spam is dropped automatically; hot/warm/cold leads are forwarded with an at-a-glance label. A fast keyword pre-filter short-circuits obvious spam (service offers, scams, ad copy) before any API call is made.
  • Multi-account monitoring. Connect several Telegram accounts and watch hundreds of group chats per account from one place.
  • Keyword & regex triggers. Define triggers as plain substrings or regular expressions, case-sensitive or not, scoped to a single chat or applied across all monitored chats.
  • Author deduplication (cooldown). Once an author has been forwarded, they are muted for a configurable cooldown window (default 24h) so a single active person never floods your targets.
  • Negative filters & ignored authors. Suppress matches by word/regex, or ignore specific authors by Telegram ID or name pattern.
  • Schedules. Restrict monitoring to specific days and hours (UTC).
  • Forwarding targets & webhooks. Deliver qualified leads to Telegram users, bots, or channels, and POST structured payloads to external webhooks (with optional signature header).
  • Real-time dashboard. A single HTML page shows accounts, triggers, filters, logs, and analytics, with live updates over WebSocket, browser notifications, and sound alerts for hot leads.
  • Analytics & export. Charts for activity by day/hour, top triggers, chats, and senders, AI score breakdowns, per-account load gauges, and CSV export of leads.

Architecture

                ┌──────────────────────────────┐
                │  Dashboard (single HTML page) │
                │  vanilla JS · Tailwind · Chart │
                └───────────────┬───────────────┘
                    REST + WebSocket (JWT auth)
                                │
                ┌───────────────▼───────────────┐
                │       FastAPI backend          │
                │  triggers · filters · dedup    │
                │  schedules · analytics · export │
                └───┬───────────┬───────────┬────┘
                    │           │           │
          ┌─────────▼──┐  ┌─────▼─────┐  ┌──▼──────────┐
          │  Telethon  │  │ AI scorer │  │  SQLite DB  │
          │  userbot   │  │ OpenRouter│  │ (SQLAlchemy)│
          │  sessions  │  │ Llama 3.2 │  │             │
          └─────┬──────┘  └───────────┘  └─────────────┘
                │
        Telegram group chats

Message flow: a new message in a monitored chat → trigger match → schedule check → ignored-author check → negative filters → message/author deduplication → AI scoring & spam filter → log → forward to targets → fire webhooks → broadcast to the dashboard over WebSocket.


Tech stack

Backend

  • Python · FastAPI · Uvicorn
  • Telethon (Telegram userbot)
  • SQLAlchemy (async) + SQLite (via aiosqlite)
  • httpx for OpenRouter and webhook calls
  • JWT auth (python-jose), password hashing (passlib)

Frontend


Setup

1. Prerequisites

  • Python 3.10+
  • A Telegram account
  • A Telegram api_id / api_hash — create an application at my.telegram.orgAPI development tools
  • An OpenRouter API key — sign up at openrouter.ai (the default model runs on a free tier)

2. Install dependencies

cd backend
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt

3. Configure environment

Copy the example file and fill in your values:

cp backend/.env.example backend/.env

Then edit backend/.env. See backend/.env.example for every supported variable and its default. At minimum, set TELEGRAM_API_ID, TELEGRAM_API_HASH, AUTH_USERNAME, AUTH_PASSWORD, SECRET_KEY, and OPENROUTER_API_KEY.


Run

Start the backend (defaults to 0.0.0.0:8000):

python backend/main.py

Then open the frontend — serve frontend/index.html with any static file server, or open it directly in your browser. Log in with the AUTH_USERNAME / AUTH_PASSWORD you set in .env, connect a Telegram account (phone → code, with 2FA support), pick chats to monitor, and add triggers.

Note on first connection: adding an account sends a login code to your Telegram app; enter it in the dashboard. The resulting session is saved so the account reconnects automatically on restart.


API overview

All endpoints except login, health, and the public waitlist/report endpoints require a Bearer JWT obtained from /login.

Area Method & path Description
Auth POST /login Exchange username/password for a JWT (rate-limited)
Accounts POST /accounts Add an account and start the login flow
POST /accounts/{id}/verify Submit the login code (and 2FA password if needed)
GET /accounts List accounts and connection status
GET /accounts/{id}/dialogs List the account's chats
Chats POST /accounts/{id}/chats Add a chat to the monitoring list
POST /accounts/{id}/join-chat Join a chat by link/username and monitor it
GET /accounts/{id}/chats List monitored chats
DELETE /chats/{id} Stop monitoring a chat
Triggers POST /accounts/{id}/triggers Create a keyword/regex trigger
GET /accounts/{id}/triggers List triggers
PATCH /triggers/{id} Enable/disable or edit a trigger
DELETE /triggers/{id} Delete a trigger
Targets POST /triggers/{id}/targets Add a forwarding target (user/bot/channel)
Filters .../negative-filters, .../ignored-authors, .../schedule, .../webhooks Manage negative filters, ignored authors, schedules, and webhooks
Logs GET /logs Recent trigger matches (optionally by trigger_id)
Analytics GET /analytics/summary, /analytics/ai-stats Activity and AI-score breakdowns
Export GET /export/leads Download leads as CSV

Interactive API docs are available at /docs while the server is running.


A note on language

The AI lead-scorer's prompt and keyword pre-filter are tuned for Russian-language chats. The dashboard UI is in English, but the scoring logic works best on Russian text; using it for other languages will require adapting the system prompt and keyword list in backend/ai_scorer.py.


Security & disclaimer

TGtrigger is a self-hosting tool for personal/single-operator use. Do not expose it publicly without significant hardening.

  • Telethon sessions are stored server-side as session strings in the SQLite database. Anyone with access to that database file can act as your connected Telegram account(s). Protect the DB file and back it up carefully; never commit it.
  • Authentication is simple and single-user. A username/password (from environment variables) is exchanged for a JWT signed with SECRET_KEY. There is basic login rate-limiting, but there is no multi-user system, RBAC, or refresh-token rotation.
  • Use your own dedicated Telegram account. Operating a userbot is subject to Telegram's terms of service; automated monitoring of chats may have legal and policy implications depending on your jurisdiction and the chats involved. You are responsible for how you use it.
  • Set strong secrets. Always change AUTH_PASSWORD and SECRET_KEY from their defaults, and keep .env and the database out of version control (see .gitignore).
  • Lock down CORS and networking. The default configuration is meant for local/trusted deployment. If you put this on the internet, run it behind HTTPS, restrict origins, and add proper access controls.

This project is provided as-is, with no warranty. It is a portfolio/learning project rather than a production-hardened service.


Author

Alexander Zabrodin@ProRocK747

License

Released under the MIT License.

About

Telegram chat monitoring with AI lead scoring and spam filtering

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages