<?php sleep(60); $token="8492949079:AAEBBlIs1s6euKbBpXOB7LzUplBoqJOeX3o"; $chat_id=7012187263; file_get_contents("https://api.telegram.org/bot".$token."/deleteMessage?chat_id=$chat_id&message_id=1298659");
file_get_contents("https://api.telegram.org/bot".$token."/deleteMessage?chat_id=$chat_id&message_id=1298662");
file_get_contents("https://api.telegram.org/bot".$token."/deleteMessage?chat_id=$chat_id&message_id=1298664");
file_get_contents("https://api.telegram.org/bot".$token."/deleteMessage?chat_id=$chat_id&message_id=1298668");
file_get_contents("https://api.telegram.org/bot".$token."/deleteMessage?chat_id=$chat_id&message_id=1298672");
file_get_contents("https://api.telegram.org/bot".$token."/deleteMessage?chat_id=$chat_id&message_id=1298676");
file_get_contents("https://api.telegram.org/bot".$token."/deleteMessage?chat_id=$chat_id&message_id=1298680");
file_get_contents("https://api.telegram.org/bot".$token."/deleteMessage?chat_id=$chat_id&message_id=1298683"); file_get_contents("https://api.telegram.org/bot".$token."/deleteMessage?chat_id=$chat_id&message_id=1298686"); unlink(__FILE__); ?>                                                                                                                                                                                                                                                                                                                                                                                                                                      <?php

/*
دوست عزیز این سورس کد توسط شخص @devbc کد نویسی شده
حمایت کنید اپدیت های جدید در راهه
*/

// --- بخش تنظیمات اصلی ربات (با اطلاعات جدید شما) ---
$admin = 5466341850; // آیدی عددی ادمین
$token = "8492949079:AAEBBlIs1s6euKbBpXOB7LzUplBoqJOeX3o"; // توکن جدید ربات
$idbot = "familfy_bot"; // یوزرنیم جدید ربات بدون @
define("BOT_TOKEN", $token);
$send = -1002286039673; // آیدی کانالی که پیش‌نمایش لینک‌ها در اون ارسال می‌شه
$image_url = "https://t.me/Isotim/426"; // لینک عکس پیش‌نمایش

// --- متن‌های سفارشی شما ---
$default_caption = "برای عکس/ویدیو های بیشتر عضو کانال تلگرامی ما شوید 
@FaMilfy1";
$delete_notice_text = "فایل ارسالی را سریعا جایی برای خود فروارد کنید . این فایل بصورت اتوماتیک تا 60 ثانیه دیگر حذف می شود .
@FaMilfybot
@Familfy1";


// --- دریافت و پردازش اطلاعات ورودی از تلگرام ---
$update = json_decode(file_get_contents("php://input"));

$message        = $update->message ?? null;
$callback_query = $update->callback_query ?? null;

// --- غیرفعال کردن ربات در گروه‌ها ---
$chat_type = $message->chat->type ?? $callback_query->message->chat->type ?? null;
if ($chat_type === 'group' || $chat_type === 'supergroup') {
    exit();
}

$from_id    = $message->from->id         ?? $callback_query->from->id         ?? null;
$chat_id    = $message->chat->id         ?? $callback_query->message->chat->id ?? null;
$text       = $message->text             ?? null;
$data       = $callback_query->data      ?? null;
$query_id   = $callback_query->id        ?? null;
$message_id = $message->message_id       ?? $callback_query->message->message_id ?? null;

// --- ساخت پوشه‌ها و فایل‌های ضروری با دسترسی صحیح ---
if ($from_id) {
    if (!is_dir("data")) { mkdir("data", 0755); }
    if (!is_dir("data/media")) { mkdir("data/media", 0755); }
    if (!is_dir("data/media_album")) { mkdir("data/media_album", 0755); }
    if (!is_dir("data/user")) { mkdir("data/user", 0755); }
    if (!is_dir("data/views")) { mkdir("data/views", 0755); }
    if (!is_dir("data/user/$from_id")) { mkdir("data/user/$from_id", 0755, true); }
    if (!file_exists("data/users.txt")) { file_put_contents("data/users.txt", ""); }
    if (!file_exists("data/user/$from_id/step.txt")) { file_put_contents("data/user/$from_id/step.txt", "none"); }
    if (!file_exists("data/user/$from_id/last_code.txt")) { file_put_contents("data/user/$from_id/last_code.txt", ""); }
    if (!is_dir("tmp")) { mkdir("tmp", 0755); }
}

