An open API service indexing awesome lists of open source software.

https://github.com/potatoenergy/telegram-ai-replier

A modular Telegram bot using AI for business replies
https://github.com/potatoenergy/telegram-ai-replier

ai bot composer docker php php8 telegram telegram-bot telegrambot

Last synced: 6 days ago
JSON representation

A modular Telegram bot using AI for business replies

Awesome Lists containing this project

README

          

# telegram-ai-replier

A modular Telegram bot using AI for business replies.

## Compliance Statement

⚠️ **Ethical Usage Requirements**

- Ensure your Telegram Business account complies with [Telegram's Terms of Service](https://telegram.org/tos).
- Use responsibly and avoid spamming.
- Be aware of the usage costs associated with your chosen AI provider (OpenAI, Ollama, custom).

## Prerequisites

- A **publicly accessible server** or hosting service capable of receiving HTTPS webhooks from Telegram (for webhook mode).
- A **domain name** pointing to your server (recommended for HTTPS, webhook mode only).
- A **Telegram Bot Token** (get it from [@BotFather](https://t.me/BotFather)).
- An **AI Provider** configured (OpenAI API Key, Ollama instance, or custom OpenAI-compatible API).

## Environment Variables

Copy `.env.example` to `.env` and fill in your values. See the file for full documentation of each variable.

| Variable | Purpose | Default |
| --------------------------- | ------------------------------------------------- | ----------------------------------- |
| `UPDATE_MODE` | `webhook` or `polling` | `webhook` |
| `BOT_TOKEN` | Telegram Bot Token | — |
| `ADMIN_USER_IDS` | Comma-separated tech admin IDs (commands only) | — |
| `BUSINESS_USER_ID` | Business owner ID (AI processing + commands) | — |
| `TELEGRAM_WEBHOOK_URL` | Webhook URL (required for webhook mode) | — |
| `TELEGRAM_API_BASE_URL` | Custom Telegram API base URL | `https://api.telegram.org` |
| `AI_PROVIDER` | `openai` or `ollama` | — |
| `OPENAI_API_KEY` | OpenAI API Key (required if `AI_PROVIDER=openai`) | — |
| `OPENAI_MODEL` | OpenAI model name | `gpt-3.5-turbo` |
| `OPENAI_BASE_URL` | Custom OpenAI-compatible API base URL | — |
| `OLLAMA_URL` | Ollama API URL | `http://host.docker.internal:11434` |
| `OLLAMA_MODEL` | Ollama model name | `llama3.2` |
| `AI_MAX_TOKENS` | Max tokens for AI response | `500` |
| `AI_TEMPERATURE` | AI creativity setting | `0.7` |
| `AI_SYSTEM_PROMPT` | System prompt for AI | "You are a helpful assistant..." |
| `CHAT_HISTORY_SIZE` | Number of messages kept per chat | `10` |
| `PROXY_URL` | Proxy for outgoing requests (HTTP/SOCKS4/SOCKS5) | — |
| `RATE_LIMIT_WINDOW` | Rate limit window (seconds) | `60` |
| `RATE_LIMIT_MAX_REQUESTS` | Max requests per window per chat | `5` |
| `MIN_RESPONSE_DELAY` | Min reply delay (ms) | `3000` |
| `MAX_RESPONSE_DELAY` | Max reply delay (ms) | `8000` |
| `CHAT_RESPONSE_PROBABILITY` | Response probability (0.0–1.0) | `1.0` |
| `IGNORE_USER_IDS` | Comma-separated user IDs to ignore | — |
| `IGNORE_USER_PATTERNS` | Comma-separated name patterns to ignore | — |
| `MAX_MESSAGE_LENGTH` | Max AI response length (chars) | `4096` |
| `POLLING_TIMEOUT` | Long polling timeout (seconds) | `30` |
| `DEBUG` | Enable verbose logging | `false` |

## Key Features

**1. Dual Update Modes:**

- **Webhook** — instant delivery via HTTPS POST (requires public URL).
- **Long Polling** — works behind NAT/firewall, no public URL needed.
- Seamless switching via `UPDATE_MODE` environment variable.

**2. Business Message Handling:**

- Processes `business_message`, `business_connection`, and `deleted_business_messages` events.
- Handles media captions in addition to plain text.
- Replies generated by selected AI provider (OpenAI, Ollama, custom).

**3. Role-Based Access Control:**

- **Tech admins** (`ADMIN_USER_IDS`) — manage bot via commands, ignored in business AI processing.
- **Business owner** (`BUSINESS_USER_ID`) — messages processed by AI + full admin command access.

**4. Contextual AI Conversations:**

- Per-chat message history with configurable size (`CHAT_HISTORY_SIZE`).
- `/clear` command to reset conversation context in a specific business chat.

**5. Safety & Timing Controls:**

- Humanized response delay (random between `MIN_RESPONSE_DELAY` and `MAX_RESPONSE_DELAY`).
- Configurable response probability (`CHAT_RESPONSE_PROBABILITY`).
- User ignore lists by ID and name patterns.
- Max response length truncation.

**6. In-Memory Rate Limiting:**

- Sliding-window rate limiting per `chat_id`.
- No external dependencies (no Redis needed).

**7. Proxy Support:**

- Universal `PROXY_URL` for all outgoing requests (Telegram API, OpenAI API).
- Supports HTTP, SOCKS4, SOCKS5 with optional authentication.

**8. Modular Command System:**

- Commands in separate classes implementing `CommandInterface`.
- `/start` — admin configuration panel with full settings overview.
- `/status` — system diagnostics (API health, rate limiter, update mode).
- `/clear` — reset AI conversation history in current business chat.

**9. Status Page:**

- Available at webhook URL root (GET request) in both webhook and polling modes.
- Displays system status, Safety & Timing settings, API diagnostics, and rate limiter info.

## Setup

1. **Configure Environment:** Copy `.env.example` to `.env` and fill in your values.
2. **Deploy:** Run `docker-compose up -d` (webhook) or `docker-compose --profile polling up -d` (polling).
3. **Link Business Account:** In Telegram Business settings → Chatbot → enter your bot username.
4. **Test:** Send a message to your Telegram Business account. The bot should respond via AI.

## Switching Between Modes

```bash
# Webhook → Polling
# Set UPDATE_MODE=polling in .env
docker-compose down
docker-compose --profile polling up -d

# Polling → Webhook
# Set UPDATE_MODE=webhook and TELEGRAM_WEBHOOK_URL in .env
docker-compose --profile polling down
docker-compose up -d
```

## Technical Architecture

**Processing Pipeline:**

1. Update received via webhook (Nginx → PHP-FPM) or long polling (CLI).
2. `UpdateHandler` routes update to appropriate handler method.
3. `SafetyFilter` checks ignore lists and response probability.
4. Admin/business owner role check determines processing path.
5. For business messages: rate limit → AI generation with chat history → humanized delay → send.
6. For commands: delegated to corresponding `CommandInterface` implementation.

**Safety Systems:**

- In-memory sliding-window rate limiting per `chat_id`.
- User filtering by ID and name patterns.
- Configurable response probability and humanized delays.
- Max response length truncation.
- Input validation and error handling.
- Debug mode for detailed request logging.

## License

MIT License