Example #1
0
// Подключаем конфигурационный файл
// Require the configuration
require 'tbConfig.php';
// Пишем лог
// Start writing log-file
$fLog = fopen($tbRootDir . "/tbServer.log", 'a');
fwrite($fLog, date("d.m.Y H:i:s") . " — starting server... ");
// Открываем и пытаемся залочить файл running, тем самым даем жить только одному процессу
// Open and try to Lock «running» file, so only one process will be alive
$fR = fopen($tbRootDir . "/running", 'w');
$fl = flock($fR, LOCK_EX | LOCK_NB);
if ($fl) {
    fwrite($fLog, " Ok!\r\n");
    require 'tbClass.php';
    // Новый экземпляр телеграм бота
    $tg = new telegramBot($tbAPIToken);
    // Функция подключения к БД
    require 'tbDatabase.php';
    /*  Сервер запущен и работает  */
    /*  Server is working now  */
    while (true) {
        if (is_file($tbRootDir . "/stopserver")) {
            unlink($tbRootDir . "/stopserver");
            echo "\r\nСервер остановлен по команде stopserver!";
            fwrite($fLog, date("d.m.Y H:i:s") . " — Сервер остановлен по команде stopserver!\r\n");
            exit;
        }
        // В обычном файле мы будем хранить ID последнего обновления
        $fileOfLastUpdate = $tbRootDir . "/lastUpdateId";
        if (is_file($fileOfLastUpdate)) {
            $lastUpdateId = intval(file_get_contents($fileOfLastUpdate)) + 1;
Example #2
0
<?php

require '../src/Telegram.php';
$token = '';
// HERE YOUR TOKEN
// You will need a file called quotes (without extension)
// from there it will take the quotes and send them to your subscribers :)
$tg = new telegramBot($token);
$offset = 0;
$response = $tg->pollUpdates($offset, 60);
$response = json_decode($response, true);
if ($response['ok']) {
    foreach ($response['result'] as $data) {
        $chatID = $data['message']['chat']['id'];
        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']);
<?php

require '../src/Telegram.php';
///////////// CONFIG YOUR BOT'S TOKEN /////////
// Create telegram Bot token with @BotFather - https://github.com/mgp25/Telegram-Bot-API/wiki/Setup-Guide
$token = "";
// HERE YOUR TOKEN
//////////////////////////////////////////////////
echo "####################################\n";
echo "#          Telegram CLIENT         #\n";
echo "####################################\n\n";
$tg = new telegramBot($token);
$chat_id = null;
$guessed = false;
$sendQuestion = false;
$offset = 0;
echo "Get Bot Information:\n";
$updates = $tg->getMe();
echo json_encode($updates) . "\n";
// Custom keyboard
$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'];
            }
//Выводим все ошибки и предупреждения
set_time_limit(0);
//Время выполнения скрипта не ограничено
ob_implicit_flush();
//Включаем вывод без буферизации
ignore_user_abort(true);
// Игнорируем закрытие окна браузера с сервером
// Create new Bot Object
require 'Telegram.php';
require 'config.php';
//$bot = new TelegramBot($tokenAPI);
$fLog = fopen($dir . "/log.txt", 'a');
fwrite($fLog, date("d.m.Y H:i:s") . " — запуск сервера... ");
$fR = fopen($dir . "/running", 'w');
$fl = flock($fR, LOCK_EX | LOCK_NB);
$tg = new telegramBot($tokenAPI);
if ($fl) {
    //	print("I`m the only running process...<hr>");
    fwrite($fLog, " Успешно!\r\n");
    while (true) {
        // Get lastUpdate ID
        $fileOfUpdate = $dir . "/lastupdate.txt";
        if (is_file($fileOfUpdate)) {
            $updateIdFrom = intval(file_get_contents($fileOfUpdate)) + 1;
        } else {
            file_put_contents($fileOfUpdate, "0");
            $updateIdFrom = 0;
        }
        $fileOfAuth = $dir . "/authchats.txt";
        if (is_file($fileOfAuth)) {
            $authDialogs = file($fileOfAuth);
    $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;
//Выводим все ошибки и предупреждения
set_time_limit(0);
//Время выполнения скрипта не ограничено
ob_implicit_flush();
//Включаем вывод без буферизации
ignore_user_abort(true);
// Игнорируем закрытие окна браузера с сервером
// Create new Bot Object
require 'Telegram.php';
require 'config.php';
//$bot = new TelegramBot($tokenAPI);
$fLog = fopen($dir . "/logMon.txt", 'a');
fwrite($fLog, date("d.m.Y H:i:s") . " — запуск монитора... ");
$fR = fopen($dir . "/running2", 'w');
$fl = flock($fR, LOCK_EX | LOCK_NB);
$tg = new telegramBot($tokenAPI);
if ($fl) {
    //	print("I`m the only running process...<hr>");
    fwrite($fLog, " Успешно!\r\n");
    while (true) {
        // Get lastUpdate ID
        $fileOfAuth = $dir . "/authchats.txt";
        if (is_file($fileOfAuth)) {
            $authDialogs = file($fileOfAuth);
        } else {
            file_put_contents($fileOfAuth, "");
            $authDialogs = array();
        }
        $photos = scandir($dir . "/new");
        foreach ($photos as $p => $photo) {
            if ($photo != ".." && $photo != ".") {
Example #7
0
<?php

include "include.php";
global $pluginManager;
global $message;
global $msg;
global $api;
global $sender;
global $db;
global $t;
$t = new Translator();
$db = new MySql();
$api = new telegramBot(TELEGRAM_API_TOKEN);
$pluginManager = new PluginManager();
$pluginManager->collectAliases();
if (defined("IS_CRONJOB")) {
    // Cronjob running
    // TODO
} else {
    // Message received
    $update = new Update($api->getWebhookUpdates());
    if ($update->type == "inlineQuery") {
    } else {
        $message = $update->message;
        $pluginManager->sendReceived($message);
        if ($message->is_command) {
            $cmd = $message->getCommand();
            if (!$cmd) {
                exit;
            }
            $cmd = $pluginManager->resolveAlias($cmd);
    $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;
// Подключаем конфигурационный файл
// Require the configuration
require 'tbConfig.php';
// Пишем лог
// Start writing log-file
$fLog = fopen($tbRootDir . "/tbServer.log", 'a');
fwrite($fLog, date("d.m.Y H:i:s") . " — starting server... ");
// Открываем и пытаемся залочить файл running, тем самым даем жить только одному процессу
// Open and try to Lock «running» file, so only one process will be alive
$fR = fopen($tbRootDir . "/running", 'w');
$fl = flock($fR, LOCK_EX | LOCK_NB);
if ($fl) {
    fwrite($fLog, " Ok!\r\n");
    require 'tbClass.php';
    // Новый экземпляр телеграм бота
    $tg = new telegramBot($tbAPIToken);
    // Функция подключения к БД
    require 'tbDatabase.php';
    /*  Сервер запущен и работает  */
    /*  Server is working now  */
    while (true) {
        if (is_file($tbRootDir . "/stopserver")) {
            unlink($tbRootDir . "/stopserver");
            echo "\r\n" . $_localization["serverStoppedByCommand"];
            fwrite($fLog, date("d.m.Y H:i:s") . " — " . $_localization["serverStoppedByCommand"] . "\r\n");
            exit;
        }
        // В обычном файле мы будем хранить ID последнего обновления
        $fileOfLastUpdate = $tbRootDir . "/lastUpdateId";
        if (is_file($fileOfLastUpdate)) {
            $lastUpdateId = intval(file_get_contents($fileOfLastUpdate)) + 1;