Skip to content

Latest commit

Β 

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

⚑ Advanced Filter Bot

A modular Telegram filter engine built for fast, persistent, and flexible group automation.

Repository Β· Issues Β· Pull Requests


What is this?

Advanced Filter Bot watches messages in Telegram groups and turns keywords into automated responses.

A filter can respond with:

  • Text
  • Photos
  • Videos
  • Documents
  • Audio
  • Animations
  • Stickers
  • Voice messages
  • Video notes
  • Inline URL buttons
  • Telegram alert buttons
  • Replied/cached media

Filter data is stored in MongoDB, while the bot keeps per-chat matching data in memory so normal message processing does not require a database query for every message.

The project is organized as a small application rather than a single monolithic bot file:

Telegram
   β”‚
   β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Pyrogram    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜
        β”‚
        β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
        β–Ό               β–Ό
   Command Flow     Message Flow
        β”‚               β”‚
        β–Ό               β–Ό
   Permissions     Filter Matcher
        β”‚               β”‚
        β””β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜
                β–Ό
        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
        β”‚ Async MongoDB β”‚
        β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

✨ Core Capabilities

Area Included
Keyword filters βœ…
Multiple keywords βœ…
Text replies βœ…
Media replies βœ…
Inline URL buttons βœ…
Alert buttons βœ…
Same-row buttons βœ…
Reply-to-message filters βœ…
Filter listing βœ…
Filter deletion βœ…
Bulk deletion βœ…
JSON export βœ…
JSON import βœ…
Group connections βœ…
User ban system βœ…
Optional user storage βœ…
Broadcast βœ…
MongoDB persistence βœ…
Health endpoint βœ…
Environment configuration βœ…
Configurable command aliases βœ…

πŸš€ Quick Start

You need:

  • Python 3.11+
  • A Telegram bot token
  • Telegram API_ID
  • Telegram API_HASH
  • A MongoDB database

1. Clone

git clone https://github.com/Kaztral-ar/advanced-filter-bot.git
cd advanced-filter-bot

2. Install

python3 -m pip install -r requirements.txt

3. Configure

Copy the example environment file:

cp .env.sample .env

Fill in the required values:

TG_BOT_TOKEN=123456:YOUR_BOT_TOKEN
API_ID=12345678
API_HASH=YOUR_API_HASH

DATABASE_URI=mongodb+srv://user:password@cluster.mongodb.net/
DATABASE_NAME=FilterBot

4. Start

python3 main.py

If everything is configured correctly, the bot will connect to Telegram and MongoDB.


πŸ” Configuration

The application is configured entirely through environment variables.

Required

Variable Purpose
TG_BOT_TOKEN Token generated by @BotFather
API_ID Telegram application ID
API_HASH Telegram application hash
DATABASE_URI MongoDB connection string

Access Control

Variable Default Purpose
AUTH_USERS empty Users allowed to perform global/admin operations
OWNER_ID 0 Primary bot owner

Multiple AUTH_USERS can be separated by spaces or commas:

AUTH_USERS=123456789 987654321

Filter Behaviour

Variable Default Purpose
MAX_FILTERS_PER_CHAT 0 Maximum filters per chat; 0 means no application-level limit
FILTER_COOLDOWN_SECONDS 2 Delay between filter additions per chat
SAVE_USER false Store user information for features such as broadcast

Example:

MAX_FILTERS_PER_CHAT=0
FILTER_COOLDOWN_SECONDS=2
SAVE_USER=yes

Runtime / Hosting

Variable Default Purpose
PORT 8080 HTTP health-server port
ENABLE_WEB_SERVER true Enables the health endpoint
WORKERS 24 Pyrogram worker count
LOG_CHANNEL 0 Optional logging channel
HEROKU_API_KEY empty Optional Heroku integration

Command Aliases

The main filter commands can be renamed without editing the source:

ADD_FILTER_CMD=add
DELETE_FILTER_CMD=del
DELETE_ALL_CMD=delall
CONNECT_COMMAND=connect
DISCONNECT_COMMAND=disconnect

For example:

ADD_FILTER_CMD=filter

would make:

/filter hello Hello there!

the add-filter command.


🧩 Filter System

Create a text filter

/add hello Hello! πŸ‘‹

When a group message matches hello, the bot sends:

Hello! πŸ‘‹

Multiple keywords

Use | to assign several triggers to one filter:

/add hello|hi|hey Hello there!

All of these can trigger the same response:

hello
hi
hey

Reply-based filters

Instead of typing the response manually, reply to an existing Telegram message:

/add rules

The bot can save supported message content and reuse it when the keyword is matched.

This is especially useful for:

  • Images
  • Videos
  • Documents
  • Audio
  • Stickers
  • Voice messages
  • Animations
  • Other supported Telegram media

πŸ”˜ Buttons

Filters can contain inline buttons.

URL button

