composer require baks-dev/telegram-support
php artisan baks:assets:install
php artisan migrate
.env with your Telegram Bot API token and webhook URL:
TELEGRAM_BOT_TOKEN=your_bot_token_here
TELEGRAM_WEBHOOK_URL=https://yourdomain.com/telegram-webhook
Create a simple command handler in app/Telegram/Commands/ (e.g., GreetingCommand.php):
<?php
namespace App\Telegram\Commands;
use BaksDev\TelegramSupport\Contracts\CommandInterface;
class GreetingCommand implements CommandInterface
{
public function handle(string $message, int $chatId): string
{
return "Hello, user! Your chat ID is: {$chatId}";
}
public function getCommand(): string
{
return '/greet';
}
}
Register the command in config/telegram-support.php under commands.
Trigger the bot via Telegram and verify the response. Check Laravel logs for errors:
tail -f storage/logs/laravel.log
CommandInterface for each bot command. Example:
class HelpCommand implements CommandInterface {
public function handle(string $message, int $chatId): string {
return "Available commands: /greet, /help";
}
public function getCommand(): string { return '/help'; }
}
commands array in config/telegram-support.php:
'commands' => [
\App\Telegram\Commands\GreetingCommand::class,
\App\Telegram\Commands\HelpCommand::class,
],
fallback key in config to define a default response:
'fallback' => \App\Telegram\Commands\FallbackCommand::class,
Extend the bot’s request pipeline by creating middleware:
namespace App\Telegram\Middleware;
use BaksDev\TelegramSupport\Contracts\MiddlewareInterface;
class LogMiddleware implements MiddlewareInterface
{
public function handle(array $payload, callable $next): array
{
\Log::info('Telegram payload:', $payload);
return $next($payload);
}
}
Register middleware in config/telegram-support.php:
'middleware' => [
\App\Telegram\Middleware\LogMiddleware::class,
],
Leverage the built-in TelegramMessage model for persistence:
use BaksDev\TelegramSupport\Models\TelegramMessage;
// Store a message
TelegramMessage::create([
'chat_id' => $chatId,
'message' => $message,
'command' => '/greet',
]);
// Retrieve messages
$messages = TelegramMessage::where('chat_id', $chatId)->latest()->take(10)->get();
validateUpdate middleware to ensure requests are from Telegram.config/telegram-support.php).Use Laravel’s scheduler to run periodic tasks (e.g., sending reminders):
// app/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
$schedule->command('telegram:send-reminders')->dailyAt('9:00');
}
Webhook Not Reachable:
ngrok:
ngrok http 80
Then set the webhook URL to https://your-ngrok-url.ngrok.io/telegram-webhook.Command Not Triggering:
config/telegram-support.php.getCommand() method (case-sensitive).@your_bot_name).Database Migrations:
php artisan migrate after publishing assets. Skipping this will cause TelegramMessage model errors.php artisan migrate --force to apply schema changes.Timezone Issues:
$localTime = (new \DateTime())->setTimestamp($payload['date'])->format('Y-m-d H:i:s');
Rate Limits:
sleep() or queue delayed jobs for bulk operations.Log Payloads:
Enable debug mode in config/telegram-support.php:
'debug' => env('APP_DEBUG', false),
This logs raw Telegram updates to storage/logs/telegram.log.
Test Locally:
Use the telegram:test artisan command to simulate updates:
php artisan telegram:test --message="Hello" --chat-id=12345
Check Webhook Status: Use Telegram’s getWebhookInfo method to verify the webhook is active:
curl "https://api.telegram.org/bot{TOKEN}/getWebhookInfo"
Custom Models:
Extend the TelegramMessage model to add fields (e.g., user_data):
php artisan make:model TelegramMessageExtension --extends=BaksDev\TelegramSupport\Models\TelegramMessage
Update the migration and model as needed.
Custom Responses:
Return objects implementing BaksDev\TelegramSupport\Contracts\ResponseInterface for complex responses (e.g., inline keyboards):
use BaksDev\TelegramSupport\Responses\InlineKeyboardResponse;
public function handle(string $message, int $chatId): ResponseInterface
{
return new InlineKeyboardResponse(
"Choose an option",
[
['text' => 'Option 1', 'callback_data' => 'opt1'],
['text' => 'Option 2', 'callback_data' => 'opt2'],
]
);
}
Event Listeners: Listen to Telegram events (e.g., new messages) via Laravel’s event system:
// app/Providers/EventServiceProvider.php
protected $listen = [
\BaksDev\TelegramSupport\Events\MessageReceived::class => [
\App\Listeners\LogTelegramMessage::class,
],
];
Queue Jobs: Offload heavy processing to queues:
use Illuminate\Support\Facades\Bus;
public function handle(string $message, int $chatId): string
{
Bus::dispatch(new ProcessMessageJob($message, $chatId));
return "Your request is being processed!";
}
Bot Token:
The token in .env must match the one set in @BotFather. A mismatch will cause the webhook to fail silently.
Update Validation:
Disable validate_update in config only for testing (not production):
'validate_update' => env('APP_ENV') !== 'local',
Default Response:
If no command matches, the bot sends nothing unless a fallback command is defined.
Caching: Cache frequent responses (e.g., help messages) to reduce database load:
$response = Cache::remember("telegram_help_{$chatId}", now()->addHours(1), function() {
return "Help text...";
});
Batch Processing: Use chunking for large data operations:
TelegramMessage::where('processed', false)->chunk(100, function ($messages) {
foreach ($messages as $message) {
// Process each message
$message->update(['processed' => true]);
}
});
How can I help you explore Laravel packages today?