prepare($query); if ($stmt === false) { throw new Exception("Prepare failed: " . $conn->error); } if (!empty($params)) { $stmt->bind_param($types, ...$params); } $stmt->execute(); $query_result = $stmt->get_result(); if ($query_result) { $result = $query_result; } else { $result = $stmt->affected_rows >= 0; } } catch (Exception $e) { file_put_contents(__DIR__ . '/db_errors.log', date('[Y-m-d H:i:s]') . " Query Error: " . $e->getMessage() . "\nQuery: $query\n", FILE_APPEND); } finally { if (isset($stmt)) $stmt->close(); $conn->close(); } return $result; } // ثبت کاربر اگر قبلاً وجود نداشته باشد function registerUser($user) { $userId = $user['id']; $firstName = $user['first_name'] ?? ''; $username = $user['username'] ?? ''; executeQuery( "INSERT INTO users (user_id, first_name, username) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE first_name = VALUES(first_name), username = VALUES(username)", [$userId, $firstName, $username], "iss" ); // ایجاد رکورد تیکت برای کاربر executeQuery("INSERT IGNORE INTO tickets (user_id) VALUES (?)", [$userId], "i"); } // دریافت لیست تمام کاربران (User IDs) function getAllUsers() { $result = executeQuery("SELECT user_id FROM users WHERE is_blocked = 0"); $users = []; if ($result) { while ($row = $result->fetch_assoc()) { $users[] = $row['user_id']; } } return $users; } // دریافت اطلاعات کاربر function getUserInfo($userId) { $result = executeQuery("SELECT * FROM users WHERE user_id = ?", [$userId], "i"); return $result ? $result->fetch_assoc() : null; } // دریافت اطلاعات کاربر با یوزرنیم function getUserInfoByUsername($username) { // حذف @ از ابتدای نام کاربری در صورت وجود if (strpos($username, '@') === 0) { $username = substr($username, 1); } $result = executeQuery("SELECT * FROM users WHERE username = ?", [$username], "s"); return $result ? $result->fetch_assoc() : null; } // مسدود یا رفع مسدودیت کاربر function toggleBlockUser($userId, $block = true) { $blockValue = $block ? 1 : 0; return executeQuery("UPDATE users SET is_blocked = ? WHERE user_id = ?", [$blockValue, $userId], "ii"); } // بررسی محدودیت زمانی ارسال تیکت function canSendTicket($userId) { $result = executeQuery("SELECT last_ticket_time FROM tickets WHERE user_id = ?", [$userId], "i"); if ($result && $row = $result->fetch_assoc()) { $lastTicketTime = strtotime($row['last_ticket_time']); if ($lastTicketTime && (time() - $lastTicketTime) < TICKET_COOLDOWN) { $remainingTime = TICKET_COOLDOWN - (time() - $lastTicketTime); $minutes = floor($remainingTime / 60); $seconds = $remainingTime % 60; return ['can_send' => false, 'remaining' => "$minutes دقیقه و $seconds ثانیه"]; } } return ['can_send' => true]; } // به‌روزرسانی زمان آخرین تیکت function updateLastTicketTime($userId) { executeQuery("UPDATE tickets SET last_ticket_time = NOW() WHERE user_id = ?", [$userId], "i"); } // دریافت لیست کانال‌های اجباری function getRequiredChannels() { $result = executeQuery("SELECT channel_id, title, invite_link FROM required_channels ORDER BY id ASC"); $channels = []; if ($result) { while ($row = $result->fetch_assoc()) { $channels[] = $row; } } return $channels; } // اضافه کردن کانال اجباری function addRequiredChannel($channelId, $title, $inviteLink = null) { // بررسی وجود کانال $checkResult = executeQuery("SELECT id FROM required_channels WHERE channel_id = ?", [$channelId], "s"); if ($checkResult && $checkResult->num_rows > 0) { return false; // کانال قبلاً اضافه شده است } return executeQuery( "INSERT INTO required_channels (channel_id, title, invite_link) VALUES (?, ?, ?)", [$channelId, $title, $inviteLink], "sss" ); } // حذف کانال اجباری function deleteRequiredChannel($channelId) { return executeQuery("DELETE FROM required_channels WHERE channel_id = ?", [$channelId], "s"); } // بررسی عضویت کاربر در یک کانال function isUserMemberOfChannel($userId, $channelId) { $response = telegramAPI('getChatMember', [ 'chat_id' => $channelId, 'user_id' => $userId ]); if (isset($response['ok']) && $response['ok']) { $status = $response['result']['status']; return in_array($status, ['member', 'creator', 'administrator']); } return false; } // بررسی عضویت کاربر در تمام کانال‌های اجباری function checkAllRequiredChannels($userId, $chatId) { $requiredChannels = getRequiredChannels(); if (empty($requiredChannels)) { return true; } $missingChannels = []; foreach ($requiredChannels as $channel) { if (!isUserMemberOfChannel($userId, $channel['channel_id'])) { $missingChannels[] = $channel; } } if (!empty($missingChannels)) { $channelListText = ""; $keyboardButtons = []; foreach ($missingChannels as $channel) { $channelListText .= "- " . ($channel['title'] ?: "کانال") . "\n"; if ($channel['invite_link']) { $keyboardButtons[] = [['text' => '➡️ ' . ($channel['title'] ?: "عضویت در کانال"), 'url' => $channel['invite_link']]]; } elseif (strpos($channel['channel_id'], '@') === 0) { $keyboardButtons[] = [['text' => '➡️ ' . ($channel['title'] ?: "عضویت در کانال"), 'url' => 'https://t.me/' . substr($channel['channel_id'], 1)]]; } } $keyboardButtons[] = [['text' => FORCE_SUBSCRIBE_CHECK_BUTTON, 'callback_data' => 'check_membership']]; $messageText = str_replace('%channels_list%', $channelListText, FORCE_SUBSCRIBE_MESSAGE); telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => $messageText, 'reply_markup' => json_encode(['inline_keyboard' => $keyboardButtons]), 'parse_mode' => 'HTML' ]); return false; } return true; } // دریافت تنظیمات ربات function getBotSetting($settingName, $default = '') { $result = executeQuery("SELECT $settingName FROM bot_settings WHERE id = 1"); if ($result && $row = $result->fetch_assoc()) { return $row[$settingName]; } return $default ?: "👋 سلام دوست من!\n\n🌟 به ربات TradeSpider_bot خوش آمدید!\n✨ من به عنوان دستیار شما در بازارهای مالی طراحی شده‌ام. از دکمه‌های زیر برای دسترسی به امکانات مختلف استفاده کنید."; } // به‌روزرسانی متن پیام /start function updateStartMessage($newMessage) { return executeQuery( "INSERT INTO bot_settings (id, start_message, last_updated) VALUES (1, ?, NOW()) ON DUPLICATE KEY UPDATE start_message = VALUES(start_message), last_updated = NOW()", [$newMessage], "s" ); } // دریافت تحلیل ارز در تایم فریم مشخص function getCryptoAnalysis($cryptoSymbol, $timeframe) { $result = executeQuery( "SELECT ca.*, c.name FROM crypto_analysis ca JOIN cryptocurrencies c ON ca.crypto_id = c.id WHERE c.symbol = ? AND ca.timeframe = ? ORDER BY ca.created_at DESC LIMIT 1", [$cryptoSymbol, $timeframe], "ss" ); return $result ? $result->fetch_assoc() : null; } // ذخیره تحلیل جدید function saveAnalysis($cryptoSymbol, $timeframe, $text = null, $imageFileId = null, $videoFileId = null, $gifFileId = null, $documentFileId = null) { $cryptoResult = executeQuery("SELECT id FROM cryptocurrencies WHERE symbol = ?", [$cryptoSymbol], "s"); if (!$cryptoResult || $cryptoResult->num_rows == 0) { return false; } $cryptoRow = $cryptoResult->fetch_assoc(); $cryptoId = $cryptoRow['id']; return executeQuery( "INSERT INTO crypto_analysis (crypto_id, timeframe, text, image_file_id, video_file_id, gif_file_id, document_file_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())", [$cryptoId, $timeframe, $text, $imageFileId, $videoFileId, $gifFileId, $documentFileId], "issssss" ); } // دریافت بونوس function getBonus($type) { $result = executeQuery("SELECT * FROM bonuses WHERE type = ?", [$type], "s"); return $result ? $result->fetch_assoc() : null; } // دریافت لیست بونوس‌ها function getBonuses() { $result = executeQuery("SELECT type, title FROM bonuses ORDER BY id ASC"); $bonuses = []; if ($result) { while ($row = $result->fetch_assoc()) { $bonuses[] = $row; } } return $bonuses; } // ذخیره بونوس function saveBonus($type, $title, $description, $link, $imageFileId = null) { return executeQuery( "INSERT INTO bonuses (type, title, description, link, image_file_id) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE title = VALUES(title), description = VALUES(description), link = VALUES(link), image_file_id = VALUES(image_file_id)", [$type, $title, $description, $link, $imageFileId], "sssss" ); } // مدیریت وضعیت کاربر function setUserState($userId, $state, $data = null) { $jsonData = $data ? json_encode($data, JSON_UNESCAPED_UNICODE) : null; executeQuery( "INSERT INTO user_states (user_id, state, data) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE state = VALUES(state), data = VALUES(data)", [$userId, $state, $jsonData], "iss" ); } function getUserState($userId) { $result = executeQuery("SELECT state, data FROM user_states WHERE user_id = ?", [$userId], "i"); $stateData = $result ? $result->fetch_assoc() : null; if ($stateData && !empty($stateData['data'])) { $stateData['data'] = json_decode($stateData['data'], true); } return $stateData; } function clearUserState($userId) { executeQuery("DELETE FROM user_states WHERE user_id = ?", [$userId], "i"); } // پیدا کردن نماد ارز بر اساس متن ورودی function findCryptoSymbolFromText($inputText) { $lowerText = mb_strtolower($inputText, 'UTF-8'); $analysisKeyword = 'تحلیل'; foreach (ALL_CRYPTOCURRENCIES_AND_FOREX_PAIRS as $item) { $symbol = $item['symbol']; $name = mb_strtolower($item['name'], 'UTF-8'); // Check for "تحلیل BTC" or "تحلیل بیت کوین" if (strpos($lowerText, $analysisKeyword) === 0) { $afterAnalysis = trim(str_replace($analysisKeyword, '', $lowerText)); if (preg_match("/^" . preg_quote(mb_strtolower($symbol, 'UTF-8'), '/') . "(\s|$)/u", $afterAnalysis) || preg_match("/^" . preg_quote($name, '/') . "(\s|$)/u", $afterAnalysis)) { return $symbol; } } // Check for just "BTC" or "بیت کوین" if (trim($lowerText) === mb_strtolower($symbol, 'UTF-8') || trim($lowerText) === $name) { return $symbol; } } // Check aliases foreach (CRYPTO_ALIASES as $symbol => $aliases) { foreach ($aliases as $alias) { $lowerAlias = mb_strtolower($alias, 'UTF-8'); if (strpos($lowerText, $analysisKeyword) === 0) { $afterAnalysis = trim(str_replace($analysisKeyword, '', $lowerText)); if (preg_match("/^" . preg_quote($lowerAlias, '/') . "(\s|$)/u", $afterAnalysis)) { return $symbol; } } if (trim($lowerText) === $lowerAlias) { return $symbol; } } } return null; } // بررسی نوع چت function isPrivateChat($chatId) { global $update; if (isset($update['message']['chat']['type'])) { return $update['message']['chat']['type'] === 'private'; } if (isset($update['callback_query']['message']['chat']['type'])) { return $update['callback_query']['message']['chat']['type'] === 'private'; } return $chatId > 0; } function isGroupChat($chatId) { global $update; if (isset($update['message']['chat']['type'])) { $type = $update['message']['chat']['type']; return ($type === 'group' || $type === 'supergroup'); } if (isset($update['callback_query']['message']['chat']['type'])) { $type = $update['callback_query']['message']['chat']['type']; return ($type === 'group' || $type === 'supergroup'); } return $chatId < 0; } // ======================================================================== // 2. Keyboard Generation Functions // ======================================================================== // ایجاد کیبورد اصلی function getMainKeyboard() { $keyboard = [ 'keyboard' => [ [ ['text' => '🔐 حساب کاربری'], ['text' => '👨‍💻 پشتیبانی'] ], [ ['text' => '📊 تحلیل بازارها'], ['text' => '📚 آموزش'] ], [ ['text' => '💰 دریافت سرمایه اولیه'] ] ], 'resize_keyboard' => true ]; return json_encode($keyboard); } // ایجاد کیبورد آموزش‌ها function getEducationKeyboard() { $keyboard = [ 'inline_keyboard' => [ [ ['text' => '💰 دوره کامل ژن تریدرها', 'callback_data' => 'edu_money_management'] ], [ ['text' => '🧠 روانشناسی ترید', 'callback_data' => 'edu_psychology'] ], [ ['text' => '📊 تحلیل فاندامنتال', 'callback_data' => 'edu_fundamental'] ], [ ['text' => '📈 مفاهیم پایه', 'callback_data' => 'edu_basic_concepts'] ] ] ]; return json_encode($keyboard); } // تابع ایجاد کیبورد پنل ادمین function getAdminPanelKeyboard() { $keyboard = [ 'inline_keyboard' => [ [ ['text' => '📨 ارسال پیام به کاربر', 'callback_data' => 'admin_send_message'] ], [ ['text' => '🚫 مسدودسازی کاربر', 'callback_data' => 'admin_block_user'], ['text' => '✅ رفع مسدودیت کاربر', 'callback_data' => 'admin_unblock_user'] ], [ ['text' => '👤 اطلاعات کاربر', 'callback_data' => 'admin_user_info'] ], [ ['text' => '📊 آپلود تحلیل', 'callback_data' => 'admin_upload_analysis'], ['text' => '🎁 مدیریت بونوس‌ها', 'callback_data' => 'admin_manage_bonuses'] ], [ ['text' => '📢 ارسال پیام همگانی', 'callback_data' => 'admin_broadcast'] ], [ ['text' => '➕ افزودن کانال اجباری', 'callback_data' => 'admin_add_channel'], ['text' => '➖ حذف کانال اجباری', 'callback_data' => 'admin_delete_channel'] ], [ ['text' => '📝 لیست کانال‌های اجباری', 'callback_data' => 'admin_list_channels'] ], [ ['text' => '✍️ تغییر پیام /start', 'callback_data' => 'admin_set_start_message'] ] ] ]; return json_encode($keyboard); } // تابع کیبورد تحلیل کریپتو function getCryptoAnalysisKeyboard($page = 0) { $keyboard = ['inline_keyboard' => []]; $perPage = 15; $offset = $page * $perPage; $cryptos = array_slice(TOP_CRYPTOCURRENCIES, $offset, $perPage); $rows = array_chunk($cryptos, 3); foreach ($rows as $row) { $keyboardRow = []; foreach ($row as $crypto) { $keyboardRow[] = [ 'text' => $crypto['symbol'], 'callback_data' => 'crypto_select_' . $crypto['symbol'] ]; } $keyboard['inline_keyboard'][] = $keyboardRow; } // Navigation buttons $navRow = []; if ($page > 0) { $navRow[] = ['text' => '⬅️ قبلی', 'callback_data' => 'crypto_page_' . ($page - 1)]; } if (count(TOP_CRYPTOCURRENCIES) > ($offset + $perPage)) { $navRow[] = ['text' => 'بعدی ➡️', 'callback_data' => 'crypto_page_' . ($page + 1)]; } if (!empty($navRow)) { $keyboard['inline_keyboard'][] = $navRow; } return json_encode($keyboard); } // تابع کیبورد تایم فریم‌ها function getTimeframeKeyboard($cryptoSymbol, $is_private_chat = true) { $keyboard = ['inline_keyboard' => []]; foreach (TIMEFRAMES as $timeframe => $config) { $keyboard['inline_keyboard'][] = [ [ 'text' => '🕒 ' . $config['name'], 'callback_data' => 'timeframe_' . $cryptoSymbol . '_' . $timeframe ] ]; } // دکمه بازگشت (فقط در چت خصوصی) if ($is_private_chat) { $keyboard['inline_keyboard'][] = [ ['text' => '🔙 بازگشت به انتخاب ارز', 'callback_data' => 'crypto_back_to_selection'] ]; } return json_encode($keyboard); } // تابع کیبورد انتخاب ارز برای ادمین function getAdminCryptoSelectionKeyboard() { $keyboard = ['inline_keyboard' => []]; $rows = array_chunk(TOP_CRYPTOCURRENCIES, 3); foreach ($rows as $row) { $keyboardRow = []; foreach ($row as $crypto) { $keyboardRow[] = [ 'text' => $crypto['symbol'], 'callback_data' => 'admin_crypto_' . $crypto['symbol'] ]; } $keyboard['inline_keyboard'][] = $keyboardRow; } return json_encode($keyboard); } // تابع کیبورد انتخاب تایم فریم برای ادمین function getAdminTimeframeKeyboard($cryptoSymbol) { $keyboard = ['inline_keyboard' => []]; foreach (TIMEFRAMES as $timeframe => $config) { $keyboard['inline_keyboard'][] = [ [ 'text' => '🕒 ' . $config['name'], 'callback_data' => 'admin_timeframe_' . $cryptoSymbol . '_' . $timeframe ] ]; } return json_encode($keyboard); } // تابع کیبورد بونوس‌ها function getBonusKeyboard() { $bonuses = getBonuses(); $keyboard = ['inline_keyboard' => []]; if (empty($bonuses)) { $keyboard['inline_keyboard'][] = [ ['text' => 'در حال حاضر بونوسی تعریف نشده است', 'callback_data' => 'no_bonuses'] ]; } else { foreach ($bonuses as $bonus) { $keyboard['inline_keyboard'][] = [ ['text' => '🎁 ' . $bonus['title'], 'callback_data' => 'show_bonus_' . $bonus['type']] ]; } } return json_encode($keyboard); } // تابع کیبورد مدیریت بونوس برای ادمین function getAdminBonusManageKeyboard() { $bonuses = getBonuses(); $keyboard = [ 'inline_keyboard' => [ [['text' => '➕ افزودن بونوس جدید', 'callback_data' => 'admin_add_new_bonus']] ] ]; if (!empty($bonuses)) { $keyboard['inline_keyboard'][] = [['text' => '⚙️ ویرایش بونوس موجود:', 'callback_data' => 'dummy']]; foreach ($bonuses as $bonus) { $keyboard['inline_keyboard'][] = [ ['text' => '✏️ ' . $bonus['title'], 'callback_data' => 'admin_edit_bonus_' . $bonus['type']] ]; } } $keyboard['inline_keyboard'][] = [['text' => '🔙 بازگشت به پنل ادمین', 'callback_data' => 'back_to_admin']]; return json_encode($keyboard); } // ======================================================================== // 3. Message Handlers // ======================================================================== // پردازش پیام‌های دارای وضعیت function handleStatefulMessage($message) { $userId = $message['from']['id']; $chatId = $message['chat']['id']; $text = $message['text'] ?? ''; $userState = getUserState($userId); if (!$userState) return false; $state = $userState['state']; $data = $userState['data'] ?? []; switch ($state) { case 'awaiting_support_message': // ارسال پیام به ادمین $userInfo = getUserInfo($userId); $userName = $userInfo['first_name'] ?? 'کاربر'; $username = $userInfo['username'] ? '@' . $userInfo['username'] : ''; $adminMessage = "💌 پیام جدید از: $userName $username\n"; $adminMessage .= "🆔 ID: `$userId`\n\n"; $adminMessage .= "📝 متن پیام:\n" . $text; telegramAPI('sendMessage', [ 'chat_id' => ADMIN_ID, 'text' => $adminMessage, 'parse_mode' => 'Markdown', 'reply_markup' => json_encode([ 'inline_keyboard' => [ [['text' => '📨 پاسخ به کاربر', 'callback_data' => 'admin_reply_' . $userId]] ] ]) ]); telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "✅ پیام شما با موفقیت برای پشتیبانی ارسال شد. منتظر پاسخ بمانید.", 'reply_markup' => getMainKeyboard() ]); clearUserState($userId); break; case 'admin_awaiting_message_text': $targetUserId = $data['target_user_id'] ?? null; if ($targetUserId) { $success = telegramAPI('sendMessage', [ 'chat_id' => $targetUserId, 'text' => "📨 پیام از پشتیبانی:\n\n" . $text, 'parse_mode' => 'HTML' ]); if ($success && $success['ok']) { telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "✅ پیام با موفقیت ارسال شد." ]); } else { telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "❌ خطا در ارسال پیام." ]); } } clearUserState($userId); break; case 'admin_awaiting_broadcast_message': $users = getAllUsers(); $successCount = 0; foreach ($users as $user) { $result = telegramAPI('sendMessage', [ 'chat_id' => $user, 'text' => "📢 پیام همگانی:\n\n" . $text, 'parse_mode' => 'HTML' ]); if ($result && $result['ok']) { $successCount++; } usleep(100000); // 0.1 second delay to avoid rate limits } telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "✅ پیام به $successCount نفر از " . count($users) . " کاربر ارسال شد." ]); clearUserState($userId); break; case 'admin_awaiting_user_id_for_info': $targetUser = is_numeric($text) ? getUserInfo($text) : getUserInfoByUsername($text); if ($targetUser) { $joinDate = date('Y-m-d H:i', strtotime($targetUser['join_date'])); $status = $targetUser['is_blocked'] ? 'مسدود' : 'فعال'; $responseText = "📋 اطلاعات کاربر:\n\n"; $responseText .= "🆔 ID: `{$targetUser['user_id']}`\n"; $responseText .= "👤 نام: {$targetUser['first_name']}\n"; $responseText .= "🔗 یوزرنیم: @{$targetUser['username']}\n"; $responseText .= "📅 تاریخ عضویت: $joinDate\n"; $responseText .= "⚡ وضعیت: $status"; telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => $responseText, 'parse_mode' => 'Markdown' ]); } else { telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "❌ کاربر با شناسه `{$text}` یافت نشد.", 'parse_mode' => 'Markdown' ]); } clearUserState($userId); break; case 'admin_awaiting_user_id_for_block': $targetUser = is_numeric($text) ? getUserInfo($text) : getUserInfoByUsername($text); if ($targetUser) { $success = toggleBlockUser($targetUser['user_id'], true); if ($success) { telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "✅ کاربر {$targetUser['first_name']} با موفقیت مسدود شد." ]); } else { telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "❌ خطا در مسدود کردن کاربر." ]); } } else { telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "❌ کاربر با شناسه `{$text}` یافت نشد.", 'parse_mode' => 'Markdown' ]); } clearUserState($userId); break; case 'admin_awaiting_user_id_for_unblock': $targetUser = is_numeric($text) ? getUserInfo($text) : getUserInfoByUsername($text); if ($targetUser) { $success = toggleBlockUser($targetUser['user_id'], false); if ($success) { telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "✅ مسدودیت کاربر {$targetUser['first_name']} رفع شد." ]); } else { telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "❌ خطا در رفع مسدودیت کاربر." ]); } } else { telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "❌ کاربر با شناسه `{$text}` یافت نشد.", 'parse_mode' => 'Markdown' ]); } clearUserState($userId); break; case 'admin_awaiting_start_message': $success = updateStartMessage($text); if ($success) { telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "✅ پیام /start با موفقیت به‌روزرسانی شد." ]); } else { telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "❌ خطا در به‌روزرسانی پیام /start." ]); } clearUserState($userId); break; case 'admin_awaiting_channel_info': $parts = explode(' ', $text, 3); if (count($parts) >= 2) { $channelId = $parts[0]; $title = $parts[1]; $inviteLink = isset($parts[2]) ? $parts[2] : null; $success = addRequiredChannel($channelId, $title, $inviteLink); if ($success) { telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "✅ کانال اجباری با موفقیت اضافه شد." ]); } else { telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "❌ کانال قبلاً وجود دارد یا خطا در افزودن کانال." ]); } } else { telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "❌ فرمت ورودی نادرست. لطفاً به شکل زیر وارد کنید:\n@channel_id عنوان_کانال [لینک_دعوت]" ]); } clearUserState($userId); break; case 'admin_awaiting_channel_id_for_delete': $success = deleteRequiredChannel($text); if ($success) { telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "✅ کانال اجباری با موفقیت حذف شد." ]); } else { telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "❌ کانال یافت نشد یا خطا در حذف کانال." ]); } clearUserState($userId); break; case 'admin_awaiting_analysis_content': $analysisData = $data['analysis_data'] ?? []; if (!empty($analysisData)) { $cryptoSymbol = $analysisData['crypto_symbol']; $timeframe = $analysisData['timeframe']; $imageFileId = null; $videoFileId = null; $gifFileId = null; $documentFileId = null; $textContent = null; if (isset($message['photo'])) { $imageFileId = end($message['photo'])['file_id']; $textContent = $message['caption'] ?? null; } elseif (isset($message['video'])) { $videoFileId = $message['video']['file_id']; $textContent = $message['caption'] ?? null; } elseif (isset($message['animation'])) { $gifFileId = $message['animation']['file_id']; $textContent = $message['caption'] ?? null; } elseif (isset($message['document'])) { $documentFileId = $message['document']['file_id']; $textContent = $message['caption'] ?? null; } else { $textContent = $text; } $success = saveAnalysis($cryptoSymbol, $timeframe, $textContent, $imageFileId, $videoFileId, $gifFileId, $documentFileId); if ($success) { telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "✅ تحلیل $cryptoSymbol در تایم فریم $timeframe با موفقیت ذخیره شد." ]); } else { telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "❌ خطا در ذخیره تحلیل." ]); } } clearUserState($userId); break; case 'admin_awaiting_bonus_data': $bonusData = $data['bonus_data'] ?? []; if (!empty($bonusData)) { $bonusType = $bonusData['type']; $title = $bonusData['title']; $description = $bonusData['description']; $link = $bonusData['link']; $imageFileId = null; if (isset($message['photo'])) { $imageFileId = end($message['photo'])['file_id']; } $success = saveBonus($bonusType, $title, $description, $link, $imageFileId); if ($success) { telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "✅ بونوس با موفقیت ذخیره شد." ]); } else { telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "❌ خطا در ذخیره بونوس." ]); } } clearUserState($userId); break; } return true; } // پردازش پیام‌های معمولی function handleRegularMessage($message) { $chatId = $message['chat']['id']; $userId = $message['from']['id']; $text = $message['text'] ?? ''; // بررسی اینکه چت خصوصی است یا خیر if (!isPrivateChat($chatId)) { // در گروه فقط درخواست‌های تحلیل را پردازش کن $foundCryptoSymbol = findCryptoSymbolFromText($text); if ($foundCryptoSymbol) { $cryptoNameForDisplay = ''; foreach (ALL_CRYPTOCURRENCIES_AND_FOREX_PAIRS as $item) { if ($item['symbol'] === $foundCryptoSymbol) { $cryptoNameForDisplay = $item['name']; break; } } if (empty($cryptoNameForDisplay)) { telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "❌ متاسفم، تحلیلی برای این ارز در حال حاضر موجود نیست.", 'parse_mode' => 'HTML' ]); return; } telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "📊 تحلیل $cryptoNameForDisplay\n\n🕒 لطفاً تایم فریم مورد نظر را انتخاب کنید:", 'reply_markup' => getTimeframeKeyboard($foundCryptoSymbol, false), 'parse_mode' => 'HTML' ]); } return; } // ثبت کاربر registerUser($message['from']); // بررسی اجبار به عضویت در کانال‌ها if ($chatId != ADMIN_ID && !checkAllRequiredChannels($userId, $chatId)) { return; } // بررسی مسدودیت کاربر $userInfo = getUserInfo($userId); if ($userInfo && $userInfo['is_blocked'] == 1 && $chatId != ADMIN_ID) { telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => '❌ حساب کاربری شما مسدود شده است. لطفاً با پشتیبانی تماس بگیرید.', 'parse_mode' => 'HTML' ]); return; } // پردازش دستورات و پیام‌ها switch ($text) { case '/start': $startMessage = getBotSetting('start_message'); telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => $startMessage, 'reply_markup' => getMainKeyboard(), 'parse_mode' => 'HTML' ]); break; case '/admin': if ($userId == ADMIN_ID) { telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => '🔐 به پنل مدیریت خوش آمدید.', 'reply_markup' => getAdminPanelKeyboard() ]); } break; case '🔐 حساب کاربری': $userInfo = getUserInfo($userId); $joinDate = $userInfo ? date('Y-m-d H:i', strtotime($userInfo['join_date'])) : 'نامشخص'; $accountText = "👤 اطلاعات حساب کاربری:\n\n"; $accountText .= "🆔 شناسه شما: `{$userId}`\n"; $accountText .= "👤 نام: {$userInfo['first_name']}\n"; $accountText .= "🔗 یوزرنیم: @{$userInfo['username']}\n"; $accountText .= "📅 تاریخ عضویت: `{$joinDate}`"; telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => $accountText, 'parse_mode' => 'Markdown' ]); break; case '👨‍💻 پشتیبانی': // بررسی محدودیت زمانی ارسال تیکت $canSend = canSendTicket($userId); if (!$canSend['can_send']) { telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "⏰ شما باید {$canSend['remaining']} صبر کنید تا بتوانید تیکت جدید ارسال کنید.", 'parse_mode' => 'HTML' ]); break; } setUserState($userId, 'awaiting_support_message'); telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "✍️ لطفاً پیام خود را برای ارسال به پشتیبانی بنویسید:", 'parse_mode' => 'HTML' ]); break; case '📊 تحلیل بازارها': telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "🚀 لطفاً نماد مورد نظر خود را برای تحلیل انتخاب کنید:", 'reply_markup' => getCryptoAnalysisKeyboard(0) ]); break; case '📚 آموزش': telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "📚 لطفاً یکی از دوره‌های آموزشی زیر را انتخاب کنید:", 'reply_markup' => getEducationKeyboard() ]); break; case '💰 دریافت سرمایه اولیه': telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "🎁 برای دریافت سرمایه، لطفاً یکی از بونوس‌های زیر را انتخاب کنید:", 'reply_markup' => getBonusKeyboard() ]); break; default: // بررسی درخواست تحلیل $foundCryptoSymbol = findCryptoSymbolFromText($text); if ($foundCryptoSymbol) { $cryptoNameForDisplay = ''; foreach (ALL_CRYPTOCURRENCIES_AND_FOREX_PAIRS as $item) { if ($item['symbol'] === $foundCryptoSymbol) { $cryptoNameForDisplay = $item['name']; break; } } if (!empty($cryptoNameForDisplay)) { telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "📊 تحلیل $cryptoNameForDisplay\n\n🕒 لطفاً تایم فریم مورد نظر را انتخاب کنید:", 'reply_markup' => getTimeframeKeyboard($foundCryptoSymbol), 'parse_mode' => 'HTML' ]); } } break; } } // ======================================================================== // 4. Callback Query Handlers // ======================================================================== function handleCallbackQuery($callbackQuery) { $chatId = $callbackQuery['message']['chat']['id']; $userId = $callbackQuery['from']['id']; $data = $callbackQuery['data']; $callbackId = $callbackQuery['id']; $messageId = $callbackQuery['message']['message_id']; // پاسخ به callback query telegramAPI('answerCallbackQuery', ['callback_query_id' => $callbackId]); // پردازش callback های ادمین if ($userId == ADMIN_ID) { handleAdminCallbacks($chatId, $userId, $data, $messageId); return; } // پردازش callback های کاربران عادی handleUserCallbacks($chatId, $userId, $data, $messageId); } function handleAdminCallbacks($chatId, $userId, $data, $messageId) { switch ($data) { case 'admin_send_message': telegramAPI('editMessageText', [ 'chat_id' => $chatId, 'message_id' => $messageId, 'text' => "📨 لطفاً ID یا یوزرنیم کاربر مورد نظر را وارد کنید:" ]); setUserState($userId, 'admin_awaiting_user_id_for_message'); break; case 'admin_broadcast': telegramAPI('editMessageText', [ 'chat_id' => $chatId, 'message_id' => $messageId, 'text' => "📢 لطفاً متن پیام همگانی را وارد کنید:" ]); setUserState($userId, 'admin_awaiting_broadcast_message'); break; case 'admin_user_info': telegramAPI('editMessageText', [ 'chat_id' => $chatId, 'message_id' => $messageId, 'text' => "👤 لطفاً ID یا یوزرنیم کاربر را وارد کنید:" ]); setUserState($userId, 'admin_awaiting_user_id_for_info'); break; case 'admin_block_user': telegramAPI('editMessageText', [ 'chat_id' => $chatId, 'message_id' => $messageId, 'text' => "🚫 لطفاً ID یا یوزرنیم کاربر مورد نظر برای مسدود کردن را وارد کنید:" ]); setUserState($userId, 'admin_awaiting_user_id_for_block'); break; case 'admin_unblock_user': telegramAPI('editMessageText', [ 'chat_id' => $chatId, 'message_id' => $messageId, 'text' => "✅ لطفاً ID یا یوزرنیم کاربر مورد نظر برای رفع مسدودیت را وارد کنید:" ]); setUserState($userId, 'admin_awaiting_user_id_for_unblock'); break; case 'admin_upload_analysis': telegramAPI('editMessageText', [ 'chat_id' => $chatId, 'message_id' => $messageId, 'text' => "📊 لطفاً ارز مورد نظر را انتخاب کنید:", 'reply_markup' => getAdminCryptoSelectionKeyboard() ]); break; case 'admin_manage_bonuses': telegramAPI('editMessageText', [ 'chat_id' => $chatId, 'message_id' => $messageId, 'text' => "🎁 مدیریت بونوس‌ها:", 'reply_markup' => getAdminBonusManageKeyboard() ]); break; case 'admin_set_start_message': telegramAPI('editMessageText', [ 'chat_id' => $chatId, 'message_id' => $messageId, 'text' => "✍️ لطفاً متن جدید پیام /start را وارد کنید:" ]); setUserState($userId, 'admin_awaiting_start_message'); break; case 'admin_add_channel': telegramAPI('editMessageText', [ 'chat_id' => $chatId, 'message_id' => $messageId, 'text' => "➕ لطفاً اطلاعات کانال را به شکل زیر وارد کنید:\n\n@channel_id عنوان_کانال [لینک_دعوت]\n\nمثال:\n@mychannel کانال من https://t.me/mychannel" ]); setUserState($userId, 'admin_awaiting_channel_info'); break; case 'admin_delete_channel': telegramAPI('editMessageText', [ 'chat_id' => $chatId, 'message_id' => $messageId, 'text' => "➖ لطفاً ID کانال (مثل @channel_id) را برای حذف وارد کنید:" ]); setUserState($userId, 'admin_awaiting_channel_id_for_delete'); break; case 'admin_list_channels': $channels = getRequiredChannels(); if (empty($channels)) { telegramAPI('editMessageText', [ 'chat_id' => $chatId, 'message_id' => $messageId, 'text' => "📝 هیچ کانال اجباری تعریف نشده است." ]); } else { $channelsList = "📝 لیست کانال‌های اجباری:\n\n"; foreach ($channels as $index => $channel) { $channelsList .= ($index + 1) . ". "; $channelsList .= "🆔 ID: `{$channel['channel_id']}`\n"; $channelsList .= "📛 عنوان: {$channel['title']}\n"; if ($channel['invite_link']) { $channelsList .= "🔗 لینک: {$channel['invite_link']}\n"; } $channelsList .= "\n"; } telegramAPI('editMessageText', [ 'chat_id' => $chatId, 'message_id' => $messageId, 'text' => $channelsList, 'parse_mode' => 'Markdown' ]); } break; } // پردازش callback های مربوط به انتخاب ارز برای آپلود تحلیل if (strpos($data, 'admin_crypto_') === 0) { $cryptoSymbol = substr($data, 13); telegramAPI('editMessageText', [ 'chat_id' => $chatId, 'message_id' => $messageId, 'text' => "📊 ارز $cryptoSymbol انتخاب شد.\n\n🕒 لطفاً تایم فریم را انتخاب کنید:", 'reply_markup' => getAdminTimeframeKeyboard($cryptoSymbol) ]); } // پردازش callback های مربوط به انتخاب تایم فریم برای آپلود تحلیل if (strpos($data, 'admin_timeframe_') === 0) { $parts = explode('_', $data); $cryptoSymbol = $parts[2]; $timeframe = $parts[3]; $timeframeName = TIMEFRAMES[$timeframe]['name'] ?? $timeframe; telegramAPI('editMessageText', [ 'chat_id' => $chatId, 'message_id' => $messageId, 'text' => "📊 ارز: $cryptoSymbol\n🕒 تایم فریم: $timeframeName\n\n📝 لطفاً محتوای تحلیل (متن، عکس، ویدیو یا فایل) را ارسال کنید:" ]); setUserState($userId, 'admin_awaiting_analysis_content', [ 'analysis_data' => [ 'crypto_symbol' => $cryptoSymbol, 'timeframe' => $timeframe ] ]); } // پردازش callback های مربوط به پاسخ به کاربر if (strpos($data, 'admin_reply_') === 0) { $targetUserId = substr($data, 12); telegramAPI('editMessageText', [ 'chat_id' => $chatId, 'message_id' => $messageId, 'text' => "📨 لطفاً پیام خود را برای ارسال به کاربر بنویسید:" ]); setUserState($userId, 'admin_awaiting_message_text', ['target_user_id' => $targetUserId]); } // پردازش callback های مربوط به مدیریت بونوس‌ها if ($data === 'admin_add_new_bonus') { telegramAPI('editMessageText', [ 'chat_id' => $chatId, 'message_id' => $messageId, 'text' => "🎁 افزودن بونوس جدید:\n\nلطفاً اطلاعات بونوس را به شکل زیر وارد کنید:\n\nنوع|عنوان|توضیحات|لینک\n\nمثال:\nwelcome_bonus|بونوس خوش‌آمدگویی|بونوس ۱۰۰ دلاری برای کاربران جدید|https://example.com" ]); setUserState($userId, 'admin_awaiting_new_bonus_data'); } if (strpos($data, 'admin_edit_bonus_') === 0) { $bonusType = substr($data, 17); $bonus = getBonus($bonusType); if ($bonus) { telegramAPI('editMessageText', [ 'chat_id' => $chatId, 'message_id' => $messageId, 'text' => "✏️ ویرایش بونوس: {$bonus['title']}\n\nاطلاعات فعلی:\n📛 عنوان: {$bonus['title']}\n📝 توضیحات: {$bonus['description']}\n🔗 لینک: {$bonus['link']}\n\nلطفاً اطلاعات جدید را به شکل زیر وارد کنید:\n\nعنوان|توضیحات|لینک" ]); setUserState($userId, 'admin_awaiting_edit_bonus_data', ['bonus_type' => $bonusType]); } } if ($data === 'back_to_admin') { telegramAPI('editMessageText', [ 'chat_id' => $chatId, 'message_id' => $messageId, 'text' => '🔐 به پنل مدیریت خوش آمدید.', 'reply_markup' => getAdminPanelKeyboard() ]); } } function handleUserCallbacks($chatId, $userId, $data, $messageId) { // بررسی عضویت در کانال‌ها if ($data === 'check_membership') { if (checkAllRequiredChannels($userId, $chatId)) { telegramAPI('editMessageText', [ 'chat_id' => $chatId, 'message_id' => $messageId, 'text' => "✅ عضویت شما تأیید شد! از تمام امکانات ربات استفاده کنید.", 'reply_markup' => getMainKeyboard() ]); } return; } // پردازش انتخاب صفحه ارزها if (strpos($data, 'crypto_page_') === 0) { $page = (int)substr($data, 12); telegramAPI('editMessageReplyMarkup', [ 'chat_id' => $chatId, 'message_id' => $messageId, 'reply_markup' => getCryptoAnalysisKeyboard($page) ]); return; } // پردازش انتخاب ارز if (strpos($data, 'crypto_select_') === 0) { $cryptoSymbol = substr($data, 14); $cryptoName = ''; foreach (ALL_CRYPTOCURRENCIES_AND_FOREX_PAIRS as $item) { if ($item['symbol'] === $cryptoSymbol) { $cryptoName = $item['name']; break; } } telegramAPI('editMessageText', [ 'chat_id' => $chatId, 'message_id' => $messageId, 'text' => "📊 تحلیل " . htmlspecialchars($cryptoName) . "\n\n🕒 لطفاً تایم فریم مورد نظر را انتخاب کنید:", 'reply_markup' => getTimeframeKeyboard($cryptoSymbol), 'parse_mode' => 'HTML' ]); return; } // پردازش انتخاب تایم فریم if (strpos($data, 'timeframe_') === 0) { $parts = explode('_', $data); $cryptoSymbol = $parts[1]; $timeframe = $parts[2]; // حذف پیام انتخاب telegramAPI('deleteMessage', [ 'chat_id' => $chatId, 'message_id' => $messageId ]); // دریافت تحلیل $analysis = getCryptoAnalysis($cryptoSymbol, $timeframe); if ($analysis) { $timeframeName = TIMEFRAMES[$timeframe]['name'] ?? $timeframe; $responseText = "📊 تحلیل {$analysis['name']}\n"; $responseText .= "🕒 تایم فریم: $timeframeName\n"; $responseText .= "📅 تاریخ: " . date('Y-m-d H:i', strtotime($analysis['created_at'])) . "\n\n"; if ($analysis['text']) { $responseText .= $analysis['text']; } // ارسال بر اساس نوع محتوا if ($analysis['image_file_id']) { telegramAPI('sendPhoto', [ 'chat_id' => $chatId, 'photo' => $analysis['image_file_id'], 'caption' => $responseText, 'parse_mode' => 'HTML' ]); } elseif ($analysis['video_file_id']) { telegramAPI('sendVideo', [ 'chat_id' => $chatId, 'video' => $analysis['video_file_id'], 'caption' => $responseText, 'parse_mode' => 'HTML' ]); } elseif ($analysis['gif_file_id']) { telegramAPI('sendAnimation', [ 'chat_id' => $chatId, 'animation' => $analysis['gif_file_id'], 'caption' => $responseText, 'parse_mode' => 'HTML' ]); } elseif ($analysis['document_file_id']) { telegramAPI('sendDocument', [ 'chat_id' => $chatId, 'document' => $analysis['document_file_id'], 'caption' => $responseText, 'parse_mode' => 'HTML' ]); } else { telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => $responseText, 'parse_mode' => 'HTML' ]); } } else { $timeframeName = TIMEFRAMES[$timeframe]['name'] ?? $timeframe; telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => "❌ متاسفانه تحلیلی برای $cryptoSymbol در تایم فریم $timeframeName یافت نشد.", 'parse_mode' => 'HTML' ]); } return; } // بازگشت به انتخاب ارز if ($data === 'crypto_back_to_selection') { telegramAPI('editMessageText', [ 'chat_id' => $chatId, 'message_id' => $messageId, 'text' => "🚀 لطفاً نماد مورد نظر خود را برای تحلیل انتخاب کنید:", 'reply_markup' => getCryptoAnalysisKeyboard(0) ]); return; } // پردازش آموزش‌ها if (strpos($data, 'edu_') === 0) { $eduType = substr($data, 4); $eduContent = ''; switch ($eduType) { case 'money_management': $eduContent = "💰 دوره کامل ژن تریدرها\n\n🎯 این دوره شامل:\n- مدیریت سرمایه\n- استراتژی‌های معاملاتی\n- کنترل ریسک\n- روانشناسی معامله\n\n📚 برای دسترسی به دوره کامل، از لینک زیر استفاده کنید."; break; case 'psychology': $eduContent = "🧠 روانشناسی ترید\n\n🎯 در این بخش خواهید آموخت:\n- کنترل احساسات در معامله\n- مدیریت ترس و طمع\n- ایجاد انضباط معاملاتی\n- تکنیک‌های آرامش"; break; case 'fundamental': $eduContent = "📊 تحلیل فاندامنتال\n\n🎯 محتوای این بخش:\n- بررسی اخبار اقتصادی\n- تأثیر وقایع جهانی بر بازار\n- تحلیل شرکت‌ها و پروژه‌ها\n- پیش‌بینی روندهای بلندمدت"; break; case 'basic_concepts': $eduContent = "📈 مفاهیم پایه\n\n🎯 در این قسمت خواهید آموخت:\n- آشنایی با بازارهای مالی\n- انواع ارزهای دیجیتال\n- مفاهیم کاندل و چارت\n- معرفی ابزارها و پلتفرم‌ها"; break; } telegramAPI('editMessageText', [ 'chat_id' => $chatId, 'message_id' => $messageId, 'text' => $eduContent, 'parse_mode' => 'HTML' ]); return; } // پردازش بونوس‌ها if (strpos($data, 'show_bonus_') === 0) { $bonusType = substr($data, 11); $bonus = getBonus($bonusType); if ($bonus) { $responseText = "🎁 " . htmlspecialchars($bonus['title']) . "\n\n"; $responseText .= htmlspecialchars($bonus['description']); $keyboard = [ 'inline_keyboard' => [ [['text' => '🔗 دریافت بونوس', 'url' => $bonus['link']]] ] ]; if ($bonus['image_file_id']) { telegramAPI('sendPhoto', [ 'chat_id' => $chatId, 'photo' => $bonus['image_file_id'], 'caption' => $responseText, 'parse_mode' => 'HTML', 'reply_markup' => json_encode($keyboard) ]); } else { telegramAPI('sendMessage', [ 'chat_id' => $chatId, 'text' => $responseText, 'parse_mode' => 'HTML', 'reply_markup' => json_encode($keyboard) ]); } // حذف پیام انتخاب بونوس telegramAPI('deleteMessage', [ 'chat_id' => $chatId, 'message_id' => $messageId ]); } return; } } // ======================================================================== // 5. Main Entry Point // ======================================================================== // دریافت و پردازش آپدیت‌های تلگرام $update = json_decode(file_get_contents('php://input'), true); // لاگ کردن آپدیت‌های تلگرام برای اشکال‌زدایی file_put_contents('telegram_updates.log', date('[Y-m-d H:i:s]') . " Received Update: " . print_r($update, true) . "\n", FILE_APPEND); if ($update) { if (isset($update['message'])) { $message = $update['message']; // بررسی وجود وضعیت کاربر $userState = getUserState($message['from']['id']); if ($userState) { handleStatefulMessage($message); } else { handleRegularMessage($message); } } elseif (isset($update['callback_query'])) { handleCallbackQuery($update['callback_query']); } } ?>