### Install TeleBot via Composer Source: https://github.com/westacks/telebot/blob/4.x/docs/installation.md Use this command to install the TeleBot package in your project. ```bash composer require westacks/telebot ``` -------------------------------- ### Streaming with Throttling Example Source: https://github.com/westacks/telebot/blob/4.x/docs/rate-limit.md Example of using rateLimit to throttle streaming AI responses to the user. ```php update->type('message'); } public function handle() { $stream = Prism::text() ->using('openai', 'gpt-5') ->withPrompt($this->update->message->text) ->asStream(); $buffer = ''; $draftId = time(); foreach ($stream as $event) { if ($event->type() === StreamEventType::TextDelta) { $buffer .= $event->delta; if ($this->rateLimit()) { $this->sendRichMessageDraft([ 'draft_id' => $draftId, 'rich_message' => [ 'markdown' => $buffer, ], ]); } } else if ($event->type() === StreamEventType::StreamEnd) { $this->sendRichMessage([ 'rich_message' => [ 'markdown' => $buffer, ], ]); } } return true; } } ``` -------------------------------- ### Initialize and use TeleBot Source: https://github.com/westacks/telebot/blob/4.x/docs/installation.md Basic implementation showing how to instantiate the TeleBot class with a token and execute an API method. ```php use WeStacks\TeleBot\TeleBot; $bot = new TeleBot('YOUR_BOT_TOKEN'); $bot->getMe(); ``` -------------------------------- ### Instantiate BotManager Source: https://github.com/westacks/telebot/blob/4.x/docs/upgrade/3.x-4.x.md The BotManager constructor now requires two parameters instead of a single array. ```php $bot = new BotManager([ 'default' => 'primary', 'bots' => [ 'primary' => new TeleBot('YOUR_BOT1_TOKEN'), 'secondary' => [ 'token' => 'YOUR_BOT2_TOKEN', 'name' => 'MyBot2' ] ] ]); ``` ```php $bot = new BotManager([ 'primary' => new TeleBot('YOUR_BOT1_TOKEN'), 'secondary' => ['token' => 'YOUR_BOT2_TOKEN', 'name' => 'MyBot2'] ], 'primary'); ``` -------------------------------- ### Create a Command Handler Source: https://github.com/westacks/telebot/blob/4.x/docs/updates.md Extend CommandHandler to define bot commands with aliases and descriptions. ```php sendMessage([ 'text' => 'Hello, World!' ]); } } ``` -------------------------------- ### Implement CommandHandler Source: https://github.com/westacks/telebot/blob/4.x/docs/upgrade/3.x-4.x.md Aliases and descriptions for CommandHandler are now defined as static methods. ```php sendMessage([ 'text' => 'Hello, World!' ]); } } ``` -------------------------------- ### Initialize a single TeleBot instance Source: https://github.com/westacks/telebot/blob/4.x/docs/configuration.md Requires a valid Telegram bot token to instantiate the TeleBot class. ```php use WeStacks\TeleBot\TeleBot; $bot = new TeleBot([ 'token' => 'YOUR_BOT_TOKEN', // Required 'name' => 'MyBot' ]); ``` -------------------------------- ### Create Custom State Storage Source: https://github.com/westacks/telebot/blob/4.x/docs/updates.md Implement the StorageContract to define custom persistence logic for bot states. ```php value('input_state') ?? $default; } public function set(string $key, $value): bool { return User::where('telegram_id', $key)->update(['input_state' => $value]); } public function delete(string $key): bool { return $this->set($key, null); } } ``` -------------------------------- ### Configure Custom Storage Source: https://github.com/westacks/telebot/blob/4.x/docs/updates.md Register the custom storage class during TeleBot initialization. ```php $bot = new TeleBot([ 'token' => '', 'storage' => \App\DatabaseStorage::class, ]); ``` -------------------------------- ### Handle updates with closures Source: https://github.com/westacks/telebot/blob/4.x/docs/updates.md Use closures for simple update handling logic. Returning the result of $next() allows the pipeline to continue to subsequent handlers. ```php $handler = function(TeleBot $bot, Update $update, $next) { if ($update->message->text === '/start') { return $bot->sendMessage( chat_id: $update->chat()->id, text: 'Hello, World!' ); } return $next(); }; ``` -------------------------------- ### Manage multiple bots with BotManager Source: https://github.com/westacks/telebot/blob/4.x/docs/configuration.md Allows grouping multiple bot configurations and switching between them. The first bot defined is treated as the primary by default. ```php use WeStacks\TeleBot\BotManager; $bot = new BotManager([ 'primary' => new TeleBot('YOUR_BOT1_TOKEN'), 'secondary' => [ // Auto-instantiated 'token' => 'YOUR_BOT2_TOKEN', 'name' => 'MyBot2' ] ]); $bot->getMe(); // Uses primary bot (first bot) $bot->bot('secondary')->getMe(); // Uses secondary bot ``` -------------------------------- ### Customize the update pipeline with a custom Kernel Source: https://github.com/westacks/telebot/blob/4.x/docs/updates.md Extend the base Kernel class to define custom handler pipelines and manage bot commands. ```php setMyCommands([ 'commands' => $this->getLocalCommands(), 'scope' => 'default' ]); } public function deleteCommands(TeleBot $bot) { return $bot->deleteMyCommands([ 'scope' => 'default' ]); } } ``` ```php $bot = new TeleBot([ 'token' => '', 'kernel' => \App\Kernel::class ]); ``` -------------------------------- ### BotManager Methods Source: https://github.com/westacks/telebot/blob/4.x/docs/methods.md Methods for managing multiple bot instances within the BotManager. ```APIDOC ## BotManager Methods - **bot(string|int $name)**: Get a specific TeleBot instance by name. - **bots()**: Get a list of registered bot names. - **add(string|int $name, TeleBot|string|array $bot)**: Add a bot instance to the manager. - **remove(string|int $name)**: Remove a bot by name. - **default(string|int $name)**: Set the default bot. ``` -------------------------------- ### Manage multiple bots with BotManager Source: https://github.com/westacks/telebot/blob/4.x/README.md Use BotManager to interact with the default bot or switch to specific bot instances by name. ```php $manager->getMe(); // Fired by default bot specified in BotManager $manager->bot('bot2')->getMe(); // Fired by `bot2` specified in BotManager ``` -------------------------------- ### Handle updates via webhook Source: https://github.com/westacks/telebot/blob/4.x/docs/api-examples.md Processes incoming updates by reading the raw input stream. ```php $update = WeStacks\TeleBot\Objects\Update::from(file_get_contents('php://input')); $bot->handle($update); ``` -------------------------------- ### Handle exceptions with default values Source: https://github.com/westacks/telebot/blob/4.x/docs/methods.md Uses the _rescue parameter to define a callback for handling exceptions instead of using try/catch blocks. ```php $result = $bot->getMe(_rescue: fn (\Throwable $e) => $e); var_dump($result); // Will be return value of _rescue callback in case of exception ``` -------------------------------- ### Work with promises Source: https://github.com/westacks/telebot/blob/4.x/docs/api-examples.md Executes asynchronous requests and handles the result using promise chains. ```php $promise = $bot->getMe(_promise: true); $promise->then(function (User $user) { echo $user->first_name; })->wait(); ``` -------------------------------- ### Register Commands on Telegram Source: https://github.com/westacks/telebot/blob/4.x/docs/updates.md Manage local command registration on the Telegram platform. ```php $bot->setLocalCommands(); $bot->deleteLocalCommands(); ``` -------------------------------- ### Configure Guzzle promises for TeleBot methods Source: https://github.com/westacks/telebot/blob/4.x/docs/methods.md Enables asynchronous request handling by setting the _promise parameter to true. ```php $promise = $bot->getMe(_promise: true); $promise->then(fn (User $user) => var_dump($user))->wait(); ``` -------------------------------- ### Implement CallbackHandler for Query Management Source: https://github.com/westacks/telebot/blob/4.x/docs/updates.md Extend CallbackHandler to process specific callback queries using regex matching for arguments. ```php arguments(); match ($action) { 'update' => $this->update($id), 'delete' => $this->delete($id), }; $this->answerCallbackQuery(); } } ``` -------------------------------- ### Send a text message with TeleBot Source: https://github.com/westacks/telebot/blob/4.x/docs/api-examples.md Initializes the TeleBot instance and sends a basic text message to a specified chat ID. ```php use WeStacks\TeleBot\TeleBot; $bot = new TeleBot('YOUR_BOT_TOKEN'); $bot->sendMessage([ 'chat_id' => 123456789, 'text' => 'Hello, World!', ]); ``` -------------------------------- ### Execute Telegram API methods with TeleBot Source: https://github.com/westacks/telebot/blob/4.x/docs/methods.md Demonstrates calling the sendMessage method using either named arguments or an associative array. ```php $bot = new TeleBot(''); // See docs for details: https://core.telegram.org/bots/api#sendmessage $message = $bot->sendMessage( chat_id: 1234567890, text: 'Test message', reply_markup: [ 'inline_keyboard' => [[[ 'text' => 'Google', 'url' => 'https://google.com/' ]]] ] ); ``` ```php $bot = new TeleBot(''); // See docs for details: https://core.telegram.org/bots/api#sendmessage $message = $bot->sendMessage([ 'chat_id' => 1234567890, 'text' => 'Test message', 'reply_markup' => [ 'inline_keyboard' => [[[ 'text' => 'Google', 'url' => 'https://google.com/' ]]] ] ]); ``` -------------------------------- ### Interacting with Update DTO properties Source: https://github.com/westacks/telebot/blob/4.x/docs/objects.md Demonstrates accessing nested properties, using dot notation, iterating over object properties, and converting to JSON or array formats. ```php // 🔗 Accessing nested properties (standard chaining) $chatId = $update->message->from->id; // 3456789 // 📍 Using dot notation (safe, readable) $chatId = $update->get('message.from.is_bot'); // false // 🔁 Iterating over properties foreach ($update->message->from as $prop => $value) { echo "$prop => $value\n"; // id => 3456789 // is_bot => false // first_name => 'John' // last_name => 'Doe' } // 🔄 JSON representation $jsonUpdate = $update->toJson(); // 🔃 Array representation $arrayUpdate = $update->toArray(); ``` -------------------------------- ### Error Handling Source: https://github.com/westacks/telebot/blob/4.x/docs/methods.md Handle exceptions gracefully using the _rescue parameter. ```APIDOC ## TeleBot Error Handling ### Description Use the `_rescue` parameter to define a callback that executes if an exception occurs during the API call. ### Example ```php $result = $bot->getMe(_rescue: fn (\Throwable $e) => $e); ``` ``` -------------------------------- ### RateLimit method signature Source: https://github.com/westacks/telebot/blob/4.x/docs/rate-limit.md The method signature for the rateLimit function. ```php protected function rateLimit(float $seconds = 1): bool ``` -------------------------------- ### Handle updates with UpdateHandler classes Source: https://github.com/westacks/telebot/blob/4.x/docs/updates.md Implement complex logic by extending the UpdateHandler class. Returning a value from handle() stops the pipeline execution. ```php update->type('message'); } public function handle() { return $this->sendMessage( text: 'Hello, World!' ); } } ``` -------------------------------- ### Implement functional and object-oriented update handlers Source: https://github.com/westacks/telebot/blob/4.x/README.md Define update logic using either functional closures or by extending the CommandHandler class. ```php // Functional handler $handler = function(TeleBot $bot, Update $update, $next) { if ($update->message->text === '/start') { return $bot->sendMessage([ 'chat_id' => $update->chat()->id, 'text' => 'Hello, World!' ]); } return $next(); }; // Object oriented handler class YourUpdateHandler extends CommandHandler { protected static function aliases(): string { return ['/start']; } protected static function description(?string $locale = null) { return 'Start command'; } public function handle() { return $this->sendMessage([ 'text' => 'Hello, World!' ]); } } ``` -------------------------------- ### Register handlers in TeleBot Source: https://github.com/westacks/telebot/blob/4.x/docs/updates.md Register handlers during bot initialization or dynamically using the handler() method. ```php $bot = new TeleBot([ 'token' => '', 'kernel' => [ \App\YourUpdateHandler::class, $handler ] ]); // Or add later $bot->handler(\App\YourUpdateHandler::class); $bot->handler($handler); ``` -------------------------------- ### Simulate Telegram API responses with fake Source: https://github.com/westacks/telebot/blob/4.x/docs/testing.md Use the fake method to provide a sequence of TeleBotResponse objects that the bot will return instead of making real network requests. This is useful for testing multi-step handler logic and state transitions. ```php use Tests\Lib\AskNameHandler; use Tests\Lib\PopupHandler; use WeStacks\TeleBot\Foundation\TeleBotResponse; use WeStacks\TeleBot\Objects; use WeStacks\TeleBot\TeleBot; $bot = new TeleBot('test'); $bot->fake([ TeleBotResponse::make(Objects\Message::from([ 'message_id' => 2, 'date' => 1, 'chat' => [ 'id' => 1, 'type' => 'private', ], 'text' => 'Please enter your name.', ])), TeleBotResponse::make(Objects\Message::from([ 'message_id' => 4, 'date' => 2, 'chat' => [ 'id' => 1, 'type' => 'private', ], 'text' => 'Sorry, I don\'t know you.', ])), TeleBotResponse::make(Objects\Message::from([ 'message_id' => 6, 'date' => 4, 'chat' => [ 'id' => 1, 'type' => 'private', ], 'text' => 'Hello, John!', ])), ]); $bot->handler(AskNameHandler::class) ->handler(function (TeleBot $bot, Objects\Update $update, callable $next) { if ($update->message()->text !== '/test' ?? null) { return $next(); } AskNameHandler::request($bot, $update->user()); return $bot->sendMessage( chat_id: $update->chat()->id, text: 'Please enter your name.', ); }); $initialUpdate = Objects\Update::from([ 'update_id' => 1, 'message' => [ 'message_id' => 1, 'text' => '/test', 'from' => [ 'id' => 1, 'is_bot' => false, 'first_name' => 'Alan', ], 'chat' => [ 'id' => 1, 'type' => 'private', ], 'date' => 1, 'entities' => [ [ 'type' => 'bot_command', 'offset' => 0, 'length' => 5 ] ] ], ]); $wrongNameUpdate = Objects\Update::from([ 'update_id' => 2, 'message' => [ 'message_id' => 3, 'text' => 'Alan', 'from' => [ 'id' => 1, 'is_bot' => false, 'first_name' => 'Alan', ], 'chat' => [ 'id' => 1, 'type' => 'private', ], 'date' => 2, ] ]); $correctNameUpdate = Objects\Update::from([ 'update_id' => 3, 'message' => [ 'message_id' => 5, 'text' => 'John', 'from' => [ 'id' => 1, 'is_bot' => false, 'first_name' => 'Alan', ], 'chat' => [ 'id' => 1, 'type' => 'private', ], 'date' => 4, ] ]); $res = $bot->handle($initialUpdate); expect($res)->toBeInstanceOf(Objects\Message::class); expect($res->text)->toBe('Please enter your name.'); $res = $bot->handle($wrongNameUpdate); expect($res)->toBeInstanceOf(Objects\Message::class); expect($res->text)->toBe('Sorry, I don\'t know you.'); $res = $bot->handle($correctNameUpdate); expect($res)->toBeInstanceOf(Objects\Message::class); expect($res->text)->toBe('Hello, John!'); ``` -------------------------------- ### Request User Input Source: https://github.com/westacks/telebot/blob/4.x/docs/updates.md Trigger the input request handler within a middleware or command flow. ```php $handler = function ($bot, $update, $next) { if ('/test' !== $update->message()->text ?? null) { return $next(); } AskNameHandler::request($bot, $update->user()); return $bot->sendMessage([ 'chat_id' => $update->chat()->id, 'text' => 'Please, type your name.', ]); }; ``` -------------------------------- ### Create an Input Request Handler Source: https://github.com/westacks/telebot/blob/4.x/docs/updates.md Extend RequestInputHandler to process and validate user input. ```php update->message()->toArray(); $validator = Validator::make($data, [ 'text' => 'required|string|max:255' ]); if ($validator->fails()) { return $this->sendMessage([ 'text' => 'Invalid input!' ]); } $this->accept(); $name = $validator->validated()['text']; return $this->sendMessage([ 'text' => "Hello, $name!", ]); } } ``` -------------------------------- ### Set a default bot in BotManager Source: https://github.com/westacks/telebot/blob/4.x/docs/configuration.md Explicitly define the default bot name as the second argument to the BotManager constructor. ```php $bot = new BotManager([ 'primary' => new TeleBot('YOUR_BOT1_TOKEN'), 'secondary' => ['token' => 'YOUR_BOT2_TOKEN', 'name' => 'MyBot2'], ], 'secondary'); $bot->getMe(); // Uses secondary bot (now the default) ``` -------------------------------- ### Handle errors gracefully Source: https://github.com/westacks/telebot/blob/4.x/docs/api-examples.md Uses the _rescue parameter to catch and handle exceptions during API calls. ```php // Use _rescue to handle exceptions gracefully $result = $bot->sendMessage( _rescue: fn (Throwable $e) => null, chat_id: 123456789, text: 'Hello!', ); if ($result === null) { // Handle error } ``` -------------------------------- ### TeleBot Helper Methods Source: https://github.com/westacks/telebot/blob/4.x/docs/methods.md Additional helper methods provided by the TeleBot class for managing updates and commands. ```APIDOC ## TeleBot Helper Methods - **handle(Update $update)**: Handle a Telegram Update using registered handlers. - **handler($handler)**: Register a new update handler. - **purge()**: Recreate bot kernel and remove all handlers. - **setLocalCommands()**: Push locally registered bot commands to Telegram. - **deleteLocalCommands()**: Remove registered commands from Telegram. ``` -------------------------------- ### Access nested object properties Source: https://github.com/westacks/telebot/blob/4.x/docs/api-examples.md Demonstrates various ways to access and transform update object data, including chaining, dot notation, and serialization. ```php $update = WeStacks\TeleBot\Objects\Update::from($telegramResponse); // Standard chaining $chatId = $update->message->chat->id; // Dot notation $text = $update->get('message.text'); // JSON $json = $update->toJson(); // Array $array = $update->toArray(); ``` -------------------------------- ### Apply RateLimit trait to UpdateHandler Source: https://github.com/westacks/telebot/blob/4.x/docs/rate-limit.md Include the RateLimit trait in your handler class to enable throttling capabilities. ```php use WeStacks eleBot oundation𝓤pdateHandler; use WeStacks eleBot oundation𝓤ateLimit; class ChatHandler extends UpdateHandler { use RateLimit; public function handle() { // Your handler logic here // Call $this->rateLimit() to throttle operations } } ``` -------------------------------- ### Send a photo Source: https://github.com/westacks/telebot/blob/4.x/docs/api-examples.md Sends an image file from a URL with an optional caption. ```php $bot->sendPhoto([ 'chat_id' => 123456789, 'photo' => 'https://example.com/image.jpg', 'caption' => 'Check out this image!', ]); ``` -------------------------------- ### Handle Updates via Webhook or Polling Source: https://github.com/westacks/telebot/blob/4.x/docs/updates.md Configure webhook endpoints or initiate a polling loop to receive and process Telegram updates. ```php $bot->setWebhook([ 'url' => 'https://example.com/webhook.php' ]); $bot->handle( \WeStacks\TeleBot\Objects\Update::from(file_get_contents('php://input')) ); ``` ```php foreach ($bot->poll() as $update) { $bot->handle($update); } ``` -------------------------------- ### Asynchronous Requests Source: https://github.com/westacks/telebot/blob/4.x/docs/methods.md Configure TeleBot methods to return Guzzle promises for non-blocking execution. ```APIDOC ## TeleBot Asynchronous Execution ### Description By passing `_promise: true` to a method, the call returns a Guzzle promise instead of executing immediately. ### Example ```php $promise = $bot->getMe(_promise: true); $promise->then(fn (User $user) => var_dump($user))->wait(); ``` ``` -------------------------------- ### Implement UpdateHandler Source: https://github.com/westacks/telebot/blob/4.x/docs/upgrade/3.x-4.x.md The trigger method in UpdateHandler is now strictly typed to return a boolean. ```php rateLimit(3)) { // Send progress update } ``` -------------------------------- ### TeleBot Method Execution Source: https://github.com/westacks/telebot/blob/4.x/docs/methods.md TeleBot supports all official Telegram Bot API methods using either named arguments or array syntax. ```APIDOC ## TeleBot::sendMessage ### Description Sends a message to a specific chat using the Telegram Bot API. ### Usage ```php $bot = new TeleBot(''); // Named arguments $message = $bot->sendMessage( chat_id: 1234567890, text: 'Test message' ); // Array syntax $message = $bot->sendMessage([ 'chat_id' => 1234567890, 'text' => 'Test message' ]); ``` ``` -------------------------------- ### Handle updates via long polling Source: https://github.com/westacks/telebot/blob/4.x/docs/api-examples.md Continuously polls for new updates and processes them sequentially. ```php foreach ($bot->poll() as $update) { $bot->handle($update); } ``` -------------------------------- ### Send a message with inline keyboard Source: https://github.com/westacks/telebot/blob/4.x/docs/api-examples.md Sends a message containing an inline keyboard structure for user interaction. ```php $bot->sendMessage([ 'chat_id' => 123456789, 'text' => 'Choose an option:', 'reply_markup' => [ 'inline_keyboard' => [ [ ['text' => 'Option 1', 'callback_data' => 'option_1'], ['text' => 'Option 2', 'callback_data' => 'option_2'], ], [ ['text' => 'Cancel', 'callback_data' => 'cancel'], ], ], ], ]); ``` -------------------------------- ### rateLimit(float $seconds = 1): bool Source: https://github.com/westacks/telebot/blob/4.x/docs/rate-limit.md The rateLimit method is used to throttle code execution within an UpdateHandler. It returns true if the specified interval has passed since the last successful call, and false otherwise. ```APIDOC ## rateLimit(float $seconds = 1): bool ### Description Checks if the specified interval has elapsed since the last call to allow throttled execution of code within an update handler. ### Parameters - **$seconds** (float) - Optional (Default: 1) - The minimum interval in seconds between allowed operations. ### Returns - **bool** - Returns true if the interval has elapsed, false otherwise. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.