forked from DJTommek/better-location
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTelegramHelper.php
372 lines (335 loc) · 11.5 KB
/
TelegramHelper.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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
<?php declare(strict_types=1);
namespace App\TelegramCustomWrapper;
use App\Config;
use App\Icons;
use App\Utils\Strict;
use Nette\Http\Url;
use Nette\Http\UrlImmutable;
use Nette\Utils\Strings;
use unreal4u\TelegramAPI\Telegram;
use unreal4u\TelegramAPI\Telegram\Types\Chat;
use unreal4u\TelegramAPI\Telegram\Types\MessageEntity;
use unreal4u\TelegramAPI\Telegram\Types\Update;
use unreal4u\TelegramAPI\Telegram\Types\User;
class TelegramHelper
{
public const API_URL = 'https://api.telegram.org';
public const WEBHOOK_SECRET_TOKEN_HEADER_KEY = 'X-Telegram-Bot-Api-Secret-Token';
public const INLINE_KEYBOARD_MAX_BUTTON_PER_ROW = 8;
/**
* (Almost) invisible character, see usage for more info.
*
* @author https://emptycharacter.com/
*/
public const INVISIBLE_CHARACTER = ' ';
/**
* Generate (almost) invisible link, that is still valid - useful for Telegram's automatic generating preview from links
*/
public static function invisibleLink(UrlImmutable|Url|string $url): string
{
return sprintf('<a href="%s" target="_blank">%s</a>', $url, self::INVISIBLE_CHARACTER);
}
/**
* Get regex for command entity
*
* @param bool $strict Enforce containing bot's case in-sensitive username (set in \Config class). Valid commands:
* - true: /command@BetterLocationBot, /command@BETTERlocationBOT
* - false: /command@BetterLocationBot, /command@betterLOCATIONbot, /command
* @return string command without bot's username if it contains
*/
public static function getCommandRegex(bool $strict): string
{
$regex = '/^';
$regex .= '(\/[a-z0-9_]+)';
$regex .= '(?:@' . Config::TELEGRAM_BOT_NAME . ')';
if ($strict === false) {
$regex .= '?'; // make last part of regex optional
}
$regex .= '$/i';
return $regex;
}
// @TODO Move CHAT_ACTION_* to some ENUM
const CHAT_ACTION_TYPING = 'typing';
const CHAT_ACTION_UPLOAD_PHOTO = 'upload_photo';
const CHAT_ACTION_RECORD_VIDEO = 'record_video';
const CHAT_ACTION_UPLOAD_VIDEO = 'upload_video';
const CHAT_ACTION_RECORD_AUDIO = 'record_audio';
const CHAT_ACTION_UPLOAD_AUDIO = 'upload_audio';
const CHAT_ACTION_UPLOAD_DOCUMENT = 'upload_document';
const CHAT_ACTION_FIND_LOCATION = 'find_location';
const CHAT_ACTION_RECORD_VIDEO_NOTE = 'record_video_note';
const CHAT_ACTION_UPLOAD_VIDEO_NOTE = 'upload_video_note';
const NOT_CHANGED = 'Bad Request: message is not modified: specified new message content and reply markup are exactly the same as a current content and reply markup of the message';
const TOO_OLD = 'Bad Request: query is too old and response timeout expired or query ID is invalid';
const MESSAGE_TO_EDIT_DELETED = 'Bad Request: message to edit not found';
const CHAT_WRITE_FORBIDDEN = 'Bad Request: CHAT_WRITE_FORBIDDEN';
const REPLIED_MESSAGE_NOT_FOUND = 'Bad Request: replied message not found';
const BOT_BLOCKED_BY_USER = 'Forbidden: bot was blocked by the user';
/**
* @param User|Chat $from If chat is private, User and Chat have similar properties
* @return string
*/
public static function getUserDisplayname($from): string
{
$displayName = $from->username ? ('@' . $from->username) : ($from->first_name . ' ' . $from->last_name);
return trim(htmlspecialchars($displayName));
}
public static function getChatDisplayname(Chat $chat): string
{
if ($chat->title) {
return trim(htmlspecialchars($chat->title));
} else {
return self::getUserDisplayname($chat);
}
}
public static function isButtonClick($update): bool
{
return (!empty($update->callback_query));
}
public static function isForward(Update $update): bool
{
return (!empty($update->message->forward_from));
}
public static function isInlineQuery(Update $update): bool
{
return (!empty($update->inline_query));
}
public static function isChosenInlineQuery(Update $update): bool
{
return (!empty($update->chosen_inline_result));
}
/** @param bool $live is location live */
public static function isLocation(Update $update, bool $live = false): bool
{
$location = $update->message->location ?? $update->edited_message->location ?? null;
if ($location) {
if ($live === true && empty($location->live_period)) {
return false;
} else {
return true;
}
} else {
return false;
}
}
public static function isVenue(Update $update): bool
{
return !empty($update->message->venue);
}
public static function isEdit(Update $update): bool
{
return ($update->edited_channel_post || $update->edited_message);
}
public static function isChannel(Update $update): bool
{
return !empty($update->channel_post);
}
public static function hasDocument($update): bool
{
return (!empty($update->message->document));
}
public static function hasPhoto($update): bool
{
return (!empty($update->message->photo));
}
public static function isViaBot(Update $update, ?string $botUsername = null): bool
{
if (empty($update->message->via_bot) === false) {
if (is_null($botUsername)) {
return true;
} else if (mb_strtolower($update->message->via_bot->username) === mb_strtolower($botUsername)) {
return true;
} else {
return false;
}
}
return false;
}
public static function chatCreated(Update $update): bool
{
return ($update->message && $update->message->group_chat_created);
}
public static function addedToChat(Update $update, ?string $username = null): bool
{
if (self::chatCreated($update)) {
return true; // User added while creating group
} else if (count($update->message->new_chat_members ?? []) > 0) {
if (is_null($username)) {
return true; // Any user was added to already group
} else {
foreach ($update->message->new_chat_members as $newChatMember) {
if (mb_strtolower($newChatMember->username) === mb_strtolower($username)) {
return true; // Specific user added to already created group
}
}
}
}
return false;
}
public static function getFileUrl(string $token, string $path): string
{
return sprintf('%s/file/bot%s/%s', self::API_URL, $token, $path);
}
/** @return bool|null null if unknown (eg. clicked on button in via_bot message) */
public static function isPM(Update $update): ?bool
{
if (self::isButtonClick($update)) {
// If the button was attached to a message sent via the bot (in inline mode),
// the field inline_message_id will be present. (https://core.telegram.org/bots/api#callbackquery)
if ($update->callback_query->inline_message_id) {
return null;
} else {
return $update->callback_query->from->id === $update->callback_query->message->chat->id;
}
} else {
return ($update->message->from->id === $update->message->chat->id);
}
}
public static function getCommand(Update $update, bool $strict = false): ?string
{
$command = null;
if (self::isButtonClick($update)) {
$fullCommand = $update->callback_query->data;
$command = explode(' ', $fullCommand)[0];
} else {
foreach ($update->message->entities as $entity) {
if ($entity->offset === 0 && $entity->type === 'bot_command') {
$command = mb_strcut($update->message->text, $entity->offset, $entity->length);
break;
}
}
}
if (self::isPM($update) === true) {
$strict = false; // there is no need to write bot username since there is one to one
}
if (self::isButtonClick($update)) {
$strict = false; // clicking on button is going only to bot, who created it
}
if ($command && preg_match(self::getCommandRegex($strict), $command, $matches)) {
return mb_strtolower($matches[1]);
} else {
return null;
}
}
public static function getParams($update): array
{
if (self::isButtonClick($update)) {
$text = $update->callback_query->data;
} else {
$text = $update->message->text;
}
$params = explode(' ', $text);
array_shift($params);
return $params;
}
public static function generateStart(string $params): string
{
return sprintf('https://t.me/%s?start=', Config::TELEGRAM_BOT_NAME) . self::InlineTextEncode($params);
}
public static function generateStartLocation(float $lat, float $lon): string
{
return sprintf('https://t.me/%s?start=%d_%d', Config::TELEGRAM_BOT_NAME, $lat * 1000000, $lon * 1000000);
}
public static function InlineTextEncode(string $input): string
{
$input = trim($input);
$input = base64_encode($input);
$input = str_replace('=', '_', $input);
$input = str_replace('+', '-', $input);
return trim($input);
}
public static function InlineTextDecode(string $input): string
{
$input = trim($input);
$input = str_replace('_', '=', $input);
$input = str_replace('-', '+', $input);
$input = base64_decode($input);
return trim($input);
}
/**
* Return entity content in UTF-8 (currently supported only for "text_link" and "url")
*
* @author https://stackoverflow.com/questions/49035310/php-telegram-bot-extract-url-in-utf-16-code-units/49430787
* @see https://stackoverflow.com/questions/30604427/php-length-of-string-containing-emojis-special-chars
*/
public static function getEntityContent(string $message, MessageEntity $entity): string
{
switch ($entity->type) {
case 'url':
$message16 = mb_convert_encoding($message, 'UTF-16', 'UTF-8');
$entityContent16 = substr($message16, $entity->offset * 2, $entity->length * 2);
return mb_convert_encoding($entityContent16, 'UTF-8', 'UTF-16');
case 'text_link':
return $entity->url;
default:
throw new \InvalidArgumentException(sprintf('Processing entity content of type "%s" is currently not supported.', $entity->type));
}
}
/**
* Simulate Telegram message by creating URL entities (currently only URLs)
*
* @return MessageEntity[]
* @see self::getEntityContent()
*/
public static function generateEntities(string $message): array
{
$message16 = mb_convert_encoding($message, 'UTF-16', 'UTF-8');
$entities = [];
foreach (\App\Utils\Utils::getUrls($message) as $url) {
$url16 = mb_convert_encoding($url, 'UTF-16', 'UTF-8');
$entity = new MessageEntity();
$entity->type = 'url';
$entity->offset = strpos($message16, $url16) / 2;
$entity->length = strlen($url16) / 2;
$entities[] = $entity;
}
return $entities;
}
/**
* Remove all URLs from Telegram message according entities.
* URLs will be replaced with ||| proper length to keep entity offset and length valid eg.:
* 'Hello https://t.me/ here!'
* ->
* 'Hello ||||||||||||| here!'
*
* @param string $text
* @param MessageEntity[] $entities
* @return string
*/
public static function getMessageWithoutUrls(string $text, array $entities): string
{
foreach (array_reverse($entities) as $entity) {
if ($entity->type === 'url') {
$entityContent = TelegramHelper::getEntityContent($text, $entity);
if (Strict::isUrl($entityContent)) {
$text = str_replace($entityContent, str_repeat('|', $entity->length), $text);
}
}
}
return $text;
}
public static function loginUrlButton(string $text, UrlImmutable $redirectUrl = null): Telegram\Types\Inline\Keyboard\Button
{
return new Telegram\Types\Inline\Keyboard\Button([
'text' => $text,
'login_url' => new Telegram\Types\LoginUrl([
'url' => Config::getLoginUrl($redirectUrl)->getAbsoluteUrl(),
]),
]);
}
public static function userLink(string $username): string
{
return 'https://t.me/' . ltrim($username, '@');
}
public static function userLinkTag(string $username): string
{
if (Strings::startsWith($username, '@') === false) {
$username = '@' . $username;
}
return sprintf('<a href="%s" target="_blank">%s</a>', self::userLink($username), $username);
}
public static function isAdmin(Telegram\Types\ChatMember $chatMember): bool
{
return in_array($chatMember->status, ['creator', 'administrator'], true);
}
}