Priority File Manager

📁 public_html
Base Directory:
/home/ecedu/public_html/telegrambot
NameTypeSizeActions
📁 .. Folder -
📄 bot.php File 2620
Edit Download
📄 db.php File 958
Edit Download
📁 logs Folder -
📄 new_telegram_bot.zip File 6891
Edit Download
📁 uploads Folder -
📄 utils.php File 6530
Edit Download

View File: utils.php

<?php
require_once "db.php";

$API_KEY = "8338469743:AAEQ8UozjdloOl9GjYCvZghJd3sZCRB7atI"; // التوكن الخاص بك

// إرسال رسالة
function sendMessage($chat_id, $text, $keyboard = null) {
    global $API_KEY;
    $url = "https://api.telegram.org/bot$API_KEY/sendMessage";
    $postFields = [
        "chat_id" => $chat_id, 
        "text" => $text, 
        "parse_mode" => "HTML"
    ];
    if ($keyboard) {
        $postFields["reply_markup"] = json_encode(["keyboard" => $keyboard, "resize_keyboard" => true]);
    }
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
    curl_exec($ch);
    curl_close($ch);
}

// إرسال إجراء "جاري الكتابة" (Typing action)
function sendChatAction($chat_id, $action = "typing") {
    global $API_KEY;
    $url = "https://api.telegram.org/bot$API_KEY/sendChatAction";
    $postFields = ["chat_id" => $chat_id, "action" => $action];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
    curl_exec($ch);
    curl_close($ch);
}

// حفظ أو تحديث حالة المستخدم في جدول 'users'
function saveUserState($chat_id, $history) {
    global $pdo;
    $stmt = $pdo->prepare("INSERT INTO users (id, history) VALUES (?, ?) ON DUPLICATE KEY UPDATE history=?");
    $stmt->execute([$chat_id, json_encode($history), json_encode($history)]);
}

// جلب حالة المستخدم
function getUserState($chat_id) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT history FROM users WHERE id=?");
    $stmt->execute([$chat_id]);
    $row = $stmt->fetch();
    return $row && $row['history'] ? json_decode($row['history'], true) : [];
}

// البحث عن عنصر (سؤال/زر) في جدول 'faq' باستخدام العنوان
function searchFAQ($text) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT * FROM faq WHERE title=?");
    $stmt->execute([$text]);
    $row = $stmt->fetch();
    return $row ?: null;
}

// البحث بالتشابه عن إجابة في قاعدة البيانات
function fuzzySearchFAQ($query) {
    global $pdo;
    
    $clean_query = preg_replace('/[^\p{L}\p{N}\s]/u', ' ', $query);
    $keywords = array_slice(array_filter(explode(' ', $clean_query), function($k) {
        return mb_strlen($k, 'UTF-8') >= 3; // البحث عن كلمات طولها 3 أحرف فأكثر
    }), 0, 3);
    
    $where_clauses = [];
    $params = [];
    
    if (empty($keywords)) {
        return null;
    }

    // بناء شروط البحث
    foreach ($keywords as $keyword) {
        // البحث عن الكلمة في العنوان أو في نص الإجابة
        $where_clauses[] = "title LIKE ?";
        $where_clauses[] = "answer LIKE ?";
        $params[] = '%' . $keyword . '%';
        $params[] = '%' . $keyword . '%';
    }
    
    // الأولوية للعناوين المطابقة
    $sql = "SELECT title, answer FROM faq WHERE answer IS NOT NULL AND (title = ? OR " . implode(" OR ", $where_clauses) . ") LIMIT 1";
    
    // إضافة الاستعلام الأصلي كأولوية في البحث
    array_unshift($params, $query); 

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $row = $stmt->fetch();
    
    return $row && !empty($row['answer']) ? $row : null;
}


// حفظ سؤال جديد مع الإجابة
function saveFAQ($title, $answer, $parent_id = null) {
    global $pdo;
    $exists = $pdo->prepare("SELECT id FROM faq WHERE title=?");
    $exists->execute([$title]);
    if ($exists->rowCount() == 0) {
        $stmt = $pdo->prepare("INSERT INTO faq (title, answer, parent_id) VALUES (?, ?, ?)");
        $stmt->execute([$title, $answer, $parent_id]);
    }
}

// البحث في DuckDuckGo (للاجوبة غير الموجودة) - تم إصلاحها لضمان العمل
function searchDuckDuckGo($query) {
    $url = "https://api.duckduckgo.com/?q=".urlencode($query)."&format=json&no_redirect=1&skip_disambig=1";
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); // زيادة وقت الاتصال
    curl_setopt($ch, CURLOPT_TIMEOUT, 20); // زيادة وقت التنفيذ
    curl_setopt($ch, CURLOPT_USERAGENT, 'TelegramBot/1.0'); // إضافة User-Agent لتجنب الحجب
    $res = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($http_code != 200 || $res === FALSE) {
        return "عذراً، فشل الاتصال بمحرك البحث ({$http_code}). يرجى المحاولة لاحقاً.";
    }
    
    $data = json_decode($res, true);
    $answer = $data['AbstractText'] ?? $data['Answer'] ?? "لم يتم العثور على إجابة دقيقة لسؤالك في محركات البحث.";
    
    // التأكد من أن النص ليس فارغاً أو مجرد مسافة
    if (empty(trim($answer))) {
        return "لم يتم العثور على إجابة دقيقة لسؤالك في محركات البحث.";
    }
    
    return $answer;
}

// جلب القائمة الرئيسية
function mainMenu() {
    global $pdo;
    $stmt = $pdo->query("SELECT title FROM faq WHERE parent_id IS NULL");
    $rows = $stmt->fetchAll();
    $buttons = [];
    foreach ($rows as $row) {
        $buttons[] = [$row['title']];
    }
    return $buttons;
}

// جلب القائمة الفرعية
function getSubMenu($parent_id) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT id, title FROM faq WHERE parent_id=?");
    $stmt->execute([$parent_id]);
    $rows = $stmt->fetchAll();
    $buttons = [];
    foreach ($rows as $row) {
        $buttons[] = [$row['title']];
    }
    $buttons[] = ["🔙 الرجوع"];
    return $buttons;
}

// التحقق من وجود قائمة فرعية
function checkSubMenu($parent_id) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT id FROM faq WHERE parent_id=? LIMIT 1");
    $stmt->execute([$parent_id]);
    return $stmt->rowCount() > 0;
}
?>