### Handle Telegram Media and Events with LaraGram Source: https://context7.com/laraxgram/core/llms.txt This snippet demonstrates how to use LaraGram's Bot facade to register handlers for various Telegram message types and events. It includes examples for photos, documents, videos, audio, voice messages, video notes, stickers, animations, location, contacts, dice rolls, new chat members, left chat members, inline queries, and successful payments. Dependencies include the LaraGram library and its Bot facade. ```php message->photo; $largestPhoto = end($photo); // Get highest resolution return request()->sendMessage([ 'chat_id' => request()->message->chat->id, 'text' => "Photo received! File ID: {$largestPhoto->file_id}" ]); }); // Document handling Bot::onDocument(function () { $doc = request()->message->document; return request()->sendMessage([ 'chat_id' => request()->message->chat->id, 'text' => "Document received: {$doc->file_name}" ]); }); // Video, audio, voice handlers Bot::onVideo(function () { /* handle video */ }); Bot::onAudio(function () { /* handle audio */ }); Bot::onVoice(function () { /* handle voice message */ }); Bot::onVideoNote(function () { /* handle video note */ }); Bot::onSticker(function () { /* handle sticker */ }); Bot::onAnimation(function () { /* handle animation/GIF */ }); // Location handling Bot::onLocation(function () { $location = request()->message->location; return request()->sendMessage([ 'chat_id' => request()->message->chat->id, 'text' => "Location: {$location->latitude}, {$location->longitude}" ]); }); // Contact handling Bot::onMessageType('contact', function () { $contact = request()->message->contact; return request()->sendMessage([ 'chat_id' => request()->message->chat->id, 'text' => "Contact: {$contact->first_name} - {$contact->phone_number}" ]); }); // Dice handler with specific emoji and value filters Bot::onDice(function () { $dice = request()->message->dice; return request()->sendMessage([ 'chat_id' => request()->message->chat->id, 'text' => "You rolled a {$dice->value}!" ]); }, emoji: ['🎲', '🎯'], value: [1, 6]); // Filter specific emoji/values // Group events Bot::onNewChatMembers(function () { $members = request()->message->new_chat_members; foreach ($members as $member) { request()->sendMessage([ 'chat_id' => request()->message->chat->id, 'text' => "Welcome, {$member->first_name}!" ]); } }); Bot::onLeftChatMember(function () { $member = request()->message->left_chat_member; return request()->sendMessage([ 'chat_id' => request()->message->chat->id, 'text' => "Goodbye, {$member->first_name}!" ]); }); // Inline query handling Bot::onInlineQuery(function () { $query = request()->inline_query->query; return request()->answerInlineQuery([ 'inline_query_id' => request()->inline_query->id, 'results' => [/* inline results */] ]); }); // Payment handlers Bot::onSuccessfulPayment(function () { $payment = request()->message->successful_payment; return request()->sendMessage([ 'chat_id' => request()->message->chat->id, 'text' => "Payment received! Amount: {$payment->total_amount}" ]); }); ``` -------------------------------- ### Manage Data Caching with Unified API Source: https://context7.com/laraxgram/core/llms.txt Provides a unified API for interacting with multiple cache drivers (e.g., file, Redis, Memcached). Supports basic operations like put, get, forget, and flush, as well as advanced features like remember, rememberForever, tags, and atomic locks. ```php addDay()); // Store until tomorrow $value = Cache::get('key'); // Retrieve value $value = Cache::get('key', 'default'); // With default value Cache::forget('key'); // Remove item Cache::flush(); // Clear all cache // Remember pattern (get or store) $users = Cache::remember('users:all', 3600, function () { return User::all(); }); // Remember forever $settings = Cache::rememberForever('app:settings', function () { return Settings::all()->pluck('value', 'key'); }); // Check existence if (Cache::has('key')) { // Key exists } // Increment/Decrement Cache::increment('page:views'); Cache::increment('counter', 5); Cache::decrement('stock', 1); // Multiple items Cache::putMany([ 'key1' => 'value1', 'key2' => 'value2', ], 3600); $values = Cache::many(['key1', 'key2']); // Tags (supported by Redis, Memcached) Cache::tags(['users', 'admins'])->put('user:1', $user, 3600); Cache::tags(['users'])->flush(); // Flush all user-tagged cache // Using different cache stores Cache::store('redis')->put('key', 'value', 3600); Cache::store('file')->get('key'); // Atomic locks $lock = Cache::lock('processing:order:123', 10); if ($lock->get()) { try { // Process order exclusively } finally { $lock->release(); } } // Block until lock is available Cache::lock('resource')->block(5, function () { // Acquired lock, process resource }); ``` -------------------------------- ### Queue System: Dispatching and Managing Jobs in PHP Source: https://context7.com/laraxgram/core/llms.txt Demonstrates how to define, dispatch, and manage background jobs using LaraGram's queue system. It covers basic dispatching, delayed jobs, jobs on specific queues, synchronous dispatching, and using the Queue facade. Dependencies include LaraGram's queue components. Inputs are job instances and optional delay/queue configurations. Outputs are background job executions. ```php sendMessage([ 'chat_id' => $this->chatId, 'text' => $this->message ]); } public function failed(\Throwable $exception): void { // Handle job failure Log::error('Notification failed', [ 'chat_id' => $this->chatId, 'error' => $exception->getMessage() ]); } } // Dispatch jobs dispatch(new SendTelegramNotification(123456, 'Hello!')); // Dispatch with delay dispatch(new SendTelegramNotification(123456, 'Reminder!')) ->delay(now()->addMinutes(30)); // Dispatch to specific queue dispatch(new SendTelegramNotification(123456, 'Priority!')) ->onQueue('high'); // Dispatch synchronously dispatch_sync(new SendTelegramNotification(123456, 'Immediate!')); // Queue facade Queue::push(new SendTelegramNotification(123456, 'Hello!')); Queue::later(now()->addHour(), new SendTelegramNotification(123456, 'Later!')); // Job chaining Bus::chain([ new ProcessPayment($order), new SendReceipt($order), new NotifyAdmin($order), ])->dispatch(); // Batch processing Bus::batch([ new SendNotification($user1), new SendNotification($user2), new SendNotification($user3), ])->then(function (Batch $batch) { // All jobs completed })->catch(function (Batch $batch, Throwable $e) { // First job failure })->finally(function (Batch $batch) { // Batch finished (success or failure) })->dispatch(); ``` -------------------------------- ### Using LaraGram Facades for Common Tasks Source: https://context7.com/laraxgram/core/llms.txt Demonstrates how to use LaraGram's static facades to interact with various services like configuration, caching, database, logging, events, queues, validation, and hashing. These facades provide a convenient, static interface to underlying container implementations. ```php User::find(123)); Cache::forget('user:123'); // Database queries $users = DB::table('users')->where('active', true)->get(); DB::transaction(function () { DB::table('users')->where('id', 1)->update(['balance' => 100]); DB::table('transactions')->insert(['user_id' => 1, 'amount' => 100]); }); // Logging Log::info('User started bot', ['user_id' => $userId]); Log::error('Payment failed', ['error' => $exception->getMessage()]); Log::channel('telegram')->warning('Rate limit approaching'); // Events Event::dispatch(new UserJoined($user)); Event::listen(UserJoined::class, SendWelcomeMessage::class); // Queue jobs Queue::push(new ProcessPayment($payment)); Queue::later(now()->addMinutes(5), new SendReminder($user)); // Validation $validator = Validator::make($data, [ 'email' => 'required|email', 'amount' => 'required|numeric|min:1' ]); if ($validator->fails()) { $errors = $validator->errors(); } // Hashing $hashed = Hash::make('password'); if (Hash::check('password', $hashed)) { // Password matches } ``` -------------------------------- ### Configure and Bootstrap LaraGram Application Source: https://context7.com/laraxgram/core/llms.txt This snippet demonstrates how to configure and bootstrap the LaraGram application using the Application class. It shows automatic base path detection and manual configuration, along with accessing the application instance and using path helpers. Requires PHP 8.2+. ```php withKernels() ->withEvents() ->withCommands() ->withProviders() ->create(); // Or manually create with explicit base path $app = new Application('/path/to/your/bot'); // Access the application instance anywhere $app = app(); // Returns Application instance $version = app()->version(); // Returns "3.0.0" // Check environment if (app()->isProduction()) { // Production-specific code } if (app()->environment('local', 'staging')) { // Local or staging environment } // Path helpers $configPath = config_path('bot.php'); // /path/to/your/bot/config/bot.php $storagePath = storage_path('logs'); // /path/to/your/bot/storage/logs $databasePath = database_path('migrations'); // /path/to/your/bot/database/migrations ``` -------------------------------- ### Build Telegram Keyboards with LaraGram Keyboard Builder (PHP) Source: https://context7.com/laraxgram/core/llms.txt Demonstrates how to create inline and reply keyboards using LaraGram's fluent Keyboard builder API. It covers various button types, dynamic modification, and special keyboard types like remove and force reply. No external dependencies are required beyond the LaraGram core. ```php inlineKeyboardMarkup( Make::row( Make::callbackData('Option 1', 'callback:option1'), Make::callbackData('Option 2', 'callback:option2') ), Make::row( Make::callbackData('Option 3', 'callback:option3'), Make::url('Visit Website', 'https://example.com') ) ) ->get(); request()->sendMessage([ 'chat_id' => request()->message->chat->id, 'text' => 'Choose an option:', 'reply_markup' => $inlineKeyboard ]); // Reply keyboard (custom keyboard below input) $replyKeyboard = (new Keyboard()) ->replyKeyboardMarkup( Make::row( Make::text('Button 1'), Make::text('Button 2') ), Make::row( Make::requestContact('Share Contact'), Make::requestLocation('Share Location') ) ) ->setOption('resize_keyboard', true) ->setOption('one_time_keyboard', true) ->get(); request()->sendMessage([ 'chat_id' => request()->message->chat->id, 'text' => 'Select an option:', 'reply_markup' => $replyKeyboard ]); // Inline keyboard with various button types $keyboard = (new Keyboard())->inlineKeyboardMarkup( Make::row( Make::url('Open Link', 'https://telegram.org'), Make::callbackData('Click Me', 'action:click') ), Make::row( Make::switchInlineQuery('Share Bot', 'hello'), Make::switchInlineQueryCurrentChat('Search Here', 'query') ), Make::row( Make::webApp('Open Web App', 'https://webapp.example.com'), Make::copyText('Copy Text', 'Text to copy') ), Make::row( Make::pay('Pay Now ⭐100') ) ) ->get(); // Modify keyboard dynamically $keyboard = (new Keyboard())->inlineKeyboardMarkup( Make::row(Make::callbackData('Initial', 'init')) ); $keyboard->appendRow(Make::row(Make::callbackData('Added Row', 'added'))); $keyboard->prependRow(Make::row(Make::callbackData('First Row', 'first'))); $keyboard->removeRow(2); // Remove row at index 2 $keyboard->rightToLeft(); // Reverse for RTL languages // Remove reply keyboard $removeKeyboard = (new Keyboard())->replyKeyboardRemove()->get(); // Force reply $forceReply = (new Keyboard()) ->forceReply('Enter your name...', selective: true) ->get(); ``` -------------------------------- ### Helper Functions: Application, Configuration, and Cache in PHP Source: https://context7.com/laraxgram/core/llms.txt Provides an overview of global helper functions for interacting with the application instance, resolving services from the container, accessing file paths, and managing configuration and cache. These functions simplify common development tasks. Dependencies include the LaraGram application instance. Inputs are service class names, configuration keys, or cache keys. Outputs are application instances, resolved services, file paths, configuration values, or cached data. ```php true]); // Set config value // Cache helpers $value = cache('key'); // Get cached value $value = cache('key', 'default'); // With default cache(['key' => 'value'], 3600); // Store value ``` -------------------------------- ### Manage Dependencies with LaraGram IoC Container (PHP) Source: https://context7.com/laraxgram/core/llms.txt Illustrates how to use LaraGram's IoC container for dependency management and injection. It covers binding interfaces to implementations, singleton and instance bindings, contextual binding, resolving dependencies, tagged bindings, and extending resolved services. Requires configuration for bot token and API URL. ```php bind(PaymentServiceInterface::class, StripePaymentService::class); // Singleton binding (same instance always returned) app()->singleton(TelegramClient::class, function ($app) { return new TelegramClient( config('bot.token'), config('bot.api_url') ); }); // Instance binding (bind existing object) $logger = new CustomLogger(); app()->instance('custom.logger', $logger); // Contextual binding app()->when(PhotoController::class) ->needs(StorageInterface::class) ->give(S3Storage::class); // Resolving from container $client = app(TelegramClient::class); $client = app()->make(TelegramClient::class); $client = app()->make(TelegramClient::class, ['timeout' => 30]); // Tagged bindings app()->tag([RedisCache::class, MemcachedCache::class], 'caches'); $caches = app()->tagged('caches'); // Returns iterable of all tagged services // Extending resolved services app()->extend(TelegramClient::class, function ($client, $app) { $client->setLogger($app->make('log')); return $client; }); // Resolving callbacks after resolution app()->resolving(TelegramClient::class, function ($client, $app) { // Called every time TelegramClient is resolved }); app()->afterResolving(TelegramClient::class, function ($client, $app) { // Called after all resolving callbacks }); ``` -------------------------------- ### Helper Functions: Encryption, Hashing, Events, Logging, Date/Time, Dispatch, Reporting, and Deferral in PHP Source: https://context7.com/laraxgram/core/llms.txt Details various global helper functions for encryption, password hashing, event dispatching, logging, date and time manipulation, job dispatching, exception reporting, and deferred execution. These functions streamline common application logic. Dependencies include LaraGram's core components for events, logging, and queues. Inputs vary based on the function, ranging from data to exceptions. Outputs are encrypted/decrypted data, hashed passwords, dispatched events/jobs, log messages, datetime objects, reported exceptions, or deferred closures. ```php 1]); // Info log logger()->error('Something failed'); // Logger instance // Date/Time $now = now(); // Current datetime $today = today(); // Today at midnight // Dispatch dispatch(new ProcessOrder($order)); // Dispatch job dispatch_sync(new ProcessOrder($order)); // Dispatch synchronously // Report exceptions report($exception); // Report exception report_if($condition, $exception); // Conditional report // Defer execution defer(fn() => Log::info('Deferred')); // Run after response ``` -------------------------------- ### Defining and Using Eloquent ORM Models in LaraGram Source: https://context7.com/laraxgram/core/llms.txt Illustrates how to define Eloquent models for database interactions, including defining fillable attributes, casting, and establishing relationships (hasMany, hasOne). It also shows basic CRUD operations, query scopes, and aggregations. ```php 'boolean', 'settings' => 'array', 'created_at' => 'datetime', ]; public function messages() { return $this->hasMany(Message::class); } public function subscription() { return $this->hasOne(Subscription::class); } } // Creating records $user = User::create([ 'telegram_id' => 123456789, 'username' => 'johndoe', 'first_name' => 'John' ]); // Querying $user = User::where('telegram_id', 123456789)->first(); $admins = User::where('is_admin', true)->get(); $user = User::findOrFail(1); // Updating $user->update(['first_name' => 'Jane']); User::where('last_seen', '<', now()->subDays(30))->update(['active' => false]); // Relationships $user = User::with('messages', 'subscription')->find(1); $recentMessages = $user->messages()->latest()->take(10)->get(); // Query scopes class User extends Model { public function scopeActive($query) { return $query->where('active', true); } public function scopeAdmin($query) { return $query->where('is_admin', true); } } $activeAdmins = User::active()->admin()->get(); // Aggregations $userCount = User::count(); $avgBalance = User::avg('balance'); $maxBalance = User::where('active', true)->max('balance'); ``` -------------------------------- ### Group LaraGram Listeners with Middleware and Scopes Source: https://context7.com/laraxgram/core/llms.txt This snippet illustrates how to group LaraGram event listeners using the Bot::group method. It demonstrates applying middleware to multiple listeners, restricting listeners to specific chat scopes (e.g., private chats), and using fluent methods like .scope() and .can() for fine-grained access control. It also shows how to set command prefixes and name listeners for later retrieval. ```php group(function () { Bot::onCommand('profile', [ProfileController::class, 'show']); Bot::onCommand('settings', [SettingsController::class, 'index']); }); // Group with scope restriction (private chat only, groups only, etc.) Bot::group(['middleware' => 'scope:private'], function () { Bot::onCommand('secret', function () { return request()->sendMessage([ 'chat_id' => request()->message->chat->id, 'text' => 'This command only works in private chat!' ]); }); }); // Using fluent scope method on individual listens Bot::onCommand('admin', function () { // Admin-only command })->scope('groups')->can('administrator'); // Restrict to specific user statuses Bot::onCommand('moderate', [ModerationController::class, 'index']) ->scope(['group', 'supergroup']) ->can(['administrator', 'creator']); // Exclude certain scopes Bot::onCommand('private_only', function () { // Works everywhere except groups })->outOfScope('groups'); // Prefix for command patterns Bot::group(['prefix' => 'admin_'], function () { Bot::onCommand('ban', function () {}); // Matches /admin_ban Bot::onCommand('kick', function () {}); // Matches /admin_kick }); // Named listens for easy referencing Bot::onCommand('start', function () { // ... })->name('bot.start'); // Use a named listen $listen = app('listener')->getListens()->getByName('bot.start'); ``` -------------------------------- ### Register LaraGram Bot Update Handlers (Listeners) Source: https://context7.com/laraxgram/core/llms.txt This snippet illustrates how to define various update handlers for a Telegram bot using the LaraGram Listener class. It covers handling text messages with parameters, commands, referral links, callback queries, and provides a fallback handler. Uses a fluent API and relies on the Bot facade. ```php sendMessage([ 'chat_id' => request()->message->chat->id, 'text' => 'Hello! Welcome to my bot!' ]); }); // Handle text with parameters (like Laravel route parameters) Bot::onText('greet {name}', function ($name) { return request()->sendMessage([ 'chat_id' => request()->message->chat->id, 'text' => "Hello, {$name}!" ]); }); // Handle commands (e.g., /start, /help) Bot::onCommand('start', function () { return request()->sendMessage([ 'chat_id' => request()->message->chat->id, 'text' => 'Welcome! Use /help to see available commands.' ]); }); Bot::onCommand('help', function () { return request()->sendMessage([ 'chat_id' => request()->message->chat->id, 'text' => "Available commands:\n/start - Start the bot\n/help - Show this help" ]); }); // Handle deep linking / referrals (/start with parameter) Bot::onReferral('{code}', function ($code) { return request()->sendMessage([ 'chat_id' => request()->message->chat->id, 'text' => "You joined via referral code: {$code}" ]); }); // Handle callback queries (inline keyboard button presses) Bot::onCallbackQueryData('action:{type}', function ($type) { return request()->answerCallbackQuery([ 'callback_query_id' => request()->callback_query->id, 'text' => "You selected: {$type}" ]); }); // Handle any callback query Bot::onCallbackQuery(function () { $data = request()->callback_query->data; return request()->answerCallbackQuery([ 'callback_query_id' => request()->callback_query->id, 'text' => "Received: {$data}" ]); }); // Fallback handler for unmatched updates Bot::fallback(function () { return request()->sendMessage([ 'chat_id' => request()->message->chat->id ?? request()->callback_query->message->chat->id, 'text' => "I don't understand that command." ]); }); ``` -------------------------------- ### Perform Data Validation with Custom Rules Source: https://context7.com/laraxgram/core/llms.txt Utilizes the Validator facade to validate data against a set of rules and custom messages. Supports various rule types like required, email, integer, string, and database-specific rules. Returns validated data or errors if validation fails. ```php 'user@example.com', 'age' => 25, 'username' => 'johndoe' ]; $validator = Validator::make($data, [ 'email' => 'required|email', 'age' => 'required|integer|min:18|max:100', 'username' => 'required|string|min:3|max:20|alpha_dash' ]); if ($validator->fails()) { $errors = $validator->errors()->all(); // ['The email field is required.', ...] } $validated = $validator->validated(); // Only validated data // Validation with custom messages $validator = Validator::make($data, [ 'amount' => 'required|numeric|min:10', ], [ 'amount.required' => 'Please enter an amount.', 'amount.min' => 'Minimum amount is 10.', ]); // Available validation rules $rules = [ 'field' => 'required', // Must be present and not empty 'email' => 'email', // Valid email format 'age' => 'integer|between:1,120', // Integer between 1 and 120 'price' => 'numeric|min:0', // Numeric, minimum 0 'name' => 'string|max:255', // String, max 255 chars 'status' => 'in:active,inactive,pending', // Must be one of listed values 'date' => 'date|after:today', // Valid date after today 'file' => 'file|mimes:jpg,png|max:2048', // File validation 'url' => 'url', // Valid URL 'ip' => 'ip', // Valid IP address 'unique_email' => 'unique:users,email', // Unique in database 'user_id' => 'exists:users,id', // Must exist in database 'password' => 'confirmed|min:8', // Must match password_confirmation 'items' => 'array|min:1', // Array with at least 1 item 'items.*' => 'string', // Each array item must be string ]; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.