[Open Website](buttonurl:https://example.com)

Alert button

[Show Alert](buttonalert:This is an alert message)

Same-row buttons

Append :same when the next button should share the current row:

[Website](buttonurl:https://example.com)
[GitHub](buttonurl:https://github.com):same

This produces a compact inline keyboard instead of putting every button on a separate row.

Security note: Imported button definitions are treated as untrusted data. Keep URLs and button structures valid and reasonable in size.


πŸ›  Command Reference

Commands are grouped by what they actually do rather than by Telegram handler implementation.

Filters

Command Function
/add <keyword> <reply> Create a filter
/del <keyword> Delete a filter
/del <keyword1> <keyword2> Delete multiple filters
/delall Delete every filter in the current chat
/viewfilters Display filters in the current chat
/exportfilters Export filters as JSON
/importfilters Restore filters from an exported JSON file

Permissions

Normal filter management requires appropriate group/admin access.

/delall is restricted more strongly than normal filter deletion.


Connections

Connections let an authorized user manage a group through private chat.

Command Function
/connect <group_id> Connect a group
/connect Connect the group where the command was issued
/connections Show/manage connected groups
/disconnect Disconnect the current group

A group ID can be obtained with:

/id

Information

Command Function
/id Display Telegram ID information
/info <user_id> Show user information
/info Use as a reply to inspect a user
/status Display bot status

Administration

Command Function
/ban <user_id> [reason] Block a user from bot access
/unban <user_id> Remove the bot-level ban
/broadcast Broadcast a replied message to stored users

Administrative commands are restricted to authorized users.


General

Command Function
/start Start the bot
/help Show command help
/about Show bot/project information

πŸ“¦ Filter Backup

Filters can be exported into JSON so they can be backed up or moved between environments.

Export

/exportfilters

Import

Reply to the exported JSON document:

/importfilters

The import path validates the structure before writing filter records.

For production deployments, keep backups outside the bot's runtime filesystem.


πŸ—„ MongoDB

MongoDB is the persistent storage layer.

The database stores information such as:

filters
users
connections

The database layer is separated from Telegram handlers:

bot/
β”œβ”€β”€ database/
β”‚   β”œβ”€β”€ db.py
β”‚   β”œβ”€β”€ filters.py
β”‚   β”œβ”€β”€ users.py
β”‚   └── connections.py
β”‚
└── handlers/
    β”œβ”€β”€ filters.py
    β”œβ”€β”€ commands.py
    β”œβ”€β”€ callbacks.py
    β”œβ”€β”€ connections.py
    └── security.py

This separation keeps Telegram event handling independent from database implementation.


⚑ Performance Model

Automatic filtering follows a cache-first design:

Incoming group message
        β”‚
        β–Ό
Normalize message text
        β”‚
        β–Ό
Check chat's filter matcher
        β”‚
        β”œβ”€β”€ No match ──────► Ignore
        β”‚
        β–Ό
Matched keyword
        β”‚
        β–Ό
Load filter response
        β”‚
        β–Ό
Send text/media/buttons

Filter changes invalidate the relevant chat cache so newly added or deleted filters become effective without requiring a bot restart.

MongoDB indexes are used for frequently accessed filter records.

Large deployments

If you operate the bot across many large groups, monitor:

  • Number of filters per chat
  • Number of active groups
  • Message throughput
  • MongoDB query latency
  • Matcher rebuild frequency
  • Memory consumption

The application-level value:

MAX_FILTERS_PER_CHAT=0

means no configured application-level limit. It does not mean infinite memory or infinite MongoDB capacity.


πŸ›‘ Security Model

Security-sensitive operations are separated from normal message processing.

The project includes:

  • Authorized-user checks
  • Group administrator checks
  • Owner-level restrictions
  • Bot-level user bans
  • Environment-based secrets
  • Input validation helpers
  • Safe path handling for generated files
  • MongoDB-backed access control
  • Callback validation
  • Filter-add cooldowns
  • Startup validation for required configuration

Protect your credentials

Never commit:

.env
TG_BOT_TOKEN
DATABASE_URI
API_HASH
HEROKU_API_KEY

If a bot token or database credential is exposed, rotate it immediately.


🌐 Health Server

The optional HTTP server is useful for hosting platforms that expect a listening port.

Enable it with:

ENABLE_WEB_SERVER=yes
PORT=8080

The health endpoints are:

/

and:

/health

A healthy instance returns a simple success response.

This server is not the Telegram bot API. It exists primarily for process/hosting health checks.


☁️ Deployment

Render

The repository contains:

render.yaml

A Render deployment can use the web service configuration supplied by the project.

Set the required environment variables in the Render dashboard.

At minimum:

TG_BOT_TOKEN
API_ID
API_HASH
DATABASE_URI
DATABASE_NAME

Recommended:

AUTH_USERS
OWNER_ID
SAVE_USER
MAX_FILTERS_PER_CHAT
ENABLE_WEB_SERVER

Render provides PORT automatically.


Heroku

The project includes:

Procfile
app.json
runtime.txt

The worker starts with:

python3 main.py

Configure the same required environment variables through the Heroku configuration panel.


VPS / Linux

git clone https://github.com/Kaztral-ar/advanced-filter-bot.git
cd advanced-filter-bot

python3 -m venv .venv
source .venv/bin/activate

pip install -r requirements.txt

cp .env.sample .env
nano .env

python3 main.py

For a production VPS, run the bot under a process manager such as systemd, Docker, or another supervisor rather than an interactive shell.


πŸ“ Repository Layout

advanced-filter-bot/
β”‚
β”œβ”€β”€ main.py                  # Application entry point
β”œβ”€β”€ requirements.txt         # Python dependencies
β”œβ”€β”€ .env.sample              # Configuration template
β”‚
β”œβ”€β”€ app.json                 # Heroku metadata
β”œβ”€β”€ Procfile                 # Process definition
β”œβ”€β”€ render.yaml              # Render deployment definition
β”œβ”€β”€ runtime.txt              # Python runtime
β”‚
β”œβ”€β”€ LICENSE
β”œβ”€β”€ README.md
β”œβ”€β”€ CHANGES.md
β”‚
└── bot/
    β”‚
    β”œβ”€β”€ config.py            # Environment/configuration
    β”œβ”€β”€ messages.py          # User-facing messages
    β”‚
    β”œβ”€β”€ database/
    β”‚   β”œβ”€β”€ db.py            # MongoDB connection/index setup
    β”‚   β”œβ”€β”€ filters.py       # Filter persistence
    β”‚   β”œβ”€β”€ users.py         # User persistence
    β”‚   └── connections.py   # Group connections
    β”‚
    └── handlers/
        β”œβ”€β”€ filters.py       # Filter commands/matching
        β”œβ”€β”€ commands.py      # General/admin commands
        β”œβ”€β”€ callbacks.py     # Inline callback handling
        β”œβ”€β”€ connections.py   # Connection workflow
        β”œβ”€β”€ security.py      # Access-control helpers
        └── utils.py         # Shared utilities

πŸ§ͺ Development Checks

Before deploying changes, run:

python3 -m compileall .

Check installed dependencies:

python3 -m pip check

Then start the application:

python3 main.py

For changes involving filters, callbacks, imports, or permissions, test both:

Private chat
Group chat

and test with:

Authorized user
Normal user
Administrator
Non-administrator
Banned user

🧰 Troubleshooting

Missing required environment variable

Check:

TG_BOT_TOKEN=
API_ID=
API_HASH=
DATABASE_URI=

The bot intentionally fails early when required configuration is missing.

Bot starts but does not respond

Check:

  1. The bot is actually running.
  2. It is a member of the group.
  3. It has the required Telegram permissions.
  4. The message is being processed by the intended handler.
  5. The filter exists:
/viewfilters

MongoDB connection failure

Verify:

  • MongoDB URI
  • Database credentials
  • Network access rules
  • Database availability
  • Deployment environment variables

/broadcast has no recipients

User storage must be enabled:

SAVE_USER=yes

Only users that have been stored can be targeted by the broadcast system.

Filters disappeared after restart

Filters should be persistent in MongoDB. If they are missing, verify:

DATABASE_URI=
DATABASE_NAME=

and make sure the deployment is connecting to the same database/cluster.


πŸ”„ Updating

Pull the latest source:

git pull

Update dependencies:

pip install -r requirements.txt --upgrade

Then restart the bot.

Always read CHANGES.md before upgrading a production instance when the release contains database or configuration changes.


🀝 Contributing

Contributions are welcome.

A good pull request should:

  • Keep the existing modular architecture.
  • Avoid unnecessary dependencies.
  • Preserve existing commands unless intentionally changed.
  • Validate user-controlled input.
  • Avoid blocking the asyncio event loop.
  • Add or update documentation when behaviour changes.
  • Avoid committing credentials or generated secrets.

For bugs and feature requests:

GitHub Issues:
https://github.com/Kaztral-ar/advanced-filter-bot/issues


πŸ“œ License

This project is released under the MIT License.

See LICENSE for the complete license text.


🧱 Built With

  • Python β€” application runtime
  • Pyrogram β€” Telegram client framework
  • MongoDB / Motor β€” asynchronous persistence
  • python-dotenv β€” local environment configuration
  • aiohttp β€” optional health server

⚑ Advanced Filter Bot

Fast filters. Persistent storage. Modular architecture.

If this project helps you, consider giving the repository a ⭐

β˜• Support the Project

Buy Me a Coffee
# advanced-filter-bot # advanced-filter-bot

About

A powerful and secure Telegram bot for creating, managing, and automatically matching custom message filters.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages