forked from DigiPlatMOOC/TelegramBotSample
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.php
More file actions
233 lines (201 loc) · 7.1 KB
/
lib.php
File metadata and controls
233 lines (201 loc) · 7.1 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
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
<?php
/**
* Telegram Bot Sample
* ===================
* UWiClab, University of Urbino
* ===================
* Support library. Don't change a thing here.
*/
include ("config.php");
/**
* Mixes together parameters for an HTTP request.
* @param array $orig_params Original parameters or null.
* @param array $add_params Additional parameters or null.
* @return array Final mixed parameters.
*/
function prepare_parameters($orig_params, $add_params) {
if(!$orig_params || !is_array($orig_params)) {
$orig_params = array();
}
if($add_params && is_array($add_params)) {
foreach ($add_params as $key => &$val) {
$orig_params[$key] = $val;
}
}
return $orig_params;
}
/**
* Performs a cURL request and returns the expected response as string.
* @param object Handle to cURL request.
* @return string | false Response as text or false on failure.
*/
function perform_curl_request($handle) {
$response = curl_exec($handle);
if ($response === false) {
$errno = curl_errno($handle);
$error = curl_error($handle);
error_log("Curl returned error $errno: $error");
curl_close($handle);
return false;
}
$http_code = intval(curl_getinfo($handle, CURLINFO_HTTP_CODE));
curl_close($handle);
if ($http_code >= 500) {
error_log('Internal server error');
return false;
}
else if($http_code == 401) {
error_log('Unauthorized request (check token)');
return false;
}
else if ($http_code != 200) {
error_log("Request failure with code $http_code ($response)");
return false;
}
else {
return $response;
}
}
/**
* Performs a cURL request to a Telegram API and returns the parsed results.
* @param object Handle to cURL request.
* @return object | false Parsed response object or false on failure.
*/
function perform_telegram_request($handle) {
$response = perform_curl_request($handle);
if($response === false) {
return false;
}
// Everything fine, return the result as object
$response = json_decode($response, true);
return $response['result'];
}
/**
* Prepares an API request using cURL.
* Returns a cURL handle, ready to perform the request, or false on failure.
*
* @param string $url HTTP request URI.
* @param string $method HTTP method ('GET' or 'POST').
* @param array $parameters Query string parameters.
* @param mixed $body String or array of values to be passed as request payload.
* @return object | false cURL handle or false on failure.
*/
function prepare_curl_api_request($url, $method, $parameters, $body = null, $headers = null) {
// Parameter checking
if(!is_string($url)) {
error_log('URL must be a string');
return false;
}
if($method !== 'GET' && $method !== 'POST') {
error_log('Method must be either GET or POST');
return false;
}
if($method !== 'POST' && $body) {
error_log('Cannot send request body content without POST method');
return false;
}
if(!$parameters) {
$parameters = array();
}
if(!is_array($parameters)) {
error_log('Parameters must be an array of values');
return false;
}
// Non-simple parameters (i.e., arrays) are encoded as JSON strings
foreach ($parameters as $key => &$val) {
if (!is_numeric($val) && !is_string($val)) {
$val = json_encode($val);
}
}
// Prepare final request URL
$final_url = $url . '?' . http_build_query($parameters);
echo $final_url . PHP_EOL;
// Prepare cURL handle
$handle = curl_init($final_url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_USERAGENT, 'Telegram Bot client, UWiClab (https://github.com/UWiClab/TelegramBotSample)');
if($method === 'POST') {
curl_setopt($handle, CURLOPT_POST, true);
if($body) {
curl_setopt($handle, CURLOPT_POSTFIELDS, $body);
}
}
if(is_array($headers)) {
curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
}
return $handle;
}
/**
* Sends a Telegram bot message.
* https://core.telegram.org/bots/api#sendmessage
* @param int $chat_id Identifier of the Telegram chat session.
* @param string $message Message to send.
* @param array $parameters Additional parameters that match the API request.
* @return object | false Parsed JSON object returned by the API or false on failure.
*/
function telegram_send_message($chat_id, $message, $parameters) {
$parameters = prepare_parameters($parameters, array(
'chat_id' => $chat_id,
'text' => $message
));
$handle = prepare_curl_api_request(TELEGRAM_API_URI_MESSAGE, 'POST', $parameters, null);
if($handle === false) {
error_log('Failed to prepare cURL handle');
return false;
}
return perform_telegram_request($handle);
}
/**
* Sends a Telegram bot location message.
* https://core.telegram.org/bots/api#sendlocation
* @param int $chat_id Identifier of the Telegram chat session.
* @param float $latitude Coordinate latitude.
* @param float $longitude Coordinate longitude.
* @param array $parameters Additional parameters that match the API request.
* @return object | false Parsed JSON object returned by the API or false on failure.
*/
function telegram_send_location($chat_id, $latitude, $longitude, $parameters) {
if(!is_numeric($latitude) || !is_numeric($longitude)) {
error_log('Latitude and longitude must be numbers');
return false;
}
$parameters = prepare_parameters($parameters, array(
'chat_id' => $chat_id,
'latitude' => $latitude,
'longitude' => $longitude
));
$handle = prepare_curl_api_request(TELEGRAM_API_URI_LOCATION, 'POST', $parameters, null);
if($handle === false) {
error_log('Failed to prepare cURL handle');
return false;
}
return perform_telegram_request($handle);
}
/**
* Requests message updates from the Telegram API.
* https://core.telegram.org/bots/api#getupdates
* @param int $offset Identifier of the first update to be returned, or null.
* @param int $limit Maximum count of updates to fetch, or null.
* @param int | bool $long_poll Performs a long polling request (defaults to false).
* If true is passed, defaults to 60 seconds.
* Otherwise, takes the timeout in seconds to wait.
* @return array | false Parsed array of updates or false on failure.
*/
function telegram_get_updates($offset = null, $limit = null, $long_poll = false) {
$parameters = array();
if(is_numeric($offset))
$parameters['offset'] = $offset;
if(is_numeric($limit) && $limit > 0)
$parameters['limit'] = $limit;
if($long_poll === true)
$long_poll = 60;
if(is_numeric($long_poll) && $long_poll > 0)
$parameters['timeout'] = $long_poll;
$handle = prepare_curl_api_request(TELEGRAM_API_URI_UPDATES, 'GET', $parameters, null);
if($handle === false) {
error_log('Failed to prepare cURL handle');
return false;
}
return perform_telegram_request($handle);
}
?>