|
6 | 6 | use Psr\Http\Message\ResponseInterface; |
7 | 7 | use Telegram\Bot\HttpClients\GuzzleHttpClient; |
8 | 8 | use Telegram\Bot\HttpClients\HttpClientInterface; |
| 9 | +use Telegram\Bot\Exceptions\TelegramSDKException; |
9 | 10 |
|
10 | 11 | final class TelegramClient |
11 | 12 | { |
12 | 13 | /** |
13 | 14 | * @var string |
14 | 15 | */ |
15 | | - public const BASE_BOT_URL = 'https://api.telegram.org/bot'; |
| 16 | + public const BASE_BOT_URL = 'https://api.telegram.org'; |
| 17 | + private string $fileUrl = '{BASE_API_URL}/file/bot{TOKEN}/{FILE_PATH}'; |
16 | 18 |
|
17 | 19 | private HttpClientInterface $httpClientHandler; |
18 | 20 |
|
@@ -55,9 +57,56 @@ public function sendRequest(TelegramRequest $request): TelegramResponse |
55 | 57 | return $response; |
56 | 58 | } |
57 | 59 |
|
| 60 | + /** |
| 61 | + * Get File URL. |
| 62 | + */ |
| 63 | + public function getFileUrl(string $path, TelegramRequest $request): string |
| 64 | + { |
| 65 | + return str_replace( |
| 66 | + ['{BASE_API_URL}', '{TOKEN}', '{FILE_PATH}'], |
| 67 | + [$this->baseBotUrl, $request->getAccessToken(), $path], |
| 68 | + $this->fileUrl |
| 69 | + ); |
| 70 | + } |
| 71 | + |
| 72 | + /** |
| 73 | + * Download file from Telegram server for given file path. |
| 74 | + * |
| 75 | + * @param string $filePath File path on Telegram server. |
| 76 | + * @param string $filename Download path to save file. |
| 77 | + * |
| 78 | + * @throws TelegramSDKException |
| 79 | + */ |
| 80 | + public function download(string $filePath, string $filename, TelegramRequest $request): string |
| 81 | + { |
| 82 | + $fileDir = dirname($filename); |
| 83 | + |
| 84 | + // Ensure dir is created. |
| 85 | + if (! @mkdir($fileDir, 0755, true) && ! is_dir($fileDir)) { |
| 86 | + throw TelegramSDKException::fileDownloadFailed('Directory '.$fileDir.' can\'t be created'); |
| 87 | + } |
| 88 | + |
| 89 | + $response = $this->httpClientHandler |
| 90 | + ->setTimeOut($request->getTimeOut()) |
| 91 | + ->setConnectTimeOut($request->getConnectTimeOut()) |
| 92 | + ->send( |
| 93 | + $url = $this->getFileUrl($filePath, $request), |
| 94 | + $request->getMethod(), |
| 95 | + $request->getHeaders(), |
| 96 | + ['sink' => $filename], |
| 97 | + $request->isAsyncRequest(), |
| 98 | + ); |
| 99 | + |
| 100 | + if ($response->getStatusCode() !== 200) { |
| 101 | + throw TelegramSDKException::fileDownloadFailed($response->getReasonPhrase(), $url); |
| 102 | + } |
| 103 | + |
| 104 | + return $filename; |
| 105 | + } |
| 106 | + |
58 | 107 | public function prepareRequest(TelegramRequest $request): array |
59 | 108 | { |
60 | | - $url = $this->baseBotUrl.$request->getAccessToken().'/'.$request->getEndpoint(); |
| 109 | + $url = $this->baseBotUrl.'/bot'.$request->getAccessToken().'/'.$request->getEndpoint(); |
61 | 110 |
|
62 | 111 | return [$url, $request->getMethod(), $request->getHeaders(), $request->isAsyncRequest()]; |
63 | 112 | } |
|
0 commit comments