Sign inSign up

srckod/tele

By srckod

•Updated 4 months ago

Telegram Automation Engine with AI agent integration

Image
Integration & delivery
API management
Machine learning & AI
0

1.7K

srckod/tele repository overview

⁠Tele - Telegram Automation Engine

.NET License: MIT Docker Telegram MTProto

A production-grade Telegram automation platform with AI agent integration, multi-account orchestration, and intelligent background job processing.


⁠Table of Contents


ā šŸŽÆ Why This Project Exists

The Telegram Automation Engine or simply Tele was designed to bridge a critical gap in the Telegram automation ecosystem: the need for an enterprise-grade platform that seamlessly integrates traditional Telegram bot operations with modern AI agent capabilities.

While numerous Telegram tools exist for basic automation, they typically suffer from:

LimitationOur Solution
Single-account constraintsMulti-account orchestration with automatic failover and health monitoring
No AI integrationModel Context Protocol (MCP) exposes full engine capabilities to AI agents like Claude & GPT
No scalable bulk operationsBackground job processing with MySQL, Redis, or in-memory queue backends
Poor member targetingCustom Filter DSL — a domain-specific language for precise member filtering
Manual session managementDatabase-persisted sessions with automatic access hash caching across restarts

ā šŸš€ Core Features

ā šŸ¤– MCP Integration (Model Context Protocol)

Our standout innovation. The engine exposes its full capabilities through the Model Context Protocol, enabling AI agents to programmatically control Telegram operations — transforming it from a simple automation tool into an AI-powered orchestration platform.

  • --mcp: Stdio transport for direct AI agent integration (Claude, GPT, etc.)
  • --mcp-http: HTTP transport for web-based AI agent connections
  • Normal mode: Traditional Telegram bot + REST API
ā šŸ‘„ Multi-Account Orchestration

Manage dozens of Telegram accounts simultaneously with enterprise-grade reliability:

  • Automatic failover — when an account gets banned, traffic is redistributed
  • Per-account flood protection — configurable thresholds prevent API-level bans
  • Database-persisted sessions — sessions survive restarts, no re-authentication needed
  • Health monitoring — track ban status, send attempts, and flood flags per phone
ā šŸ”‘ Intelligent Access Hash Management

Telegram's MTProto requires access hashes for efficient peer communication. Our engine:

  • Automatically collects and caches access hashes during operations
  • Persists hashes to MySQL for reuse across sessions and restarts
  • Reduces peer resolution API calls by ~90%
  • Eliminates the dreaded PEER_ID_INVALID errors
ā šŸŽÆ Custom Filter DSL

A powerful domain-specific language for precise member targeting:

firstname~A,batch=50
active=false,group=mychannel
lastseen>30d,withusername=true

Supports operators: =, !=, ~ (contains), >, <, >=, <=

ā šŸ“Š Background Job Processing

Long-running operations run asynchronously with full lifecycle management:

  • Pluggable queue backends: MySQL, Redis (Upstash-compatible), or In-Memory
  • Unique job IDs for tracking and status polling
  • Status monitoring: pending → running → completed / failed
  • Pagination and filtering — list jobs by status, page through results
  • Polymorphic job serialization — each job type carries its own payload schema
⁠🌐 Dual Interface Architecture
  • Telegram Bot Interface: Interactive keyboard-based navigation for human operators
  • REST API: Swagger-documented endpoints secured with API key authentication
  • MCP Interface: AI agent consumable tools
ā šŸ“¤ Data Exporting

Export filtered member data with background job support, ready for integration with external analytics tools.


ā šŸ—ļø Architecture Overview

The project follows a feature-based architecture with clean separation of concerns:

Tele/
ā”œā”€ā”€ Features/                 # Business logic by feature
│   ā”œā”€ā”€ Api/                  # REST API controllers
│   ā”œā”€ā”€ BulkAdding/           # Bulk join members to channels
│   ā”œā”€ā”€ BulkSending/          # Bulk message delivery
│   ā”œā”€ā”€ Exporting/            # Member data export
│   ā”œā”€ā”€ Mcp/                  # MCP AI agent integration layer
│   ā”œā”€ā”€ Scraping/             # Channel member scraping
│   ā”œā”€ā”€ TelegramBot/          # Interactive bot (keyboards, states, actions)
│   └── TelegramClient/       # MTProto client wrapper with access hash mgmt
ā”œā”€ā”€ Infrastructure/           # Cross-cutting concerns
│   ā”œā”€ā”€ Database/             # EF Core context, DAOs, models
│   ā”œā”€ā”€ Extensions/           # DI service registration
│   ā”œā”€ā”€ Middleware/            # API key authentication
│   └── Queue/                # Job queue (MySQL, Redis, Memory)
└── Shared/                   # Shared models, enums, utilities
    └── Models/               # Config, MemberFilter, FilterCondition
