aymericcucherousset/telegram-bot
A simple PHP Telegram Bot library for sending messages, handling updates, and interacting with Telegram’s Bot API. Includes helpers for requests, webhooks/long polling, keyboards, and common methods to build bots quickly and cleanly.
Installation
composer require aymericcucherousset/telegram-bot
Add the service provider to config/app.php:
'providers' => [
// ...
AymericCucherousset\TelegramBot\TelegramBotServiceProvider::class,
],
Configuration Publish the config file:
php artisan vendor:publish --provider="AymericCucherousset\TelegramBot\TelegramBotServiceProvider"
Update config/telegram-bot.php with your bot token and webhook URL:
'token' => env('TELEGRAM_BOT_TOKEN'),
'webhook_url' => env('APP_URL') . '/telegram/webhook',
First Use Case: Basic Command Handling Define a command in a controller or service:
use AymericCucherousset\TelegramBot\TelegramBot;
class TelegramController extends Controller
{
public function handleCommand(TelegramBot $bot)
{
$bot->onCommand('start', function ($bot, $update) {
$bot->sendMessage($update->getChat()->getId(), 'Welcome!');
});
}
}
Register the route in routes/web.php:
Route::post('/telegram/webhook', [TelegramController::class, 'handleCommand']);
Command-Based Interactions
Use onCommand() to handle /start, /help, or custom commands:
$bot->onCommand('custom', function ($bot, $update) {
$bot->sendMessage($update->chat->id, 'Custom command triggered!');
});
Message Handling
Listen for all messages (text, media, etc.) with onMessage():
$bot->onMessage(function ($bot, $update) {
$bot->sendMessage($update->message->chat->id, "You said: " . $update->message->text);
});
Inline Keyboards Create interactive buttons:
$keyboard = [
['Yes', 'No'],
];
$replyMarkup = $bot->replyKeyboardMarkup($keyboard, ['resize_keyboard' => true]);
$bot->sendMessage($chatId, 'Choose:', $replyMarkup);
Middleware for Authentication Use middleware to validate users before processing:
$bot->onCommand('secure', function ($bot, $update) use ($middleware) {
$middleware->authenticate($update->message->chat->id);
$bot->sendMessage($update->chat->id, 'Access granted!');
});
Modular Design Split logic into services:
// TelegramService.php
class TelegramService {
public function __construct(private TelegramBot $bot) {}
public function handleOrderUpdate($chatId, $orderData) {
$this->bot->sendMessage($chatId, "Order updated: " . $orderData);
}
}
event(new OrderUpdated($orderData));
TelegramJob::dispatch($bot, $chatId, $data)->onQueue('telegram');
\Log::info('Telegram interaction', ['chat_id' => $update->chat->id, 'text' => $update->message->text]);
Webhook SSL Requirements Telegram requires HTTPS for webhooks. Use a reverse proxy (e.g., Nginx) or a service like ngrok for local testing:
ngrok http 8000
Update webhook_url to https://your-ngrok-url.ngrok.io/telegram/webhook.
Rate Limits
Avoid flooding Telegram’s API. Use delay() between messages:
$bot->sendMessage($chatId, 'Message 1');
sleep(1); // Respect rate limits
$bot->sendMessage($chatId, 'Message 2');
Update Handling Always validate updates to prevent malicious requests:
if (!$update->validate()) {
abort(403, 'Invalid update');
}
Session Management Store user sessions in the database or cache to persist state:
$user = User::firstOrCreate(['telegram_id' => $update->message->chat->id]);
Enable Debug Mode
Set debug to true in config/telegram-bot.php to log raw updates:
'debug' => env('APP_DEBUG', false),
Update Dumping Log raw updates for inspection:
\Log::debug('Raw update:', $update->toArray());
Custom Update Types
Extend the Update class to handle custom payloads:
class CustomUpdate extends \AymericCucherousset\TelegramBot\Update {
public function getCustomData() { ... }
}
Middleware Create middleware for cross-cutting concerns (e.g., logging, auth):
$bot->onMessage(function ($bot, $update) {
$bot->middleware->run($update);
// ...
});
Database Models Attach Telegram data to Eloquent models:
class User extends Model {
public function telegramUpdates() {
return $this->hasMany(TelegramUpdate::class);
}
}
Testing Use mocks for unit tests:
$bot = Mockery::mock(TelegramBot::class);
$bot->shouldReceive('sendMessage')->once();
How can I help you explore Laravel packages today?