shokirjonmk/telegram-bot
Composer 安装命令:
composer require shokirjonmk/telegram-bot
包简介
Professional Telegram Bot Extension for Yii2 Framework with multi-bot support, queue integration, command routing, and rate limiting
README 文档
README
Professional Telegram Bot Extension for Yii2 Framework with advanced features: multi-bot support, queue integration, command routing, rate limiting, and more.
✨ Xususiyatlar
- ✔ Yii2 uchun maxsus yozilgan
- ✔ Multi-bot support - bir nechta botlarni boshqarish (student, staff, va boshqalar)
- ✔ Queue integration - background message sending
- ✔ Command Router - Laravel-like command handling
- ✔ Rate Limiting - per-user va per-bot rate limiting (Redis bilan)
- ✔ Retry mechanism - exponential backoff bilan avtomatik retry
- ✔ File Helper - Telegram fayllarini yuklab olish
- ✔ Update Handler Middleware - update handling uchun middleware
- ✔ Exception, Logging, MarkdownV2 escape
- ✔ Inline keyboard builder
- ✔ Chat actions support
📦 O'rnatish
Composer orqali
composer require shokirjonmk/telegram-bot
Yoki composer.json ga qo'shing:
{
"require": {
"shokirjonmk/telegram-bot": "*"
}
}
Qo'shimcha paketlar (ixtiyoriy, lekin tavsiya etiladi)
Queue va rate limiting uchun:
composer require yiisoft/yii2-queue composer require yiisoft/yii2-redis
⚙️ Konfiguratsiya
Asosiy konfiguratsiya (config/web.php va config/console.php)
'components' => [ // Redis (rate limiting va queue uchun) 'redis' => [ 'class' => 'yii\redis\Connection', 'hostname' => '127.0.0.1', 'port' => 6379, 'database' => 0, ], // Queue (background jobs uchun) 'queue' => [ 'class' => \yii\queue\redis\Queue::class, 'redis' => 'redis', 'channel' => 'queue', ], // HTTP Client 'httpClient' => [ 'class' => \yii\httpclient\Client::class, ], // Telegram Manager (multi-bot support) 'telegramManager' => [ 'class' => 'shokirjonmk\telegram\TelegramManager', 'bots' => [ 'student' => [ 'token' => getenv('TELEGRAM_STUDENT_TOKEN'), 'apiUrl' => 'https://api.telegram.org/bot', ], 'staff' => [ 'token' => getenv('TELEGRAM_STAFF_TOKEN'), 'apiUrl' => 'https://api.telegram.org/bot', ], ], 'defaultBot' => 'student', 'enableLogs' => true, ], // Yoki oddiy single bot (backward compatibility) 'telegram' => [ 'class' => 'shokirjonmk\telegram\Telegram', 'botToken' => getenv('TELEGRAM_TOKEN'), 'apiUrl' => 'https://api.telegram.org/bot', 'timeout' => 5, 'enableLogs' => true, ], ]
Queue worker ishga tushirish
php yii queue/listen
# yoki
php yii queue/run
Lokal polling ishga tushirish (Development)
# Console command orqali php yii telegram-polling/polling --bot=student --timeout=30 # Yoki standalone script php examples/polling.php --bot=student --timeout=30
🚀 Ishlatish
1. Oddiy xabar yuborish (eski usul - backward compatible)
use shokirjonmk\telegram\Telegram; Yii::$app->telegram->sendMessage( $chatId, Telegram::escape("Salom, aka!") );
2. Multi-bot support (yangi usul)
// Student bot $studentBot = Yii::$app->telegramManager->get('student'); $studentBot->sendMessage($chatId, "Student botdan xabar"); // Staff bot $staffBot = Yii::$app->telegramManager->get('staff'); $staffBot->sendMessage($chatId, "Staff botdan xabar");
3. Options bilan xabar yuborish
use shokirjonmk\telegram\TelegramComponent; use shokirjonmk\telegram\Keyboard; $tg = Yii::$app->telegramManager->get('student'); $kb = Keyboard::inline([ [ Keyboard::inlineButton("📊 Statistika", "stats"), Keyboard::inlineButton("📅 Darslar", "schedule") ] ]); $tg->sendMessage($chatId, "Menyuni tanlang:", [ 'keyboard' => $kb, 'parse_mode' => 'MarkdownV2', 'disable_web_page_preview' => true, ]);
4. Queue orqali background xabar yuborish
$tg = Yii::$app->telegramManager->get('student'); $tg->enqueueSendMessage( $chatId, TelegramComponent::escapeMarkdownV2("Background xabar!") );
5. Chat action yuborish
$tg = Yii::$app->telegramManager->get('student'); $tg->sendChatAction($chatId, 'typing'); // typing, upload_photo, record_voice, etc.
6. Fayl yuklab olish
use shokirjonmk\telegram\FileHelper; $tg = Yii::$app->telegramManager->get('student'); $localPath = FileHelper::downloadFile($tg, $fileId, '@runtime/tg_files');
7. Command Router ishlatish
use shokirjonmk\telegram\CommandRouter; use shokirjonmk\telegram\TelegramComponent; use shokirjonmk\telegram\commands\StartCommand; $router = new CommandRouter(); // Closure bilan $router->register('/start', function($message, $tg) { $chatId = $message['chat']['id']; $tg->sendMessage($chatId, TelegramComponent::escapeMarkdownV2("Welcome, aka!")); }); // Class bilan $router->register('/start', [new StartCommand(), 'handle']); // Default command $router->register('/default', function($message, $tg) { $tg->sendMessage($message['chat']['id'], "Type /start or /help"); }); // Callback query $router->register('stats', function($callback, $tg) { $chatId = $callback['message']['chat']['id']; $messageId = $callback['message']['message_id']; $tg->editMessageText($chatId, $messageId, "📊 Statistika:"); $tg->answerCallbackQuery($callback['id'], "Statistika ko'rsatildi"); });
8. Update Handler Middleware bilan to'liq webhook
use shokirjonmk\telegram\CommandRouter; use shokirjonmk\telegram\UpdateHandlerMiddleware; use shokirjonmk\telegram\RateLimiter; use shokirjonmk\telegram\TelegramComponent; public function actionWebhook() { $body = file_get_contents('php://input'); $update = json_decode($body, true); if (!$update) { return 'ok'; } $botName = Yii::$app->request->get('bot', 'student'); $manager = Yii::$app->telegramManager; $component = $manager->get($botName); // Command Router $router = new CommandRouter(); $router->register('/start', function($msg, $tg) { $tg->sendMessage($msg['chat']['id'], TelegramComponent::escapeMarkdownV2("Welcome, aka!")); }); $router->register('/default', function($msg, $tg) { $tg->sendMessage($msg['chat']['id'], "Unknown command"); }); // Rate Limiter (6 requests per second per user) $rateLimiter = new RateLimiter(6, 1); // Middleware $handler = new UpdateHandlerMiddleware($router, $rateLimiter); $handler->handle($update, $component); return 'ok'; }
📚 API Metodlari
TelegramComponent
Xabar metodlari
sendMessage($chatId, $text, $options = [])- Xabar yuborisheditMessageText($chatId, $messageId, $text, $options = [])- Xabarni o'zgartirisheditMessageReplyMarkup($chatId, $messageId, $keyboard = null)- Xabar keyboardini o'zgartirishdeleteMessage($chatId, $messageId)- Xabarni o'chirishforwardMessage($chatId, $fromChatId, $messageId, $options = [])- Xabarni forward qilish
Media metodlari
sendPhoto($chatId, $photo, $caption = null, $keyboard = null)- Rasm yuborishsendDocument($chatId, $document, $caption = null, $keyboard = null, $options = [])- Hujjat yuborishsendVideo($chatId, $video, $caption = null, $keyboard = null, $options = [])- Video yuborishsendLocation($chatId, $latitude, $longitude, $keyboard = null, $options = [])- Lokatsiya yuborish
Callback va Actions
answerCallbackQuery($callbackQueryId, $text = null, $showAlert = false)- Callback javob berishsendChatAction($chatId, $action = 'typing')- Chat action yuborish (typing, upload_photo, record_voice, etc.)
Webhook va Updates
setWebhook($url, $options = [])- Webhook o'rnatishdeleteWebhook($dropPendingUpdates = false)- Webhook o'chirishgetWebhookInfo()- Webhook ma'lumotlarini olishgetUpdates($offset = null, $limit = null, $timeout = null, $allowedUpdates = null)- Updates olish (polling)
Fayl va Bot ma'lumotlari
getFile($fileId)- Fayl ma'lumotlarini olishgetMe()- Bot ma'lumotlarini olish
Queue va Utility
enqueueSendMessage($chatId, $text, $options = [])- Queue orqali xabar yuborishescapeMarkdownV2($text)- MarkdownV2 uchun matnni escape qilishescape($text)- Alias for escapeMarkdownV2
TelegramManager
get($name = null)- Bot component olishgetBotNames()- Barcha bot nomlarini olishhas($name)- Bot mavjudligini tekshirish
Keyboard
Keyboard::inline($buttons)- Inline keyboard yaratishKeyboard::inlineButton($text, $callback)- Inline button yaratishKeyboard::reply($buttons, $resize = true)- Reply keyboard yaratish
FileHelper
FileHelper::downloadFile($component, $fileId, $saveDir)- Fayl yuklab olish
CommandRouter
register($name, $callable)- Command ro'yxatdan o'tkazishhandleUpdate($update, $component)- Update ni handle qilish
RateLimiter
allow($userId)- Rate limit tekshirish
🎛 Konfiguratsiya parametrlari
TelegramComponent
token- Bot tokenapiUrl- Telegram API URL (default:https://api.telegram.org/bot)timeout- Request timeout (default: 5)enableLogs- Logging yoqish/yoqmaslik (default: true)rateLimitPerSecond- Per-bot rate limit (default: 20)
RateLimiter
limit- Requests per window (default: 5)window- Time window in seconds (default: 1)
📝 Webhook Controller namunasi
controllers/TelegramController.php:
<?php namespace app\controllers; use Yii; use yii\web\Controller; use shokirjonmk\telegram\CommandRouter; use shokirjonmk\telegram\UpdateHandlerMiddleware; use shokirjonmk\telegram\RateLimiter; use shokirjonmk\telegram\TelegramComponent; class TelegramController extends Controller { public $enableCsrfValidation = false; public function actionWebhook() { $body = file_get_contents('php://input'); $update = json_decode($body, true); if (!$update) { Yii::error('Empty update', 'telegram-error'); return 'ok'; } $botName = Yii::$app->request->get('bot', 'student'); $manager = Yii::$app->telegramManager; $component = $manager->get($botName); try { $router = new CommandRouter(); $router->register('/start', function($msg, $tg) { $tg->sendMessage($msg['chat']['id'], TelegramComponent::escapeMarkdownV2("Welcome, aka!")); }); $router->register('/default', function($msg, $tg) { $tg->sendMessage($msg['chat']['id'], "Unknown command"); }); $rateLimiter = new RateLimiter(6, 1); $handler = new UpdateHandlerMiddleware($router, $rateLimiter); $handler->handle($update, $component); } catch (\Throwable $e) { Yii::error(['err' => $e->getMessage(), 'update' => $update], 'telegram-error'); } return 'ok'; } }
Webhook URL: https://your.domain/telegram/webhook?bot=student yoki ?bot=staff
🔧 Qo'shimcha xususiyatlar
- Retry mechanism: Exponential backoff bilan avtomatik retry (default: 3 attempts)
- Rate limiting: Ikki darajali - global per-bot va per-user
- Queue support: Background message sending
- Logging: Barcha xatolar
telegram-errorkategoriyasi bilan loglanadi - Backward compatibility: Eski
Telegramclass hali ham ishlaydi - Local polling support: Python telegram bot kabi lokalda ishlash uchun polling
🖥️ Lokalda ishlatish (Polling)
Python telegram bot kabi lokalda ishlatish uchun polling ishlatishingiz mumkin. Ikki usul bor:
1. Console Command (Tavsiya etiladi)
console/commands/TelegramPollingCommand.php faylini yarating (misol: examples/PollingCommand.php):
<?php namespace app\console\commands; use Yii; use yii\console\Controller; use shokirjonmk\telegram\CommandRouter; use shokirjonmk\telegram\UpdateHandlerMiddleware; use shokirjonmk\telegram\RateLimiter; use shokirjonmk\telegram\TelegramComponent; class TelegramPollingCommand extends Controller { public $bot = 'student'; public $timeout = 30; public function actionPolling() { $manager = Yii::$app->telegramManager; $component = $manager->get($this->bot); $router = new CommandRouter(); // Register your commands here $router->register('/start', function($msg, $tg) { $tg->sendMessage($msg['chat']['id'], "Welcome!"); }); $rateLimiter = new RateLimiter(6, 1); $handler = new UpdateHandlerMiddleware($router, $rateLimiter); $offset = 0; while (true) { $updates = $component->getUpdates($offset, 100, $this->timeout, null); if (!empty($updates['ok']) && !empty($updates['result'])) { foreach ($updates['result'] as $update) { $offset = $update['update_id'] + 1; $handler->handle($update, $component); } } } } }
Ishga tushirish:
php yii telegram-polling/polling --bot=student --timeout=30
2. Standalone Script
examples/polling.php faylini ishlatishingiz mumkin:
php examples/polling.php --bot=student --timeout=30
Polling vs Webhook
| Xususiyat | Polling (Lokal) | Webhook (Production) |
|---|---|---|
| Ishlash joyi | Lokal kompyuter | Server |
| Webhook kerakmi | ❌ Yo'q | ✅ Ha |
| Natijaviylik | Pastroq | Yuqori |
| Development | ✅ Qulay | ❌ Qiyin |
| Production | ❌ Tavsiya etilmaydi | ✅ Tavsiya etiladi |
Tavsiya:
- Development uchun: Polling ishlating (lokalda)
- Production uchun: Webhook ishlating (serverda)
📝 License
MIT
👤 Author
ShokirjonMK
shokirjonmk/telegram-bot 适用场景与选型建议
shokirjonmk/telegram-bot 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 3 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 11 月 18 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「queue」 「extension」 「bot」 「yii2」 「telegram」 「telegram-bot」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 shokirjonmk/telegram-bot 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 shokirjonmk/telegram-bot 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 shokirjonmk/telegram-bot 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Dialogflow php sdk
A custom URL rule class for Yii 2 which allows to create translated URL rules
PHP AMQP Binding Library
A Laravel package to monitor queue jobs.
The Yii2 extension uses jQuery jquery.carousel-1.1.min.js and makes image carousel from php array of structure defined.
Laravel 5.6 Monolog custom telegram channel
统计信息
- 总下载量: 3
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 9
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-11-18