PHPackages                             tourze/telegram-bot-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. tourze/telegram-bot-bundle

ActiveSymfony-bundle[API Development](/categories/api)

tourze/telegram-bot-bundle
==========================

Telegram 机器人 Symfony Bundle，提供完整的机器人开发功能

0.2.0(4mo ago)03MITPHPCI passing

Since May 5Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/tourze/telegram-bot-bundle)[ Packagist](https://packagist.org/packages/tourze/telegram-bot-bundle)[ RSS](/packages/tourze-telegram-bot-bundle/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (5)Dependencies (47)Versions (6)Used By (0)

TelegramBotBundle
=================

[](#telegrambotbundle)

[![PHP Version Require](https://camo.githubusercontent.com/24dabd5e283adce2d805c951b88d308ea8a80c7a1a6bc950a90a4c24fee20615/68747470733a2f2f706f7365722e707567782e6f72672f746f75727a652f74656c656772616d2d626f742d62756e646c652f726571756972652f706870)](https://packagist.org/packages/tourze/telegram-bot-bundle)[![License](https://camo.githubusercontent.com/4d90e2acafb4ed82bfb26f9451da3bc5cd5346ddfd7aca10a73c7111534e2c9c/68747470733a2f2f706f7365722e707567782e6f72672f746f75727a652f74656c656772616d2d626f742d62756e646c652f6c6963656e7365)](https://packagist.org/packages/tourze/telegram-bot-bundle)[![Latest Version](https://camo.githubusercontent.com/37cd8564b0a063baa4c15aa2250973964a66c7fabbffcd80cd0af38e9b2af5ac/68747470733a2f2f706f7365722e707567782e6f72672f746f75727a652f74656c656772616d2d626f742d62756e646c652f76)](https://packagist.org/packages/tourze/telegram-bot-bundle)[![Build Status](https://github.com/tourze/php-monorepo/workflows/CI/badge.svg)](https://github.com/tourze/php-monorepo/actions)[![Code Coverage](https://camo.githubusercontent.com/f613e51be1087f0d304eb6b376019e4a48edc93dbc80ef2a900ca0e1538fee9c/68747470733a2f2f636f6465636f762e696f2f67682f746f75727a652f7068702d6d6f6e6f7265706f2f6272616e63682f6d61737465722f67726170682f62616467652e737667)](https://codecov.io/gh/tourze/php-monorepo)

[English](README.md) | [中文](README.zh-CN.md)

A Symfony bundle for managing Telegram bots, providing comprehensive bot management capabilities including:

- Bot creation, editing, and management
- Webhook message reception
- Auto-reply rule management
- Message processing and sending
- Command handling system

Table of Contents
-----------------

[](#table-of-contents)

- [Features](#features)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Auto-Reply Rules](#auto-reply-rules)
- [Command Handling](#command-handling)
- [Event System](#event-system)
- [API](#api)
- [Advanced Usage](#advanced-usage)
- [License](#license)

Features
--------

[](#features)

### 🤖 Bot Management

[](#-bot-management)

- Create and manage multiple Telegram bots
- Set up webhook URLs automatically
- Bot validation and status tracking
- Comprehensive bot configuration options

### 📨 Message Processing

[](#-message-processing)

- Receive and process webhook messages
- Support for all Telegram message types
- Message persistence and tracking
- Real-time message handling

### 🎯 Auto-Reply System

[](#-auto-reply-system)

- Rule-based automatic replies
- Exact and fuzzy text matching
- Priority-based rule processing
- HTML-formatted response support

### ⚡ Command System

[](#-command-system)

- Extensible command handling framework
- Custom command handlers
- Argument parsing and validation
- Built-in system commands

### 📊 Analytics &amp; Logging

[](#-analytics--logging)

- Command execution logging
- Message tracking and statistics
- User interaction analytics
- System monitoring capabilities

Installation
------------

[](#installation)

### Requirements

[](#requirements)

- PHP 8.1 or higher
- ext-json
- Symfony 7.3 or higher
- Doctrine ORM 3.0+
- Doctrine DBAL 4.0+
- EasyAdmin Bundle 4+

### Install via Composer

[](#install-via-composer)

```
composer require tourze/telegram-bot-bundle
```

### Core Dependencies

[](#core-dependencies)

- `doctrine/orm`: ^3.0
- `doctrine/dbal`: ^4.0
- `doctrine/doctrine-bundle`: ^2.13
- `symfony/framework-bundle`: ^7.3
- `symfony/http-client-contracts`: ^3.6
- `easycorp/easyadmin-bundle`: ^4
- Plus additional Tourze bundles for enhanced functionality

Quick Start
-----------

[](#quick-start)

### 1. Bundle Registration

[](#1-bundle-registration)

Register the bundle in your `config/bundles.php`:

```
return [
    // ... other bundles
    TelegramBotBundle\TelegramBotBundle::class => ['all' => true],
];
```

### 2. Basic Configuration

[](#2-basic-configuration)

The bundle works out-of-the-box without additional configuration files. The webhook endpoint is automatically available at:

```
POST /telegram/webhook/{bot-id}

```

For advanced configuration, you can customize services in your `config/services.yaml` if needed.

### 3. Usage

[](#3-usage)

1. Run database migrations to create required tables:

```
bin/console doctrine:migrations:migrate
```

2. Access the EasyAdmin interface to manage bots:

    - Bots: `/admin?crudAction=index&crudControllerFqcn=TelegramBotBundle\Controller\Admin\TelegramBotCrudController`
    - Auto-Reply Rules: `/admin?crudAction=index&crudControllerFqcn=TelegramBotBundle\Controller\Admin\AutoReplyRuleCrudController`
    - Bot Commands: `/admin?crudAction=index&crudControllerFqcn=TelegramBotBundle\Controller\Admin\BotCommandCrudController`
3. Set up webhook URLs using the console command:

```
# Set webhook for a bot
bin/console telegram:set-webhook

# Example:
bin/console telegram:set-webhook 123 https://your-domain.com
# This generates: https://your-domain.com/telegram/webhook/123
```

Auto-Reply Rules
----------------

[](#auto-reply-rules)

Create intelligent auto-reply rules through the admin interface:

- **Exact Matching**: Messages must match the keyword exactly
- **Fuzzy Matching**: Messages containing the keyword will trigger replies
- **Priority System**: Higher priority rules (larger numbers) are processed first
- **HTML Support**: Reply content supports HTML formatting
- **Per-Bot Rules**: Each bot can have its own set of rules

Command Handling
----------------

[](#command-handling)

The bundle provides a command handling system that allows easy addition of new command handlers:

1. Create a command handler class:

```
use TelegramBotBundle\Handler\CommandHandlerInterface;
use TelegramBotBundle\Entity\TelegramBot;
use TelegramBotBundle\Entity\Embeddable\TelegramMessage;
use TelegramBotBundle\Service\TelegramBotService;

class YourCommandHandler implements CommandHandlerInterface
{
    public function __construct(
        private readonly TelegramBotService $botService,
    ) {
    }

    public function handle(TelegramBot $bot, string $command, array $args, TelegramMessage $message): void
    {
        // Handle your command logic here
        $response = "Your reply message";
        $this->botService->sendMessage($bot, (string) $message->getChat()?->getId(), $response);
    }
}
```

2. Command handlers will be automatically registered and handle corresponding commands

Event System
------------

[](#event-system)

The bundle uses an event system to handle Webhook messages. You can create your own EventSubscriber to handle messages:

```
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use TelegramBotBundle\Event\TelegramUpdateEvent;

class YourSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            TelegramUpdateEvent::class => ['onTelegramUpdate', -10], // lower priority than auto-reply
        ];
    }

    public function onTelegramUpdate(TelegramUpdateEvent $event): void
    {
        $update = $event->getUpdate();
        $bot = $event->getBot();

        // Handle message...
    }
}
```

API
---

[](#api)

### Sending Messages

[](#sending-messages)

```
use TelegramBotBundle\Service\TelegramBotService;
use TelegramBotBundle\Repository\TelegramBotRepository;

class YourService
{
    public function __construct(
        private readonly TelegramBotService $botService,
        private readonly TelegramBotRepository $botRepository,
    ) {
    }

    public function sendMessage(string $botId, string $chatId, string $message): void
    {
        $bot = $this->botRepository->find($botId);
        if ($bot) {
            $this->botService->sendMessage($bot, $chatId, $message);
        }
    }
}
```

Advanced Usage
--------------

[](#advanced-usage)

### Database Schema

[](#database-schema)

The bundle creates several tables for managing bots and tracking activity:

- `tg_bot`: Bot configuration (name, token, webhook URL)
- `tg_auto_reply_rule`: Auto-reply rules with priority and matching options
- `telegram_bot_command`: Custom command definitions
- `telegram_update`: All received Telegram updates (with Snowflake IDs)
- `command_log`: Command execution audit trail

### Event-Driven Architecture

[](#event-driven-architecture)

Monitor bot activity by subscribing to events:

### Custom Message Handlers

[](#custom-message-handlers)

Create sophisticated message processing by implementing custom handlers:

```
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use TelegramBotBundle\Event\TelegramUpdateEvent;
use TelegramBotBundle\Event\TelegramCommandEvent;

class CustomBotSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            TelegramUpdateEvent::class => ['onTelegramUpdate', -10],
            TelegramCommandEvent::class => ['onTelegramCommand', 0],
        ];
    }

    public function onTelegramUpdate(TelegramUpdateEvent $event): void
    {
        $update = $event->getUpdate();
        $bot = $event->getBot();

        // Handle all types of updates (messages, edits, etc.)
        if ($messageText = $event->getMessageText()) {
            // Process text messages
        }
    }

    public function onTelegramCommand(TelegramCommandEvent $event): void
    {
        $command = $event->getCommand();
        $args = $event->getArgs();

        // Handle specific command executions
    }
}
```

### Custom Command Handlers

[](#custom-command-handlers)

Implement the `CommandHandlerInterface` to create custom commands:

```
use TelegramBotBundle\Handler\CommandHandlerInterface;
use TelegramBotBundle\Entity\TelegramBot;
use TelegramBotBundle\Entity\Embeddable\TelegramMessage;
use TelegramBotBundle\Service\TelegramBotService;

class WeatherCommandHandler implements CommandHandlerInterface
{
    public function __construct(
        private readonly TelegramBotService $botService,
    ) {
    }

    public function handle(TelegramBot $bot, string $command, array $args, TelegramMessage $message): void
    {
        $location = $args[0] ?? 'Unknown';
        $chatId = (string) $message->getChat()?->getId();

        $weatherInfo = $this->fetchWeatherData($location);
        $this->botService->sendMessage($bot, $chatId, $weatherInfo);
    }

    private function fetchWeatherData(string $location): string
    {
        // Implement your weather API integration
        return "Weather in {$location}: Sunny, 24°C";
    }
}
```

Register your handler in the admin interface by creating a `BotCommand` entry with your handler's FQCN.

Contributing
------------

[](#contributing)

We welcome contributions to improve this bundle! Please:

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes and add tests
4. Ensure all tests pass (`./vendor/bin/phpunit packages/telegram-bot-bundle/tests`)
5. Run static analysis (`php -d memory_limit=2G ./vendor/bin/phpstan analyse packages/telegram-bot-bundle`)
6. Commit your changes (`git commit -m 'Add amazing feature'`)
7. Push to the branch (`git push origin feature/amazing-feature`)
8. Open a Pull Request

### Development Setup

[](#development-setup)

```
# Run tests
./vendor/bin/phpunit packages/telegram-bot-bundle/tests

# Run static analysis
php -d memory_limit=2G ./vendor/bin/phpstan analyse packages/telegram-bot-bundle

# Check package integrity
bin/console app:check-packages telegram-bot-bundle -o -f
```

Changelog
---------

[](#changelog)

### Latest Changes

[](#latest-changes)

- Enhanced test coverage with comprehensive integration tests
- Improved PHPStan compliance and type safety
- Added support for all Telegram message types
- Implemented robust command parsing and logging
- Enhanced EasyAdmin integration for better management

### Version History

[](#version-history)

- **v0.1.x**: Core bot management and webhook handling
- **v0.2.x**: Auto-reply system and command framework
- **v0.3.x**: Enhanced logging and event system
- **Current**: Full-featured bot development platform

License
-------

[](#license)

This bundle is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.

Reference Documentation
-----------------------

[](#reference-documentation)

- [Telegram Bot API](https://core.telegram.org/bots/api)
- [Getting updates](https://core.telegram.org/bots/api#getting-updates)
- [Available types](https://core.telegram.org/bots/api#available-types)
- [Available methods](https://core.telegram.org/bots/api#available-methods)
- [EasyAdmin Documentation](https://symfony.com/doc/current/bundles/EasyAdminBundle/index.html)

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance79

Regular maintenance activity

Popularity3

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity30

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~57 days

Total

5

Last Release

141d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e354fdb316da535dfa8ba2e9193a473c403b6bc6fb9170778d1dc50e304c6e9d?d=identicon)[tourze](/maintainers/tourze)

---

Top Contributors

[![tourze](https://avatars.githubusercontent.com/u/13899502?v=4)](https://github.com/tourze "tourze (4 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tourze-telegram-bot-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/tourze-telegram-bot-bundle/health.svg)](https://phpackages.com/packages/tourze-telegram-bot-bundle)
```

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M646](/packages/sylius-sylius)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)[contao/core-bundle

Contao Open Source CMS

1231.6M2.3k](/packages/contao-core-bundle)[ec-cube/ec-cube

EC-CUBE EC open platform.

78527.0k1](/packages/ec-cube-ec-cube)[shopware/platform

The Shopware e-commerce core

3.3k1.5M3](/packages/shopware-platform)[prestashop/prestashop

PrestaShop is an Open Source e-commerce platform, committed to providing the best shopping cart experience for both merchants and customers.

9.0k15.4k](/packages/prestashop-prestashop)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
