### Install phptg/bot-api with Composer Source: https://github.com/phptg/bot-api/blob/master/README.md Install the package using Composer. Ensure you have PHP 64-bit version 8.2 or higher. ```shell composer require phptg/bot-api ``` -------------------------------- ### Initialize TelegramBotApi with CurlTransport Source: https://github.com/phptg/bot-api/blob/master/docs/transport.md Use CurlTransport for making API requests. It's often the default choice as the cURL extension is widely available in PHP installations. ```php use Phptg\BotApi\TelegramBotApi; use Phptg\BotApi\Transport\CurlTransport; // Telegram bot authentication token $token = '110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw'; $transport = new CurlTransport(); $api = new TelegramBotApi($token, transport: $transport); ``` -------------------------------- ### Get Updates Source: https://github.com/phptg/bot-api/blob/master/README.md Retrieve updates from the Telegram Bot API. The result is an array of `Update` objects. ```php // Result is an array of `Phptg\BotApi\Update\Update` objects $updates = $api->getUpdates(); ``` -------------------------------- ### Get Raw Update Data Source: https://github.com/phptg/bot-api/blob/master/docs/webhook-handling.md Retrieve the raw JSON string or decoded array of an `Update` object. Useful for debugging or accessing original payload. ```php /** * @var Phptg\BotApi\Type\Update\Update $update */ /** * @var string $raw Raw data, for example: * * {"update_id":33991112,"message":{"message_id":422,"from":{"id":1234567,"is_bot":false,"first_name":"John","last_name":"Doe","username":"john_doe","language_code":"ru","is_premium":true},"chat":{"id":1234567,"first_name":"John","last_name":"Doe","username":"john_doe","type":"private"},"date":1720523588,"text":"Hello!"}} */ $raw = $update->getRaw(); /** * @var array $raw Decoded raw data, for example: * * [ * 'update' => 33991112, * 'message' => [ * 'message_id' => 422, * 'from' => [ * 'id' => 1234567, * 'is_bot' => false, * 'first_name' => 'John', * 'last_name' => 'Doe', * 'username' => 'john_doe', * 'language_code' => 'ru', * 'is_premium' => true, * ], * 'chat' => [ * 'id' => 1234567, * 'first_name' => 'John', * 'last_name' => 'Doe', * 'username' => 'john_doe', * 'type' => 'private', * ], * 'date' => 1720523588, * 'text' => 'Hello!' * ], * ] */ $raw = $update->getRaw(decoded: true); ``` -------------------------------- ### Run Static Analysis with Psalm Source: https://github.com/phptg/bot-api/blob/master/docs/internals.md Check your code for static analysis errors using the Psalm tool. ```shell ./vendor/bin/psalm ``` -------------------------------- ### Run Unit Tests with PHPUnit Source: https://github.com/phptg/bot-api/blob/master/docs/internals.md Execute all unit tests for the package using the PHPUnit command-line tool. ```shell ./vendor/bin/phpunit ``` -------------------------------- ### Initialize TelegramBotApi Source: https://github.com/phptg/bot-api/blob/master/README.md Create an instance of the TelegramBotApi class using your bot's authentication token. The default base URL is https://api.telegram.org. ```php use Phptg\BotApi\TelegramBotApi; // API $api = new TelegramBotApi( // Telegram bot authentication token '110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw' ); ``` -------------------------------- ### General Usage Source: https://github.com/phptg/bot-api/blob/master/README.md Instantiate the TelegramBotApi class and use its methods to interact with the Telegram Bot API. Method names correspond to the official Telegram Bot API documentation. ```php use Phptg\BotApi\TelegramBotApi; // API $api = new TelegramBotApi( // Telegram bot authentication token '110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw' ); // Specify a URL for outgoing webhook $api->setWebhook('https://example.com/webhook'); // Send text message $api->sendMessage( chatId: 22351, text: 'Hello, world!', ); // Send local photo $api->sendPhoto( chatId: 22351, photo: new InputFile('/path/to/photo.jpg'), ); // Get updates $updates = $api->getUpdates(); ``` -------------------------------- ### Initialize TelegramBotApi with a Logger Source: https://github.com/phptg/bot-api/blob/master/docs/logging.md Pass a PSR-3 compatible logger instance to the `TelegramBotApi` constructor to enable logging of API requests and responses. Ensure the logger implements `Psr\Log\LoggerInterface`. ```php use Psr\Log\LoggerInterface; use Phptg\BotApi\TelegramBotApi; /** * @var string $token * @var LoggerInterface $logger */ // API $api = new TelegramBotApi($token, logger: $logger); ``` -------------------------------- ### Run Mutation Testing with Infection Source: https://github.com/phptg/bot-api/blob/master/docs/internals.md Perform mutation testing to check the effectiveness of your test suite using the Infection framework. ```shell composer infection ``` -------------------------------- ### File URL Source: https://github.com/phptg/bot-api/blob/master/README.md Use `TelegramBotApi::makeFileUrl()` to create a URL for downloading a file from the Telegram server. ```php /** * @var allageot-api elegrambotapi $api * @var allageot-api ype ile $file */ // By `File` instance $url = $api->makeFileUrl($file); // By file path is taken from the Telegram response $url = $api->makeFileUrl('photos/file_2'); ``` -------------------------------- ### TelegramBotApi Constructor Source: https://github.com/phptg/bot-api/blob/master/README.md Parameters for the TelegramBotApi constructor. ```php /** * @param string $token Telegram bot authentication token * @param string $baseUrl the base URL for Telegram Bot API requests (default https://api.telegram.org) * @param allageot-api ransport ransport|null $transport the transport to make requests to Telegram Bot API ([cURL](docs/transport.md#curl) or [native](docs/transport.md#native) transport will be used by default) * @param allageot-api ransport ransport|null $logger the [PSR-3](https://www.php-fig.org/psr/psr-3/) compatible logger to log requests to Telegram Bot API and response handling errors. See [logging](docs/logging.md) for more information. */ ``` -------------------------------- ### Create Update via Constructor Source: https://github.com/phptg/bot-api/blob/master/docs/webhook-handling.md Manually create an `Update` object using its constructor. Useful for testing or when constructing updates programmatically. ```php use Phptg\BotApi\Type\Message; use Phptg\BotApi\Type\Update\Update; /** * @var Message $message */ $update = new Update( updateId: 33436234444, message: $message, ); ``` -------------------------------- ### File Downloading Source: https://github.com/phptg/bot-api/blob/master/README.md Use `TelegramBotApi::downloadFile()` to download a file from the Telegram server. The method returns a `DownloadedFile` instance. ```php /** * @var allageot-api elegrambotapi $api * @var allageot-api ype ile $file */ // Get file content as string $content = $api->downloadFile($file)->getBody(); // Get file content as stream $stream = $api->downloadFile('photos/file_2')->getStream(); // Download and save file $api->downloadFile($file)->saveTo('/local/path/to/file.jpg'); ``` -------------------------------- ### Download and Save File Source: https://github.com/phptg/bot-api/blob/master/README.md Download a file from the Telegram server and save it to a local path. Use the `saveTo()` method on the `DownloadedFile` instance. ```php // Download and save file $api->downloadFile($file)->saveTo('/local/path/to/file.jpg'); ``` -------------------------------- ### Check and Handle Unsupported Webhook Methods Source: https://github.com/phptg/bot-api/blob/master/docs/webhook-handling.md Use this code to check if a webhook response method is supported and to catch exceptions when attempting to send files via webhook. For unsupported methods, you must make a separate API call. ```php use Phptg\BotApi\Method\SendPhoto; use Phptg\BotApi\Type\InputFile; use Phptg\BotApi\WebhookResponse\WebhookResponse; use Phptg\BotApi\WebhookResponse\MethodNotSupportedException; $method = new SendPhoto( chatId: 12345, photo: InputFile::fromLocalFile('/path/to/photo.jpg'), ); $webhookResponse = new WebhookResponse($method); if (!$webhookResponse->isSupported()) { // Method contains InputFile - cannot be sent via webhook response // You'll need to make a separate API call for this } try { $data = $webhookResponse->getData(); } catch (MethodNotSupportedException $e) { // Exception: "InputFile is not supported in Webhook response." } ``` -------------------------------- ### Send Local Photo Source: https://github.com/phptg/bot-api/blob/master/README.md Send a local photo file to a specified chat. Use `InputFile` to specify the path to the photo. ```php // Send local photo $api->sendPhoto( chatId: 22351, photo: new InputFile('/path/to/photo.jpg'), ); ``` -------------------------------- ### Initialize TelegramBotApi with NativeTransport Source: https://github.com/phptg/bot-api/blob/master/docs/transport.md Use NativeTransport for making API requests without external extensions. This requires the 'allow_url_fopen' PHP ini setting to be enabled. ```php use Phptg\BotApi\TelegramBotApi; use Phptg\BotApi\Transport\NativeTransport; // Telegram bot authentication token $token = '110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw'; $transport = new NativeTransport(); $api = new TelegramBotApi($token, transport: $transport); ``` -------------------------------- ### Create Webhook Response Source: https://github.com/phptg/bot-api/blob/master/docs/webhook-handling.md Wrap a Bot API method in a `WebhookResponse` object to prepare it for sending back in an HTTP response. Checks if the method is suitable for webhook responses. ```php use Phptg\BotApi\Method\SendMessage; use Phptg\BotApi\WebhookResponse\WebhookResponse; $method = new SendMessage(chatId: 12345, text: 'Hello!'); $webhookResponse = new WebhookResponse($method); // Check if the method is supported for webhook responses (doesn't use InputFile) if ($webhookResponse->isSupported()) { $data = $webhookResponse->getData(); // Returns: ['method' => 'sendMessage', 'chat_id' => 12345, 'text' => 'Hello!'] } ``` -------------------------------- ### Generate File URL Source: https://github.com/phptg/bot-api/blob/master/README.md Create a URL to download a file from the Telegram server. This can be done using a `File` instance or a file path string. ```php /** * @var \Phptg\BotApi\TelegramBotApi $api * @var \Phptg\BotApi\Type\File $file */ // By `File` instance $url = $api->makeFileUrl($file); // By file path is taken from the Telegram response $url = $api->makeFileUrl('photos/file_2'); ``` -------------------------------- ### Implement Custom MIME Type Resolver Source: https://github.com/phptg/bot-api/blob/master/docs/mime-type-resolvers.md Implement the MimeTypeResolverInterface to create a custom resolver. Return the MIME type as a string or null if it cannot be determined. ```php use Phptg\BotApi\Transport\MimeTypeResolver\MimeTypeResolverInterface; use Phptg\BotApi\Type\InputFile; final class MyMimeTypeResolver implements MimeTypeResolverInterface { public function resolve(InputFile $inputFile): ?string { // Return MIME type or null if it cannot be determined return null; } } ``` -------------------------------- ### Configure Real Telegram API Test Token Source: https://github.com/phptg/bot-api/blob/master/docs/internals.md Add your bot authentication token to the TOKEN constant in RealTelegramApiTest.php before running manual tests. ```php // ... final class RealTelegramApiTest extends TestCase { private const TOKEN = '110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw'; // ... ``` -------------------------------- ### Log Context for Sending Request Source: https://github.com/phptg/bot-api/blob/master/docs/logging.md When a request is sent, an 'info' message is logged with context including the log type, request payload, and the method being called. ```php [ 'type' => LogType::SEND_REQUEST, 'payload' => $payload, // Request data as array with string keys 'method' => $method, // `MethodInterface` implementation ] ``` -------------------------------- ### Detect Transitive Dependencies with ComposerRequireChecker Source: https://github.com/phptg/bot-api/blob/master/docs/internals.md Identify transitive Composer dependencies using the ComposerRequireChecker tool. ```shell ./vendor/bin/composer-require-checker ``` -------------------------------- ### Run Tests with Real Telegram Bot API Source: https://github.com/phptg/bot-api/blob/master/docs/internals.md Execute tests against the actual Telegram Bot API using PHPUnit with the 'realApi' group. ```shell ./vendor/bin/phpunit --group=realApi # or composer test-real ``` -------------------------------- ### Check and Fix Code Style with PHP CS Fixer Source: https://github.com/phptg/bot-api/blob/master/docs/internals.md Ensure code style compliance with PER CS 2.0 and automatically fix style issues using PHP CS Fixer. ```shell composer cs-fix ``` -------------------------------- ### Set Webhook Source: https://github.com/phptg/bot-api/blob/master/README.md Configure an outgoing webhook for receiving updates from Telegram. This method requires the URL where your webhook server is listening. ```php use Phptg\BotApi\Type\InputFile; // Specify a URL for outgoing webhook $api->setWebhook('https://example.com/webhook'); ``` -------------------------------- ### Download File Content Source: https://github.com/phptg/bot-api/blob/master/README.md Download a file from the Telegram server and retrieve its content as a string or a stream. The `File` instance or file path can be used. ```php /** * @var \Phptg\BotApi\TelegramBotApi $api * @var \Phptg\BotApi\Type\File $file */ // Get file content as string $content = $api->downloadFile($file)->getBody(); // Get file content as stream $stream = $api->downloadFile('photos/file_2')->getStream(); ``` -------------------------------- ### Combine Multiple MIME Type Resolvers Source: https://github.com/phptg/bot-api/blob/master/docs/mime-type-resolvers.md Use CompositeMimeTypeResolver to combine multiple MIME type resolvers. It returns the first non-null result from the provided resolvers. ```php use Phptg\BotApi\Transport\MimeTypeResolver\ApacheMimeTypeResolver; use Phptg\BotApi\Transport\MimeTypeResolver\CompositeMimeTypeResolver; use Phptg\BotApi\Transport\MimeTypeResolver\CustomMimeTypeResolver; use Phptg\BotApi\Transport\NativeTransport; $transport = new NativeTransport( mimeTypeResolver: new CompositeMimeTypeResolver( new CustomMimeTypeResolver(['webp' => 'image/webp']), new ApacheMimeTypeResolver(), ), ); ``` -------------------------------- ### Pass Custom Resolver to Transport Source: https://github.com/phptg/bot-api/blob/master/docs/mime-type-resolvers.md Instantiate your custom MIME type resolver and pass it to the NativeTransport constructor when creating the TelegramBotApi instance. ```php use Phptg\BotApi\TelegramBotApi; use Phptg\BotApi\Transport\NativeTransport; $transport = new NativeTransport( mimeTypeResolver: new MyMimeTypeResolver(), ); $api = new TelegramBotApi($token, transport: $transport); ``` -------------------------------- ### Create Update from JSON String Source: https://github.com/phptg/bot-api/blob/master/docs/webhook-handling.md Instantiate an `Update` object from a JSON string received in a POST request body. Handles potential parsing errors. ```php use Phptg\BotApi\Type\Update\Update; use Phptg\BotApi\ParseResult\TelegramParseResultException; /** * @var string $jsonString */ try { $update = Update::fromJson($jsonString); } catch (TelegramParseResultException $e) { // ... } ``` -------------------------------- ### Create Update Object with a Logger Source: https://github.com/phptg/bot-api/blob/master/docs/logging.md You can also pass a logger instance when creating an `Update` object from a JSON string. This allows for logging of potential errors during the JSON parsing process. ```php use Psr\Log\LoggerInterface; use Phptg\BotApi\Type\Update\Update; /** * @var string $jsonString * @var LoggerInterface $logger */ $update = Update::fromJson($jsonString, $logger); ``` -------------------------------- ### Making a Custom API Request Source: https://github.com/phptg/bot-api/blob/master/docs/custom-requests.md Use `CustomMethod` to define a custom API call, specifying the method name, data, expected result type, and HTTP method. The result will be an object of the specified type. ```php use Phptg\BotApi\CustomMethod; use Phptg\BotApi\ParseResult\ValueProcessor\ObjectValue; /** * @var \Phptg\BotApi\TelegramBotApi $api */ $method = new CustomMethod( apiMethod: 'getChat', data: ['chat_id' => '@sergei_predvoditelev'], resultType: new ObjectValue(ChatFullInfo::class), httpMethod: HttpMethod::GET, ); // Result is an object of `Phptg\BotApi\Type\ChatFullInfo` $result = $api->call($method); ``` -------------------------------- ### Log Context for Successful API Response Source: https://github.com/phptg/bot-api/blob/master/docs/logging.md Upon a successful API response, an 'info' message is logged. The context includes the log type, the decoded response payload, the method called, the raw API response, and the decoded response. ```php [ 'type' => LogType::SUCCESS_RESULT, 'payload' => $payload, // Decoded response body as array 'method' => $method, // `MethodInterface` implementation 'response' => $response, // `ApiResponse` object 'decodedResponse' => $decodedResponse, // Decoded response body as array ] ``` -------------------------------- ### Send Text Message Source: https://github.com/phptg/bot-api/blob/master/README.md Send a text message to a specified chat. The `chatId` and `text` parameters are required. ```php // Send text message $api->sendMessage( chatId: 22351, text: 'Hello, world!', ); ``` -------------------------------- ### Log Context for Failed API Response Source: https://github.com/phptg/bot-api/blob/master/docs/logging.md If an API response indicates an error, a 'warning' message is logged. The context contains the log type, the response body as a string, the method called, the API response object, and the decoded response. ```php [ 'type' => LogType::FAIL_RESULT, 'payload' => $payload, // Response body as string 'method' => $method, // `MethodInterface` implementation 'response' => $response, // `ApiResponse` object 'decodedResponse' => $decodedResponse, // Decoded response body as array ] ``` -------------------------------- ### JSON Webhook Response Factory Source: https://github.com/phptg/bot-api/blob/master/docs/webhook-handling.md Utilize `JsonWebhookResponseFactory` to generate JSON strings for webhook responses. Can create JSON directly from a method or a `WebhookResponse` object. ```php use Phptg\BotApi\Method\SendMessage; use Phptg\BotApi\WebhookResponse\JsonWebhookResponseFactory; use Phptg\BotApi\WebhookResponse\WebhookResponse; $factory = new JsonWebhookResponseFactory(); // Create JSON from WebhookResponse object $webhookResponse = new WebhookResponse(new SendMessage(chatId: 12345, text: 'Hello!')); $json = $factory->create($webhookResponse); // Or create JSON directly from method $method = new SendMessage(chatId: 12345, text: 'Hello!'); $json = $factory->byMethod($method); // Now you can send this JSON in your HTTP response body header('Content-Type: application/json; charset=utf-8'); echo $json; ``` -------------------------------- ### Log Context for Parse Result Error Source: https://github.com/phptg/bot-api/blob/master/docs/logging.md In case of an error while parsing the API response, an 'error' message is logged. The context includes the log type and the raw parsed data that caused the error. ```php [ 'type' => LogType::PARSE_RESULT_ERROR, 'payload' => $payload, // Raw parsed data as string ] ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.