-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtelegramBot.php
More file actions
118 lines (76 loc) · 2.76 KB
/
telegramBot.php
File metadata and controls
118 lines (76 loc) · 2.76 KB
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
<?php
namespace bottest;
include_once 'key.php';
class TelegramBot extends Key
{
private $handlers= array();
private $updateId = 0;
// public function __construct($token)
// {
// }
public function requestApi($metod, $fields= array())
{
$url = "https://api.telegram.org/bot". $this->token . "/" .$metod;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
if($response === false)
$this->processRequestError(curl_error($ch));
curl_close($ch);
$response = json_decode($response);
if(!$response->{"ok"})
$this->processAPIError($response);
return $response;
}
public function sendMessage($chat_id, $text)
{
$this->requestApi('sendMessage', array(
'chat_id' => $chat_id,
'text' => $text
));
}
private function processRequestError($error)
{
$this->processError("Ошибка" . $error);
}
private function processAPIError($response)
{
$this->processError("Ошибка при работе с API. Детали: " . json_encode($response));
}
private function processError($error)
{
// Уведомляем сервер о последнем успешно обработанном обновлении
$this->requestApi('getUpdates', array('offset' => $this->updateId + 1));
// Если указан id чата администратора, то уведомить его
if(defined('TELEGRAM_ADMIN_CHATID'))
$this->sendMessage(TELEGRAM_ADMIN_CHATID, $error);
die($error);
}
public function getUpdates(){
return $this->requestApi('getUpdates', array('offset' => $this->updateId + 1));
}
public function addHandler($handler){
$this->handlers[] = $handler;
}
private function processUpdate($update){
$this->updateId = $update->{"update_id"};
for($j = 0; $j < count($this->handlers); $j++)
if($this->handlers[$j]($update, $this) === false)
break;
}
public function poll($timeout){
while(true) {
$updates = $this->getUpdates();
// Передать обновления на обработку
for($i = 0; $i < count($updates->{"result"}); $i++)
$this->processUpdate($updates->{"result"}[$i]);
sleep($timeout);
}
}
}