Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Telegram Bot Laravel Package

baks-dev/telegram-bot

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Install the Package

    composer require baks-dev/telegram-bot
    

    Pin the version in composer.json for stability:

    "baks-dev/telegram-bot": "7.4.5"
    
  2. 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
    ],
    
  3. 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.

  4. Install Assets (if applicable)

    php artisan baks:assets:install
    
  5. Register Service Provider Add to config/app.php (if not auto-discovered):

    BaksDev\TelegramBot\TelegramBotServiceProvider::class,
    
  6. Define Webhook Route In routes/web.php:

    Route::post('/telegram-webhook', [\BaksDev\TelegramBot\Http\Controllers\TelegramBotController::class, 'handleWebhook']);
    
  7. Set Telegram Webhook Use the Telegram Bot API:

    curl "https://api.telegram.org/bot<TOKEN>/setWebhook?url=<WEBHOOK_URL>"
    
  8. 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
    

First Use Case: Basic Command Handler

Extend the package’s command system to handle /hello:

  1. 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']}! 👋";
        }
    }
    
  2. 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();
        });
    }
    
  3. Map the Command Configure the command in the package’s config (or extend the config):

    'commands' => [
        'hello' => \App\TelegramBot\Commands\HelloCommand::class,
    ],
    
  4. Test Send /hello to your bot. The response should trigger your handler.


Implementation Patterns

Core Workflows

1. Webhook-Driven Bot

  • Pattern: Use Telegram’s webhooks for real-time updates.
  • Implementation:
    • The package’s handleWebhook method parses incoming payloads and routes them to command handlers.
    • Extend 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);
          }
      }
      

2. Polling-Based Bot

  • Pattern: Use long polling for environments where webhooks aren’t feasible (e.g., local dev).
  • Implementation:
    • Configure polling in config/services.php:
      'telegram-bot' => [
          'use_polling' => true,
          'polling_interval' => 60, // seconds
      ],
      
    • Run the polling command manually or via a cron job:
      php artisan telegram-bot:poll
      

3. Command-Response Cycle

  • Pattern: Map Telegram commands to Laravel logic.
  • Implementation:
    • Define Commands: Implement 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! 🎉";
          }
      }
      
    • Register Commands: Bind commands in a service provider or config:
      'commands' => [
          'feedback' => \App\TelegramBot\Commands\FeedbackCommand::class,
      ],
      
    • Trigger Commands: Users send /feedback followed by their message.

4. Inline Keyboards

  • Pattern: Create interactive menus using Telegram’s inline keyboards.
  • Implementation:
    • Use the package’s keyboard builder (if available) or manually construct keyboards:
      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 '';
          }
      }
      
    • Handle callback queries in a 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!',
                  ]);
              }
          }
      }
      

5. Middleware for Auth/Validation

  • Pattern: Filter or modify payloads before processing.
  • Implementation:
    • Create middleware to validate users or sanitize input:
      // 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);
          }
      }
      
    • Register middleware in the package’s config or service provider:
      'middleware' => [
          \App\TelegramBot\Middleware\ValidateUser::class,
      ],
      

6. Database Integration

  • Pattern: Store bot interactions or user data.
  • Implementation:
    • Use the package’s migrations to create tables (e.g., telegram_users, telegram_messages).
    • Extend models or create custom repositories:
      // 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
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php