Skip to content
This repository was archived by the owner on Nov 1, 2025. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
15243b6
fix menu handling & other optimization
Cordtus Apr 14, 2025
9009538
fix help menu
Cordtus Apr 14, 2025
15e5a78
Merge pull request #3 from cac-group/main
Cordtus Apr 14, 2025
143b009
adds msg deletion with ban, fixing workflow node ver
Cordtus Apr 14, 2025
8a5a12a
Merge remote-tracking branch 'origin/streamlining' into streamlining
Cordtus Apr 14, 2025
fdce2af
fix deletion
Cordtus Apr 14, 2025
8954caf
improve private chat / menus handler
Cordtus Apr 14, 2025
09a4dd6
separate banned patterns list per chat
Cordtus May 10, 2025
60cf2fc
Merge branch 'streamlining' of https://github.com/cac-group/nameBanBo…
Cordtus May 10, 2025
aeb6456
significant fixes
Cordtus May 10, 2025
cef15ab
add logging to all parts of the process
Cordtus May 10, 2025
b85c61f
reorg
Cordtus May 24, 2025
9f1d246
major adds - better group handling, metrics +++
Cordtus May 24, 2025
1f25fe3
add simple tests, improve management
Cordtus May 24, 2025
6a709d2
pre-deployment
Cordtus May 24, 2025
b12e83d
replace default action > kick for unconfigured groups
Cordtus May 24, 2025
122644c
fix config path
Cordtus May 24, 2025
2e1967b
export req functions for tests
Cordtus May 25, 2025
6400431
fix regex matching
Cordtus May 25, 2025
85af750
fix matching 2
Cordtus May 25, 2025
5a8a69d
fix matching 3
Cordtus May 25, 2025
f10df51
fix final 2 test cases
Cordtus May 25, 2025
426899e
further test fixes
Cordtus May 25, 2025
8e05a3b
fix oops
Cordtus May 25, 2025
baff876
...
Cordtus May 25, 2025
c953c1a
fix function
Cordtus May 25, 2025
e3f85e0
fix ci error
Cordtus May 25, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 17 additions & 9 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,26 +11,34 @@ jobs:
name: Lint Code
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node
- name: Checkout code
uses: actions/checkout@v3

- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '16'
- name: Install Dependencies
node-version: '18.x'

- name: Install dependencies
run: yarn install

- name: Run ESLint
run: yarn lint

audit:
name: Audit Dependencies
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node
- name: Checkout code
uses: actions/checkout@v3

- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '16'
- name: Install Dependencies
node-version: '18.x'

- name: Install dependencies
run: yarn install
- name: Run Yarn Audit

- name: Run yarn audit
run: yarn audit --level moderate
35 changes: 34 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,36 @@
# Environment variables
.env

# Local configuration with sensitive data
config.js

# Runtime data and settings
config/
data/

# Dependencies
node_modules/
update.sh

# Logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Optional npm cache directory
.npm

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity
251 changes: 182 additions & 69 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,99 +1,212 @@
# Telegram Ban Bot

## Overview
Automated user filtering bot for Telegram groups that monitors usernames and display names against configurable patterns.

This bot automatically triggers actions against users whose usernames match banned patterns. It monitors:
1. New users joining a group
2. Username changes after joining
3. Messages sent by users
## Features

- **Group-specific pattern management** - Each group maintains separate filter lists
- **Real-time monitoring** - Checks users on join, name changes (30s window), and messages
- **Pattern types** - Text, wildcards (`*`, `?`), and regex patterns
- **Flexible actions** - Ban (permanent) or kick (temporary) per group
- **Hit tracking** - Statistics on pattern matches
- **Admin interface** - DM menu system for pattern management
- **Pattern sharing** - Browse and copy patterns between groups

## Installation

1. **Clone and Install:**
```bash
git clone <repository-url>
cd telegram-ban-bot
yarn install
```

## Configuration

1. **Environment file** - Copy and configure:

```bash
cp example.env .env
```

2. **Bot token** - Add your Telegram bot token to `.env`:

```bash
git clone https://github.com/yourusername/telegram-ban-bot.git
cd telegram-ban-bot
yarn install
BOT_TOKEN=your_bot_token_here
```

2. **Configure:**
- Create `.env` file:
```
BOT_TOKEN=your_bot_token_here
BANNED_PATTERNS_FILE=banned_patterns.toml
DEFAULT_ACTION=ban # or 'kick'
SETTINGS_FILE=settings.json
```
- Edit `config.js` with your user IDs and group IDs
- Create initial `banned_patterns.toml`

3. **Start:**
3. **Configuration file** - Copy and configure:

```bash
yarn start
cp config.example.js config.js
```

## Configuration Files
4. **User/Group IDs** - Edit `config.js`:

```javascript
export const WHITELISTED_USER_IDS = [123456789]; // Global admins
export const WHITELISTED_GROUP_IDS = [-1001234567890]; // Monitored groups
```

5. **Create directories**:

```bash
mkdir -p config data/banned_patterns
```

### config.js
```js
import dotenv from 'dotenv';
dotenv.config();
## Usage

export const BOT_TOKEN = process.env.BOT_TOKEN;
export const BANNED_PATTERNS_FILE = process.env.BANNED_PATTERNS_FILE || 'banned_patterns.toml';
export const DEFAULT_ACTION = process.env.DEFAULT_ACTION || 'ban';
export const SETTINGS_FILE = process.env.SETTINGS_FILE || 'settings.json';
export const WHITELISTED_USER_IDS = [123456789, 987654321];
export const WHITELISTED_GROUP_IDS = [-1001111111111];
```bash
yarn start
```

### banned_patterns.toml
```toml
patterns = [
"spam",
"/^bad.*user$/i",
"*malicious*"
]
## Commands

