### Basic Nutgram Setup and Run Source: https://nutgram.dev/docs/1.x/usage/getting_updates This snippet shows the fundamental structure for initializing a Nutgram bot and starting its update processing loop. It requires the Nutgram class and an environment variable for the bot token. ```php use SergiX44\Nutgram\Nutgram; $bot = new Nutgram($_ENV['TOKEN']); // new instance // register callbacks // middlewares // do your stuff $bot->run(); // finally, begin to process incoming updates ``` -------------------------------- ### Initialize Nutgram with API Token (PHP) Source: https://nutgram.dev/docs/configuration/installation Demonstrates the basic initialization of a Nutgram bot instance using a Telegram API token in PHP. This is the minimum required step to start using Nutgram. ```php use SergiX44\Nutgram\Nutgram; $bot = new Nutgram('you telegram token here'); ``` -------------------------------- ### Basic Nutgram Bot Setup and Command Handling (PHP) Source: https://nutgram.dev/docs/2.x/introduction This snippet demonstrates the basic setup of a Nutgram bot using PHP. It initializes the bot with a token, registers a command handler for '/start' that sends a 'Ciao!' message, and a text handler for messages matching 'My name is {name}' to respond with a personalized greeting. The bot then starts processing updates. ```php onCommand('start', function(Nutgram $bot) { $bot->sendMessage('Ciao!'); }); $bot->onText('My name is {name}', function(Nutgram $bot, string $name) { $bot->sendMessage("Hi $name"); }) $bot->run(); ``` -------------------------------- ### Initialize and Run Nutgram Bot Source: https://nutgram.dev/docs/2.x/usage/getting_updates This snippet shows the basic initialization of a Nutgram bot instance and the final call to the `run()` method to start processing updates. It's the fundamental setup required for any Nutgram bot. ```php use SergiX44\Nutgram\Nutgram; $bot = new Nutgram($_ENV['TOKEN']); // new instance // register callbacks // middlewares // do your stuff $bot->run(); // finally, begin to process incoming updates ``` -------------------------------- ### Basic Bot Example with Nutgram (PHP) Source: https://nutgram.dev/docs/3.x/introduction This snippet demonstrates a basic Telegram bot setup using the Nutgram library in PHP. It shows how to initialize the bot with a token, handle the '/start' command, and respond to specific text patterns. The bot then runs to process incoming messages. This requires the Nutgram library and a Telegram Bot Token. ```php onCommand('start', function(Nutgram $bot) { $bot->sendMessage('Ciao!'); }); $bot->onText('My name is {name}', function(Nutgram $bot, string $name) { $bot->sendMessage("Hi $name"); }); $bot->run(); ``` -------------------------------- ### Send Feedback Conversation (PHP) Source: https://nutgram.dev/docs/testing/examples This snippet demonstrates the process of sending feedback. It starts a conversation, prompts the user to send their feedback, and asserts that the conversation is active. The second step shows how to receive the feedback and end the conversation. ```php $bot->willStartConversation() ->hearText('/feedback') ->reply() ->assertReplyMessage([ 'text' => 'Send your feedback', 'reply_markup' => InlineKeyboardMarkup::make()->addRow( InlineKeyboardButton::make('Cancel', callback_data: 'feedback.cancel') ), ]) ->assertActiveConversation(); // second step $bot->hearText('this is a feedback') ->reply() ->assertReplyText('Thanks for your feedback!') ->assertNoConversation(); ``` -------------------------------- ### Nutgram Configuration File Example Source: https://nutgram.dev/docs/1.x/configuration/laravel An example of the `config/nutgram.php` file, showing key configuration options such as the Telegram BOT API token, extra configurations, and route loading settings. ```php return [ // The Telegram BOT api token 'token' => env('TELEGRAM_TOKEN', ''), // Extra or specific configurations 'config' => [], // Set if the service provider should automatically load // handlers from /routes/telegram.php 'routes' => true, ]; ``` -------------------------------- ### Initialize and Run Nutgram Bot Source: https://nutgram.dev/docs/3.x/usage/getting_updates This snippet demonstrates the basic setup for a Nutgram bot, including creating a new instance with a token and initiating the update processing loop. ```php use SergiX44\Nutgram\Nutgram; $bot = new Nutgram($_ENV['TOKEN']); // new instance // register callbacks // middlewares // do your stuff $bot->run(); // finally, begin to process incoming updates ``` -------------------------------- ### Install Nutgram Symfony Bundle Source: https://nutgram.dev/docs/3.x/configuration/symfony Installs the Nutgram Symfony Bundle using Composer. If the base Nutgram package was previously installed, it should be removed first. ```bash composer require nutgram/symfony-bundle # remove the base package if you have installed it: # composer remove nutgram/nutgram ``` -------------------------------- ### Feedback Conversation Logic (PHP) Source: https://nutgram.dev/docs/testing/examples This PHP class defines the logic for the feedback conversation. It handles the start of the conversation, prompts the user, and manages the 'getFeedback' state to process user input or cancellation, ultimately saving or discarding the feedback. ```php class FeedbackConversation extends Conversation { public function start(Nutgram $bot): void { // ask for feedback $bot->sendMessage( text: 'Send your feedback', reply_markup: InlineKeyboardMarkup::make()->addRow( InlineKeyboardButton::make('Cancel', callback_data: 'feedback.cancel') ), ); // wait for the user to send feedback $this->next('getFeedback'); } public function getFeedback(Nutgram $bot): void { //handle cancel button if ($bot->callbackQuery()?->data === 'feedback.cancel') { $bot->sendMessage('Feedback cancelled'); $bot->answerCallbackQuery(); //close conversation $this->end(); return; } //get the input $feedback = $bot->message()?->text; //check valid input if ($feedback === null) { $bot->sendMessage('Invalid input, please send your feedback again'); $this->start($bot); return; } //save the feedback // TODO: save $feedback to database // thanks the user $bot->sendMessage('Thanks for your feedback!'); //close conversation $this->end(); } } ``` -------------------------------- ### Create Advanced Ice Cream Conversation in PHP Source: https://nutgram.dev/docs/1.x/usage/conversations An advanced Nutgram conversation example for ordering ice cream. It guides the user through selecting cup size via inline buttons, then asking for flavors. It uses `InlineKeyboardMarkup` and `InlineKeyboardButton` for user interaction. Requires `SergiX44\Nutgram\Conversations\Conversation`, `SergiX44\Nutgram\Nutgram`, and types for keyboards. It stores the cup size and then displays a recap. ```php use SergiX44\Nutgram\Conversations\Conversation;use SergiX44\Nutgram\Nutgram;use SergiX44\Nutgram\Telegram\Types\Keyboard\InlineKeyboardButton;use SergiX44\Nutgram\Telegram\Types\Keyboard\InlineKeyboardMarkup; class AskIceCreamConversation extends Conversation { protected ?string $step = 'askCupSize'; public $cupSize; public function askCupSize(Nutgram $bot) { $bot->sendMessage('How big should be you ice cream cup?', [ 'reply_markup' => InlineKeyboardMarkup::make() ->addRow(InlineKeyboardButton::make('Small', callback_data: 'S'), InlineKeyboardButton::make('Medium', callback_data: 'M')) ->addRow(InlineKeyboardButton::make('Big', callback_data: 'L'), InlineKeyboardButton::make('Super Big', callback_data: 'XL')), ]); $this->next('askFlavors'); } public function askFlavors(Nutgram $bot) { // if is not a callback query, ask again! if (!$bot->isCallbackQuery()) { $this->askCupSize($bot); return; } $this->cupSize = $bot->callbackQuery()->data; $bot->sendMessage('What flavors do you like?'); $this->next('recap'); } public function recap(Nutgram $bot) { $flavors = $bot->message()->text; $bot->sendMessage("You want an $this->cupSize cup with this flavors: $flavors"); $this->end(); } } ``` -------------------------------- ### Bulk Messenger Usage Examples Source: https://nutgram.dev/docs/3.x/usage/bulk_messenger Examples demonstrating how to use the Bulk Messenger feature, both in standalone scripts and within command handlers during polling. Includes examples for sending default messages and custom documents. ```APIDOC ## Bulk Messenger Usage Examples ### Sending Default Messages in Scripts **Description**: Configures and starts the bulk sending of default text messages from a script. **Method**: POST **Endpoint**: `/bulk-messenger/start-sync` **Request Example** ```php getBulkMessenger() ->setChats($chats) ->setText('Hello!') ->setOpt(['parse_mode' => 'HTML']) ->startSync(); ?> ``` ### Sending Default Messages in Handlers (Polling) **Description**: Configures and starts the bulk sending of default text messages when a specific command is received during polling. **Method**: POST **Endpoint**: `/bulk-messenger/start-async` **Request Example** ```php onCommand('start', function (Nutgram $bot) use ($chats) { $bot->getBulkMessenger() ->setChats($chats) ->setText('Hello!') ->setOpt(['parse_mode' => 'MarkdownV2']) ->startAsync(); }); $bot->run(); ?> ``` ### Sending Custom Documents in Scripts **Description**: Configures and starts the bulk sending of custom documents from a script using a custom action. **Method**: POST **Endpoint**: `/bulk-messenger/using` and `/bulk-messenger/start-sync` **Request Example** ```php getBulkMessenger() ->setChats($chats) ->using(fn (Nutgram $bot, int $chatId) => $bot->sendDocument($document, ['chat_id' => $chatId])) ->startSync(); ?> ``` ### Sending Custom Documents in Handlers (Polling) **Description**: Configures and starts the bulk sending of custom documents when a specific command is received during polling, using a custom action. **Method**: POST **Endpoint**: `/bulk-messenger/using` and `/bulk-messenger/start-async` **Request Example** ```php onCommand('send_doc', function (Nutgram $bot) use ($document, $chats) { $bot->getBulkMessenger() ->setChats($chats) ->using(fn (Nutgram $bot, int $chatId) => $bot->sendDocument($document, ['chat_id' => $chatId])) ->startAsync(); }); $bot->run(); ?> ``` ``` -------------------------------- ### Configure and Start Bulk Messenger (Sync) Source: https://nutgram.dev/docs/usage/bulk_messenger Demonstrates how to configure the Bulk Messenger with chats, text, and options, then start the sending process synchronously. This is suitable for script execution. ```php use SergiX44\Nutgram\Nutgram; $bot = new Nutgram($_ENV['TOKEN']); $chats = []; $bot->getBulkMessenger() ->setChats($chats) ->setText('Hello!') ->setOpt(['parse_mode' => 'HTML']); // Optional parameters ->startSync(); ``` -------------------------------- ### Send Multiple Messages in Sequence with Nutgram Source: https://nutgram.dev/docs/testing/examples This example shows how to send a sequence of messages in response to a command. It utilizes `assertSequence` with chained assertions to verify each message in the order it is sent. ```php $bot->hearText('/start') ->reply() ->assertSequence( fn (FakeNutgram $x) => $x->assertReplyText('foo'), fn (FakeNutgram $x) => $x->assertReplyText('bar'), ); ``` ```php $bot->onCommand('start', function (Nutgram $bot) { $bot->sendMessage('foo'); $bot->sendMessage('bar'); }); ``` -------------------------------- ### Implement Force Reply with Nutgram PHP Source: https://nutgram.dev/docs/usage/keyboards This example shows how to use the `ForceReply` class to compel the user to reply to a specific message, optionally providing a placeholder. This is useful for guiding user input. The Nutgram library is necessary for this functionality. ```php $bot->onCommand('start', function(Nutgram $bot){ $bot->sendMessage( text: 'Welcome!', reply_markup: ForceReply::make( force_reply: true, input_field_placeholder: 'Type something', selective: true, ), ); }); ``` -------------------------------- ### Install Nutgram using Composer Source: https://nutgram.dev/docs/1.x/configuration/installation Installs the Nutgram package using the Composer dependency manager. This is the standard method for adding Nutgram to your PHP project. ```bash composer require nutgram/nutgram ``` -------------------------------- ### Nutgram Webhook Mode Setup Source: https://nutgram.dev/docs/1.x/usage/getting_updates Sets up Nutgram to operate in Webhook mode, recommended for production environments with high traffic. This mode requires manual webhook configuration and allows the script to continue execution after processing an update. ```php use SergiX44\Nutgram\Nutgram; use SergiX44\Nutgram\RunningMode\Webhook; $bot = new Nutgram($_ENV['TOKEN']); // new instance $bot->setRunningMode(Webhook::class); // ... $bot->run(); // after this, the script continues execution ``` -------------------------------- ### Nutgram Middleware Execution Order Example (PHP) Source: https://nutgram.dev/docs/3.x/usage/middleware Provides a concrete example of how Nutgram executes middlewares, clarifying the order for global middlewares (descending) and handler middlewares (ascending), including grouped middlewares. ```php use SergiX44\Nutgram\Nutgram; $bot = new Nutgram($_ENV['TOKEN']); $bot->middleware(MiddlewareA::class); // 1° $bot->middleware(MiddlewareB::class); // 2° $bot->group([MiddlewareC::class, MiddlewareD::class], function (Nutgram $bot){ // 3°, 4° $bot->group(MiddlewareE::class, function (Nutgram $bot){ // 5° $bot->onCommand('start', StartCommand::class) // 8° ->middleware(MiddlewareF::class) // 7° ->middleware(MiddlewareG::class); // 6° }); }); $bot->run(); ``` -------------------------------- ### Nutgram Laravel Configuration Example Source: https://nutgram.dev/docs/configuration/laravel An example of the nutgram.php configuration file, showing options like API token, webhook safe mode, custom configurations, route loading, mixins, namespace for handlers, and log channel. ```php // The Telegram BOT api token 'token' => env('TELEGRAM_TOKEN'), // if the webhook mode must validate the incoming IP range is from a telegram server 'safe_mode' => env('APP_ENV', 'local') === 'production', // Extra or specific configurations 'config' => [], // Set if the service provider should automatically load // handlers from /routes/telegram.php 'routes' => true, // Enable or disable Nutgram mixins 'mixins' => false, // Path to save files generated by nutgram:make command 'namespace' => app_path('Telegram'), // Set log channel 'log_channel' => env('TELEGRAM_LOG_CHANNEL', 'null'), ``` -------------------------------- ### Configure Nutgram with Options (PHP) Source: https://nutgram.dev/docs/configuration/installation Shows how to initialize Nutgram with a Telegram API token and custom configuration options using the Configuration class in PHP. This allows for fine-tuning behavior like client timeouts. ```php use SergiX44\Nutgram\Nutgram; use SergiX44\Nutgram\Configuration; $config = new Configuration( clientTimeout: 10, // default in seconds, when contacting the Telegram API ); $bot = new Nutgram('you telegram token here', $config); ``` -------------------------------- ### PHP Inline Menu Example - Nutgram Source: https://nutgram.dev/docs/usage/inline_menu This example demonstrates how to create an inline menu using the InlineMenu class in PHP with Nutgram. It shows how to set menu text, add button rows with callback data, define a fallback handler, and display the menu. It also includes a handler for callback queries and a method to end the conversation. ```php class ChooseColorMenu extends InlineMenu { public function start(Nutgram $bot) { $this->menuText('Choose a color:') ->addButtonRow(InlineKeyboardButton::make('Red', callback_data: 'red@handleColor')) ->addButtonRow(InlineKeyboardButton::make('Green', callback_data: 'green@handleColor')) ->addButtonRow(InlineKeyboardButton::make('Yellow', callback_data: 'yellow@handleColor')) ->orNext('none') ->showMenu(); } public function handleColor(Nutgram $bot) { $color = $bot->callbackQuery()->data; $this->menuText("Choosen: $color!") ->showMenu(); } public function none(Nutgram $bot) { $bot->sendMessage('Bye!'); $this->end(); } } ``` -------------------------------- ### Start Conversation via Command in PHP Source: https://nutgram.dev/docs/1.x/usage/conversations Initiates a Nutgram conversation directly from a command handler. This approach replaces the standard handler with a conversation, starting the defined conversation flow. Requires `SergiX44\Nutgram\StartConversation` and `SergiX44\Nutgram\Nutgram`. The `StartConversation::class` is passed to `onCommand`. ```php use SergiX44\Nutgram\StartConversation; use SergiX44\Nutgram\Nutgram; $bot = new Nutgram($_ENV['TOKEN']); $bot->onCommand('start', StartConversation::class); $bot->run(); ``` -------------------------------- ### Send a Simple Message with Nutgram Source: https://nutgram.dev/docs/testing/examples This example demonstrates how to send a single text message in response to a specific text input. It uses the `hearText`, `reply`, and `assertReplyText` methods for testing. ```php $bot->hearText('/start') ->reply() ->assertReplyText('Hello World!'); ``` ```php $bot->onCommand('start', function (Nutgram $bot) { $bot->sendMessage('Hello World!'); }); ``` -------------------------------- ### Customize Conversation Start Step in PHP Source: https://nutgram.dev/docs/1.x/usage/conversations Demonstrates how to customize the initial step of a Nutgram conversation by overriding the `$step` property. This allows specifying a different method name for the conversation's starting point. Requires `SergiX44\Nutgram\Conversations\Conversation` and `SergiX44\Nutgram\Nutgram`. The `myStart` method is invoked first. ```php use SergiX44\Nutgram\Conversations\Conversations\Conversation; use SergiX44\Nutgram\Nutgram; class MyConversation extends Conversation { protected ?string $step = 'myStart'; public function myStart(Nutgram $bot) { $bot->sendMessage('This is the first step!'); } // ... } ``` -------------------------------- ### Registering OOP Middleware and Handler in PHP Source: https://nutgram.dev/docs/1.x/usage/middleware Provides an example of registering an invokable command handler class and an invokable middleware class with the Nutgram bot. This demonstrates how to integrate object-oriented components into the middleware and command handling process. This example uses PHP. ```php use SergiX44\Nutgram\Nutgram; $bot = new Nutgram($_ENV['TOKEN']); $bot->onCommand('start {param}', MyCommand::class) ->middleware(MyMiddleware::class); $bot->run(); ``` -------------------------------- ### Basic Bot Message Sending with sendMessage Source: https://nutgram.dev/docs/testing/asserting This snippet shows a basic bot setup using `onText` to listen for a specific text and then respond with `sendMessage`. This is a foundational example for bot message handling. ```php $bot->onText('foo', function (Nutgram $bot) { $bot->sendMessage('bar'); }); ``` -------------------------------- ### Nutgram Polling Mode Setup Source: https://nutgram.dev/docs/1.x/usage/getting_updates Configures Nutgram to use the Polling mode for processing updates. This mode is suitable for development or low-traffic bots, as it blocks script execution to continuously check for new updates. ```php use SergiX44\Nutgram\Nutgram; use SergiX44\Nutgram\RunningMode\Polling; $bot = new Nutgram($_ENV['TOKEN']); // new instance $bot->setRunningMode(Polling::class); // ... $bot->run(); // start to listen to updates, until stopped ``` -------------------------------- ### Create and Run a Basic Nutgram Bot (PHP) Source: https://nutgram.dev/docs/1.x/introduction This snippet demonstrates how to initialize a Nutgram bot using an API token and set up basic command and text handlers. It requires the Nutgram library and a valid Telegram Bot API token. The bot responds to the '/start' command and custom text messages, echoing back information. ```php onCommand('start', fn(Nutgram $bot) => $bot->sendMessage('Ciao!')); $bot->onText('My name is {name}', fn(Nutgram $bot, $name) => $bot->sendMessage("Hi {$name}")); $bot->run(); ``` -------------------------------- ### Registering Invokable Commands and Middleware in Nutgram (PHP) Source: https://nutgram.dev/docs/usage/middleware Shows how to register an invokable class as a command handler and apply middleware to it using the Nutgram framework. This example initializes Nutgram with a token and sets up a '/start' command processed by `MyCommand` with `MyMiddleware`. ```php use SergiX44\Nutgram\Nutgram; $bot = new Nutgram($_ENV['TOKEN']); $bot->onCommand('start {param}', MyCommand::class) ->middleware(MyMiddleware::class); $bot->run(); ``` -------------------------------- ### Set up and Test with Fake Nutgram Instance (PHP) Source: https://nutgram.dev/docs/2.x/testing/introduction Illustrates setting up a fake Nutgram instance within a PHPUnit test case, including registering handlers and asserting mocked responses. The `FakeNutgram` class provides methods for simulating API interactions and verifying them. This setup is crucial for testing bot logic without external dependencies. ```PHP use PHPUnit\Framework\TestCase; use SergiX44\Nutgram\Testing\FakeNutgram; use SergiX44\Nutgram\Nutgram; class BotTest extends TestCase { private FakeNutgram $bot; public function setUp(): void { $this->bot = Nutgram::fake(); $this->bootInstance($this->bot); // Assuming bootInstance registers handlers/middleware } public function test_retrieve_mocked_instance(): void { // Define assertions for mocked replies $this->bot->reply() ->assertReply('sendMessage', ['text' => 'bar'], 0); ->assertReply('sendMessage', ['text' => 'baz'], 1); } } ``` -------------------------------- ### Middleware Execution Flow in Nutgram Source: https://nutgram.dev/docs/usage/middleware Details the execution order of global and handler-specific middlewares in Nutgram. Global middlewares execute in descending order of declaration, while handler middlewares execute in ascending order. The example provides a clear sequence of middleware execution for a complex setup. ```php use SergiX44\Nutgram\Nutgram; $bot = new Nutgram('TOKEN'); $bot->middleware(MiddlewareA::class); // 1° $bot->middleware(MiddlewareB::class); // 2° $bot->group(function (Nutgram $bot) { $bot->group(function (Nutgram $bot) { $bot->onCommand('start', StartCommand::class) // 8° ->middleware(MiddlewareF::class) // 7° ->middleware(MiddlewareG::class); // 6° })->middleware(MiddlewareE::class); // 5° }) ->middleware(MiddlewareC::class) // 3° ->middleware(MiddlewareD::class); // 4° $bot->run(); ``` -------------------------------- ### Configure and Test Mocked Nutgram Instance (PHP) Source: https://nutgram.dev/docs/3.x/testing/introduction Illustrates setting up a fake Nutgram instance within a test class, registering handlers, and making assertions on mocked responses. This example uses `FakeNutgram` to simulate bot behavior and verify specific API calls like 'sendMessage'. It depends on `SergiX44NutgramTestingFakeNutgram` and `SergiX44NutgramNutgram`. ```PHP use PHPUnit\Framework\TestCase; use SergiX44\Nutgram\Testing\FakeNutgram; use SergiX44\Nutgram\Nutgram; class BotTest extends TestCase { private FakeNutgram $bot; public function setUp(): void { $this->bot = Nutgram::fake(); $this->bootInstance($this->bot); } public function test_retrieve_mocked_instance(): void { // define assertions $this->bot->reply() ->assertReply('sendMessage', ['text' => 'bar'], 0); ->assertReply('sendMessage', ['text' => 'baz'], 1); } } ``` -------------------------------- ### Create and Handle Reply Keyboards with Nutgram PHP Source: https://nutgram.dev/docs/usage/keyboards This example shows how to create a reply keyboard with predefined user options and handle text messages matching those options. It utilizes `ReplyKeyboardMarkup`, `KeyboardButton`, and `onText` for creating the keyboard and listening for specific user inputs. The Nutgram library must be available. ```php $bot->onCommand('start', function(Nutgram $bot){ $bot->sendMessage( text: 'Welcome!', reply_markup: ReplyKeyboardMarkup::make()->addRow( KeyboardButton::make('Give me food!'), KeyboardButton::make('Give me animal!'), ) ); }); $bot->onText('Give me food!', function (Nutgram $bot) { $bot->sendMessage('Apple!'); }); $bot->onText('Give me animal!', function (Nutgram $bot) { $bot->sendMessage('Dog!'); }); ``` -------------------------------- ### Install Nutgram Laravel Package Source: https://nutgram.dev/docs/configuration/laravel To use Nutgram with Laravel, install the specific laravel package using composer. If the base package was previously installed, it should be removed. ```bash composer require nutgram/laravel # remove the base package if you have installed it: # composer remove nutgram/nutgram ``` -------------------------------- ### Initialize Nutgram Configuration Source: https://nutgram.dev/docs/3.x/configuration/symfony Generates the initial configuration files for Nutgram, including `config/telegram.php` for handlers and `config/packages/nutgram.yaml` for bundle configuration. Requires running the console command. ```bash php bin/console nutgram:init ``` -------------------------------- ### Configure Nutgram Bot with Options Source: https://nutgram.dev/docs/1.x/configuration/installation Initializes the Nutgram bot with an API token and a configuration array. This allows customization of settings like API timeout. ```php use SergiX44\Nutgram\Nutgram; $config = [ 'timeout' => 10, // default in seconds, when contacting the Telegram API ]; $bot = new Nutgram('you telegram token here', $config); ``` -------------------------------- ### Initialize Fake Nutgram Instance with Handlers Source: https://nutgram.dev/docs/testing/introduction Shows how to initialize a fake Nutgram instance and register custom handlers or middleware before running tests. This setup is crucial for testing specific bot functionalities and command responses. ```php use PHPUnit\Framework\TestCase; use SergiX44\Nutgram\Testing\FakeNutgram; use SergiX44\Nutgram\Nutgram; class BotTest extends TestCase { private FakeNutgram $bot; public function setUp(): void { $this->bot = Nutgram::fake(); // your custom method to register handlers $this->bootInstance($this->bot); /* * Example: * * $this->bot->onCommand('hello', function (Nutgram $bot) { * $bot->sendMessage('Hello!'); * }); */ } public function test_retrieve_mocked_instance(): void { // define assertions $this->bot ->hearText('/hello') ->reply() ->assertReplyText('Hello!'); } } ``` -------------------------------- ### Remove Keyboard with Nutgram Source: https://nutgram.dev/docs/testing/examples This example demonstrates how to remove the user's keyboard using `ReplyKeyboardRemove`. It includes assertions to verify the message content and the call to delete the message. ```php $bot->hearText('/remove_keyboard') ->reply() ->assertReplyMessage([ 'text' => 'Removing keyboard...', 'reply_markup' => ReplyKeyboardRemove::make(true), ]) ->assertCalled('deleteMessage'); ``` ```php $bot->onCommand('remove_keyboard', function (Nutgram $bot) { $message = $bot->sendMessage( text: 'Removing keyboard...', reply_markup: ReplyKeyboardRemove::make(true), ); $message->delete(); }); ``` -------------------------------- ### Starting a Conversation Mock Source: https://nutgram.dev/docs/3.x/testing/mocking This code demonstrates how to mock the start of a conversation using `willStartConversation`. This method caches the `userId` and `chatId`, which is particularly useful when testing with `assertActiveConversation` and `assertNoConversation`. The `remember` parameter is optional. ```php ->willStartConversation(remember: true); ``` -------------------------------- ### Register Feedback Command (PHP) Source: https://nutgram.dev/docs/testing/examples This code registers the '/feedback' command to trigger the FeedbackConversation class in Nutgram. It's a simple routing mechanism to direct specific user commands to their corresponding conversation handlers. ```php $bot->onCommand('feedback', FeedbackConversation::class); ``` -------------------------------- ### Define a Basic Conversation in PHP Source: https://nutgram.dev/docs/usage/conversations This snippet demonstrates how to define a simple conversation class in PHP by extending Nutgram's `Conversation` class. It includes methods for starting the conversation, proceeding to the next step, and ending it. The `start` method initiates the conversation, and `secondStep` concludes it. It also shows how to register this conversation with a command. ```php use SergiX44\Nutgram\Conversations\Conversation; use SergiX44\Nutgram\Nutgram; class MyConversation extends Conversation { public function start(Nutgram $bot) { $bot->sendMessage('This is the first step!'); $this->next('secondStep'); } public function secondStep(Nutgram $bot) { $bot->sendMessage('Bye!'); $this->end(); } } $bot = new Nutgram($_ENV['TOKEN']); $bot->onCommand('start', MyConversation::class); $bot->run(); ``` -------------------------------- ### Handling Commands with Parameters in PHP Source: https://nutgram.dev/docs/1.x/usage/handlers Demonstrates how to handle specific commands with optional parameters using Nutgram's `onCommand` method. It shows how to define callbacks that accept and use parameters from the command. The example includes handling both commands with parameters and simple commands. ```php use SergiX44\Nutgram\Nutgram; $bot = new Nutgram($_ENV['TOKEN']); // Called when a message contains the command "/start someParameter" $bot->onCommand('start {parameter}', function (Nutgram $bot, $parameter) { $bot->sendMessage("The parameter is {$parameter}"); }); // Called on command "/help" $bot->onCommand('help', function (Nutgram $bot) { $bot->sendMessage('Help me!'); }); $bot->run(); ``` -------------------------------- ### Create and Handle Inline Keyboards with Nutgram PHP Source: https://nutgram.dev/docs/usage/keyboards This snippet demonstrates how to create an inline keyboard with buttons and handle the callback queries triggered by user interactions. It uses the `InlineKeyboardMarkup` and `InlineKeyboardButton` classes for building the keyboard and `onCallbackQueryData` for event handling. Ensure Nutgram library is installed. ```php $bot->onCommand('start', function(Nutgram $bot){ $bot->sendMessage( text: 'Welcome!', reply_markup: InlineKeyboardMarkup::make() ->addRow( InlineKeyboardButton::make('A', callback_data: 'type:a'), InlineKeyboardButton::make('B', callback_data: 'type:b') ) ); }); $bot->onCallbackQueryData('type:a', function(Nutgram $bot){ $bot->answerCallbackQuery( text: 'You selected A' ); }); $bot->onCallbackQueryData('type:b', function(Nutgram $bot){ $bot->answerCallbackQuery( text: 'You selected B' ); }); ``` -------------------------------- ### InlineMenu Class Example in PHP Source: https://nutgram.dev/docs/3.x/usage/inline_menu Demonstrates how to create and use the InlineMenu class in PHP to build an interactive menu for a bot. It shows how to set the menu text, add button rows with callback data, define a handler for button clicks, and manage subsequent actions. The example utilizes the `menuText`, `addButtonRow`, `orNext`, `showMenu`, and `end` methods of the InlineMenu class. ```php class ChooseColorMenu extends InlineMenu { public function start(Nutgram $bot) { $this->menuText('Choose a color:') ->addButtonRow(InlineKeyboardButton::make('Red', callback_data: 'red@handleColor')) ->addButtonRow(InlineKeyboardButton::make('Green', callback_data: 'green@handleColor')) ->addButtonRow(InlineKeyboardButton::make('Yellow', callback_data: 'yellow@handleColor')) ->orNext('none') ->showMenu(); } public function handleColor(Nutgram $bot) { $color = $bot->callbackQuery()->data; $this->menuText("Choosen: $color!") ->showMenu(); } public function none(Nutgram $bot) { $bot->sendMessage('Bye!'); $this->end(); } } ``` -------------------------------- ### Start Conversation with Command Handler in PHP Source: https://nutgram.dev/docs/usage/conversations This PHP code demonstrates how to initiate a Nutgram conversation directly from a command handler. It shows two methods: the first registers a conversation class (e.g., `StartConversation`) to be executed when a specific command (e.g., '/start') is received. The second method shows how to programmatically begin a conversation from within another handler using `StartConversation::begin($bot)`. ```php use SergiX44\Nutgram\StartConversation; use SergiX44\Nutgram\Nutgram; $bot = new Nutgram($_ENV['TOKEN']); $bot->onCommand('start', StartConversation::class); $bot->run(); ``` ```php use SergiX44\Nutgram\StartConversation; use SergiX44\Nutgram\Nutgram; $bot = new Nutgram($_ENV['TOKEN']); $bot->onCommand('start', function (Nutgram $bot) { // do stuff StartConversation::begin($bot); // the first step will be automatically fired }); $bot->run(); ``` -------------------------------- ### Get upload progress Source: https://nutgram.dev/docs/usage/sending_requests Demonstrates how to track the upload progress of a file. ```APIDOC ## POST /sendVideo (with progress) ### Description Sends a video to a specified chat and reports upload progress. ### Method POST ### Endpoint /sendVideo ### Parameters #### Query Parameters - **chat_id** (string|integer) - Required - Unique identifier for the target chat or username of the target channel. - **video** (InputFile) - Required - Video to send. Pass an `InputFile` object for local files. - **progressCallback** (callable) - Optional - A callback function to be executed during the upload process. ### Request Example ```php use SergiX44\Nutgram\Nutgram; use SergiX44\Nutgram\Telegram\Types\Internal\InputFile; use SergiX44\Nutgram\Telegram\Types\Progress; // Assuming Progress class exists $bot = new Nutgram($_ENV['TOKEN']); $message = $bot ->withProgress(function (Progress $progress) { echo sprintf("Uploading video: %s%% - Uploded: %s bytes of %s bytes\n", $progress->uploadPercentage(), $progress->uploadedBytes, $progress->totalUploadBytes, ); }) ->sendVideo( video: InputFile::make('video.mp4'), chat_id: 123456789 ); ``` ### Response #### Success Response (200) - **message** (Message) - An object containing the sent Message. #### Response Example ```json { "ok": true, "result": { "message_id": 1, "from": { "id": 123456789, "is_bot": true, "first_name": "Nutgram Bot", "username": "nutgram_bot" }, "chat": { "id": 123456789, "first_name": "User Name", "username": "username", "type": "private" }, "date": 1678886400, "video": { "duration": 10, "width": 640, "height": 360, "file_name": "video.mp4", "mime_type": "video/mp4", "file_id": "BAACAgIAAxkBAAEH3xZl98wO7z1o1q4z73o9q5q5q5q5q5q5q5qAAMIBAAECHgQ", "file_unique_id": "AQAD7o9q5q5q5q5q5q5q5q5q5q5q5q5qAAMIBA", "file_size": 1234567 } } } ``` ``` -------------------------------- ### Configure Nutgram Bot with API Token Source: https://nutgram.dev/docs/1.x/configuration/installation Initializes the Nutgram bot by providing your Telegram API token. This is the minimum configuration required for the bot to function. ```php use SergiX44\Nutgram\Nutgram; $bot = new Nutgram('you telegram token here'); ``` -------------------------------- ### Uploading Videos via File Resource with Nutgram Source: https://nutgram.dev/docs/usage/sending_requests Demonstrates uploading a video file using a file resource (obtained via fopen) with the sendVideo method and InputFile::make(). The framework manages the file upload from the resource. Ensure the file is opened in the correct mode and the Nutgram instance is initialized. ```php use SergiX44\Nutgram\Nutgram; use SergiX44\Nutgram\Telegram\Types\Internal\InputFile; use SergiX44\Nutgram\Telegram\Types\Message\Message; $bot = new Nutgram($_ENV['TOKEN']); $message = $bot->sendVideo( video: InputFile::make(fopen('funnyvideo.mp4', 'r+')), chat_id: 123456789 ); ``` -------------------------------- ### Configure Nutgram Cache Pool Source: https://nutgram.dev/docs/3.x/configuration/symfony Defines a Redis cache pool named `nutgram.cache` for the Nutgram framework. This requires the `symfony/cache` component to be installed. ```yaml # config/packages/cache.yaml framework: cache: # ... pools: nutgram.cache: adapter: cache.adapter.redis # or whatever adapter you want tags: true ``` -------------------------------- ### Create Inline Keyboard with Callbacks (PHP) Source: https://nutgram.dev/docs/3.x/usage/keyboards Demonstrates how to create an inline keyboard with buttons that trigger specific callback queries. It uses the InlineKeyboardMarkup and InlineKeyboardButton classes. The bot responds to callback data by answering the query. ```PHP $bot->onCommand('start', function(Nutgram $bot){ $bot->sendMessage('Welcome!', [ 'reply_markup' => InlineKeyboardMarkup::make() ->addRow( InlineKeyboardButton::make('A', callback_data: 'type:a'), InlineKeyboardButton::make('B', callback_data: 'type:b') ) ]); }); $bot->onCallbackQueryData('type:a', function(Nutgram $bot){ $bot->answerCallbackQuery([ 'text' => 'You selected A' ]); }); $bot->onCallbackQueryData('type:b', function(Nutgram $bot){ $bot->answerCallbackQuery([ 'text' => 'You selected B' ]); }); ``` -------------------------------- ### Get Bot Information - PHP Source: https://nutgram.dev/docs/2.x/usage/sending_requests Retrieves basic information about the bot, such as its user ID and username. This method does not require any parameters and returns a User object. ```php getMe(); if ($me) { echo "Bot username: " . $me->username; } ``` -------------------------------- ### Inject Nutgram Instance in Controller Source: https://nutgram.dev/docs/configuration/laravel The Nutgram framework instance can be accessed anywhere within your Laravel application via the dependency injection container, as demonstrated in this example controller. ```php