Install the Package
composer require andrew-gos/telegram-bot
Configure Laravel Service Provider Create a service provider to initialize the bot:
// app/Providers/TelegramBotServiceProvider.php
namespace App\Providers;
use AndrewGos\TelegramBot\TelegramBot;
use Illuminate\Support\ServiceProvider;
class TelegramBotServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton(TelegramBot::class, function ($app) {
$bot = new TelegramBot(config('telegram.bot_token'));
$bot->addHandlerGroup(new \AndrewGos\TelegramBot\Handler\HandlerGroup());
return $bot;
});
}
}
Register it in config/app.php under providers.
Set Up Basic Configuration
Add to config/telegram.php:
return [
'bot_token' => env('TELEGRAM_BOT_TOKEN'),
'webhook_url' => env('TELEGRAM_WEBHOOK_URL'),
];
Create a Simple Command Handler
// app/Handlers/StartCommandHandler.php
namespace App\Handlers;
use AndrewGos\TelegramBot\Handler\CommandHandler;
use AndrewGos\TelegramBot\Types\Update;
use AndrewGos\TelegramBot\Types\Message;
class StartCommandHandler implements CommandHandler
{
public function handle(Update $update): void
{
$message = $update->getMessage();
if ($message && $message->getText() === '/start') {
$message->reply('Hello! I am your bot.');
}
}
}
Register the Handler
// In your service provider's boot method
public function boot()
{
$bot = $this->app->make(TelegramBot::class);
$bot->getHandlerGroup()->addCommandHandler('/start', new StartCommandHandler());
}
Run the Bot For polling:
php artisan telegram:bot
Or set up a webhook in routes/web.php:
Route::post('/telegram/webhook', function () {
$bot = app(TelegramBot::class);
$bot->processWebhookUpdate();
});
CommandHandler for /command messages.$bot->getHandlerGroup()->addCommandHandler('/help', new HelpCommandHandler());
MessageHandler for text/callback queries.$bot->getHandlerGroup()->addMessageHandler(new TextMessageHandler());
$bot->getMiddlewareStack()->add(new LoggingMiddleware());
$bot->getHandlerGroup()->addMiddleware('/start', new AuthMiddleware());
TelegramBot::run() in a Laravel command.TelegramBot constructor:
$bot = new TelegramBot(config('telegram.bot_token'), null, null, config('telegram.webhook_url'));
$bot->getHandlerGroup()->addUpdateHandler(new QueuedUpdateHandler());
// app/Jobs/ProcessTelegramUpdate.php
public function handle()
{
$bot = app(TelegramBot::class);
$bot->processUpdate($this->update);
}
Service Container Binding: Bind the bot to Laravel’s container for dependency injection:
$this->app->bind(TelegramBot::class, function ($app) {
return new TelegramBot(config('telegram.bot_token'));
});
Event Dispatching: Trigger Laravel events from handlers:
// In a handler
event(new TelegramMessageReceived($message));
Middleware Integration: Reuse Laravel middleware in bot middleware:
use Illuminate\Http\Middleware\ThrottleRequests;
$bot->getMiddlewareStack()->add(new class extends ThrottleRequests {
protected function handle($request, Closure $next)
{
// Custom logic
return $next($request);
}
});
Artisan Commands: Create a command to manage the bot:
// app/Console/Commands/RunTelegramBot.php
public function handle()
{
$bot = app(TelegramBot::class);
$bot->run();
}
Dynamic Handler Registration: Register handlers dynamically based on config:
foreach (config('telegram.handlers') as $command => $handler) {
$bot->getHandlerGroup()->addCommandHandler($command, new $handler());
}
Plugin System: Extend the bot with plugins:
// app/Plugins/AnalyticsPlugin.php
class AnalyticsPlugin
{
public function register(TelegramBot $bot)
{
$bot->getMiddlewareStack()->add(new AnalyticsMiddleware());
}
}
Testing: Mock the bot in tests:
$bot = Mockery::mock(TelegramBot::class);
$bot->shouldReceive('sendMessage')->once();
Strict Typing Quirks:
CommandHandler, MessageHandler).implements and IDE autocompletion to avoid runtime errors.Webhook Configuration:
env() and validate in the service provider:
if (!config('telegram.webhook_url')) {
throw new \RuntimeException('Webhook URL not configured.');
}
Middleware Order:
$bot->getMiddlewareStack()->prepend(new AuthMiddleware());
Update Processing Delays:
$bot->getHandlerGroup()->addUpdateHandler(new QueuedUpdateHandler());
Dependency Conflicts:
andrew-gos/serializer may conflict with Laravel’s symfony/serializer.replace:
"replace": {
"andrew-gos/serializer": "symfony/serializer"
}
Error Handling:
$bot->getMiddlewareStack()->add(new ErrorHandlingMiddleware());
Enable Debug Logging:
$bot->setLogger(new \Monolog\Logger('telegram', [
new \Monolog\Handler\StreamHandler(storage_path('logs/telegram.log'))
]));
Inspect Updates: Use a middleware to log raw updates:
$bot->getMiddlewareStack()->add(new class {
public function __invoke($update, Closure $next)
{
\Log::debug('Raw update:', $update->toArray());
return $next($update);
}
});
Test Locally:
Use ngrok to expose a local webhook for testing:
ngrok http 8000
Set the webhook URL to https://your-ngrok-url.ngrok.io/telegram/webhook.
Validate API Responses: Telegram’s API may return unexpected data. Use a middleware to validate responses:
$bot->getMiddlewareStack()->add(new class {
public function __invoke($response, Closure $next)
{
if (!$response->isOk()) {
throw new \RuntimeException('API error: ' . $response->getDescription());
}
return $next($response);
}
});
Checker to validate updates:
class AdminChecker implements Checker
{
public function check(Update $update):
How can I help you explore Laravel packages today?