-
Notifications
You must be signed in to change notification settings - Fork 1
/
MTProxyAdmin.class.php
434 lines (388 loc) · 13 KB
/
MTProxyAdmin.class.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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
<?php
class MTProxyAdmin extends \danog\MadelineProto\EventHandler
{
const ADMINS = [672150123, 1626995];
const MTPROXYBOT = 571465504;
const TAG = '7a616b4a7bde72f938749e312b63bb4d'; // TAG от которого требуется менять пароль по умолчанию
const EXPIRE_TIME = 30; // Время в секундах, через сколько сгорает таск
private $stack = [];
private $lock = false;
private $setchannel = [];
private $from_id;
private $message;
public function __construct($MadelineProto)
{
parent::__construct($MadelineProto);
}
public function onAny($update)
{
\danog\MadelineProto\Logger::log("Received an update of type ".$update['_']);
}
public function onLoop()
{
\danog\MadelineProto\Logger::log("Working...");
if($this->hasTasks()) {
if ($this->getCurrentCommand() === 'promo' && $this->getCurrentStep() === 0) {
$this->incStep();
$this->sendMessage(self::MTPROXYBOT, '/myproxies');
}
if($this->getCurrentTaskTimeDiff() > self::EXPIRE_TIME){
$this->deleteCurrentTask();
}
}
}
public function onUpdateNewChannelMessage($update)
{
$this->onUpdateNewMessage($update);
}
public function onUpdateEditMessage($update)
{
// Игнорировать исходящие сообщения
if (isset($update['message']['out']) && $update['message']['out']) {
return;
}
// Игнорируем если не можем определить от кого сообщение
if(!isset($update['message']['from_id'], $update['message']['message'])){
return;
}
$this->message = $update['message']['message'];
$this->from_id = $update['message']['from_id'];
if ($update['message']['from_id'] === self::MTPROXYBOT){
if($this->hasTasks()) {
if ($this->getCurrentCommand() === 'promo') {
$this->searchProxy($update);
if (strpos($update['message']['message'], 'Promoted channel:') !== false) {
// TODO: устранить баг, залипает, если установить тот же самый канал, то бот не редактирует сообщение.
if ($this->getCurrentStep() === 2) {
$this->forwardMessage($this->getCurrentTaskUser(), self::MTPROXYBOT, [$update['message']['id']]);
$this->deleteCurrentTask();
return;
}
$bytes = strpos($update['message']['message'], 'Promoted channel: n/a.') !== false
? $this->findButtonWithText($update, 'Set promotion')
: $this->findButtonWithText($update, 'Edit promotion');
if ($bytes) {
$this->clickOnButton($update['message']['id'], $bytes);
}
}
}
}
}
}
/**
* @param $update
*/
public function onUpdateNewMessage($update)
{
// Игнорировать исходящие сообщения
if (isset($update['message']['out']) && $update['message']['out']) {
return;
}
// Игнорируем если не можем определить от кого сообщение
if (!isset($update['message']['from_id'], $update['message']['message'])) {
return;
}
$this->message = $update['message']['message'];
$this->from_id = $update['message']['from_id'];
if ($this->isAdmin()) {
$this->onUpdateDRProxyBot($update);
}
if ($this->from_id === self::MTPROXYBOT) {
$this->newMessageMTProxyBot($update);
}
}
private function onUpdateDRProxyBot($update)
{
if(preg_match('/\/promo\s+(?:.*\/)?(?:\@)?(?<channel>\w+)(?:\s+)?(?<tag>\w+)?/', $update['message']['message'], $match)){
$tag = self::TAG;
if(isset($match['tag'])){
if(strlen($match['tag']) !== 32) {
$this->sendMessage($this->from_id, 'Error! The third argument TAG must be 32 characters long.');
return;
}
$tag = $match['tag'];
}
$this->setchannel['channel'] = $match['channel'];
$task = $this->prepareTask($match['channel'], $tag);
$this->addTask($task);
}
if($this->assertText('/tasks')){
if(!empty($this->stack)) {
$this->sendMessage($this->from_id, json_encode($this->stack, JSON_PRETTY_PRINT));
}else{
$this->sendMessage($this->from_id, 'Tasks is empty...');
}
}
if($this->assertText('/clear')){
$this->stack = [];
$this->sendMessage($this->from_id, 'Tasks is clear...');
}
}
private function newMessageMTProxyBot($update)
{
if($this->hasTasks()) {
if ($this->getCurrentCommand() === 'promo') {
$this->searchProxy($update);
if (strpos($update['message']['message'], 'This allows you to set up a promoted channel for your proxy', 0)
=== 0) {
$this->sendMessage(
self::MTPROXYBOT, '@' . $this->getCurrentTaskChannel(), $update['message']['id']
);
}
if (strpos($update['message']['message'], 'New promoted channel has been set', 0) === 0) {
$this->incStep();
$this->forwardMessage($this->getCurrentTaskUser(), $update['message']['from_id'], [$update['message']['id']]);
//$this->deleteCurrentTask();
}
if ($this->assertText('Sorry, this username doesn\'t point to a channel.')) {
$this->forwardMessage($this->getCurrentTaskUser(), $update['message']['from_id'], [$update['message']['id']]);
$this->deleteCurrentTask();
}
}
}
}
/**
* @param $text
*
* @return bool
*/
private function assertText($text)
{
return strpos($this->message, $text) !== false;
}
/**
* Проверяет, что пришла команда
*
* @param $message
* @param $cmd
*
* @return bool
*/
private function isCommand($message, $cmd)
{
return strpos($message, $cmd, 0) === 0;
}
/**
* Отправить сообщение пользователю
*
* @param $peer
* @param $message
*/
private function sendMessage($peer, $message, $reply_to_msg_id = null)
{
try{
$this->messages->sendMessage(
[
'peer' => $peer,
'message' => $message,
'reply_to_msg_id' => $reply_to_msg_id,
]
);
}catch(\danog\MadelineProto\RPCErrorException $e){
\danog\MadelineProto\Logger::log($e);
}
}
private function forwardMessage($peer, $from_peer, array $message_ids)
{
try{
$this->messages->forwardMessages(
[
'to_peer' => $peer,
'from_peer' => $from_peer,
'id' => $message_ids
]
);
}catch (\danog\MadelineProto\RPCErrorException $e){
\danog\MadelineProto\Logger::log($e);
}
}
private function clickOnButton($msg_id, $bytes)
{
try{
$this->messages->getBotCallbackAnswer(
[
'game' => false,
'peer' => self::MTPROXYBOT,
'msg_id' => $msg_id,
'data' => base64_decode($bytes),
]
);
}catch (\danog\MadelineProto\RPCErrorException $e){
\danog\MadelineProto\Logger::log($e);
}
}
private function findButtonWithText($update, $text)
{
$update = json_encode($update, JSON_PRETTY_PRINT);
$update = json_decode($update, true);
$rows = $update['message']['reply_markup']['rows'];
foreach ($rows as $key){
foreach ($key['buttons'] as $button){
if(strpos($button['text'], $text) !== false){
// Если нашли кнопку с нужным текстом, то кликаем на нее, в случае, если есть кнопка листать дальше, листаем
return $button['data']['bytes'];
}
}
}
return false;
}
private function searchProxy($update)
{
$this->updateCurrentTaskTime();
if(strpos($update['message']['message'], 'Here is the list of all proxies you created:', 0)===0){
$bytes = $this->findButtonWithText($update, $this->getCurrentTaskTag());
if($bytes) {
$this->clickOnButton($update['message']['id'], $bytes);
}else{
$bytes = $this->findButtonWithText($update, '»');
if($bytes){
$this->clickOnButton($update['message']['id'], $bytes);
}else {
$this->sendMessage($this->getCurrentTaskUser(), 'Can\'t find tag ' . $this->getCurrentTaskTag());
$this->deleteCurrentTask();
}
}
}
}
/**
* Проверяет, от имеет ли человек устанавливать промо канал.
*
* @return bool
*/
private function isAdmin(): bool
{
return in_array($this->from_id, self::ADMINS, true) ? true : false;
}
/**
* Подготавливает task, временный метод.
* Готовые таски в будущем должен присылать @DRProxyBot
*
* @param $channel
* @param $tag
*
* @return string
*/
private function prepareTask($channel, $tag): string
{
$task = [
'command' => 'promo',
'channel' => $channel,
'from_id' => $this->from_id,
'tag' => $tag
];
return json_encode($task);
}
/**
* Возвращает разность, когда последний раз был обновлен таск
*
* @return int
*/
private function getCurrentTaskTimeDiff(): int
{
return time() - $this->stack[key($this->stack)]['updated'];
}
/**
* Обновляем метку, что все еще работаем над текущим таском.
*/
private function updateCurrentTaskTime()
{
$this->stack[key($this->stack)]['updated'] = time();
}
/**
*
*
* @param $item
*/
private function addTask($item)
{
if($this->isValidTask($item)){
$arr = json_decode($item, true);
$arr['step'] = 0;
$arr['updated'] = time();
$this->stack[] = $arr;
}
}
private function isValidTask($item): bool
{
$arr = json_decode($item, true);
if(json_last_error()!==0){
return false;
}
return isset($arr['command']);
}
private function setLock(bool $status)
{
$this->lock = $status;
}
private function enableLock()
{
$this->setLock(true);
}
private function disableLock()
{
$this->setLock(false);
}
/**
* @return bool
*/
private function getLock(): bool
{
return $this->lock;
}
private function removeTask()
{
}
/**
* @return array
*/
private function getCurrentTask()
{
return current($this->stack);
}
private function hasTasks(): bool
{
if (!empty($this->stack)){
return true;
}
return false;
}
/**
* @return string
*/
private function getCurrentCommand(): string
{
return current($this->stack)['command'];
}
/**
* @return int
*/
private function getCurrentStep(): int
{
return current($this->stack)['step'];
}
/**
* @return string
*/
private function getCurrentTaskUser():string
{
return current($this->stack)['from_id'];
}
private function getCurrentTaskChannel()
{
return current($this->stack)['channel'];
}
private function getCurrentTaskTag()
{
return current($this->stack)['tag'];
}
private function incStep()
{
$this->stack[key($this->stack)]['step']++;
$this->updateCurrentTaskTime();
}
private function deleteCurrentTask()
{
$this->lock = false;
unset($this->stack[key($this->stack)]);
}
}