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

Users Table Telegram Laravel Package

baks-dev/users-table-telegram

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require baks-dev/users-table-telegram
    php bin/console baks:assets:install
    
    • Runs migrations and publishes config/assets automatically.
  2. First Use Case: Track User Work Hours

    • Publish the config:
      php artisan vendor:publish --provider="BaksDev\UsersTableTelegram\UsersTableTelegramServiceProvider" --tag="config"
      
    • Configure config/users-table-telegram.php with your Telegram bot token and database settings.
    • Run migrations:
      php artisan migrate
      
  3. Key Classes to Explore

    • BaksDev\UsersTableTelegram\Models\UserWorkTime – Core model for tracking hours.
    • BaksDev\UsersTableTelegram\Services\TelegramBotService – Handles Telegram integration.
    • BaksDev\UsersTableTelegram\Http\Controllers\WorkTimeController – API endpoints for CRUD operations.

Implementation Patterns

Workflow: Daily User Time Tracking

  1. Telegram Bot Integration

    • Extend TelegramBotService to handle custom commands (e.g., /start, /clockin, /clockout).
    • Example command handler:
      $bot->command('clockin', function ($message) {
          $user = User::findOrFail($message->from->id);
          $user->workTime()->create(['started_at' => now()]);
          return "⏳ Clocked in!";
      });
      
  2. Laravel API Endpoints

    • Use the pre-built WorkTimeController for RESTful operations:
      Route::apiResource('work-times', \BaksDev\UsersTableTelegram\Http\Controllers\WorkTimeController::class);
      
    • Customize validation in app/Http/Requests/StoreWorkTimeRequest (published via --tag="requests").
  3. Scheduling Automatic Reports

    • Use Laravel’s scheduler to generate daily/weekly reports:
      $schedule->command('baks:generate-work-reports')->dailyAt('18:00');
      
    • Implement BaksDev\UsersTableTelegram\Contracts\ReportGenerator for custom logic.
  4. Blade Integration (Admin Panel)

    • Publish views:
      php artisan vendor:publish --provider="BaksDev\UsersTableTelegram\UsersTableTelegramServiceProvider" --tag="views"
      
    • Extend resources/views/users-table-telegram/reports.blade.php to display data in your admin dashboard.

Gotchas and Tips

Pitfalls

  1. Telegram Bot Token Leaks

    • Never hardcode the bot token in config/users-table-telegram.php. Use Laravel’s .env:
      TELEGRAM_BOT_TOKEN=your_token_here
      
    • Restrict the token to your IP in BotFather.
  2. Timezone Mismatches

    • Ensure config/app.php and config/database.php use the same timezone as your Telegram bot’s server.
    • Debug with:
      \Carbon\Carbon::now()->timezone('Europe/Moscow')->format('Y-m-d H:i:s');
      
  3. Migration Conflicts

    • If you’ve modified user_work_times table manually, reset migrations:
      php artisan migrate:fresh --env=testing
      
    • Check for reserved column names (e.g., id, created_at) in database/migrations/.
  4. Rate Limiting

    • Telegram APIs throttle requests. Cache responses in TelegramBotService:
      $cacheKey = "telegram_{$message->chat->id}_{$command}";
      return Cache::remember($cacheKey, now()->addMinutes(5), fn() => $this->processCommand($message));
      

Debugging Tips

  1. Log Telegram Webhook Payloads

    • Add middleware to log incoming requests:
      // app/Http/Middleware/LogTelegramWebhook.php
      public function handle($request, Closure $next) {
          \Log::debug('Telegram Webhook', ['payload' => $request->all()]);
          return $next($request);
      }
      
    • Register in app/Http/Kernel.php.
  2. Test Locally with ngrok

    • Expose your Laravel dev server to Telegram:
      ngrok http 8000
      
    • Set the WEBHOOK_URL in config to https://your-ngrok-url.ngrok.io/telegram-webhook.
  3. Common SQL Queries

    • Get today’s active users:
      $activeUsers = UserWorkTime::whereDate('started_at', today())
          ->whereNull('ended_at')
          ->with('user')
          ->get();
      
    • Calculate weekly hours:
      $hours = UserWorkTime::whereBetween('started_at', [now()->startOfWeek(), now()->endOfWeek()])
          ->sum(\DB::raw('TIMESTAMPDIFF(MINUTE, started_at, ended_at) / 60'));
      

Extension Points

  1. Custom Fields

    • Add columns to user_work_times via migration, then extend the model:
      // app/Models/UserWorkTime.php
      protected $casts = [
          'is_remote' => 'boolean',
          'project_id' => 'integer',
      ];
      
  2. Webhook Validation

    • Override TelegramBotService::validateWebhook() to add custom checks:
      public function validateWebhook(array $payload): bool {
          return parent::validateWebhook($payload) &&
              $payload['message']['chat']['id'] === config('users-table-telegram.allowed_chat_id');
      }
      
  3. Export Formats

    • Implement BaksDev\UsersTableTelegram\Contracts\ExporterInterface for CSV/Excel:
      class CustomExporter implements ExporterInterface {
          public function export(UserWorkTime $workTime): string {
              return "Custom format: {$workTime->started_at} - {$workTime->ended_at}";
          }
      }
      
    • Bind in config/users-table-telegram.php:
      'exporter' => \App\Services\CustomExporter::class,
      
  4. Event Listeners

    • Listen for WorkTimeStarted/WorkTimeEnded events:
      // app/Listeners/SendSlackNotification.php
      public function handle(WorkTimeStarted $event) {
          Slack::send("User {$event->user->name} started work at {$event->workTime->started_at}");
      }
      
    • Register in EventServiceProvider:
      protected $listen = [
          \BaksDev\UsersTableTelegram\Events\WorkTimeStarted::class => [
              SendSlackNotification::class,
          ],
      ];
      
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.
besmartand-pro/php-quality-config
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views
spatie/ignition-contracts