composer require baks-dev/telegram
php artisan vendor:publish --provider="BaksDev\Telegram\TelegramServiceProvider" --tag="telegram-config"
config/telegram.php (default: BOT_TOKEN and WEBHOOK_URL).use BaksDev\Telegram\Telegram;
$telegram = app(Telegram::class);
$response = $telegram->sendMessage([
'chat_id' => -100123456789,
'text' => 'Hello from Laravel!',
]);
config/telegram.php: Bot token, webhook settings, and API defaults.app/Providers/TelegramServiceProvider.php: Service binding and boot logic.src/Telegram.php: Core API client methods.$telegram->sendMessage([
'chat_id' => $userChatId,
'text' => 'Your order #123 is processing.',
'parse_mode' => 'HTML', // Optional
]);
$telegram->sendPhoto([
'chat_id' => $chatId,
'photo' => 'https://example.com/image.jpg',
'caption' => 'Check this out!',
]);
$telegram->setWebhook([
'url' => route('telegram.webhook'),
'max_connections' => 40,
]);
Route::post('/telegram/webhook', function (Request $request) {
$update = $request->json()->all();
$telegram = app(Telegram::class);
$telegram->handleUpdate($update); // Built-in handler
// OR custom logic:
// if ($update['message']['text'] === '/start') { ... }
});
$telegram->setMyCommands([
['command' => 'start', 'description' => 'Start the bot'],
['command' => 'help', 'description' => 'Get help'],
]);
$keyboard = [
['text' => 'Option 1', 'callback_data' => 'opt1'],
['text' => 'Option 2', 'callback_data' => 'opt2'],
];
$telegram->sendMessage([
'chat_id' => $chatId,
'text' => 'Choose:',
'reply_markup' => json_encode(['inline_keyboard' => $keyboard]),
]);
$telegram->getUpdates(['offset' => -1, 'limit' => 10]);
$this->app->bind(Telegram::class, function ($app) {
return new Telegram(config('telegram.bot_token'), [
'timeout' => 10,
'proxy' => env('TELEGRAM_PROXY'),
]);
});
public function handle(Request $request, Closure $next) {
$update = $request->json()->all();
if (!$this->validateTelegramUpdate($update)) {
abort(403);
}
return $next($request);
}
event(new TelegramUpdateReceived($update));
EventServiceProvider:
protected $listen = [
TelegramUpdateReceived::class => [
HandleTelegramStartCommand::class,
],
];
Webhook SSL Requirements
ngrok locally or configure your server:
$telegram->setWebhook(['url' => 'https://yourdomain.com/webhook']);
curl:
curl -X POST https://api.telegram.org/bot<TOKEN>/setWebhook?url=https://yourdomain.com/webhook
Rate Limits
try {
$telegram->sendMessage(...);
} catch (RateLimitException $e) {
sleep($e->getRetryAfter());
retry();
}
Chat ID Handling
-100 prefix (e.g., -100123456789).chat_id is positive (e.g., 123456789).chat_id to verify:
\Log::debug('Chat ID:', [$update['message']['chat']['id']]);
File Uploads
sendDocument or sendPhoto with local paths:
$telegram->sendDocument([
'chat_id' => $chatId,
'document' => fopen('path/to/file.pdf', 'r'),
]);
Locale/Encoding
parse_mode => 'HTML' for rich text (e.g., <b>bold</b>).Enable API Debugging
$telegram->setDebug(true); // In config or constructor
telegram.* entries.Update Validation
if (!isset($update['update_id'])) {
throw new \InvalidArgumentException('Invalid Telegram update format');
}
Token Security
.env:
TELEGRAM_BOT_TOKEN=your_token_here
Testing
@test accounts to avoid spamming real users.$mock = Mockery::mock(Telegram::class);
$mock->shouldReceive('sendMessage')->once()->andReturn(['ok' => true]);
$this->app->instance(Telegram::class, $mock);
Custom API Methods
Telegram.php:
public function pinChatMessage($chatId, $messageId) {
return $this->request('pinChatMessage', [
'chat_id' => $chatId,
'message_id' => $messageId,
]);
}
Middleware for Updates
$telegram->onUpdate(function ($update) {
if ($update['message']['text'] === '/admin') {
return false; // Skip
}
return true; // Proceed
});
Database Integration
$chat = Chat::firstOrCreate(['telegram_id' => $update['message']['chat']['id']]);
$chat->update(['last_active' => now()]);
Queue Delayed Tasks
TelegramJob::dispatch($telegram, $chatId, 'Delayed message')
->delay(now()->addMinutes(5));
How can I help you explore Laravel packages today?