Repository Β· Issues Β· Pull Requests
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 β
βββββββββββββββββ
| 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 | β |
You need:
- Python 3.11+
- A Telegram bot token
- Telegram
API_ID - Telegram
API_HASH - A MongoDB database
git clone https://github.com/Kaztral-ar/advanced-filter-bot.git
cd advanced-filter-botpython3 -m pip install -r requirements.txtCopy the example environment file:
cp .env.sample .envFill 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=FilterBotpython3 main.pyIf everything is configured correctly, the bot will connect to Telegram and MongoDB.
The application is configured entirely through environment variables.
| Variable | Purpose |
|---|---|
TG_BOT_TOKEN |
Token generated by @BotFather |
API_ID |
Telegram application ID |
API_HASH |
Telegram application hash |
DATABASE_URI |
MongoDB connection string |
| 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| 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| 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 |
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=disconnectFor example:
ADD_FILTER_CMD=filterwould make:
/filter hello Hello there!
the add-filter command.
/add hello Hello! π
When a group message matches hello, the bot sends:
Hello! π
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
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
Filters can contain inline buttons.
[Open Website](buttonurl:https://example.com)
[Show Alert](buttonalert:This is an alert message)
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.
Commands are grouped by what they actually do rather than by Telegram handler implementation.
| 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 |
Normal filter management requires appropriate group/admin access.
/delall is restricted more strongly than normal filter deletion.
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
| 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 |
| 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.
| Command | Function |
|---|---|
/start |
Start the bot |
/help |
Show command help |
/about |
Show bot/project information |
Filters can be exported into JSON so they can be backed up or moved between environments.
/exportfilters
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 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.
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.
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=0means no configured application-level limit. It does not mean infinite memory or infinite MongoDB capacity.
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
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.
The optional HTTP server is useful for hosting platforms that expect a listening port.
Enable it with:
ENABLE_WEB_SERVER=yes
PORT=8080The 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.
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.
The project includes:
Procfile
app.json
runtime.txt
The worker starts with:
python3 main.pyConfigure the same required environment variables through the Heroku configuration panel.
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.pyFor a production VPS, run the bot under a process manager such as systemd, Docker, or another supervisor rather than an interactive shell.
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
Before deploying changes, run:
python3 -m compileall .Check installed dependencies:
python3 -m pip checkThen start the application:
python3 main.pyFor 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
Check:
TG_BOT_TOKEN=
API_ID=
API_HASH=
DATABASE_URI=The bot intentionally fails early when required configuration is missing.
Check:
- The bot is actually running.
- It is a member of the group.
- It has the required Telegram permissions.
- The message is being processed by the intended handler.
- The filter exists:
/viewfilters
Verify:
- MongoDB URI
- Database credentials
- Network access rules
- Database availability
- Deployment environment variables
User storage must be enabled:
SAVE_USER=yesOnly users that have been stored can be targeted by the broadcast system.
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.
Pull the latest source:
git pullUpdate dependencies:
pip install -r requirements.txt --upgradeThen restart the bot.
Always read CHANGES.md before upgrading a production instance when the release contains database or configuration changes.
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
This project is released under the MIT License.
See LICENSE for the complete license text.
- Python β application runtime
- Pyrogram β Telegram client framework
- MongoDB / Motor β asynchronous persistence
- python-dotenv β local environment configuration
- aiohttp β optional health server
# advanced-filter-bot # advanced-filter-bot