⁠Key Design Decisions
DecisionRationale
Feature-based foldersEach feature is self-contained with its own services, requests, and handlers — easy to extend without touching unrelated code
Separated InfrastructureDatabase, queue, middleware, and DI registration are decoupled from business logic
Polymorphic job queueIJobQueue interface with MySQL, Redis, and In-Memory implementations — swap backends via config
DAOs over direct DbContextDatabase access is abstracted behind interfaces for testability
Background worker patternQueueWorker as a hosted service processes jobs asynchronously without blocking the API
SHA256 bot reply verificationBot responses are hashed for secure state machine matching

ā šŸ› ļø Technology Stack

ComponentTechnology
Runtime.NET 9.0 with C# 13
Telegram MTProto ClientWTelegramClient⁠
Telegram Bot APITelegram.Bot⁠
ORMEntity Framework Core with MySQL (Pomelo)
AI IntegrationModel Context Protocol (.NET SDK)
Job QueueMySQL / Redis (Upstash-compatible) / In-Memory
API DocumentationSwagger / OpenAPI
ConfigurationYAML via YamlDotNet
LoggingSerilog (console + rolling file)
ContainerizationDocker (multi-stage build)
CI/CDGitHub Actions

⁠⚔ Quick Start

⁠Prerequisites
⁠Installation
git clone https://github.com/srckod/tele.git
cd tele
dotnet restore
dotnet build
⁠Configuration

Copy config.yaml.example to config.yaml and fill in your credentials:

ActiveMode: "Test"

Brand:
  BotName: "My Automation Bot"

Test:
  ApiToken: "your_bot_token"
  DBHost: "localhost"
  DBName: "telegram_automation"
  DBUser: "root"
  DBPassword: "your_password"
  AppId: 12345678
  AppHash: "your_app_hash"
  AppPhone: "+1234567890"

# Queue backend: "redis", "mysql", or "memory"
QueueType: "memory"

Admins:
  your_username: 123456789

AutomationAPIKey: "generate-a-secure-api-key"
⁠Running
# Normal mode (Telegram Bot + REST API)
dotnet run

# MCP stdio mode (AI agent integration)
dotnet run -- --mcp

# MCP HTTP mode (web-based AI agents)
dotnet run -- --mcp-http

ā šŸ“„ Downloads & Releases

Pre-built single-file executables are available from the GitHub Releases⁠ page:

PlatformFileArchitecture
WindowsTele-win-x64.zipx64
LinuxTele-linux-x64.tar.gzx64
macOS (Intel)Tele-osx-x64.tar.gzx64
macOS (Apple Silicon)Tele-osx-arm64.tar.gzARM64
⁠Windows
  1. Download Tele-win-x64.zip from the latest release
  2. Extract the archive to a folder of your choice
  3. Copy your config.yaml file next to Tele.exe (same directory)
  4. Open a terminal in that folder and run:
    Tele.exe
    

Need a config template? Download config.yaml.example from the repository⁠, rename it to config.yaml, and fill in your credentials.

⁠Linux / macOS
# Download and extract
wget https://github.com/srcKod/tele/releases/latest/download/Tele-linux-x64.tar.gz
tar -xzf Tele-linux-x64.tar.gz
cd linux-x64

# Copy your config.yaml next to the executable
cp /path/to/your/config.yaml .

# Run
./Tele

ā āš™ļø Configuration

The config.yaml supports extensive configuration:

SettingDescription
ActiveMode"Test" or "Production" — switches between environment-specific settings
QueueType"redis", "mysql", or "memory" — backend for background job processing
ChunkParallelism factor for scraper operations (default: 8)
FloodThreasholdMax send operations before cooldown (default: 50)
FloodThreasholdPeriodCooldown period in hours (default: 24)
AutomationAPIKeyAPI key for REST endpoint authentication

Dual-environment configuration supports Test and Production blocks, each with independent database, Telegram credentials, and MTProto server settings.


ā šŸŽ® Running Modes

⁠1. Normal Mode (Default)
dotnet run

Starts the Telegram Bot interface (interactive keyboard navigation) alongside the REST API on port 5000. Swagger UI is available at /swagger.

⁠2. MCP Stdio Mode
dotnet run -- --mcp

Communicates via stdio JSON-RPC. Ideal for direct integration with AI agents like Claude Desktop, Cline, or custom AI orchestration pipelines.

⁠3. MCP HTTP Mode
dotnet run -- --mcp-http

Exposes the MCP endpoint at /mcp over HTTP. Perfect for web-based AI agents (e.g. llama.cpp Web UI), remote MCP clients, and distributed AI pipelines. Swagger UI is also available at /swagger in this mode.

