定制 morfeditorial/telegram-bot-bundle 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

morfeditorial/telegram-bot-bundle

Composer 安装命令:

composer require morfeditorial/telegram-bot-bundle

包简介

A universal Symfony Bundle for building Telegram bots with screens and commands routing.

README 文档

README

Stand With Ukraine

Telegram Bot Bundle

Latest Stable Version Total Downloads License

A powerful, object-oriented, and highly extensible Telegram Bot integration bundle for Symfony applications. This bundle provides a robust architecture for building complex Telegram bots using state machines, modular screens, and dependency injection, moving away from monolithic switch-case handlers to clean, maintainable classes.

Features

  • Object-Oriented Screen Architecture: Build bots using individual Screen classes that handle specific states and actions.
  • State Management: Flexible architecture allowing you to track user progression through complex multi-step flows (e.g., forms, wizards) using your own persistence layer.
  • Standardized Payload Routing: Automatically route callback_query data using a structured payload format (domain:action:args).
  • Seamless Symfony Integration: Full support for Symfony Dependency Injection, autowiring, and event dispatching.
  • Support for Long Polling & Webhooks: Flexible transport layer adapting to your deployment environment.
  • Asynchronous Ready: Built with non-blocking architectures in mind (compatible with AsyncHttp and ReactPHP).

Installation

To install the Telegram Bot Bundle, run the following command in your terminal:

composer require morfeditorial/telegram-bot-bundle

Configuration

Add your Telegram Bot credentials to your .env file:

TELEGRAM_BOT_TOKEN=your_bot_token_here
TELEGRAM_BOT_USERNAME=your_bot_username

If the bundle is not automatically registered, add it to config/bundles.php:

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

Core Concepts

1. The Screen System (AbstractScreen)

Instead of one massive loop handling all updates, this bundle uses "Screens". A Screen is a dedicated class that answers two questions:

  • Can I handle this update? — Implemented via supports()
  • How do I handle this update? — Implemented via handle()

Screens are automatically discovered and registered by the bundle.

2. Payload Routing

The bundle encourages using a standard payload structure for inline keyboards: domain:action:args. For example, feedback:delete:42. This allows your screens to precisely intercept events meant for them.

3. State Management

When asking a user for input (e.g., "Please type your feedback"), you can track their state in your application's database or cache. Your screen can then intercept their next text message based on this state.

Usage

Creating a Screen

Create a new class extending AbstractScreen (or your project's BaseScreen).

namespace App\Screen\Feedback;

use Morfeditorial\TelegramBotBundle\Screen\AbstractScreen;

class FeedbackViewScreen extends AbstractScreen
{
    public function supports(array $update): bool
    {
        $data = $update['callback_query']['data'] ?? '';
        
        // This screen intercepts any payload starting with 'feedback:view:'
        return str_starts_with($data, 'feedback:view:');
    }

    public function handle(array $update): void
    {
        $chatId = $update['callback_query']['message']['chat']['id'] ?? $update['message']['chat']['id'] ?? 0;
        $data = $update['callback_query']['data'] ?? '';
        
        // Extract arguments
        $parts = explode(':', $data);
        $feedbackId = $parts[2] ?? null;

        // Use the injected client to send a message
        $this->client->sendMessage([
            'chat_id' => $chatId,
            'text' => "Viewing feedback #" . $feedbackId,
        ]);
    }
}

Handling Multi-Step Forms (State Machine)

To handle user input sequentially, you can inject your own state tracking service (e.g., a Doctrine Repository or Redis Cache):

namespace App\Screen\Feedback;

use Morfeditorial\TelegramBotBundle\Screen\AbstractScreen;
use App\Service\MyStateService; // Example custom service

class FeedbackCreateScreen extends AbstractScreen
{
    private MyStateService $stateService;

    public function __construct(MyStateService $stateService)
    {
        $this->stateService = $stateService;
    }

    public function supports(array $update): bool
    {
        $userId = $update['message']['from']['id'] ?? 0;
        
        return ($update['callback_query']['data'] ?? '') === 'feedback:create' ||
               $this->stateService->getState($userId) === 'awaiting_feedback_text';
    }

    public function handle(array $update): void
    {
        $chatId = $update['message']['chat']['id'] ?? $update['callback_query']['message']['chat']['id'] ?? 0;
        $userId = $update['message']['from']['id'] ?? $update['callback_query']['from']['id'] ?? 0;
        
        if (isset($update['callback_query'])) {
            // Step 1: Start creation
            $this->stateService->setState($userId, 'awaiting_feedback_text');
            $this->client->sendMessage(['chat_id' => $chatId, 'text' => "Please type your feedback:"]);
            return;
        }

        // Step 2: Receive input
        if ($this->stateService->getState($userId) === 'awaiting_feedback_text') {
            $feedbackText = $update['message']['text'];
            // Save to DB...
            
            $this->stateService->clearState($userId);
            $this->client->sendMessage(['chat_id' => $chatId, 'text' => "Thank you for your feedback!"]);
        }
    }
}

Contributing

Contributions are welcome and appreciated! Here's how you can contribute:

  1. Fork the project
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Please make sure to update tests as appropriate and adhere to the existing coding style.

License

This library is licensed under the CSSM Unlimited License v2.0 (CSSM-ULv2). See the LICENSE file for details.

统计信息

  • 总下载量: 0
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 8
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: LicenseRef-CSSM-Unlimited-2.0
  • 更新时间: 2026-07-01