承接 reactmore/telegram-bot-sdk 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

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

reactmore/telegram-bot-sdk

Composer 安装命令:

composer require reactmore/telegram-bot-sdk

包简介

README 文档

README

This library integrates the Telegram BOT API with the CodeIgniter 4 framework.
It supports .env configuration, custom commands, and the option to run the bot using the Telegram Local Server for improved performance.

📦 Installation

  1. Clone Repository / Install Library
   composer require reactmore/TelegramBotSdk

Configuration

  1. Publish Telegram Config
php spark telegram:publish
  1. Overide Config env:
#--------------------------------------------------------------------
# Bot Configuration
#--------------------------------------------------------------------

telegram.apiKey = 'xxxxxxxxx'
telegram.username = 'xxxxxxxxxxxxx'
telegram.chatsAdmin = 'xxxxxx, xxxxx, xxxxx'
telegram.accessCodesLogin = 'xxxxx'

# for developer only or local server, default is false
telegram.localServer = false
telegram.customBotApiUrl = "http://192.168.1.17:3366"

Example Custom Webhook Controller:

<?php

namespace App\Controllers;

use Reactmore\TelegramBotSdk\Controllers\Services\BaseServicesController;
use Reactmore\TelegramBotSdk\Telegram;
use Reactmore\TelegramBotSdk\Exception\TelegramException;
use Reactmore\TelegramBotSdk\Entities\Update;

class TelegramController extends BaseServicesController
{
    protected $telegram;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        // register local running before init 
        if ($this->telegramSettings->localServer) {
            \Reactmore\TelegramBotSdk\Request::setCustomBotApiUri($this->telegramSettings->customBotApiUrl);
        }
        // init telegram service 
        $this->telegram = service('telegram');
    }

    public function index()
    {
        try {
            // filter webhook return false to block incoming  
            $this->telegram->setUpdateFilter(function (Update $update, Telegram $telegram) {
                $message = $update->getMessage() ?: $update->getCallbackQuery()->getMessage();
                $chat    = $message->getChat();
                $user    = $message->getFrom();
                $chat_id = $chat->getId();
                $user_id = $user->getId();

                // make logic here 

                return true;
            });

            // dont delete this method 
            $this->telegram->handle();
        } catch (TelegramException $e) {
            log_message('error', '[ERROR] {exception}', ['exception' => $e]);
        }
    }
}

Dont forget overide routes webhook with your custom webhook

$routes->group('telegram', function ($routes) {
    $routes->post('hook', 'TelegramController::index');
});

Spark Command

// make setwebhook https://yourdomain.com/telegram/hook
php spark telegram:run setwebhook 

// delete your webhook
php spark telegram:run deletewebhook 

// support 1 argument drop pending update 
// example : 
php spark telegram:run setwebhook --drop-pending-updates true

Webhook Secret Code:

## 🔐 Webhook Secret Token

For enhanced security, you can set a secret token when you [set your webhook](https://core.telegram.org/bots/api#setwebhook). Telegram will then send this token in the `X-Telegram-Bot-Api-Secret-Token` header with every update. This library can automatically validate this token for you.

### 1. Set the Webhook with a Secret Token

When setting your webhook, provide a `secret_token`:

```php
$telegram->setWebhook('https://your-domain.com/hook.php', [
    'secret_token' => 'YOUR_SECRET_TOKEN',
]);

2. Configure Your Bot to Verify the Token

In your webhook handler (e.g., hook.php), set the same secret token on your Telegram object. The library will then automatically check the header on incoming requests and throw an exception if the token is missing or invalid.

<?php

require_once __DIR__ . '/vendor/autoload.php';

$bot_api_key  = 'YOUR_BOT_API_KEY';
$bot_username = 'YOUR_BOT_USERNAME';
$bot_secret   = 'YOUR_SECRET_TOKEN';

try {
    $telegram = new Reactmore\TelegramBotSdk\Telegram($bot_api_key, $bot_username);

    // Set the secret token for incoming webhook requests
    $telegram->setSecretToken($bot_secret);

    // Handle the update
    $telegram->handle();

} catch (Reactmore\TelegramBotSdk\Exception\TelegramException $e) {
    // Log the error
    error_log($e->getMessage());
}

This ensures that only requests from Telegram with the correct secret token are processed by your bot.

3. Prevent Duplicate Updates

Enabling Redis also activates the built-in duplicate update prevention mechanism. This is useful when the bot receives the same update multiple times due to timeouts or retries from Telegram.

When Redis is enabled:

  1. The library checks if the update_id exists in Redis.
  2. If it exists, the update is ignored, and a fake success response is returned to Telegram to stop retries.
  3. If it doesn't exist, the update_id is stored in Redis with a retention time (TTL) of 60 seconds.

You can customize the retention time (in seconds):

// Set retention time to 120 seconds
Longman\TelegramBot\Telegram::setUpdateRetentionTime(120);

⚙️ Advanced Configuration

Request Timeout

To prevent your server from hanging on slow Telegram API requests (e.g., cURL error 28), you can set a custom timeout for the HTTP client. The default timeout is 60 seconds.

use Reactmore\TelegramBotSdk\Request;

// Set request timeout to 30 seconds
Request::setClientTimeout(30);

⚡ Running Telegram Local Server

For better performance and to avoid rate limits, use the Telegram Local Server.

  1. Build Telegram Bot API Follow the official guide: Telegram Bot API - GitHub

  2. Start the Local Server

telegram-bot-api --local --api-id xxxxx --api-hash xxxxx --dir bots --http-ip-address=192.168.1.12 -p 3366 --http-stat-ip-address=192.168.1.12 -s 3355 -v 3
  1. Log Out from the Official Telegram Server This step is required so the bot can connect to the local server: https://api.telegram.org/bot[BOTTOKEN]/logOut

reactmore/telegram-bot-sdk 适用场景与选型建议

reactmore/telegram-bot-sdk 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 25 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 08 月 10 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 reactmore/telegram-bot-sdk 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 reactmore/telegram-bot-sdk 我们能提供哪些服务?
定制开发 / 二次开发

基于 reactmore/telegram-bot-sdk 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-08-10