zend-blog-3-backend

Форк
0
/
TelegramRequester.php 
180 строк · 4.1 Кб
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: morontt
5
 * Date: 24.09.17
6
 * Time: 11:15
7
 */
8

9
namespace Xelbot\Telegram;
10

11
use GuzzleHttp\Client;
12
use GuzzleHttp\Exception\RequestException;
13
use Psr\Log\LoggerInterface;
14
use Xelbot\Telegram\Exception\TelegramException;
15

16
/**
17
 * @method TelegramResponse getWebhookInfo()
18
 * @method TelegramResponse deleteWebhook()
19
 * @method TelegramResponse setWebhook(array $data)
20
 */
21
class TelegramRequester
22
{
23
    /**
24
     * @var array
25
     */
26
    public static $availableMethods = [
27
        'setWebhook',
28
        'getWebhookInfo',
29
        'deleteWebhook',
30
    ];
31

32
    /**
33
     * @var Client
34
     */
35
    protected $client;
36

37
    /**
38
     * @var string
39
     */
40
    protected $token = '';
41

42
    /**
43
     * @var LoggerInterface|null
44
     */
45
    protected $logger = null;
46

47
    /**
48
     * @param string $token
49
     */
50
    public function __construct(string $token)
51
    {
52
        $this->token = $token;
53
        $this->client = new Client(
54
            [
55
                'base_uri' => 'https://api.telegram.org',
56
            ]
57
        );
58
    }
59

60
    /**
61
     * @param LoggerInterface|null $logger
62
     */
63
    public function setLogger(LoggerInterface $logger = null)
64
    {
65
        $this->logger = $logger;
66
    }
67

68
    /**
69
     * @param array $data
70
     *
71
     * @return TelegramResponse
72
     */
73
    public function sendMessage(array $data): TelegramResponse
74
    {
75
        $text = $data['text'];
76

77
        do {
78
            $data['text'] = mb_substr($text, 0, 4096);
79
            $response = $this->send('sendMessage', $data);
80

81
            $text = mb_substr($text, 4096);
82
        } while (mb_strlen($text, 'UTF-8') > 0);
83

84
        return $response;
85
    }
86

87
    /**
88
     * @param $method
89
     * @param $args
90
     *
91
     * @throws TelegramException
92
     *
93
     * @return mixed
94
     */
95
    public function __call($method, $args)
96
    {
97
        if (in_array($method, self::$availableMethods)) {
98
            array_unshift($args, $method);
99

100
            return call_user_func_array([$this, 'send'], $args);
101
        }
102

103
        throw new TelegramException('Undefined method: ' . $method);
104
    }
105

106
    /**
107
     * @param string $action
108
     * @param array $data
109
     *
110
     * @return TelegramResponse
111
     */
112
    protected function send(string $action, array $data = []): TelegramResponse
113
    {
114
        if ($this->logger) {
115
            $this->logger->info('Request: ' . $action, $data);
116
        }
117

118
        $responseBody = null;
119
        $context = [];
120
        try {
121
            $response = $this->client->post(
122
                sprintf('/bot%s/%s', $this->token, $action),
123
                $this->prepareRequestParams($data)
124
            );
125
            $responseBody = (string)$response->getBody();
126
        } catch (RequestException $e) {
127
            if ($e->hasResponse()) {
128
                $responseBody = (string)$e->getResponse()->getBody();
129
            } else {
130
                $context = ['RequestException' => $e->getMessage()];
131
            }
132
        } catch (\Throwable $e) {
133
            $context = ['Error' => $e->getMessage()];
134
        }
135

136
        $responseData = null;
137
        if ($responseBody) {
138
            try {
139
                $responseData = json_decode($responseBody, true, 512, JSON_BIGINT_AS_STRING | JSON_THROW_ON_ERROR);
140
            } catch (\JsonException $e) {
141
                $context = ['JsonException' => $e->getMessage()];
142
            }
143
        }
144

145
        if ($this->logger) {
146
            $this->logger->info('Response: ' . $action, $responseData ?: $context);
147
        }
148

149
        return new TelegramResponse($responseData ?: []);
150
    }
151

152
    /**
153
     * @param array $params
154
     *
155
     * @return array
156
     */
157
    protected function prepareRequestParams(array $params)
158
    {
159
        $hasResource = false;
160
        $multipart = [];
161

162
        foreach ($params as $key => $item) {
163
            $hasResource |= is_resource($item);
164
            $multipart[] = [
165
                'name' => $key,
166
                'contents' => $item,
167
            ];
168
        }
169

170
        if ($hasResource) {
171
            return [
172
                'multipart' => $multipart,
173
            ];
174
        }
175

176
        return [
177
            'form_params' => $params,
178
        ];
179
    }
180
}
181

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.