telegram-bot/api
Native PHP wrapper for the Telegram Bot API with no extra requirements. Supports all API methods and response types, including sending messages, documents, reply/inline keyboards, and media groups. Install via Composer and start building bots quickly.
Installation:
composer require telegram-bot/api
Add to composer.json if using Laravel:
"require": {
"telegram-bot/api": "^3.0"
}
Basic Bot Initialization:
use TelegramBot\Api\BotApi;
$bot = new BotApi(config('services.telegram.bot_token'));
First Use Case: Send a message in a Laravel controller:
public function sendWelcomeMessage(Request $request)
{
$chatId = $request->input('chat_id');
$bot->sendMessage($chatId, 'Welcome to our service!');
}
BotApi and Client classes for core functionality.// In a Laravel service provider or controller
$bot->command('start', function ($message) use ($bot) {
$chatId = $message->getChat()->getId();
$bot->sendMessage($chatId, "Hello! Use /help for options.");
});
// Handle all text messages
$bot->on(function ($update) use ($bot) {
$message = $update->getMessage();
if ($message) {
$bot->sendMessage(
$message->getChat()->getId(),
"You said: " . $message->getText()
);
}
}, function () {
return true; // Always run
});
// Handle document uploads
$bot->on(function ($update) use ($bot) {
$document = $update->getMessage()->getDocument();
if ($document) {
$file = $bot->getFile($document->getFileId());
$bot->sendMessage(
$update->getMessage()->getChat()->getId(),
"Received file: " . $file->getFilePath()
);
}
});
// Inline keyboard for buttons
$keyboard = new \TelegramBot\Api\Types\Inline\InlineKeyboardMarkup([
[
['text' => 'Option 1', 'callback_data' => 'opt1'],
['text' => 'Option 2', 'callback_data' => 'opt2'],
]
]);
$bot->sendMessage($chatId, "Choose:", null, false, null, $keyboard);
// Handle callback queries
$bot->onCallbackQuery(function ($callbackQuery) use ($bot) {
$data = $callbackQuery->getData();
$bot->answerCallbackQuery($callbackQuery->getId(), "You selected: $data");
});
// In AppServiceProvider@boot()
$this->app->singleton('telegram.bot', function ($app) {
return new \TelegramBot\Api\BotApi(config('services.telegram.bot_token'));
});
// Usage in controllers
public function __construct(private BotApi $bot) {}
// routes/web.php
Route::post('/telegram/webhook', function (Request $request) {
$update = \TelegramBot\Api\Types\Update::fromArray($request->all());
$bot = app('telegram.bot');
// Process update (e.g., dispatch Laravel events)
event(new TelegramUpdateReceived($update));
return response()->json(['status': 'ok']);
});
use TelegramBot\Api\Exception\HttpException;
try {
$bot->sendMessage($chatId, $text);
} catch (HttpException $e) {
if ($e->getCode() === 429) { // Rate limited
sleep($e->getRetryAfter());
$bot->sendMessage($chatId, $text);
}
}
use Symfony\Component\HttpClient\HttpClient;
use TelegramBot\Api\Http\SymfonyHttpClient;
$client = HttpClient::create();
$bot = new \TelegramBot\Api\BotApi(
config('services.telegram.bot_token'),
null,
new SymfonyHttpClient($client)
);
// For testing without hitting Telegram's servers
$bot = new \TelegramBot\Api\Client(
'token',
null,
null,
'http://localhost:8081'
);
Chat ID Types:
"12345678").-100123456789).Bad Request errors.Webhook SSL:
ngrok for local testing.Rate Limits:
429 Too Many Requests with retries.File Handling:
sendDocument must be CURLFile objects or URLs.open_basedir restrictions).Deprecated Methods:
thumb* methods (use thumbnail* instead).banChatMember over deprecated kickChatMember.Enable Logging:
$bot = new \TelegramBot\Api\BotApi('token', null, null, null, [
'logger' => function ($level, $message) {
\Log::channel('telegram')->$level($message);
}
]);
Inspect Updates:
$bot->on(function ($update) {
\Log::debug('Raw update:', $update->toArray());
});
Validate Webhook URL:
/setwebhook https://yourdomain.com/telegram/webhook?secret=SECRET
Custom Update Handlers:
// Dispatch Laravel events
$bot->on(function ($update) {
event(new TelegramUpdateReceived($update));
});
Middleware for Requests:
$bot = new \TelegramBot\Api\BotApi('token', null, null, null, [
'http' => [
'headers' => [
'User-Agent' => 'LaravelBot/1.0',
],
],
]);
Proxy Support:
$bot = new \TelegramBot\Api\BotApi('token', null, null, null, [
'proxy' => 'http://proxy.example.com:8080',
]);
Third-Party HTTP Clients:
SymfonyHttpClient or GuzzleHttpClient for advanced features (e.g., async requests).Configuration:
Add to config/services.php:
'telegram' => [
'bot_token' => env('TELEGRAM_BOT_TOKEN'),
'webhook_secret' => env('TELEGRAM_WEBHOOK_SECRET'),
],
Environment Variables:
TELEGRAM_BOT_TOKEN=your_token_here
TELEGRAM_WEBHOOK_URL=https://yourdomain.com/telegram/webhook
Artisan Commands:
// Example: Send a test message via CLI
$bot = app('telegram.bot');
$bot->sendMessage(env('TEST_CHAT_ID'), 'Bot is running!');
Testing:
TelegramBot\Api\Client with a local server for unit tests.BotApi in PHPUnit:
$mockBot = Mockery::mock(\TelegramBot\Api\BotApi::class);
$mockBot->shouldReceive('sendMessage')->once();
How can I help you explore Laravel packages today?