Telegram Bot Script for Mod Categories with Subscription Check

Answered using ChatGPT 4o by ChatGPT4o

Question:
<?php $api_key = '7057364849:AAGaq3bYR_maPoKw_es9mM_QzhG43qPKpT0'; // Замените на ваш токен $telegram_api = "https://api.telegram.org/bot$api_key/"; $channel_username = '@grudovblog'; // Имя вашего канала $host = 'localhost'; $db = 'upic_modslive'; $user = 'upic_modslive'; $pass = 'Roma809567'; // Подключаемся к базе данных try { $pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pass); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { file_put_contents('log.txt', "Database connection failed: " . $e->getMessage() . "\n", FILE_APPEND); exit; // Завершаем выполнение скрипта при ошибке подключения } // Получаем входящие данные $update = json_decode(file_get_contents("php://input"), true); $chat_id = $update['message']['chat']['id'] ?? null; $text = $update['message']['text'] ?? ''; // Основные категории модов $categories = ['Графика', 'Скрипты', 'Фиксы']; // Проверка подписки на канал при вводе /start if ($text
Answer:
== '/start') {
    $response = file_get_contents($telegram_api . "getChatMember?chat_id=$channel_username&user_id=$chat_id");
    $response = json_decode($response, true);

    if ($response['result']['status'] == 'left') {
        $message = "Пожалуйста, подпишитесь на наш канал, чтобы использовать бота.";
        file_get_contents($telegram_api . "sendMessage?chat_id=$chat_id&text=" . urlencode($message));
        exit;
    } else {
        $message = "Добро пожаловать! Выберите категорию модов:\n" . implode("\n", $categories);
        file_get_contents($telegram_api . "sendMessage?chat_id=$chat_id&text=" . urlencode($message));
    }
}

// Обработка выбора категории  
if (in_array($text, $categories)) {
    $stmt = $pdo->prepare("SELECT name, description FROM mods WHERE category = :category");
    $stmt->execute(['category' => $text]);
    $mods = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if ($mods) {
        $message = "Моды в категории $text:\n";
        foreach ($mods as $mod) {
            $message .= "\nНазвание: " . $mod['name'] . "\nОписание: " . $mod['description'] . "\n";
        }
    } else {
        $message = "В категории $text пока нет модов.";
    }

    file_get_contents($telegram_api . "sendMessage?chat_id=$chat_id&text=" . urlencode($message));
}

// Логирование ошибок  
function logError($error) {
    file_put_contents('log.txt', $error . "\n", FILE_APPEND);
}
?>

This PHP script is a Telegram bot that interacts with users to provide information about mods in different categories. Here's a breakdown of the script:

  1. Database Connection: The script connects to a MySQL database using PDO. If the connection fails, it logs the error and exits.

  2. Telegram API Setup: The script sets up the Telegram API using the provided bot token and channel username.

  3. Handling Incoming Updates: The script reads incoming updates from Telegram, which include messages from users.

  4. Subscription Check: When a user sends the /start command, the bot checks if the user is subscribed to the specified Telegram channel. If not, it prompts the user to subscribe.

  5. Category Selection: If the user sends a message that matches one of the predefined categories, the bot fetches the corresponding mods from the database and sends the details back to the user.

  6. Error Logging: The script includes a function to log errors to a file.

Make sure to replace the placeholders with your actual database credentials and Telegram bot token. Also, ensure that your server has the necessary permissions to access the database and write to the log file.