Important: When running the compiled EXE, --urls must be the last argument. The --mcp-http flag is filtered out internally before it reaches the host builder:

Tele --mcp-http --urls "http://localhost:4951"

If it still doesn't work, use the ASPNETCORE_URLS environment variable instead:

set ASPNETCORE_URLS=http://localhost:4951
Tele --mcp-http
⁠MCP API Key Authentication

The MCP HTTP endpoint uses the same X-API-Key authentication as the REST API. All POST requests to /mcp (tool calls) require a valid API key. GET requests (SSE connection initialization) are allowed without auth.

Provide the API key either via the X-API-Key header or the api_key query parameter.

Cline / VS Code MCP configuration:

{
  "mcpServers": {
    "tele": {
      "url": "http://localhost:4951/mcp",
      "type": "streamableHttp",
      "headers": {
        "X-API-Key": "your-api-key-here"
      },
      "disabled": false,
      "autoApprove": []
    }
  }
}

If your MCP client does not support custom headers, use the api_key query parameter instead:

{
  "mcpServers": {
    "tele": {
      "url": "http://localhost:4951/mcp?api_key=your-api-key-here",
      "type": "streamableHttp",
      "disabled": false,
      "autoApprove": []
    }
  }
}

Claude Desktop MCP configuration (claude_desktop_config.json):

{
  "mcpServers": {
    "tele": {
      "command": "dotnet",
      "args": ["run", "--project", "/path/to/Tele", "--mcp"],
      "disabled": false,
      "autoApprove": []
    }
  }
}

For the stdio mode (--mcp), no API key is needed since communication happens via stdin/stdout.

⁠Testing MCP tools via curl:

List available tools:

curl -X POST http://localhost:4951/mcp \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your-api-key-here" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'

Get member count:

curl -X POST http://localhost:4951/mcp \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your-api-key-here" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_member_count","arguments":{}}}'

Windows cmd.exe users: Replace single quotes with escaped double quotes:

curl -X POST http://localhost:4951/mcp -H "Content-Type: application/json" -H "X-API-Key: your-api-key-here" -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\",\"params\":{}}"

ā šŸ“” REST API

All endpoints are secured with API key authentication (X-API-Key header) and documented via Swagger at /swagger.

MethodEndpointDescription
GET/api/automation/membersQuery members with optional Filter DSL
GET/api/automation/members/countTotal member count
GET/api/automation/phonesList registered phones with health status
GET/api/automation/healthDatabase connection health check
POST/api/automation/scrapeStart channel member scraping (background job)
POST/api/automation/bulk-sendSend bulk messages to filtered members (background job)
POST/api/automation/bulk-addBulk join filtered members to target channel (background job)
GET/api/automation/jobs/{id}Get job status and result
GET/api/automation/jobsList all jobs (filterable by status, paginated)

ā šŸ¤– MCP AI Agent Integration

The engine exposes the same functionality as the REST API through MCP tools, consumable by any MCP-compatible AI agent:

MCP ToolDescription
query_membersQuery members with Filter DSL, pagination support. Use filterDsl: "none" for all members
list_phonesList phones with ban status, send attempts, flood flags
get_member_countTotal members in database
check_database_healthVerify database connectivity
scrape_channelStart background channel scraping
bulk_sendSend bulk messages to filtered members
bulk_addBulk add filtered members to target channel
get_job_statusPoll background job status
list_jobsList jobs with status filtering and pagination

Important: Tool names use snake_case (e.g., get_member_count, list_phones, query_members).

⁠filterDsl cheat sheet for query_members:
You wantSet filterDsl to
All members (no filter)"none" (or leave default)
First name contains "john", max 5"firstname~john,batch=5"
From specific channel"group=mychannel"
Only active members, max 100"active=true,batch=100"
Skip first 50, get 10"skip=50,batch=10"
Empty/null firstname"firstname=null"
With username, not active"withusername=true,active=false"

Example MCP integration with Claude:

{
  "server_name": "tele",
  "tool_name": "query_members",
  "arguments": {
    "filterDsl": "active=true,group=mychannel,batch=50",
    "pageSize": 20
  }
}

ā šŸŽÆ Custom Filter DSL

A compact, expressive domain-specific language for filtering Telegram members.

⁠Syntax
field=value,field!=value,field~value,batch=N,skip=N
⁠Supported Fields
FieldAliasesTypeExample
firstnamefnTextfirstname~Ali
lastnamelnTextlastname=Smith
usernameunTextusername~john
phone—Textphone=+1234
lastseen—Text (relative)lastseen>30d
active—Booleanactive=true
access—Booleanaccess=false
withusername—Booleanwithusername=true
groupchannelTextgroup=mychannel
collected—DateTimecollected>2024-01-01
batchlimitIntegerbatch=100
skipoffsetIntegerskip=20
⁠Operators
OperatorMeaning
=Exact match
!=Not equal
~Contains (text fields only)
>Greater than (numeric/date)
<Less than (numeric/date)
>=Greater than or equal
<=Less than or equal
⁠Examples
# Find active users named "Ali" in a specific channel, limit to 50
active=true,fn~Ali,group=my_channel,batch=50