### Private Chat (Authorized Users)

- `/start` - Initialize bot and show welcome
- `/menu` - Interactive configuration interface
- `/addFilter <pattern>` - Add pattern to selected group
- `/removeFilter <pattern>` - Remove pattern from selected group
- `/listFilters` - Show all patterns for selected group
- `/setaction <ban|kick>` - Set action for selected group
- `/testpattern <pattern> <text>` - Test pattern matching
- `/hits [pattern]` - Show hit statistics
- `/help` - Command reference

### Any Chat

- `/chatinfo` - Display chat ID and configuration status

## Pattern Formats

| Type | Format | Example | Matches |
|------|--------|---------|---------|
| Text | `pattern` | `spam` | "SPAM", "spammer", "123spam" |
| Wildcard | `*pattern*` | `*bot*` | "testbot", "bot_user", "mybot123" |
| Wildcard | `pattern*` | `evil*` | "evil", "eviluser", "evil123" |
| Wildcard | `test?` | `test?` | "test1", "testa", "tests" |
| Regex | `/pattern/flags` | `/^bad.*$/i` | Lines starting with "bad" (case-insensitive) |

## Authorization Levels

1. **Global Admins** - Users in `WHITELISTED_USER_IDS`
- Manage all whitelisted groups
- Full configuration access

2. **Group Admins** - Telegram group administrators
- Manage only their own groups
- Group must be in `WHITELISTED_GROUP_IDS`

## File Structure

```sh
.
├── bot.js # Main bot logic
├── security.js # Pattern validation and matching
├── config.js # User/group configuration and paths
├── config/
│ ├── settings.json # Runtime settings (auto-generated)
│ └── hit_counters.json # Statistics (auto-generated)
├── data/
│ └── banned_patterns/ # Pattern storage (auto-generated)
│ └── patterns_<groupId>.toml
└── tests/ # Test suite
```

## Features
## Security Features

- Pattern validation with length limits (500 chars)
- Regex timeout protection (100ms)
- Control character filtering
- Dangerous regex detection
- Safe compilation with error handling

## Monitoring Triggers

### Patterns
The bot checks users when they:

Supports three matching modes:
- **Plain text:** Case-insensitive substring match (e.g., `spam`)
- **Wildcards:** `*` for any sequence, `?` for one character (e.g., `*bad*`)
- **Regex:** Custom regex patterns (e.g., `/^evil.*$/i`)
1. Join a group (immediate check)
2. Change username/display name (monitored for 30 seconds)
3. Send messages (ongoing check)

### Actions
## Pattern Management

Two configurable actions when a user matches patterns:
- **Ban:** Permanently bans the user from the group
- **Kick:** Removes the user but allows them to rejoin
### Interactive Menu

### User Commands
Access via `/menu` in private chat:

Available in private chat for authorized users:
- Select target group
- Add/remove patterns
- Toggle ban/kick actions
- Browse patterns from other groups
- Copy patterns between groups

- `/start` - Begin configuration and show help
- `/help` - Show usage information
- `/menu` - Display the filter management menu
- `/addFilter <pattern>` - Add a filter pattern
- `/removeFilter <pattern>` - Remove a filter pattern
- `/listFilters` - Show all active filter patterns
- `/setaction <ban|kick>` - Change the action for matched usernames
- `/chatinfo` - Show chat information (works in groups too)
### Direct Commands

### Authorization
Use specific commands for scripting or quick changes:

Users can configure the bot if they:
- Are listed in `WHITELISTED_USER_IDS`
- Are admin in any whitelisted group
- Are admin in the current group (for group commands)
```bash
/addFilter *scam*
/setaction kick
/listFilters
```

## Testing

```bash
yarn test
```

## Deployment

### Environment Variables

Optional environment variable overrides:

- `BOT_TOKEN` - Telegram bot token (required)
- `BANNED_PATTERNS_DIR` - Pattern storage directory (default: `./data/banned_patterns`)
- `SETTINGS_FILE` - Settings file path (default: `./config/settings.json`)

### Systemd Service

Example service file:

```ini
[Unit]
Description=Telegram Ban Bot
After=network.target

[Service]
Type=simple
User=telegram
WorkingDirectory=/path/to/bot
ExecStart=/usr/bin/node bot.js
Restart=always
Environment=NODE_ENV=production

[Install]
WantedBy=multi-user.target
```

## Troubleshooting

- Use `/chatinfo` to verify group IDs and current settings
- For supergroups, IDs must have `-100` prefix in config.js
- Bot requires admin privileges with ban permissions
- Check console logs for detailed operation information
- **Group ID verification** - Use `/chatinfo` to confirm group IDs
- **Supergroup IDs** - Must include `-100` prefix in config
- **Bot permissions** - Requires admin privileges with ban permissions
- **Pattern testing** - Use `/testpattern` to verify regex/wildcard behavior
- **Logs** - Console output shows detailed operation information

## Updates

Use the included update script for production deployments:

```bash
./update.sh
```

Script performs:

- Git pull from main branch
- Dependency updates
- Service restart
- Preserves local configuration
8 changes: 0 additions & 8 deletions banned_patterns.toml

This file was deleted.

Loading