Install the Package
composer require baks-dev/telegram-bot
Pin the version in composer.json for stability:
"baks-dev/telegram-bot": "7.4.5"
Publish Configuration
Add Telegram bot credentials to .env:
TELEGRAM_BOT_TOKEN=your_bot_token_here
TELEGRAM_WEBHOOK_URL=https://your-app.com/telegram-webhook
Publish the package’s config (if supported) or manually add to config/services.php:
'telegram-bot' => [
'token' => env('TELEGRAM_BOT_TOKEN'),
'webhook_url' => env('TELEGRAM_WEBHOOK_URL'),
'polling_interval' => 60, // seconds
],
Set Up Database Run migrations to create bot-related tables:
php artisan doctrine:migrations:diff
php artisan doctrine:migrations:migrate
Verify no schema conflicts with existing Laravel models.
Install Assets (if applicable)
php artisan baks:assets:install
Register Service Provider
Add to config/app.php (if not auto-discovered):
BaksDev\TelegramBot\TelegramBotServiceProvider::class,
Define Webhook Route
In routes/web.php:
Route::post('/telegram-webhook', [\BaksDev\TelegramBot\Http\Controllers\TelegramBotController::class, 'handleWebhook']);
Set Telegram Webhook Use the Telegram Bot API:
curl "https://api.telegram.org/bot<TOKEN>/setWebhook?url=<WEBHOOK_URL>"
Test the Bot
Send a test message to your bot (e.g., /start). Check Laravel logs for incoming webhook payloads:
tail -f storage/logs/laravel.log
Extend the package’s command system to handle /hello:
Create a Command Handler
// app/TelegramBot/Commands/HelloCommand.php
namespace App\TelegramBot\Commands;
use BaksDev\TelegramBot\Contracts\CommandInterface;
class HelloCommand implements CommandInterface
{
public function handle(array $payload): string
{
return "Hello, {$payload['from']['first_name']}! 👋";
}
}
Register the Command
Bind the command in a service provider (e.g., AppServiceProvider):
public function register()
{
$this->app->bind(\BaksDev\TelegramBot\Contracts\CommandInterface::class, function ($app) {
return new \App\TelegramBot\Commands\HelloCommand();
});
}
Map the Command Configure the command in the package’s config (or extend the config):
'commands' => [
'hello' => \App\TelegramBot\Commands\HelloCommand::class,
],
Test
Send /hello to your bot. The response should trigger your handler.
handleWebhook method parses incoming payloads and routes them to command handlers.TelegramBotController to customize webhook logic:
// app/Http/Controllers/TelegramBotController.php
namespace App\Http\Controllers;
use BaksDev\TelegramBot\Http\Controllers\TelegramBotController as BaseController;
class TelegramBotController extends BaseController
{
public function handleWebhook(array $payload)
{
// Pre-process payload (e.g., logging, auth)
logger()->info('Telegram payload', $payload);
// Call parent handler
parent::handleWebhook($payload);
}
}
config/services.php:
'telegram-bot' => [
'use_polling' => true,
'polling_interval' => 60, // seconds
],
php artisan telegram-bot:poll
CommandInterface for each command:
class FeedbackCommand implements CommandInterface
{
public function handle(array $payload): string
{
$feedback = $payload['text'] ?? 'No feedback provided';
// Save to database or process
\App\Models\Feedback::create([
'user_id' => $payload['from']['id'],
'message' => $feedback,
]);
return "Thanks for your feedback! 🎉";
}
}
'commands' => [
'feedback' => \App\TelegramBot\Commands\FeedbackCommand::class,
],
/feedback followed by their message.use BaksDev\TelegramBot\TelegramBot;
class MenuCommand implements CommandInterface
{
public function handle(array $payload, TelegramBot $bot): string
{
$keyboard = [
'inline_keyboard' => [
[
['text' => 'Option 1', 'callback_data' => 'opt1'],
['text' => 'Option 2', 'callback_data' => 'opt2'],
],
],
];
$bot->sendMessage([
'chat_id' => $payload['message']['chat']['id'],
'text' => 'Choose an option:',
'reply_markup' => json_encode($keyboard),
]);
return '';
}
}
CallbackQueryHandler:
class CallbackQueryHandler
{
public function handle(array $payload, TelegramBot $bot)
{
$data = $payload['data'];
if ($data === 'opt1') {
$bot->answerCallbackQuery([
'callback_query_id' => $payload['id'],
'text' => 'You selected Option 1!',
]);
}
}
}
// app/TelegramBot/Middleware/ValidateUser.php
namespace App\TelegramBot\Middleware;
use Closure;
class ValidateUser
{
public function handle(array $payload, Closure $next)
{
$userId = $payload['message']['from']['id'];
if (!\App\Models\User::where('telegram_id', $userId)->exists()) {
return "Access denied. Please register first.";
}
return $next($payload);
}
}
'middleware' => [
\App\TelegramBot\Middleware\ValidateUser::class,
],
telegram_users, telegram_messages).// app/Repositories/TelegramUserRepository.php
namespace App\Repositories;
use BaksDev\TelegramBot\Entity\TelegramUser;
use Doctrine\ORM\EntityManagerInterface;
class TelegramUserRepository
{
public function __construct(private EntityManagerInterface $em)
{}
public function findOrCreate(array $telegramUserData): TelegramUser
{
$user = $this->em->getRepository(TelegramUser::class)
->findOneBy(['telegram_id' => $telegramUserData['id']]);
if (!$user) {
$user = new TelegramUser();
$user->setTelegramId($telegramUserData['id']);
$user->setFirstName($telegramUserData['first_name'] ?? '');
$this->em->persist($user);
$this->em->flush
How can I help you explore Laravel packages today?