Send text messages.
public sendMessage ( integer $chat_id, string $text, string $parse_mode = null, boolean $disable_web_page_preview = false, integer $reply_to_message_id = null, KeyboardMarkup $reply_markup = null ) : Array | ||
$chat_id | integer | |
$text | string | |
$parse_mode | string | |
$disable_web_page_preview | boolean | |
$reply_to_message_id | integer | |
$reply_markup | KeyboardMarkup | |
return | Array |
} else { file_put_contents($fileOfLastUpdate, "0"); $lastUpdateId = 0; } // Делаем long-poll запрос 60 секунд к серверу телеграм $updates = $tg->pollUpdates($lastUpdateId, 60); // Обрабатываем Updates, если они есть. foreach ($updates['result'] as $data) { $updateId = $updates['result'][count($updates['result']) - 1]['update_id']; $message = $data['message']['text']; $chatId = $data['message']['chat']['id']; // Эта команда для дебага, чтобы не перезапускать apache каждый раз, когда нужно перезапустить tbServer.php // Отправляешь боту команду /reboot и сервер останавливается. // В рабочей версии - нужно закоментить этот IF(){} if ($message == "/reboot") { $tg->sendMessage($chatId, 'Сервер будет перезапущен в течение минуты!'); file_put_contents($fileOfLastUpdate, $updateId); exit; } $db = tbDatabase(); // Проверим, авторизован ли пользователь $sth = $db->prepare("SELECT count(*) as count FROM tbManagers WHERE mBotChatId=:mBotChatId"); $sth->execute(array(":mBotChatId" => $chatId)); $answer = $sth->fetch(); if ($answer["count"] > 0) { $isAuth = true; } else { $isAuth = false; } if ($isAuth === false) { if ($message == $tbManagerPassword) {
switch ($data['message']['text']) { case '/start': addContact($chatID); break; case '/remove': deleteContact($chatID); break; } } $offset = $response['result'][count($response['result']) - 1]['update_id'] + 1; } $chats = allChats(); $quotes = readQuotes(); $i = 0; for ($i; $i < count($chats); $i++) { $tg->sendMessage($chats[$i]['chat_id'], $quotes[$chats[$i]['init']]); updateInit($chats[$i]['chat_id']); if ($chats[$i]['init'] == count($quotes) - 1) { resetInit($chats[$i]['chat_id']); } } function addContact($chatID) { $contactsDB = __DIR__ . DIRECTORY_SEPARATOR . 'contacts.db'; if (!file_exists($contactsDB)) { $db = new \PDO("sqlite:" . $contactsDB, null, null, array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)); $db->exec('CREATE TABLE contacts (`chat_id` TEXT, `init` INT)'); } else { $db = new \PDO("sqlite:" . $contactsDB, null, null, array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)); } $sql = 'SELECT chat_id FROM contacts WHERE chat_id = :chat_id';
$updates = $tg->pollUpdates($updateIdFrom, 60); foreach ($updates['result'] as $data) { $updateId = $updates['result'][count($updates['result']) - 1]['update_id']; $chatId = $data['message']['chat']['id']; $message = ""; if ($data['message']['voice']) { $voice = $data['message']['voice']; } if ($data['message']['text']) { $message = $data['message']['text']; } //var_dump($data); print "\r\n"; if (in_array($chatId, $authDialogs)) { if ($message == "/reboot") { $tg->sendMessage($chatId, 'Сервер будет перезапущен в течение минуты!'); file_put_contents($fileOfUpdate, $updateId); fopen($dir . "/stopserver"); exit; } if ($message == "/start") { $tg->sendMessage($chatId, "Вы вошли в режим наблюдения!"); } elseif ($message == "/stop") { $k = array_search($chatId, $authDialogs); if ($k !== false) { unset($authDialogs[$k]); $f = fopen($fileOfAuth, "w+"); foreach ($authDialogs as $i => $item) { if (trim($item) != null) { fwrite($f, $item . "\r\n"); }
$customKeyboard = [['7', '8', '9'], ['4', '5', '6'], ['1', '2', '3'], ['0']]; $reply_markup = $tg->replyKeyboardMarkup($customKeyboard, true, true); do { // Get updates the bot has received // Offset to confirm previous updates $updates = $tg->pollUpdates($offset); if ($updates['ok'] && count($updates['result']) > 0) { foreach ($updates['result'] as $data) { if (is_null($chat_id)) { $chat_id = $data['message']['chat']['id']; } if (!$sendQuestion) { // sends an action 'typing' $tg->sendChatAction($chat_id, 'typing'); // send message with a custom reply markup $tg->sendMessage($chat_id, 'Guess the number', null, false, null, $reply_markup); $sendQuestion = true; } if ($data['message']['text'] == 5) { $tg->sendChatAction($chat_id, 'typing'); $tg->sendMessage($chat_id, 'You did it! :)'); $tg->sendChatAction($chat_id, 'upload_photo'); $tg->sendPhoto($chat_id, 'https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/718smiley.png/220px-718smiley.png'); $guessed = true; } else { $tg->sendMessage($chat_id, 'Wrong number :/ try again', null, false, null, $reply_markup); } } $offset = $updates['result'][count($updates['result']) - 1]['update_id'] + 1; } } while (!$guessed);
$managers = array(); while ($a = $sth->fetch()) { $managers[] = $a; } if (count($managers) > 0) { $r = rand(0, count($managers) - 1); $managerId = $managers[$r]['mId']; $chatId = $managers[$r]['mBotChatId']; $managerName = $managers[$r]['mName']; } else { echo json_encode(array("status" => "error", "error" => "NO_MANAGERS")); exit; } if ($params['tbChatHash'] == null) { $chHash = uniqid("chat_"); } else { $chHash = $params['tbChatHash']; } $sth = $db->prepare("INSERT INTO tbChats (chHash, chManager) VALUES (:chHash, :chManager)"); $sth->execute(array(":chHash" => $chHash, ":chManager" => $managerId)); $chId = $db->lastInsertId(); } require_once "tbClass.php"; // Новый экземпляр телеграм бота $tg = new telegramBot($tbAPIToken); $tg->sendMessage($chatId, $params['tbMessage'] . "\r\n\r\nДля ответа перейти в чат — /chat_" . $chId . "\r\nПосмотреть историю — /history_" . $chId . ""); $sth = $db->prepare("INSERT INTO tbMessages (msgChatId, msgFrom, msgTime, msgText) VALUES (:msgChatId, :msgFrom, :msgTime, :msgText)"); $sth->execute(array(":msgChatId" => $chId, ":msgFrom" => "c", ":msgTime" => time(), ":msgText" => $params['tbMessage'])); $mId = $db->lastInsertId(); echo json_encode(array("status" => "ok", "managerName" => $managerName, "tbChatHash" => $chHash, "lastMessageId" => $mId, "lastMessageDate" => date("H:i:s"))); exit;
$managers = array(); while ($a = $sth->fetch()) { $managers[] = $a; } if (count($managers) > 0) { $r = rand(0, count($managers) - 1); $managerId = $managers[$r]['mId']; $chatId = $managers[$r]['mBotChatId']; $managerName = $managers[$r]['mName']; } else { echo json_encode(array("status" => "error", "error" => "NO_MANAGERS")); exit; } if ($params['tbChatHash'] == null) { $chHash = uniqid("chat_"); } else { $chHash = $params['tbChatHash']; } $sth = $db->prepare("INSERT INTO tbChats (chHash, chManager) VALUES (:chHash, :chManager)"); $sth->execute(array(":chHash" => $chHash, ":chManager" => $managerId)); $chId = $db->lastInsertId(); } require_once "tbClass.php"; // Новый экземпляр телеграм бота $tg = new telegramBot($tbAPIToken); $tg->sendMessage($chatId, $params['tbMessage'] . "\r\n\r\n" . $_localization["forAnswerGoToChat"] . " — /chat_" . $chId . "\r\n" . $_localization["viewHistory"] . " — /history_" . $chId); $sth = $db->prepare("INSERT INTO tbMessages (msgChatId, msgFrom, msgTime, msgText) VALUES (:msgChatId, :msgFrom, :msgTime, :msgText)"); $sth->execute(array(":msgChatId" => $chId, ":msgFrom" => "c", ":msgTime" => time(), ":msgText" => $params['tbMessage'])); $mId = $db->lastInsertId(); echo json_encode(array("status" => "ok", "managerName" => $managerName, "tbChatHash" => $chHash, "lastMessageId" => $mId, "lastMessageDate" => date("H:i:s"))); exit;
} else { file_put_contents($fileOfLastUpdate, "0"); $lastUpdateId = 0; } // Делаем long-poll запрос 60 секунд к серверу телеграм $updates = $tg->pollUpdates($lastUpdateId, 60); // Обрабатываем Updates, если они есть. foreach ($updates['result'] as $data) { $updateId = $updates['result'][count($updates['result']) - 1]['update_id']; $message = $data['message']['text']; $chatId = $data['message']['chat']['id']; // Эта команда для дебага, чтобы не перезапускать apache каждый раз, когда нужно перезапустить tbServer.php // Отправляешь боту команду /reboot и сервер останавливается. // В рабочей версии - нужно закоментить этот IF(){} if ($message == "/reboot") { $tg->sendMessage($chatId, $_localization["serverRestart"]); file_put_contents($fileOfLastUpdate, $updateId); exit; } $db = tbDatabase(); // Проверим, авторизован ли пользователь $sth = $db->prepare("SELECT count(*) as count FROM tbManagers WHERE mBotChatId=:mBotChatId"); $sth->execute(array(":mBotChatId" => $chatId)); $answer = $sth->fetch(); if ($answer["count"] > 0) { $isAuth = true; } else { $isAuth = false; } if ($isAuth === false) { if ($message == $tbManagerPassword) {