### Registering Handlers and Middleware in Routes Source: https://context7.com/nutgram/laravel/llms.txt This example shows how to register a photo handler and apply middleware to specific commands or groups of commands within your Telegram routes file. ```php // routes/telegram.php - Using handlers and middleware use App\Telegram\Handlers\PhotoHandler; use App\Telegram\Middleware\AdminMiddleware; // Register handler class $bot->onPhoto(PhotoHandler::class); // Apply middleware to specific commands $bot->onCommand('admin', function (Nutgram $bot) { $bot->sendMessage('Welcome, admin!'); })->middleware(AdminMiddleware::class); // Apply middleware to a group of handlers $bot->group(function (Nutgram $bot) { $bot->onCommand('ban {user_id}', function (Nutgram $bot, string $userId) { $bot->sendMessage("User {$userId} has been banned."); }); $bot->onCommand('broadcast {message}', function (Nutgram $bot, string $message) { $bot->sendMessage("Broadcasting: {$message}"); }); })->middleware(AdminMiddleware::class); ``` -------------------------------- ### Photo Handler Example Source: https://context7.com/nutgram/laravel/llms.txt This handler processes incoming photos, downloads the largest one, and saves it to storage. It then sends a confirmation message with photo details. ```php // app/Telegram/Handlers/PhotoHandler.php message()->photo; $largestPhoto = end($photos); // Get file info $file = $bot->getFile($largestPhoto->file_id); // Download and store $path = "photos/{$bot->userId()}/{$file->file_unique_id}.jpg"; $bot->downloadFile($file, Storage::path($path)); $bot->sendMessage( text: "📸 Photo saved!\n" . "Size: {$largestPhoto->width}x{$largestPhoto->height}\n" . "File size: " . number_format($largestPhoto->file_size / 1024, 2) . " KB" ); } } ``` -------------------------------- ### Run Bot in Polling Mode Source: https://context7.com/nutgram/laravel/llms.txt Start your bot in polling mode, which is suitable for development. The bot will continuously fetch updates from Telegram. ```bash # Run bot in polling mode (development) php artisan nutgram:run ``` -------------------------------- ### Generate Bot Command Class with Artisan Source: https://context7.com/nutgram/laravel/llms.txt Use the Artisan command to generate new command classes, organizing your bot commands into dedicated files. This requires the Nutgram package to be installed. ```bash php artisan nutgram:make:command StartCommand ``` -------------------------------- ### Admin Middleware Implementation Source: https://context7.com/nutgram/laravel/llms.txt An example middleware that checks if the user ID is in a predefined list of administrators. If not, it sends an unauthorized message; otherwise, it proceeds to the next middleware or handler. ```php // app/Telegram/Middleware/AdminMiddleware.php userId(), $this->adminIds)) { $bot->sendMessage('⛔ You are not authorized to use this command.'); return; } $next($bot); } } ``` -------------------------------- ### Download Telegram Files to Laravel Disks Source: https://context7.com/nutgram/laravel/llms.txt Handle document, photo, and voice message downloads by integrating with Laravel's filesystem. This example shows how to save files to the default disk, a specific disk like 's3', or local storage with custom options. ```php // routes/telegram.php onDocument(function (Nutgram $bot) { $document = $bot->message()->document; $file = $bot->getFile($document->file_id); // Save to default disk $path = "documents/{$bot->userId()}/{$document->file_name}"; $bot->downloadFileToDisk($file, $path); $bot->sendMessage("Document saved to: {$path}"); }); $bot->onPhoto(function (Nutgram $bot) { $photos = $bot->message()->photo; $photo = end($photos); $file = $bot->getFile($photo->file_id); // Save to specific disk (e.g., 's3') $path = "photos/{$file->file_unique_id}.jpg"; $file->saveToDisk($path, 's3'); $bot->sendMessage("Photo uploaded to S3!"); }); $bot->onVoice(function (Nutgram $bot) { $voice = $bot->message()->voice; $file = $bot->getFile($voice->file_id); // Save to local storage with custom options $path = "voice/{$bot->userId()}/{$file->file_unique_id}.ogg"; $file->saveToDisk($path, 'local', [ 'timeout' => 30, ]); $bot->sendMessage("Voice message saved!"); }); ``` -------------------------------- ### Start Conversation from a Telegram Command Source: https://context7.com/nutgram/laravel/llms.txt This PHP code demonstrates how to initiate a Nutgram conversation when a specific Telegram command is received. It maps the '/register' command to the RegistrationConversation class. ```php // routes/telegram.php - Start conversation from a command use App\Telegram\Conversations\RegistrationConversation; $bot->onCommand('register', RegistrationConversation::class) ->description('Register a new account'); ``` -------------------------------- ### Get Webhook Info Source: https://context7.com/nutgram/laravel/llms.txt Retrieve information about the currently configured webhook for your Telegram bot. ```bash # Get webhook info php artisan nutgram:hook:info ``` -------------------------------- ### Install Nutgram Laravel Package Source: https://github.com/nutgram/laravel/blob/master/README.md Use this Composer command to add the Nutgram package to your Laravel project. Ensure you are using Laravel 9.0 or later. ```bash composer require nutgram/laravel ``` -------------------------------- ### Implement a Registration Conversation in Laravel Source: https://context7.com/nutgram/laravel/llms.txt This PHP code defines a multi-step registration process. It guides the user through providing their name and email, validates the email format, and confirms the details before saving the user. The conversation manages state across multiple messages. ```php sendMessage('Welcome! Let\'s get you registered.'); $bot->sendMessage('What is your name?'); $this->next('askEmail'); } public function askEmail(Nutgram $bot): void { $this->name = $bot->message()->text; $bot->sendMessage("Nice to meet you, {$this->name}!"); $bot->sendMessage('What is your email address?'); $this->next('confirm'); } public function confirm(Nutgram $bot): void { $this->email = $bot->message()->text; if (!filter_var($this->email, FILTER_VALIDATE_EMAIL)) { $bot->sendMessage('That doesn\'t look like a valid email. Please try again:'); return; // Stay on this step } $bot->sendMessage( "Great! Please confirm your details:\n\n" . "Name: {$this->name}\n" . "Email: {$this->email}\n\n" . "Type 'yes' to confirm or 'no' to start over." ); $this->next('save'); } public function save(Nutgram $bot): void { $response = strtolower($bot->message()->text); if ($response === 'yes') { // Save to database User::create([ 'telegram_id' => $bot->userId(), 'name' => $this->name, 'email' => $this->email, ]); $bot->sendMessage('Registration complete! Welcome aboard! 🎉'); $this->end(); } elseif ($response === 'no') { $bot->sendMessage('No problem, let\'s start over.'); $this->start($bot); } else { $bot->sendMessage('Please type "yes" or "no".'); } } } ``` -------------------------------- ### Define and Handle Bot Commands Source: https://context7.com/nutgram/laravel/llms.txt Create a command class extending SergiX44\Nutgram\Handlers\Type\Command to define bot commands. The `handle` method contains the logic executed when the command is triggered. ```php // app/Telegram/Commands/StartCommand.php user(); $bot->sendMessage( text: "Welcome, {$user->first_name}! 👋\n\n" . "I'm your assistant bot. Here's what I can do:\n" . "/help - Show available commands\n" . "/settings - Configure preferences\n" . "/status - Check your status" ); } } ``` -------------------------------- ### Listen Mode for Development Source: https://context7.com/nutgram/laravel/llms.txt Run the bot in listen mode, which typically includes auto-reloading for development. This command is useful for rapid development cycles. ```bash # Listen mode for development (auto-reload) php artisan nutgram:listen --pollingTimeout=5 ``` -------------------------------- ### Run Bot Once Source: https://context7.com/nutgram/laravel/llms.txt Execute the bot once to process a single update. This is useful for testing specific scenarios or for running the bot in environments where continuous polling is not desired. ```bash # Run bot once (single update) php artisan nutgram:run --once ``` -------------------------------- ### Enable Nutgram Filesystem Mixins Source: https://context7.com/nutgram/laravel/llms.txt Enable filesystem mixins in your Nutgram configuration to allow direct file downloads to Laravel's filesystem disks. This setting should be set to true in your config/nutgram.php file. ```php // config/nutgram.php return [ // ... other config 'mixins' => true, // Enable filesystem mixins ]; ``` -------------------------------- ### Register Bot Commands Source: https://context7.com/nutgram/laravel/llms.txt Register your custom command classes with the bot instance in the `routes/telegram.php` file to make them active. ```php // routes/telegram.php - Register the command class registerCommand(StartCommand::class); ``` -------------------------------- ### Generate Middleware with Artisan Source: https://context7.com/nutgram/laravel/llms.txt Use this Artisan command to create a new middleware class for your Telegram bot. This is useful for implementing access control or request filtering. ```bash php artisan nutgram:make:middleware AdminMiddleware ``` -------------------------------- ### Generate Conversation Class with Artisan Source: https://context7.com/nutgram/laravel/llms.txt Use the Artisan command to generate conversation classes, which are used for handling multi-step user interactions that persist across multiple messages. ```bash # Generate a basic conversation php artisan nutgram:make:conversation RegistrationConversation ``` -------------------------------- ### Set Webhook with Custom Options Source: https://context7.com/nutgram/laravel/llms.txt Configure the webhook URL with additional options like IP address and maximum connections. This allows for more control over how Telegram connects to your webhook. ```bash # Set webhook with custom options php artisan nutgram:hook:set https://yourdomain.com/telegram/webhook --ip=1.2.3.4 --max-connections=100 ``` -------------------------------- ### Define Bot Handlers in routes/telegram.php Source: https://context7.com/nutgram/laravel/llms.txt Register bot handlers for commands, text messages, callback queries, and other events in `routes/telegram.php`. Use the Nutgram facade for bot interactions. ```php // routes/telegram.php onCommand('start', function (Nutgram $bot) { $bot->sendMessage('Welcome to my bot!'); })->description('Start the bot'); // Command with parameters using regex $bot->onCommand('greet {name}', function (Nutgram $bot, string $name) { $bot->sendMessage("Hello, {$name}!"); })->description('Greet a user'); // Handle text messages with pattern matching $bot->onText('Hello', function (Nutgram $bot) { $bot->sendMessage('Hi there!'); }); // Handle any text message $bot->onMessage(function (Nutgram $bot) { $bot->sendMessage('You said: ' . $bot->message()->text); }); // Handle callback queries from inline keyboards $bot->onCallbackQueryData('action:confirm', function (Nutgram $bot) { $bot->answerCallbackQuery(text: 'Confirmed!'); $bot->editMessageText('You confirmed the action.'); }); // Send message with inline keyboard $bot->onCommand('menu', function (Nutgram $bot) { $bot->sendMessage( text: 'Choose an option:', reply_markup: InlineKeyboardMarkup::make() ->addRow( InlineKeyboardButton::make('Option 1', callback_data: 'option:1'), InlineKeyboardButton::make('Option 2', callback_data: 'option:2') ) ->addRow( InlineKeyboardButton::make('Cancel', callback_data: 'action:cancel') ) ); })->description('Show menu'); // Handle photos $bot->onPhoto(function (Nutgram $bot) { $photo = $bot->message()->photo; $bot->sendMessage('Nice photo! Size: ' . end($photo)->file_size . ' bytes'); }); // Handle documents $bot->onDocument(function (Nutgram $bot) { $doc = $bot->message()->document; $bot->sendMessage("Received: {$doc->file_name}"); }); // Fallback for unhandled messages $bot->fallback(function (Nutgram $bot) { $bot->sendMessage("I don't understand that command. Try /help"); }); ``` -------------------------------- ### Create a New Conversation with Nutgram CLI Source: https://context7.com/nutgram/laravel/llms.txt Use the Nutgram Artisan command to generate a new conversation class. This command scaffolds the basic structure for your conversation logic. ```bash php artisan nutgram:make:conversation SettingsMenu --menu ``` -------------------------------- ### Send Various Message Types with Telegram Facade Source: https://context7.com/nutgram/laravel/llms.txt Use the Telegram facade for static method calls to send text, formatted text, messages with inline keyboards, photos with captions, and documents with captions. ```php Important Notice\n\nThis is a formatted message.', chat_id: $chatId, parse_mode: ParseMode::HTML ); } public function sendWithKeyboard(int $chatId) { // Send message with inline keyboard Telegram::sendMessage( text: 'Please confirm your action:', chat_id: $chatId, reply_markup: InlineKeyboardMarkup::make() ->addRow( InlineKeyboardButton::make('Confirm', callback_data: 'confirm'), InlineKeyboardButton::make('Cancel', callback_data: 'cancel') ) ); } public function sendPhoto(int $chatId, string $photoPath) { // Send a photo with caption Telegram::sendPhoto( photo: fopen($photoPath, 'r'), chat_id: $chatId, caption: 'Check out this image!' ); } public function sendDocument(int $chatId, string $filePath) { // Send a document Telegram::sendDocument( document: fopen($filePath, 'r'), chat_id: $chatId, caption: 'Here is your document' ); } public function getBotInfo() { // Get bot information $me = Telegram::getMe(); return [ 'id' => $me->id, 'username' => $me->username, 'first_name' => $me->first_name, ]; } } ``` -------------------------------- ### Run Bot with Custom Polling Timeout Source: https://context7.com/nutgram/laravel/llms.txt Configure the polling timeout in seconds when running the bot in polling mode. This affects how often the bot checks for new updates. ```bash # Run with custom polling timeout php artisan nutgram:run --pollingTimeout=30 ``` -------------------------------- ### Register Bot Commands Source: https://context7.com/nutgram/laravel/llms.txt Synchronize your bot's commands with Telegram. This ensures that commands defined in your bot are available to users in the Telegram client. ```bash # Register bot commands with Telegram php artisan nutgram:register-commands ``` -------------------------------- ### Test Bot Commands with FakeNutgram Source: https://context7.com/nutgram/laravel/llms.txt Write unit tests for your bot handlers using the Telegram facade's fake method and FakeNutgram. This allows you to simulate user interactions and assert bot responses without actual Telegram API calls. ```php // tests/Feature/BotCommandTest.php hearText('/start') ->reply() ->assertReplyText('Welcome to my bot!'); } public function test_greet_command_with_parameter(): void { Telegram::fake(); $bot = app(Nutgram::class); $bot->hearText('/greet John') ->reply() ->assertReplyText('Hello, John!'); } public function test_callback_query_handler(): void { Telegram::fake(); $bot = app(Nutgram::class); $bot->willReceive(['ok' => true, 'result' => true]); $bot->hearCallbackQueryData('action:confirm') ->reply() ->assertCalled('answerCallbackQuery') ->assertReply('editMessageText', ['text' => 'You confirmed the action.']); } public function test_conversation_flow(): void { Telegram::fake(); $bot = app(Nutgram::class); // Start conversation $bot->willStartConversation() ->hearText('/register') ->reply() ->assertReplyText('Welcome! Let\'s get you registered.') ->assertActiveConversation(); // Continue conversation $bot->hearText('John Doe') ->reply() ->assertReplyText('Nice to meet you, John Doe!'); } public function test_middleware_blocks_unauthorized_user(): void { Telegram::fake(); $bot = app(Nutgram::class); $bot->setCommonUser(new \SergiX44\Nutgram\Telegram\Types\User\User( id: 999999, is_bot: false, first_name: 'Unauthorized' )); $bot->hearText('/admin') ->reply() ->assertReplyText('⛔ You are not authorized to use this command.'); } } ``` -------------------------------- ### Remove Webhook and Drop Pending Updates Source: https://context7.com/nutgram/laravel/llms.txt Remove the webhook and discard any pending updates that have not yet been delivered. Use this when you want a clean slate. ```bash # Remove webhook and drop pending updates php artisan nutgram:hook:remove --drop-pending-updates ``` -------------------------------- ### Register Global Exception Handler in Nutgram Source: https://context7.com/nutgram/laravel/llms.txt Catch all exceptions thrown during bot execution. Logs the error and sends a generic message to the user. Ensure proper logging is configured. ```php // routes/telegram.php onException(function (Nutgram $bot, \Throwable $e) { // Log the error logger()->error('Bot error', [ 'message' => $e->getMessage(), 'user_id' => $bot->userId(), 'update' => $bot->update(), ]); $bot->sendMessage('An error occurred. Please try again later.'); }); // Handle specific exception types $bot->onException(\InvalidArgumentException::class, function (Nutgram $bot, \InvalidArgumentException $e) { $bot->sendMessage("Invalid input: {$e->getMessage()}"); }); // Handle Telegram API errors $bot->onApiError(function (Nutgram $bot, TelegramException $e) { logger()->warning('Telegram API error', [ 'code' => $e->getCode(), 'message' => $e->getMessage(), ]); if ($e->getCode() === 403) { // User blocked the bot logger()->info('User blocked bot', ['user_id' => $bot->userId()]); } }); // Handle specific API error patterns $bot->onApiError('.*bot was blocked.*', function (Nutgram $bot, TelegramException $e) { // Remove user from database or mark as inactive logger()->info('Bot blocked by user', ['user_id' => $bot->userId()]); }); ``` -------------------------------- ### Nutgram Laravel Configuration Source: https://context7.com/nutgram/laravel/llms.txt Configure your Telegram bot token, safe mode, API settings, and handler routes in the `config/nutgram.php` file. Ensure your `.env` file contains the TELEGRAM_TOKEN. ```php // config/nutgram.php return [ // The Telegram BOT API token 'token' => env('TELEGRAM_TOKEN'), // Validate incoming requests are from Telegram servers in production 'safe_mode' => env('APP_ENV', 'local') === 'production', // Extra configurations passed to Nutgram 'config' => [ 'api_url' => 'https://api.telegram.org', 'bot_name' => 'MyBot', 'timeout' => 10, 'polling' => [ 'timeout' => 10, 'limit' => 100, ], ], // Auto-load handlers from routes/telegram.php 'routes' => true, // Enable Laravel filesystem mixins 'mixins' => false, // Path for generated Telegram classes 'namespace' => app_path('Telegram'), // Log channel for bot activity 'log_channel' => env('TELEGRAM_LOG_CHANNEL', 'null'), ]; ``` ```env # .env TELEGRAM_TOKEN=123456789:ABCDefGhIJKlmnOPQRstUVwxYZ TELEGRAM_LOG_CHANNEL=stack ``` -------------------------------- ### Set Webhook URL Source: https://context7.com/nutgram/laravel/llms.txt Use this Artisan command to configure the webhook URL for your Telegram bot. This is essential for receiving updates from Telegram. ```bash # Set webhook URL php artisan nutgram:hook:set https://yourdomain.com/telegram/webhook ``` -------------------------------- ### Create Inline Menu Conversation in Laravel Source: https://context7.com/nutgram/laravel/llms.txt Defines an inline menu conversation for interactive navigation with callback handling. Use this to create multi-level menus and manage user interactions via buttons. ```php menuText('⚙️ Settings\n\nChoose a category:') ->addButtonRow( InlineKeyboardButton::make('🔔 Notifications', callback_data: 'notifications@showNotifications') ) ->addButtonRow( InlineKeyboardButton::make('🌐 Language', callback_data: 'language@showLanguage') ) ->addButtonRow( InlineKeyboardButton::make('🔒 Privacy', callback_data: 'privacy@showPrivacy') ) ->addButtonRow( InlineKeyboardButton::make('❌ Close', callback_data: 'close@closeMenu') ) ->showMenu(); } public function showNotifications(Nutgram $bot): void { $this->menuText('🔔 Notification Settings\n\nToggle your preferences:') ->clearButtons() ->addButtonRow( InlineKeyboardButton::make('✅ Daily Digest', callback_data: 'toggle:daily@toggleSetting'), InlineKeyboardButton::make('❌ Promotions', callback_data: 'toggle:promo@toggleSetting') ) ->addButtonRow( InlineKeyboardButton::make('⬅️ Back', callback_data: 'back@start') ) ->showMenu(); } public function showLanguage(Nutgram $bot): void { $this->menuText('🌐 Language Settings\n\nSelect your preferred language:') ->clearButtons() ->addButtonRow( InlineKeyboardButton::make('🇬🇧 English', callback_data: 'lang:en@setLanguage'), InlineKeyboardButton::make('🇪🇸 Spanish', callback_data: 'lang:es@setLanguage') ) ->addButtonRow( InlineKeyboardButton::make('🇫🇷 French', callback_data: 'lang:fr@setLanguage'), InlineKeyboardButton::make('🇩🇪 German', callback_data: 'lang:de@setLanguage') ) ->addButtonRow( InlineKeyboardButton::make('⬅️ Back', callback_data: 'back@start') ) ->showMenu(); } public function setLanguage(Nutgram $bot): void { $data = $bot->callbackQuery()->data; $lang = str_replace('lang:', '', explode('@', $data)[0]); // Save language preference $bot->answerCallbackQuery(text: "Language set to: {$lang}"); $this->start($bot); } public function toggleSetting(Nutgram $bot): void { $data = $bot->callbackQuery()->data; $setting = str_replace('toggle:', '', explode('@', $data)[0]); $bot->answerCallbackQuery(text: "Toggled: {$setting}"); $this->showNotifications($bot); } public function closeMenu(Nutgram $bot): void { $bot->deleteMessage( chat_id: $bot->chatId(), message_id: $bot->messageId() ); $this->end(); } public function showPrivacy(Nutgram $bot): void { $this->menuText('🔒 Privacy Settings\n\nManage your data:') ->clearButtons() ->addButtonRow( InlineKeyboardButton::make('📊 Download Data', callback_data: 'download@downloadData') ) ->addButtonRow( InlineKeyboardButton::make('🗑️ Delete Account', callback_data: 'delete@confirmDelete') ) ->addButtonRow( InlineKeyboardButton::make('⬅️ Back', callback_data: 'back@start') ) ->showMenu(); } } ``` -------------------------------- ### List Registered Handlers Source: https://context7.com/nutgram/laravel/llms.txt Display a list of all handlers that are currently registered with your Nutgram bot. This is useful for debugging and understanding your bot's structure. ```bash # List all registered handlers php artisan nutgram:list ``` -------------------------------- ### Generate Nutgram Handler in Laravel Source: https://context7.com/nutgram/laravel/llms.txt Generates a new handler class for Nutgram. Use this command to create reusable classes for organizing your bot's logic and request processing. ```bash # Generate a handler php artisan nutgram:make:handler PhotoHandler ``` -------------------------------- ### Validate Web App Data in Routes Source: https://context7.com/nutgram/laravel/llms.txt Use the ValidateWebAppData middleware in your Laravel routes to automatically validate data received from a Telegram Mini App. This ensures the data is legitimate before processing. ```php // routes/web.php group(function () { Route::post('/webapp/submit', function () { // Access validated web app data $data = webAppData(); return response()->json([ 'user_id' => $data->user->id, 'username' => $data->user->username, 'first_name' => $data->user->first_name, 'auth_date' => $data->auth_date, ]); }); Route::get('/webapp/profile', function () { $data = webAppData(); return view('webapp.profile', [ 'user' => $data->user, ]); }); }); ``` -------------------------------- ### Custom ValidateWebAppData Middleware Source: https://context7.com/nutgram/laravel/llms.txt Extend the default ValidateWebAppData middleware to implement custom error handling for invalid Web App data. This allows you to define specific responses for validation failures. ```php // Custom ValidateWebAppData middleware with custom error handling json([ 'error' => 'Invalid Web App data', 'message' => 'The provided initData is invalid or expired.', ], 403); } } ``` -------------------------------- ### Remove Webhook Source: https://context7.com/nutgram/laravel/llms.txt Unregister the webhook from Telegram. This will stop your bot from receiving updates via the webhook. ```bash # Remove webhook php artisan nutgram:hook:remove ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.