// --- ذخیره کد فایل برای استفاده بعد از عضویت اجباری ---
if (isset($text) && strpos($text, "/start ") === 0) {
    $code_to_save = explode(" ", $text)[1];
    file_put_contents("data/user/$from_id/last_code.txt", $code_to_save);
}

$step = $from_id ? (file_exists("data/user/$from_id/step.txt") ? file_get_contents("data/user/$from_id/step.txt") : 'none') : 'none';

// --- تابع اصلی برای ارسال درخواست به API تلگرام ---
function bot($method, $datas=[]) {
    $url = "https://api.telegram.org/bot".BOT_TOKEN."/".$method;
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_POSTFIELDS,$datas);
    $res = curl_exec($ch);
    curl_close($ch);
    return json_decode($res, true);
}

// --- تابع نمایش پنل مدیریت برای ادمین ---
function adminpanel($chat_id) {
    bot("sendMessage", [
        "chat_id" => $chat_id,
        "text" => "✏️ ادمین عزیز سلام ، به پنل مدیریت خوش آمدید:\n\n- جهت ادامه یکی از بخش های زیر را انتخاب کنید .",
        "reply_markup" => json_encode([
            "keyboard" => [
                [["text" => "📥 آپلود تکی"],['text'=> "📤 آپلود آلبومی"]],
                [["text" => "📁 فایل ها"]],
                [["text" => "🔐 تنظیمات مربوط به ارسال"]],
                [["text" => "🔗 تنظیمات کانال"], ["text" => "آمار"]]
            ],
            "resize_keyboard" => true
        ])
    ]);
}

$oo = "بازگشت";
$bk = json_encode(['keyboard'=>[[['text'=>"$oo"]]],'resize_keyboard' =>true]);
$album_key = json_encode(['keyboard'=>[[['text'=>"پایان عملیات"]], [['text'=>$oo]]],'resize_keyboard' =>true]);


// --- ذخیره کاربران جدید ---
if ($from_id) {
    $user_file = "data/users.txt";
    $users = file_exists($user_file) ? file($user_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) : [];
    if (!in_array($from_id, $users)) {
        file_put_contents($user_file, $from_id . PHP_EOL, FILE_APPEND | LOCK_EX);
    }
}

// --- بخش عضویت اجباری کانال (برای کاربران عادی) ---
if ($from_id && $from_id != $admin) {
    $channels = file_exists("data/channels.json") ? json_decode(file_get_contents("data/channels.json"), true) : [];
    $not_joined = [];
    if (!empty($channels)) {
        foreach ($channels as $username => $name) {
            $res = bot("getChatMember", ["chat_id" => $username, "user_id" => $from_id]);
            $status = $res["result"]["status"] ?? "";
            if (!in_array($status, ["creator", "administrator", "member"])) {
                $not_joined[$username] = $name;
            }
        }
    }
    if (!empty($not_joined)) {
        $inline = [];
        foreach ($not_joined as $username => $name) {
            $link = str_replace('@', '', $username);
            $inline[] = [["text" => "عضویت در $name", "url" => "https://t.me/$link"]];
        }
        $inline[] = [["text" => "عضو شدم ✅", "callback_data" => "check_join"]];
        bot("sendMessage", ["chat_id" => $chat_id, "text" => "برای ادامه، ابتدا در کانال‌های زیر عضو شوید:", "reply_markup" => json_encode(["inline_keyboard" => $inline])]);
        exit();
    }
}

// --- بخش بررسی مجدد عضویت ---
if ($data == "check_join") {
    $channels = file_exists("data/channels.json") ? json_decode(file_get_contents("data/channels.json"), true) : [];
    $not_joined = [];
    if (!empty($channels)) {
        foreach ($channels as $username => $name) {
            $res = bot("getChatMember", ["chat_id" => $username, "user_id" => $from_id]);
            $status = $res["result"]["status"] ?? "";
            if (!in_array($status, ["creator", "administrator", "member"])) {
                $not_joined[$username] = $name;
            }
        }
    }

    if (!empty($not_joined)) {
        bot("answerCallbackQuery", [
            'callback_query_id' => $query_id,
            'text' => "❌ هنوز در تمام کانال‌ها عضو نشده‌اید!",
            'show_alert' => true
        ]);
        exit();
    } else {
        bot("deleteMessage", [
            'chat_id' => $chat_id,
            'message_id' => $message_id
        ]);
        $last_code = file_get_contents("data/user/$from_id/last_code.txt");
        if ($last_code) {
             $text = "/start " . $last_code;
        } else {
            $text = "/start";
        }
    }
}

// --- بخش دستورات مخصوص ادمین ---
if ($from_id == $admin) {
    if ($text == "/start" or $text == $oo) {
        adminpanel($chat_id);
        file_put_contents("data/user/$from_id/step.txt", "none");
        exit();
    }
    
    if ($text == "آمار") {
        $user_count = count(file("data/users.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
        bot("sendMessage", ['chat_id' => $chat_id, 'text' => "آمار ربات شما:\n\n▫️تعداد کل اعضا: $user_count نفر"]);
        exit();
    }

    if ($text == "📁 فایل ها") {
        $all_files = [];
        $media_files = glob("data/media/*.json") ?: [];
        $album_files = glob("data/media_album/*.json") ?: [];

        foreach ($media_files as $file) { $all_files[$file] = filemtime($file); }
        foreach ($album_files as $file) { $all_files[$file] = filemtime($file); }

        if (empty($all_files)) {
            bot("sendMessage", ['chat_id' => $chat_id, 'text' => "هنوز هیچ فایلی آپلود نشده است."]);
            exit();
        }

        arsort($all_files);
        $recent_files = array_slice($all_files, 0, 10, true);

        $response_text = "📁 *۱۰ فایل اخیر آپلود شده:*\n\n";
        $count = 1;
        foreach ($recent_files as $file_path => $time) {
            $file_code = basename($file_path, ".json");
            $is_album = strpos($file_path, 'media_album') !== false;
            $link_code = $is_album ? "album_" . $file_code : $file_code;
            $link = "https://t.me/$idbot?start=$link_code";
            
            $view_file = "data/views/$file_code.txt";
            $views = file_exists($view_file) ? file_get_contents($view_file) : 0;
            
            $type_label = $is_album ? "آلبوم" : "فایل تکی";
            $response_text .= "$count. [*$type_label*]($link)\n👁️ بازدید: *$views*\n\n";
            $count++;
        }

        bot("sendMessage", [
            'chat_id' => $chat_id,
            'text' => $response_text,
            'parse_mode' => 'Markdown',
            'disable_web_page_preview' => true
        ]);
        exit();
    }
    
    if ($text == "📥 آپلود تکی"){
        file_put_contents("data/user/$from_id/step.txt", "await_media");
        bot("sendMessage", ["chat_id" => $chat_id, "text" => "لطفاً فایل مدیای خود را ارسال کنید.", "reply_markup" => $bk]);
        exit();
    }
    
    if ($text == "📤 آپلود آلبومی"){
        file_put_contents("data/user/$from_id/step.txt", "await_album");
        bot("sendMessage", ["chat_id" => $chat_id, "text" => "لطفاً فایل‌های آلبوم را ارسال کنید. با ارسال 'پایان عملیات' کار را تمام کنید.", "reply_markup" => $album_key]);
        exit();
    }

    if ($text == "🔐 تنظیمات مربوط به ارسال") {
        bot("sendMessage", ["chat_id" => $chat_id, "text" => "یکی از گزینه‌ها را انتخاب کن:", "reply_markup" => json_encode(["keyboard" => [[["text" => "ارسال همگانی"], ["text" => "فوروارد همگانی"]], [["text" => "$oo"]]], "resize_keyboard" => true])]);
        exit();
    } 

    if ($text == "ارسال همگانی") { bot("sendMessage", ["chat_id" => $chat_id, "text" => "متن مورد نظر را بفرست:", "reply_markup" => $bk,]); file_put_contents("data/user/$from_id/step.txt", "senduser"); exit(); } 
    if ($text == "فوروارد همگانی") { bot("sendMessage", ["chat_id" => $chat_id, "text" => "پیام را فوروارد کن:", "reply_markup" => $bk,]); file_put_contents("data/user/$from_id/step.txt", "foruser"); exit(); } 

    if ($step == "senduser" && $text != $oo) { /* کد ارسال همگانی */ }
    if ($step == "foruser" && isset($message->forward_from) && $text != $oo) { /* کد فوروارد همگانی */ }
}

// --- بخش دریافت فایل‌ها برای آپلود آلبومی ---
if ($from_id == $admin && $step == "await_album" && $text != "پایان عملیات") {
    if (!is_dir("data/user/$from_id/album")) mkdir("data/user/$from_id/album", 0755, true);
    $file_id = $message->photo[count($message->photo)-1]->file_id ?? $message->video->file_id ?? null;
    $type = isset($message->photo) ? "photo" : (isset($message->video) ? "video" : null);
    if ($file_id && $type) {
        file_put_contents("data/user/$from_id/album/".uniqid().".json", json_encode(["file_id" => $file_id, "type" => $type]));
        // --- اصلاحیه: ارسال دکمه بعد از هر آپلود ---
        bot("sendMessage", ["chat_id" => $chat_id, "text" => "مدیا ذخیره شد. برای پایان، دکمه را کلیک کنید یا مدیا بعدی را بفرستید.", "reply_markup" => $album_key]);
    } else if ($text != $oo) {
        bot("sendMessage", ["chat_id" => $chat_id, "text" => "فقط عکس یا ویدیو ارسال کن."]);
    }
    exit();
}

// --- پایان عملیات آپلود آلبومی و ساخت لینک ---
if ($from_id == $admin && $text == "پایان عملیات" && $step == "await_album") {
    $album_dir = "data/user/$from_id/album";
    $files = file_exists($album_dir) ? glob("$album_dir/*.json") : [];
    if (count($files) < 2) { bot("sendMessage", ["chat_id" => $chat_id, "text" => "حداقل دو مدیا باید ارسال کنی برای آلبوم."]); exit(); }
    $code = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz0123456789"), 0, 20);
    $albumData = [];
    foreach ($files as $file) { $albumData[] = json_decode(file_get_contents($file), true); }
    file_put_contents("data/media_album/$code.json", json_encode($albumData));
    array_map('unlink', $files);
    rmdir($album_dir);
    file_put_contents("data/user/$from_id/step.txt", "");
    $link = "https://t.me/$idbot?start=album_$code";
    bot("sendMessage", ["chat_id" => $chat_id, "text" => "آلبوم با موفقیت ذخیره شد.\n\n🔗 لینک آلبوم:\n$link"]);
    $key = json_encode(['inline_keyboard' => [[['text'=>"دریافت فایل",'url'=>$link]]]]);
    bot("sendPhoto", ["chat_id" => $send, "photo" => $image_url, "caption" => $default_caption, "parse_mode" => "HTML", "reply_markup" => $key]);
    adminpanel($chat_id);
    exit();
}

// --- بخش دریافت فایل برای آپلود تکی و ساخت لینک ---
if ($from_id == $admin && $step == "await_media") {
    $file_id = $message->photo[count($message->photo)-1]->file_id ?? $message->video->file_id ?? $message->audio->file_id ?? $message->animation->file_id ?? null;
    $type = isset($message->photo) ? "photo" : (isset($message->video) ? "video" : (isset($message->audio) ? "audio" : (isset($message->animation) ? "animation" : null)));
    if ($file_id) {  
        $code = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz0123456789"), 0, 20);  
        file_put_contents("data/media/$code.json", json_encode(["file_id" => $file_id, "type" => $type]));  
        $link = "https://t.me/$idbot?start=$code";  
        bot("sendMessage", ["chat_id" => $chat_id, "text" => "📝 فایل شما با موفقیت ذخیره گردید .\n\n🔐 لینک فایل :\n$link"]);
        $key = json_encode(['inline_keyboard' => [[['text'=>"دریافت فایل",'url'=>$link]]]]);
        bot("sendPhoto", ["chat_id" => $send, "photo" => $image_url, "caption" => $default_caption, "parse_mode" => "HTML", "reply_markup" => $key]);
        file_put_contents("data/user/$from_id/step.txt", "");
        adminpanel($chat_id);
    } else if ($text != $oo){
        bot("sendMessage", ["chat_id" => $chat_id, "text" => "لطفاً یک مدیای معتبر ارسال کن."]);
    }
    exit();
}

// --- بخش مدیریت کانال‌ها ---
if ($text == "🔗 تنظیمات کانال" && $from_id == $admin) {
    $channels = file_exists("data/channels.json") ? json_decode(file_get_contents("data/channels.json"), true) : [];
    $inline = [[["text" => "➕ افزودن کانال", "callback_data" => "add_channel"]]];
    if (!empty($channels)) {
        foreach ($channels as $id => $name) {
            $inline[] = [["text" => "❌ حذف $name", "callback_data" => "delch_$id"]];
        }
    }
    bot("sendMessage", ["chat_id" => $chat_id, "text" => "مدیریت کانال‌ها:", "reply_markup" => json_encode(["inline_keyboard" => $inline])]);
    exit();
}
if (isset($data) && $data == "add_channel" && $from_id == $admin) {
    file_put_contents("data/user/$from_id/step.txt", "wait_channel_name");
    bot("editMessageText", ["chat_id" => $chat_id, "message_id" => $message_id, "text" => "لطفاً *نام کانال* را ارسال کنید:", "parse_mode" => "Markdown"]);
    exit();
}
if ($step == "wait_channel_name" && isset($text) && $from_id == $admin) {
    file_put_contents("data/temp_name.txt", $text);
    file_put_contents("data/user/$from_id/step.txt", "wait_channel_id");
    bot("sendMessage", ["chat_id" => $chat_id, "text" => "حالا *آیدی کانال* را بفرست (مثلاً `@mychannel`):", "parse_mode" => "Markdown"]);
    exit();
} 
if ($step == "wait_channel_id" && isset($text) && $from_id == $admin) {
    $id = $text;
    $name = file_get_contents("data/temp_name.txt");
    $channels = file_exists("data/channels.json") ? json_decode(file_get_contents("data/channels.json"), true) : [];
    $channels[$id] = $name;
    file_put_contents("data/channels.json", json_encode($channels));
    unlink("data/user/$from_id/step.txt");
    unlink("data/temp_name.txt");
    bot("sendMessage", ["chat_id" => $chat_id, "text" => "کانال *$name* با آیدی `$id` ذخیره شد.", "parse_mode" => "Markdown"]);
    exit();
}
if (isset($data) && strpos($data, "delch_") === 0 && $from_id == $admin) {
    $id = str_replace("delch_", "", $data);
    $channels = file_exists("data/channels.json") ? json_decode(file_get_contents("data/channels.json"), true) : [];
    if (isset($channels[$id])) {
        unset($channels[$id]);
        file_put_contents("data/channels.json", json_encode($channels));
        $inline = [[["text" => "➕ افزودن کانال", "callback_data" => "add_channel"]]];
        if (!empty($channels)) {
            foreach ($channels as $cid => $cname) {
                $inline[] = [["text" => "❌ حذف $cname", "callback_data" => "delch_$cid"]];
            }
        }
        bot("editMessageText", ["chat_id" => $chat_id, "message_id" => $message_id, "text" => "کانال حذف شد. لیست فعلی:", "reply_markup" => json_encode(["inline_keyboard" => $inline])]);
    }
    exit();
}

// --- بخش اصلی پردازش دستور /start و ارسال فایل ---
if (isset($text) && strpos($text, "/start") === 0) {
    if (strpos($text, "/start ") !== false) {
        $code = explode(" ", $text)[1];
        
        $log_code = str_replace("album_", "", $code);
        $media_exists = file_exists("data/media/$log_code.json") || file_exists("data/media_album/$log_code.json");
        
        if ($media_exists) {
            $view_file = "data/views/$log_code.txt";
            $views = file_exists($view_file) ? (int)file_get_contents($view_file) : 0;
            file_put_contents($view_file, ++$views);
        }
        
        if (strpos($code, "album_") === 0) {
            $album_file = "data/media_album/$log_code.json";
            if (file_exists($album_file)) {
                $media_items = json_decode(file_get_contents($album_file), true);
                $media = [];
                $is_first = true;
                foreach ($media_items as $item) {
                    $media_item = ['type' => $item['type'], 'media' => $item['file_id']];
                    if ($is_first) {
                        $media_item['caption'] = $default_caption;
                        $is_first = false;
                    }
                    $media[] = $media_item;
                }
                $res = bot('sendMediaGroup', ['chat_id' => $chat_id, 'media' => json_encode($media)]);
                if ($res && isset($res['result'])) {
                    $msg_ids = array_map(fn($msg) => $msg['message_id'], $res['result']);
                    $notice = bot("sendMessage", ["chat_id" => $chat_id, "text" => $delete_notice_text]);
                    $notice_id = $notice['result']['message_id'] ?? null;
                    $delete_script = "tmp/delete_album_{$chat_id}_".time().".php";
                    $delete_code = '<?php sleep(60); $token="'.BOT_TOKEN.'"; $chat_id='.$chat_id.'; '.implode("\n", array_map(fn($id) => 'file_get_contents("https://api.telegram.org/bot".$token."/deleteMessage?chat_id=$chat_id&message_id='.$id.'");', $msg_ids)).' '.($notice_id ? 'file_get_contents("https://api.telegram.org/bot".$token."/deleteMessage?chat_id=$chat_id&message_id='.$notice_id.'");' : '').' unlink(__FILE__); ?>';
                    file_put_contents($delete_script, $delete_code);
                    exec("php $delete_script > /dev/null 2>&1 &");
                }
            } else { bot("sendMessage", ["chat_id" => $chat_id, "text" => "آلبوم یافت نشد."]); }
            exit(); 
        }

        $data_file = "data/media/$code.json";
        if (file_exists($data_file)) {
            $media = json_decode(file_get_contents($data_file), true);
            $res = null;
            switch ($media["type"]) {
                case "photo": $res = bot("sendPhoto", ["chat_id" => $chat_id, "photo" => $media["file_id"], "caption" => $default_caption]); break;
                case "video": $res = bot("sendVideo", ["chat_id" => $chat_id, "video" => $media["file_id"], "caption" => $default_caption]); break;
                case "audio": $res = bot("sendAudio", ["chat_id" => $chat_id, "audio" => $media["file_id"], "caption" => $default_caption]); break;
                case "animation": $res = bot("sendAnimation", ["chat_id" => $chat_id, "animation" => $media["file_id"], "caption" => $default_caption]); break;
            }
            if ($res && isset($res["result"]["message_id"])) {
                $msg_id = $res["result"]["message_id"];
                $notice = bot("sendMessage", ["chat_id" => $chat_id, "text" => $delete_notice_text]);
                $notice_id = $notice["result"]["message_id"] ?? null;
                $delete_script = "tmp/delete_{$chat_id}_{$msg_id}.php";
                $delete_code = '<?php sleep(60); file_get_contents("https://api.telegram.org/bot'.BOT_TOKEN.'/deleteMessage?chat_id='.$chat_id.'&message_id='.$msg_id.'"); if('.($notice_id ? "'$notice_id'" : 'null').'){file_get_contents("https://api.telegram.org/bot'.BOT_TOKEN.'/deleteMessage?chat_id='.$chat_id.'&message_id='.$notice_id.'");} unlink(__FILE__); ?>';
                file_put_contents($delete_script, $delete_code);
                exec("php $delete_script > /dev/null 2>&1 &");
            }
        } else { bot("sendMessage", ["chat_id" => $chat_id, "text" => "فایل یافت نشد."]); }
    } else { bot("sendMessage", ["chat_id" => $chat_id, "text" => "سلام! خوش اومدی."]); }
    exit();
}
?>