# Find inactive members without username, collected recently
active=false,withusername=false,collected>2025-01-01

# Find members not seen in 30+ days
lastseen>30d,batch=200

ā šŸ“‹ Background Job Processing

All bulk operations run as background jobs, ensuring the API and bot remain responsive.

⁠Architecture
Client → API/MCP → IJobQueue.EnqueueAsync() → MySQL/Redis/Memory
                                                    ↓
                                          QueueWorker (HostedService)
                                                    ↓
                                        ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¼ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
                                        ↓             ↓             ↓
                                   ScrapeHandler  BulkSend     BulkAdd
                                        ↓             ↓             ↓
                                   IJobQueue.UpdateJobStatus() → MySQL/Redis/Memory
⁠Queue Backends
BackendWhen to Use
MySQLProduction — durable, supports transactions and SELECT ... FOR UPDATE SKIP LOCKED
RedisHigh-throughput — Upstash-compatible, ideal for serverless deployments
MemoryDevelopment — no external dependencies, in-process

ā šŸ”„ CI/CD & Deployment

⁠GitHub Actions Pipeline

The project includes a comprehensive CI/CD pipeline (.github/workflows/ci-cd.yml) that:

  • Builds and tests on every push and pull request
  • Builds and publishes Docker images to Docker Hub on pushes to main
  • Creates GitHub Releases with cross-platform single-file executables when version tags are pushed
⁠Cross-Platform Releases

Pushing a version tag automatically produces standalone executables:

git tag v1.0.0
git push origin v1.0.0
PlatformFormatArchitecture
Linux.tar.gzx64
Windows.zipx64
macOS (Intel).tar.gzx64
macOS (Apple Silicon).tar.gzARM64

Each executable is self-contained (no .NET runtime required).


⁠🐳 Docker

Pre-built Docker images are available on Docker Hub⁠:

docker pull srckod/tele:1.0
⁠Run with config.yaml (Normal Mode)

Mount your config.yaml file into the container — do not mount the entire /app/ directory (that would overwrite the application files):

docker run -d \
  --name tele \
  -p 4951:4951 \
  -v $(pwd)/config.yaml:/app/config.yaml:ro \
  srckod/tele:1.0
FlagPurpose
-dRun in background (detached)
-p 4951:4951Map host port 4951 to container port 4951
-v $(pwd)/config.yaml:/app/config.yaml:roMount your config file as read-only
srckod/tele:1.0Docker Hub image
⁠Run with MCP HTTP mode

To run in --mcp-http mode, pass it as a command argument after the image name. You also need to set ASPNETCORE_URLS to control the listening port:

docker run -d \
  --name tele-mcp \
  -p 4951:4951 \
  -e ASPNETCORE_URLS=http://0.0.0.0:4951 \
  -v $(pwd)/config.yaml:/app/config.yaml:ro \
  srckod/tele:1.0 \
  --mcp-http

The --mcp-http argument is appended after the image name (Docker passes it to the ENTRYPOINT). The -e flag sets the environment variable for the port.

⁠Check the logs
docker logs tele -f

Note: Port 4951 is the HTTP API port (Swagger available at http://localhost:4951/swagger). No HTTPS port is exposed — use a reverse proxy (Nginx, Traefik, Caddy) for production HTTPS.

⁠Build from source
docker build -t tele .
docker run -d \
  --name tele \
  -p 4951:4951 \
  -v $(pwd)/config.yaml:/app/config.yaml:ro \
  tele

ā šŸ¤ Contributing

We welcome contributions! Areas of particular interest:

  • Additional MCP tools — extend AI agent capabilities
  • New Filter DSL operators — enhance member targeting precision
  • Additional queue backends — RabbitMQ, Azure Service Bus, etc.
  • Performance optimizations — chunk tuning, caching strategies
  • Web dashboard — real-time monitoring and control UI
  • Test coverage — unit and integration tests

Please open an issue first to discuss your proposed changes.


ā šŸ“„ License & Disclaimer

License: MIT — see LICENSE⁠ for details.

Disclaimer: This tool is designed for educational and legitimate marketing purposes only. Users are responsible for ensuring compliance with applicable laws, regulations, and Telegram's Terms of Service. The authors assume no liability for misuse of this software.


Built for the future of Telegram automation šŸš€

Tag summary

Content type

Image

Digest

sha256:0988159a5…

Size

62.3 MB

Last updated

4 months ago

docker pull srckod/tele