### Install PHPTG Transport PSR with Composer Source: https://github.com/phptg/transport-psr/blob/master/README.md Installs the PHPTG Transport PSR package using Composer. This is the primary method for adding the library to your PHP project. ```shell composer require phptg/transport-psr ``` -------------------------------- ### Install PSR-18 HTTP Client and PSR-17 Factories Source: https://github.com/phptg/transport-psr/blob/master/README.md Installs a PSR-18 HTTP client (php-http/curl-client) and PSR-17 HTTP factories (httpsoft/http-message) required for the PSR transport implementation. These are necessary dependencies for the `PsrTransport` class. ```shell composer require php-http/curl-client httpsoft/http-message ``` -------------------------------- ### Install PHPTG Transport PSR and Dependencies Source: https://context7.com/phptg/transport-psr/llms.txt Installs the PHPTG Transport PSR package along with a PSR-18 HTTP client and PSR-17 factories using Composer. This sets up the necessary components for integrating with the Telegram Bot API. ```bash # Install the transport package composer require phptg/transport-psr # Install a PSR-18 client and PSR-17 factories (example with php-http/curl-client and httpsoft/http-message) composer require php-http/curl-client httpsoft/http-message ``` -------------------------------- ### Complete Telegram Webhook Handler in PHP Source: https://context7.com/phptg/transport-psr/llms.txt This PHP class, `TelegramWebhookHandler`, demonstrates a complete webhook handler for the Telegram Bot API. It utilizes `PsrWebhookResponseFactory` and `PsrUpdateFactory` to process incoming requests and generate responses conforming to PSR-7. It handles message parsing, command routing (start, help), and echo functionality, as well as callback query responses. ```php responseFactory = new PsrWebhookResponseFactory( new ResponseFactory(), new StreamFactory() ); } public function handle(ServerRequestInterface $request): ResponseInterface { // Parse incoming update $update = PsrUpdateFactory::create($request); // Handle message updates if ($update->message !== null) { $message = $update->message; $chatId = $message->chat->id; $text = $message->text ?? ''; // Command handling return match (true) { str_starts_with($text, '/start') => $this->handleStart($chatId), str_starts_with($text, '/help') => $this->handleHelp($chatId), default => $this->handleEcho($chatId, $text), }; } // Handle callback queries if ($update->callbackQuery !== null) { return $this->responseFactory->byMethod( new AnswerCallbackQuery( callbackQueryId: $update->callbackQuery->id, text: 'Action processed!', ) ); } // Empty response for unhandled updates return (new ResponseFactory())->createResponse(200); } private function handleStart(int $chatId): ResponseInterface { return $this->responseFactory->byMethod( new SendMessage( chatId: $chatId, text: "Welcome! I'm a bot built with PHPTG Transport PSR.\n\nUse /help to see available commands.", parseMode: 'HTML', ) ); } private function handleHelp(int $chatId): ResponseInterface { return $this->responseFactory->byMethod( new SendMessage( chatId: $chatId, text: "Available commands:\n/start - Start the bot\n/help - Show this help", parseMode: 'HTML', ) ); } private function handleEcho(int $chatId, string $text): ResponseInterface { return $this->responseFactory->byMethod( new SendMessage( chatId: $chatId, text: "You said: " . $text, ) ); } } ``` -------------------------------- ### Configure and Use PSR Transport with TelegramBotApi (PHP) Source: https://github.com/phptg/transport-psr/blob/master/README.md Demonstrates how to instantiate and use the `PsrTransport` with the `TelegramBotApi`. It requires setting up PSR-17 factories and a PSR-18 HTTP client before initializing the `TelegramBotApi` with the custom transport. ```php use Http\Client\Curl\Client; use HttpSoft\Message\RequestFactory; use HttpSoft\Message\ResponseFactory; use HttpSoft\Message\StreamFactory; use Phptg\BotApi\TelegramBotApi; use Phptg\TransportPsr\PsrTransport; $streamFactory = new StreamFactory(); $responseFactory = new ResponseFactory(); $requestFactory = new RequestFactory(); $client = new Client($responseFactory, $streamFactory); $transport = new PsrTransport( $client, $requestFactory, $streamFactory ); $api = new TelegramBotApi( token: '110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw', transport: $transport, ); // Now you can use the API as usual $api->sendMessage( chatId: 123456789, text: 'Hello from PSR transport!', ); ``` -------------------------------- ### Download Files from Telegram using PsrTransport::downloadFile (PHP) Source: https://context7.com/phptg/transport-psr/llms.txt Illustrates the usage of the `downloadFile` method within the `PsrTransport` class to retrieve files from Telegram servers. It shows how to obtain a stream resource, read its content, save it to a local file, and handle potential `DownloadFileException` errors. ```php /photos/file_123.jpg'; $stream = $transport->downloadFile($fileUrl); // Read content from the stream resource $content = stream_get_contents($stream); // Save to local file file_put_contents('/path/to/downloaded_file.jpg', $content); // Close the stream fclose($stream); } catch (DownloadFileException $e) { echo "Failed to download file: " . $e->getMessage(); } ``` -------------------------------- ### Create PSR-7 Webhook Response (PHP) Source: https://github.com/phptg/transport-psr/blob/master/README.md Shows how to use `PsrWebhookResponseFactory` to create PSR-7 compliant HTTP responses for webhook handlers. It can create responses from a `WebhookResponse` object or directly from a Telegram Bot API method. ```php use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\StreamFactoryInterface; use Phptg\BotApi\Method\SendMessage; use Phptg\BotApi\WebhookResponse\PsrWebhookResponseFactory; use Phptg\BotApi\WebhookResponse\WebhookResponse; /** * @var ResponseFactoryInterface $responseFactory * @var StreamFactoryInterface $streamFactory */ $factory = new PsrWebhookResponseFactory($responseFactory, $streamFactory); // Create response from WebhookResponse object $webhookResponse = new WebhookResponse(new SendMessage(chatId: 12345, text: 'Hello!')); $response = $factory->create($webhookResponse); // Or create response directly from method, if you are sure that InputFile is not used $method = new SendMessage(chatId: 12345, text: 'Hello!'); $response = $factory->byMethod($method); ``` -------------------------------- ### Use PsrTransport for Telegram Bot API Requests (PHP) Source: https://context7.com/phptg/transport-psr/llms.txt Demonstrates how to initialize and use the PsrTransport class to interact with the Telegram Bot API. It shows setting up PSR-17 factories, a PSR-18 HTTP client, and then using the transport to send text messages, photos with captions, and retrieve bot information. ```php sendMessage( chatId: 123456789, text: 'Hello from PSR transport!', ); // Send a photo with caption $photoStream = $streamFactory->createStream(file_get_contents('/path/to/photo.png')); $result = $api->sendPhoto( chatId: 123456789, photo: new InputFile($photoStream, 'photo.png'), caption: 'Check out this photo!', ); // Get bot information $me = $api->getMe(); echo "Bot username: " . $me->username; ``` -------------------------------- ### Enable Sending Files from PSR-7 Streams - PHP Source: https://github.com/phptg/transport-psr/blob/master/README.md The StreamResourceReader handles PSR-7 StreamInterface instances, enabling the transport to send files directly from these streams. It is passed to the transport during its initialization. ```php use Phptg\BotApi\Transport\NativeTransport; use Phptg\TransportPsr\StreamResourceReader; $transport = new NativeTransport( resourceReaders: [ new StreamResourceReader(), ], ); ``` -------------------------------- ### Create PSR-7 Webhook Responses with PsrWebhookResponseFactory Source: https://context7.com/phptg/transport-psr/llms.txt The `PsrWebhookResponseFactory` simplifies the creation of PSR-7 compliant HTTP responses for Telegram webhook handlers. It automatically encodes method calls into JSON and sets the necessary `Content-Type` and `Content-Length` headers, requiring PSR-17 factories. ```php create($webhookResponse); // Response headers will be: // Content-Type: application/json; charset=utf-8 // Content-Length: // Method 2: Create response directly from a method (convenience shorthand) $method = new SendMessage( chatId: 123456789, text: 'Quick reply!', parseMode: 'HTML', ); $response = $factory->byMethod($method); // Response body will be JSON: // {"method":"sendMessage","chat_id":123456789,"text":"Quick reply!","parse_mode":"HTML"} // Example: Respond to a callback query $callbackResponse = $factory->byMethod( new AnswerCallbackQuery( callbackQueryId: 'query_123', text: 'Button clicked!', showAlert: true, ) ); // Return the PSR-7 response in your framework's request handler return $response; ``` -------------------------------- ### Send Files with PsrTransport Source: https://context7.com/phptg/transport-psr/llms.txt The `postWithFiles` method within `PsrTransport` is used to send multipart form data requests, primarily for uploading files to Telegram. It handles the creation of multipart streams with correct boundaries and content types, requiring PSR-17 factories and an HTTP client. ```php createStream(file_get_contents('/path/to/document.pdf')); $result = $api->sendDocument( chatId: 123456789, document: new InputFile($documentStream, 'report.pdf'), caption: 'Here is your report', ); // Upload a photo with thumbnail $photoStream = $streamFactory->createStream(file_get_contents('/path/to/photo.jpg')); $thumbStream = $streamFactory->createStream(file_get_contents('/path/to/thumb.jpg')); $result = $api->sendPhoto( chatId: 123456789, photo: new InputFile($photoStream, 'photo.jpg'), caption: 'Photo with custom thumbnail', ); // Upload a video with all metadata $videoStream = $streamFactory->createStream(file_get_contents('/path/to/video.mp4')); $result = $api->sendVideo( chatId: 123456789, video: new InputFile($videoStream, 'video.mp4'), caption: 'Check out this video!', duration: 120, width: 1920, height: 1080, ); ``` -------------------------------- ### Create Update Object from PSR-7 Request - PHP Source: https://github.com/phptg/transport-psr/blob/master/README.md The PsrUpdateFactory creates Update objects from PSR-7 server requests, commonly used in webhook handlers. It takes a ServerRequestInterface as input and returns an Update object. ```php use Phptg\TransportPsr\PsrUpdateFactory; use Psr\Http\Message\ServerRequestInterface; /** * @var ServerRequestInterface $request */ $update = PsrUpdateFactory::create($request); // Now you can use the Update object $message = $update->message; ``` -------------------------------- ### Read PSR-7 Stream Interface Content Source: https://context7.com/phptg/transport-psr/llms.txt The StreamResourceReader checks if a given value is a PSR-7 StreamInterface and provides methods to read its content and retrieve its URI. It's designed to work with transport implementations that need to send files represented by streams. ```php createStream('file content here'); // Check if resource is supported if ($reader->supports($stream)) { // Read content from the stream (automatically rewinds if seekable) $content = $reader->read($stream); echo "Content: " . $content . "\n"; // Get stream URI metadata $uri = $reader->getUri($stream); echo "URI: " . $uri . "\n"; // e.g., "php://temp" } // Supports check returns false for non-StreamInterface values $reader->supports('string'); // false $reader->supports(123); // false $reader->supports(null); // false $reader->supports(new stdClass()); // false $reader->supports($stream); // true // Use with NativeTransport to enable PSR-7 stream file uploads $transport = new NativeTransport( resourceReaders: [ new StreamResourceReader(), // Add other resource readers as needed ], ); // Example: Reading from different stream types $tempStream = $streamFactory->createStream('temp content'); $fileStream = $streamFactory->createStreamFromFile('/path/to/file.txt', 'r'); // Both can be read by StreamResourceReader echo $reader->read($tempStream); // "temp content" echo $reader->read($fileStream); // Contents of file.txt ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.