|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types = 1); |
| 4 | + |
| 5 | +include __DIR__.'/basics.php'; |
| 6 | + |
| 7 | +use React\EventLoop\Factory; |
| 8 | +use unreal4u\TelegramAPI\HttpClientRequestHandler; |
| 9 | +use unreal4u\TelegramAPI\Telegram\Methods\SendDocument; |
| 10 | +use unreal4u\TelegramAPI\Telegram\Types\Custom\InputFile; |
| 11 | +use unreal4u\TelegramAPI\TgLog; |
| 12 | + |
| 13 | +$loop = Factory::create(); |
| 14 | +$tgLog = new TgLog(BOT_TOKEN, new HttpClientRequestHandler($loop)); |
| 15 | + |
| 16 | +// File name shown in Telegram clients has exactly same name as file is saved on system. So if we want to upload |
| 17 | +// file but with different name, we have to rename it or in this example, copy it as new name. |
| 18 | +// Later, after Telegram request is completed, temporary file can be easily deleted |
| 19 | +$tempFilePath = sprintf('%s/binary-test-data/%s/custom-file-name.txt', __DIR__, uniqid()); |
| 20 | +mkdir(dirname($tempFilePath)); |
| 21 | +copy(__FILE__, $tempFilePath); |
| 22 | + |
| 23 | +$sendDocument = new SendDocument(); |
| 24 | +$sendDocument->chat_id = A_USER_CHAT_ID; |
| 25 | +$sendDocument->document = new InputFile($tempFilePath); |
| 26 | +$sendDocument->parse_mode = 'HTML'; |
| 27 | +$sendDocument->caption = sprintf('Uploaded file was originaly named as <b>%s</b> but display name in Telegram client is <b>%s</b>', basename(__FILE__), basename($tempFilePath)); |
| 28 | + |
| 29 | +$promise = $tgLog->performApiRequest($sendDocument); |
| 30 | + |
| 31 | +$promise->then( |
| 32 | + function ($response) use ($tempFilePath) { |
| 33 | + echo '<pre>'; |
| 34 | + var_dump($response); |
| 35 | + echo '</pre>'; |
| 36 | + |
| 37 | + // Delete temporary file and directory after upload to Telegram server is completed |
| 38 | + if (@unlink($tempFilePath) && @rmdir(dirname($tempFilePath))) { |
| 39 | + var_dump('Temporary file and folder were deleted.'); |
| 40 | + } else { |
| 41 | + var_dump('Error while deleting temporary file or directory:', error_get_last()); |
| 42 | + } |
| 43 | + }, |
| 44 | + function (\Exception $exception) { |
| 45 | + // Onoes, an exception occurred... |
| 46 | + echo 'Exception ' . get_class($exception) . ' caught, message: ' . $exception->getMessage(); |
| 47 | + } |
| 48 | +); |
| 49 | + |
| 50 | +$loop->run(); |
0 commit comments