Installation
composer require irazasyed/telegram-bot-sdk
Configure Bot Token
Add your bot token to .env:
TELEGRAM_BOT_TOKEN=your_bot_token_here
Basic Webhook Setup
In routes/web.php:
use Telegram\Bot\Api;
use Telegram\Bot\Laravel\Telegram;
Telegram::route(function (Api $telegram) {
$telegram->commands(['start', 'help'], function ($message) {
$telegram->sendMessage([
'chat_id' => $message->getChat()->getId(),
'text' => 'Welcome to my bot!'
]);
});
});
Verify Webhook Run:
php artisan telegram:webhook-setup
/start CommandTelegram::route(function (Api $telegram) {
$telegram->onCommand('start', function ($message) {
$telegram->replyToChatId($message->getChat()->getId(), 'Hello!');
});
});
Pattern: Use onCommand() for structured interactions.
Telegram::route(function (Api $telegram) {
$telegram->commands(['start', 'help'], function ($message) {
$telegram->sendMessage([
'chat_id' => $message->getChat()->getId(),
'text' => 'Available commands: /start, /help'
]);
});
});
Pattern: Validate users via middleware.
Telegram::route(function (Api $telegram) {
$telegram->middleware(function ($update) {
$chat = $update->getMessage()->getChat();
if ($chat->getType() !== 'private') {
return false; // Ignore non-private chats
}
return true;
});
$telegram->onCommand('secret', function ($message) {
$telegram->sendMessage([
'chat_id' => $message->getChat()->getId(),
'text' => 'Access granted!'
]);
});
});
Pattern: Inject Laravel services into bot logic.
Telegram::route(function (Api $telegram) {
$telegram->onText(/\/user (\d+)/, function ($message, $userId) {
$user = app(\App\Models\User::class)->find($userId);
$telegram->sendMessage([
'chat_id' => $message->getChat()->getId(),
'text' => "User: {$user->name}"
]);
});
});
Pattern: Offload processing to queues for scalability.
Telegram::route(function (Api $telegram) {
$telegram->onText(/\/process/, function ($message) {
dispatch(new ProcessUpdateJob($message));
});
});
telegram:webhook-setup with --force-https if testing locally.update_id and message_id to avoid replay attacks.config/telegram-bot-sdk.php:
'debug' => env('TELEGRAM_DEBUG', false),
try {
$telegram->sendMessage($params);
} catch (\Telegram\Bot\Exceptions\TelegramException $e) {
if ($e->getCode() === 429) {
sleep(1); // Retry after 1 second
$telegram->sendMessage($params);
}
}
Telegram\Bot\Api to handle custom update types:
$telegram->on('my_custom_update', function ($update) {
// Handle custom logic
});
$telegram->middleware([AuthMiddleware::class, LogMiddleware::class]);
.env and config/telegram-bot-sdk.php.config/telegram-bot-sdk.php to avoid timestamp issues:
'timezone' => 'UTC',
config/telegram-bot-sdk.php:
'log_updates' => true,
$update->rawContent for debugging complex cases.Telegram\Bot\Api::sendMessage() with disable_notification for bulk messages.How can I help you explore Laravel packages today?