PHP code example of shokirjonmk / telegram-bot
1. Go to this page and download the library: Download shokirjonmk/telegram-bot library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
shokirjonmk / telegram-bot example snippets
'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,
],
]
use shokirjonmk\telegram\Telegram;
Yii::$app->telegram->sendMessage(
$chatId,
Telegram::escape("Salom, aka!")
);
// 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");
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,
]);
$tg = Yii::$app->telegramManager->get('student');
$tg->enqueueSendMessage(
$chatId,
TelegramComponent::escapeMarkdownV2("Background xabar!")
);
$tg = Yii::$app->telegramManager->get('student');
$tg->sendChatAction($chatId, 'typing'); // typing, upload_photo, record_voice, etc.
use shokirjonmk\telegram\FileHelper;
$tg = Yii::$app->telegramManager->get('student');
$localPath = FileHelper::downloadFile($tg, $fileId, '@runtime/tg_files');
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");
});
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';
}
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';
}
}
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);
}
}
}
}
}
bash
php yii queue/listen
# yoki
php yii queue/run
bash
# Console command orqali
php yii telegram-polling/polling --bot=student --timeout=30
# Yoki standalone script
php examples/polling.php --bot=student --timeout=30
bash
php yii telegram-polling/polling --bot=student --timeout=30
bash
php examples/polling.php --bot=student --timeout=30