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 Support Laravel Package

baks-dev/telegram-support

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require baks-dev/telegram-support
    
  2. Publish assets and config (if not auto-published):
    php artisan baks:assets:install
    
  3. Run migrations to set up the required database tables:
    php artisan migrate
    
  4. Configure .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
    

First Use Case: Basic Bot Response

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.

First Webhook Test

Trigger the bot via Telegram and verify the response. Check Laravel logs for errors:

tail -f storage/logs/laravel.log

Implementation Patterns

Command-Handler Workflow

  1. Define Commands: Implement 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'; }
    }
    
  2. Register Commands: Add commands to the commands array in config/telegram-support.php:
    'commands' => [
        \App\Telegram\Commands\GreetingCommand::class,
        \App\Telegram\Commands\HelpCommand::class,
    ],
    
  3. Handle Unknown Commands: Use the fallback key in config to define a default response:
    'fallback' => \App\Telegram\Commands\FallbackCommand::class,
    

Middleware Integration

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,
],

Database Integration

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();

Webhook Security

  • Validate Updates: Use the validateUpdate middleware to ensure requests are from Telegram.
  • HTTPS: Always use HTTPS for webhook URLs to avoid security warnings.
  • IP Whitelisting: Restrict webhook access to Telegram’s IP ranges (configurable in config/telegram-support.php).

Scheduling

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');
}

Gotchas and Tips

Common Pitfalls

  1. Webhook Not Reachable:

    • Ensure your server’s firewall allows traffic on the webhook port (default: 80/443).
    • Test locally with ngrok:
      ngrok http 80
      
      Then set the webhook URL to https://your-ngrok-url.ngrok.io/telegram-webhook.
  2. Command Not Triggering:

    • Verify the command is registered in config/telegram-support.php.
    • Check for typos in the getCommand() method (case-sensitive).
    • Ensure the bot’s username is correct in Telegram (e.g., @your_bot_name).
  3. Database Migrations:

    • Run php artisan migrate after publishing assets. Skipping this will cause TelegramMessage model errors.
    • If updating the package, run php artisan migrate --force to apply schema changes.
  4. Timezone Issues:

    • Telegram timestamps are in UTC. Convert to local time in your handlers:
      $localTime = (new \DateTime())->setTimestamp($payload['date'])->format('Y-m-d H:i:s');
      
  5. Rate Limits:

    • Telegram enforces rate limits (e.g., 30 messages/second). Avoid rapid-fire responses in loops.
    • Use sleep() or queue delayed jobs for bulk operations.

Debugging Tips

  • 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"
    

Extension Points

  1. 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.

  2. 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'],
            ]
        );
    }
    
  3. 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,
        ],
    ];
    
  4. 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!";
    }
    

Configuration Quirks

  • 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.

Performance

  • 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]);
        }
    });
    
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.
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle
dmstr/api-platform-utils-bundle
dmstr/api-configuration-bundle
chrisdev/ux-components
baks-dev/finances
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle