Hellobot
This sample PHP bot demonstrates the basics of the Telegram Bot API.
If you have questions, try our FAQ or check out this page for more examples.
if (!$parameters) < $parameters = array(); >else if (!is_array($parameters)) < error_log("Parameters must be an array\n"); return false; >$parameters["method"] = $method; $payload = json_encode($parameters); header('Content-Type: application/json'); header('Content-Length: '.strlen($payload)); echo $payload; return true; > function exec_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\n"); curl_close($handle); return false; >$http_code = intval(curl_getinfo($handle, CURLINFO_HTTP_CODE)); curl_close($handle); if ($http_code >= 500) < // do not wat to DDOS server if something goes wrong sleep(10); return false; >else if ($http_code != 200) < $response = json_decode($response, true); error_log("Request has failed with error : \n"); if ($http_code == 401) < throw new Exception('Invalid access token provided'); >return false; > else < $response = json_decode($response, true); if (isset($response['description'])) < error_log("Request was successful: \n"); > $response = $response['result']; > return $response; > function apiRequest($method, $parameters) < if (!is_string($method)) < error_log("Method name must be a string\n"); return false; >if (!$parameters) < $parameters = array(); >else if (!is_array($parameters)) < error_log("Parameters must be an array\n"); return false; >foreach ($parameters as $key => &$val) < // encoding to JSON array parameters, for example reply_markup if (!is_numeric($val) && !is_string($val)) < $val = json_encode($val); >> $url = API_URL.$method.'?'.http_build_query($parameters); $handle = curl_init($url); curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($handle, CURLOPT_TIMEOUT, 60); return exec_curl_request($handle); > function apiRequestJson($method, $parameters) < if (!is_string($method)) < error_log("Method name must be a string\n"); return false; >if (!$parameters) < $parameters = array(); >else if (!is_array($parameters)) < error_log("Parameters must be an array\n"); return false; >$parameters["method"] = $method; $handle = curl_init(API_URL); curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($handle, CURLOPT_TIMEOUT, 60); curl_setopt($handle, CURLOPT_POST, true); curl_setopt($handle, CURLOPT_POSTFIELDS, json_encode($parameters)); curl_setopt($handle, CURLOPT_HTTPHEADER, array("Content-Type: application/json")); return exec_curl_request($handle); > function processMessage($message) < // process incoming message $message_id = $message['message_id']; $chat_id = $message['chat']['id']; if (isset($message['text'])) < // incoming text message $text = $message['text']; if (strpos($text, "/start") === 0) < apiRequestJson("sendMessage", array('chat_id' =>$chat_id, "text" => 'Hello', 'reply_markup' => array( 'keyboard' => array(array('Hello', 'Hi')), 'one_time_keyboard' => true, 'resize_keyboard' => true))); > else if ($text === "Hello" || $text === "Hi") < apiRequest("sendMessage", array('chat_id' =>$chat_id, "text" => 'Nice to meet you')); > else if (strpos($text, "/stop") === 0) < // stop now >else < apiRequestWebhook("sendMessage", array('chat_id' =>$chat_id, "reply_to_message_id" => $message_id, "text" => 'Cool')); > > else < apiRequest("sendMessage", array('chat_id' =>$chat_id, "text" => 'I understand only text messages')); > > define('WEBHOOK_URL', 'https://my-site.example.com/secret-path-for-webhooks/'); if (php_sapi_name() == 'cli') < // if run from console, set or delete webhook apiRequest('setWebhook', array('url' =>isset($argv[1]) && $argv[1] == 'delete' ? '' : WEBHOOK_URL)); exit; > $content = file_get_contents("php://input"); $update = json_decode($content, true); if (!$update) < // receive wrong update, must not happen exit; >if (isset($update["message"]))
Telegram
Бот Телеграм на PHP
Примеры как зарегистрировать бота в Telegram, описание и взаимодействие с основными методами API. Документация на core.telegram.org и tlgrm.ru (неофициальный, на русском).
Все запросы к API должны осуществляться по HTTPS, подойдет бесплатный сертификат «Let’s Encrypt».
Регистрация бота
Для регистрации нового бота нужно написать «папе ботов» @BotFather команду /newbot
Следующим сообщением отправляем название для бота, обязательно на конце имени должно быть слово «bot» или «_bot». Ответным сообщением получим токен:
Тут же можно настроить описание и аватарку:
/setname | Имя |
/setdescription | Краткое описание |
/setabouttext | Описание бота |
/setuserpic | Юзерпик |
Далее нужно поставить «Webhook» чтобы все сообщения из Telegram приходили на PHP скрипт ( https://example.com/bot.php ). Для этого нужно пройти по ссылке в которой подставлены полученный токен и адрес скрипта. https://api.telegram.org/bot /setWebhook?url= https://example.com/bot.php
В ответе будет
Входящие сообщения
Сообщения приходят POST-запросом, с типом application/json . Получить его в PHP можно следующим образом:
$data = file_get_contents('php://input'); $data = json_decode($data, true);
file_put_contents(__DIR__ . '/message.txt', print_r($data, true));
Текстовое сообщение
Запрос от Телеграм:
Array ( [update_id] => 17584194 [message] => Array ( [message_id] => 26 [from] => Array ( [id] => 123456789 [is_bot] => [first_name] => UserName [language_code] => ru-US ) [chat] => Array ( [id] => 123456789 [first_name] => UserName [type] => private ) [date] => 1541888068 [text] => Привет бот! ) )
Получим текст сообщения:
Фотографии
При отправки фото боту, на скрипт приходит массив превьюшек, последним элементом будет оригинальное фото. Максимальный размер файла 20МБ.
Запрос от Телеграм:
Array ( [update_id] => 17584194 [message] => Array ( [message_id] => 38 [from] => Array ( [id] => 123456789 [is_bot] => [first_name] => UserName [language_code] => ru-US ) [chat] => Array ( [id] => 123456789 [first_name] => UserName [type] => private ) [date] => 1541924962 [photo] => Array ( [0] => Array ( [file_id] => AgADAgADUqexG7u8OEudBvlhgMzKC1agOQ8ABC6Bx26USA7Mw3gAAgI [file_size] => 1196 [width] => 51 [height] => 90 ) [1] => Array ( [file_id] => AgttAgADUqoxG7u8OEudBvlhgMzKC1agOQ8ABKwp_3jDPrIlxHgAAgI [file_size] => 21146 [width] => 180 [height] => 320 ) [2] => Array ( [file_id] => AgADAgADUqyxG7u8OEudBvlhgMzKC1agOQ8ABAN8gJWpUT1MxXgAAgI [file_size] => 90940 [width] => 449 [height] => 800 ) [3] => Array ( [file_id] => AgADAgADUqouu7u8OEudBvlhgMzKC1agOQ8ABIqVC1nEpbLDwngAAgI [file_size] => 114363 [width] => 719 [height] => 1280 ) ) ) )
Чтобы скачать файл нужно отправить POST или GET запрос на получение c параметром file_id изображения по URL: https://api.telegram.org/bot
Array ( [ok] => 1 [result] => Array ( [file_id] => AgADAgADUqoxG5u88E0dBvlhgMzKC1agOQ8ABIqVC1nEpbLDwngAAgI [file_size] => 114363 [file_path] => photos/file_1.jpg ) )
Далее его можно скачать по ссылке: https://api.telegram.org/file/bot
$token = '123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11'; if (!empty($data['message']['photo'])) < $photo = array_pop($data['message']['photo']); $ch = curl_init('https://api.telegram.org/bot' . $token . '/getFile'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, array('file_id' =>$photo['file_id'])); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, false); $res = curl_exec($ch); curl_close($ch); $res = json_decode($res, true); if ($res['ok']) < $src = 'https://api.telegram.org/file/bot' . $token . '/' . $res['result']['file_path']; $dest = __DIR__ . '/' . time() . '-' . basename($src); copy($src, $dest); >>
Документ
Запрос от Телеграм:
Array ( [update_id] => 17474201 [message] => Array ( [message_id] => 44 [from] => Array ( [id] => 123456789 [is_bot] => [first_name] => UserName [language_code] => ru-US ) [chat] => Array ( [id] => 123456789 [first_name] => UserName [type] => private ) [date] => 1541925844 [document] => Array ( [file_name] => IMG_7947.JPG [mime_type] => image/jpeg [thumb] => Array ( [file_id] => AAQCABMNv_QOAATwQugveIZBldZ3AAIC [file_size] => 2644 [width] => 67 [height] => 90 ) [file_id] => BQADAgADtQEAAqu9OEhzn2cEz8LpkgI [file_size] => 1976218 ) ) )
if (!empty($data['message']['document'])) < $file_id = $data['message']['document']['file_id']; $ch = curl_init('https://api.telegram.org/bot' . $token . '/getFile'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, array('file_id' =>$file_id)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, false); $res = curl_exec($ch); curl_close($ch); $res = json_decode($res, true); if ($res['ok']) < $src = 'https://api.telegram.org/file/bot' . $token . '/' . $res['result']['file_path']; $dest = __DIR__ . '/' . time() . '-' . basename($src); copy($src, $dest); >>
Ответы бота
Отправка текста
$response = array( 'chat_id' => $data['message']['chat']['id'], 'text' => 'Хай!' ); $ch = curl_init('https://api.telegram.org/bot' . $token . '/sendMessage'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $response); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, false); curl_exec($ch); curl_close($ch);
Отправка картинки
$response = array( 'chat_id' => $data['message']['chat']['id'], 'photo' => curl_file_create(__DIR__ . '/image.png') ); $ch = curl_init('https://api.telegram.org/bot' . $token . '/sendPhoto'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $response); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, false); curl_exec($ch); curl_close($ch);
Отправка файла
$response = array( 'chat_id' => $data['message']['chat']['id'], 'document' => curl_file_create(__DIR__ . '/file.xls') ); $ch = curl_init('https://api.telegram.org/bot' . $token . '/sendDocument'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $response); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, false); curl_exec($ch); curl_close($ch);
Пример скрипта
define('TOKEN', '123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11'); // Функция вызова методов API. function sendTelegram($method, $response) < $ch = curl_init('https://api.telegram.org/bot' . TOKEN . '/' . $method); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $response); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, false); $res = curl_exec($ch); curl_close($ch); return $res; >// Прислали фото. if (!empty($data['message']['photo'])) < $photo = array_pop($data['message']['photo']); $res = sendTelegram( 'getFile', array( 'file_id' =>$photo['file_id'] ) ); $res = json_decode($res, true); if ($res['ok']) < $src = 'https://api.telegram.org/file/bot' . TOKEN . '/' . $res['result']['file_path']; $dest = __DIR__ . '/' . time() . '-' . basename($src); if (copy($src, $dest)) < sendTelegram( 'sendMessage', array( 'chat_id' =>$data['message']['chat']['id'], 'text' => 'Фото сохранено' ) ); > > exit(); > // Прислали файл. if (!empty($data['message']['document'])) < $res = sendTelegram( 'getFile', array( 'file_id' =>$data['message']['document']['file_id'] ) ); $res = json_decode($res, true); if ($res['ok']) < $src = 'https://api.telegram.org/file/bot' . TOKEN . '/' . $res['result']['file_path']; $dest = __DIR__ . '/' . time() . '-' . $data['message']['document']['file_name']; if (copy($src, $dest)) < sendTelegram( 'sendMessage', array( 'chat_id' =>$data['message']['chat']['id'], 'text' => 'Файл сохранён' ) ); > > exit(); > // Ответ на текстовые сообщения. if (!empty($data['message']['text'])) < $text = $data['message']['text']; if (mb_stripos($text, 'привет') !== false) < sendTelegram( 'sendMessage', array( 'chat_id' =>$data['message']['chat']['id'], 'text' => 'Хай!' ) ); exit(); > // Отправка фото. if (mb_stripos($text, 'фото') !== false) < sendTelegram( 'sendPhoto', array( 'chat_id' =>$data['message']['chat']['id'], 'photo' => curl_file_create(__DIR__ . '/torin.jpg') ) ); exit(); > // Отправка файла. if (mb_stripos($text, 'файл') !== false) < sendTelegram( 'sendDocument', array( 'chat_id' =>$data['message']['chat']['id'], 'document' => curl_file_create(__DIR__ . '/example.xls') ) ); exit(); > >