<?php
require
DIR . '/SourceQuery/bootstrap.php';
use xPaw\SourceQuery\SourceQuery;
const TOKEN = "************************************************";
const COMMANDS = ['/start', '/info'];
const URL = 'https://***************'; // ДОМЕН ПИШЕМ БЕЗ СЛЕША ("/") в конце
const DEFAULT_IMAGE = 'noimage.jpg'; // Когда не находит карту с названием maps/cs_mansion.jpg будет отправлять maps/no_image.png
const DEBUG = true; // Не забудьте отключить DEBUG после тестов! (true|false)
$servers = [
'/csdm' => '**************'
];
$data = json_decode(file_get_contents('php://input'), true);
if (empty($data['message']['chat']['id'])) {
exit();
}
$chatId = $data['message']['chat']['id'];
$messageId = $data['message']['message_id'];
$text = $data['message']['text'] ?? '';
if (isset($data['message']['new_chat_members'])) {
welcomeUser($data['message']['from'], $chatId, $messageId);
exit();
}
if (!empty($text)) {
processMessage($text, $chatId, $messageId, $servers);
}
function debug($message) {
if(DEBUG) {
file_put_contents(
DIR . '/debug.log', date("Y-m-d H:i:s") . " - " . $message . "\n", FILE_APPEND);
}
}
function welcomeUser($user, $chatId, $messageId) {
$name = "<a href='tg://user?id={$user['id']}'>{$user['first_name']}" . (!empty($user['last_name']) ? " {$user['last_name']}" : "") . "</a>";
sendTelegramMessage($chatId, "Добро пожаловать {$name}!", $messageId);
}
function processMessage($text, $chatId, $messageId, $servers) {
debug("Получено сообщение: $text");
foreach(COMMANDS as $command) {
if (mb_stripos($text, $command) !== false) {
debug("Команда {$command}, отправляем информацию о всех серверах.");
sendAllServersInfo($chatId, $messageId, $servers);
return;
}
}
foreach ($servers as $key => $server) {
if (mb_stripos($text, $key) !== false) {
debug("Команда $key найдена, отправляем информацию о сервере $server.");
sendServerInfo($key, $server, $chatId, $messageId);
exit();
}
}
debug("Команда не распознана: $text");
}
function sendAllServersInfo($chatId, $messageId, $servers) {
$info = "";
foreach ($servers as $key => $server) {
$info .= getServerStatus($server, $key, false) . "\n\n";
}
sendTelegramMessage($chatId, $info, $messageId);
}
function sendServerInfo($key, $server, $chatId, $messageId) {
$image = URL . '/maps/' . DEFAULT_IMAGE;
$info = getServerStatus($server, $key, true, $image);
sendTelegramPhoto($chatId, $info, $image, $messageId);
}
function getServerStatus($server, $key, $includePlayers = false, &$image = null) {
$cacheDir =
DIR . "/cache";
$cacheFile = "$cacheDir/{$key}.json";
$cacheTime = 30;
if (!is_dir($cacheDir)) {
mkdir($cacheDir, 0777, true);
}
if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheTime) {
$cachedData = json_decode(file_get_contents($cacheFile), true);
if (!$includePlayers) {
return $cachedData['info'];
}
return $cachedData['info'] . $cachedData['players'];
}
$query = new SourceQuery();
try {
$query->Connect(strstr($server, ':', true), str_replace(':', '', strstr($server, ':')), 1, SourceQuery::GOLDSOURCE);
$infos = $query->GetInfo();
$replace2x2Map = $infos['Map'];
if (substr($replace2x2Map, -4) === '_2x2') {
$replace2x2Map = substr($replace2x2Map, 0, -4);
}
$imagePath =
DIR . '/maps/' . $replace2x2Map . '.jpg';
if (file_exists($imagePath)) {
$image = URL . '/maps/' . $replace2x2Map . '.jpg';
}
$info = "<blockquote>{$infos['HostName']}</blockquote>\nКарта: <code>{$infos['Map']}</code> {$key}\n" .
"Игроки: {$infos['Players']} из {$infos['MaxPlayers']} ({$infos['Bots']} ботов)\nIP: <code>{$server}</code>";
$players = getPlayersInfo($query->GetPlayers());
file_put_contents($cacheFile, json_encode([
'info' => $info,
'players' => $players
]));
return $includePlayers ? $info . $players : $info;
} catch (Exception $e) {
return "<blockquote>Ошибка</blockquote>\nКарта: Неизвестно {$key}\nИгроки: 0 из 0 (0 ботов)\nIP: $server";
} finally {
$query->Disconnect();
}
}
function getPlayersInfo($players) {
if (empty($players)) {
return "\n\n<strong>Игроков нет.</strong>";
}
$info = "\n\n<strong>Ник (Фраги | Время в игре)</strong>\n";
foreach ($players as $index => $player) {
$info .= ($index + 1) . ".

<code>{$player['Name']}</code> (<code>{$player['Frags']}</code> | <code>{$player['TimeF']}</code>)\n";
}
return $info;
}
function sendTelegramMessage($chatId, $text, $replyToMessageId = null) {
$url = "
https://api.telegram.org/bot" . TOKEN . "/sendMessage?" . http_build_query([
'chat_id' => $chatId,
'text' => $text,
'parse_mode' => "HTML",
'disable_web_page_preview' => true,
'reply_to_message_id' => $replyToMessageId
]);
debug("Отправка сообщения в Telegram: $url");
$response = file_get_contents($url);
debug("Ответ Telegram API: $response");
}
function sendTelegramPhoto($chatId, $caption, $image, $replyToMessageId = null) {
$url = "
https://api.telegram.org/bot" . TOKEN . "/sendPhoto";
$postData = [
'chat_id' => $chatId,
'caption' => $caption,
'parse_mode' => "HTML",
'disable_web_page_preview' => true,
'reply_to_message_id' => $replyToMessageId,
'photo' => new CURLFile($image)
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
debug("Ответ Telegram API: " . $response);
if ($error) {
debug("Ошибка cURL: " . $caption . $error);
}
}