-
Notifications
You must be signed in to change notification settings - Fork 0
/
TelegramBot.php
211 lines (192 loc) · 5.99 KB
/
TelegramBot.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
<?php
namespace prowebcraft\yii2log;
use yii\httpclient\Response;
use yii\base\Component;
use yii\base\InvalidConfigException;
use yii\httpclient\Client;
use yii\httpclient\Exception;
/**
* Telegram Bot
*/
class TelegramBot extends Component
{
public const API_BASE_URL = 'https://api.telegram.org/bot';
protected const MAX_MESSAGE_LENGTH = 4096;
protected const MAX_TOTAL_LENGTH = self::MAX_MESSAGE_LENGTH * 5;
/**
* Bot api token secret key
* @var string
*/
public string $token;
/**
* Default telegram target
* @var string
*/
public string $defaultChatId;
/**
* Override default target per log category
* @var array
*/
public array $targetPerCategory = [];
protected ?Client $client = null;
/**
* Check required property
*/
public function init()
{
parent::init();
foreach (['token', 'defaultChatId'] as $property) {
if ($this->$property === null) {
throw new InvalidConfigException(self::class . "::\$$property property must be set");
}
}
}
/**
* Get client
* @return Client
*/
public function getClient(): Client
{
if ($this->client === null) {
$this->client = new Client(['baseUrl' => self::API_BASE_URL . $this->token]);
}
return $this->client;
}
/**
* Get telegram target by message category
* @param string|null $category
* @return string
*/
public function getTarget(string $category = null): string
{
return $this->targetPerCategory[$category] ?? $this->defaultChatId;
}
/**
* Send message to the telegram chat or channel
* @param string $chatId
* Target telegram id
* @param string $message
* Message to be sent
* @param string $parseMode
* Parse html or markdown markup
* @param array $payload
* Extra params
* @see https://core.telegram.org/bots/api#sendmessage
* @param bool $autoSplit
* Auto-split long messages to chunks
* @return mixed
* @throws \yii\httpclient\Exception
* return array
*/
public function sendMessage(
string $chatId,
string $message,
string $parseMode = 'html',
array $payload = [],
bool $autoSplit = true,
)
{
$message = strip_tags($message, '<b><strong><i><em><a><code><pre>');
$payload = array_merge([
'chat_id' => $chatId,
'parse_mode' => $parseMode,
'disable_web_page_preview' => null,
'disable_notification' => null,
'reply_to_message_id' => null,
], $payload);
if ($autoSplit && ($size = mb_strlen($message)) > self::MAX_MESSAGE_LENGTH) {
if ($size > self::MAX_TOTAL_LENGTH) {
$size = self::MAX_TOTAL_LENGTH;
$message = mb_substr($message, 0, self::MAX_TOTAL_LENGTH);
}
$textChunks = [ ];
for ($i = 0; $i < ceil($size / self::MAX_MESSAGE_LENGTH); $i ++) {
$textChunks[] = mb_substr($message, $i > 0 ? $i * self::MAX_MESSAGE_LENGTH : 0, self::MAX_MESSAGE_LENGTH);
}
} else {
$textChunks = [ $message ];
}
foreach ($textChunks as $text) {
$payload['text'] = $text;
$response = $this->getClient()->post('sendMessage', $payload)->send();
}
return isset($response) ? $response->data : null;
}
/**
* Send document to telegram. You must provide content or file path to send
* @param string|null $chatId
* target chat id
* @param string|null $content
* Content to send
* @param string|null $file
* File to send
* @param string|null $caption
* File Caption
* @param string|null $filename
* File name.
* @param array $payload
* Extra/overrided payload params
* @return array|null
* @throws Exception
* @throws InvalidConfigException
*/
public function sendDocument(
string $chatId = null,
string $content = null,
string $file = null,
string $filename = null,
string $caption = null,
array $payload = [],
) {
if ($chatId === null) {
$chatId = $this->getTarget();
}
if (!$file && !$content) {
throw new \InvalidArgumentException('No file or content provided');
}
$payload = array_merge([
'chat_id' => $chatId,
'disable_web_page_preview' => null,
'disable_notification' => null,
'reply_to_message_id' => null,
], $payload);
if ($caption) {
$caption = strip_tags($caption, '<b><strong><i><em><a><code><pre>');
$payload['caption'] = $caption;
$payload['parse_mode'] = 'html';
}
$request = $this->getClient()->createRequest()
->setUrl('sendDocument')
->setData($payload)
;
if ($file) {
if (empty($filename)) {
$filename = basename($file);
}
$request->addFile('document', $file, [
'fileName' => $filename
]);
} else {
$request->addFileContent('document', $content, [
'fileName' => $filename
]);
}
$response = $request->send();
$this->validateResponse($response);
return isset($response) ? $response->data : null;
}
/**
* Validate Api response and throw exception if necessary
* @param Response $response
* @return void
*/
protected function validateResponse(Response $response): void
{
if (!empty($response->data['error_code'])) {
if (!empty($response->data['description'])) {
throw new \RuntimeException('Telegram Api Error: ' . $response->data['description']);
}
throw new \RuntimeException('Telegram Api Error: ' . $response->content);
}
}
}