OXIESEC PANEL
- Current Dir:
/
/
var
/
www
/
cream
/
back_whatsappBot
Server IP: 139.59.38.164
Upload:
Create Dir:
Name
Size
Modified
Perms
📁
..
-
06/17/2025 10:17:24 AM
rwxrwxr-x
📄
db.php
368 bytes
05/19/2025 10:07:16 AM
rw-r--r--
📄
demoForm.html
1.99 KB
04/10/2025 08:12:36 AM
rw-r--r--
📄
news_pagination.json
35 bytes
04/10/2025 05:40:59 AM
rwxrwxrwx
📄
posts_pagination.json
52 bytes
04/10/2025 05:44:17 AM
rwxrwxrwx
📄
saveDemo.php
1.82 KB
05/19/2025 10:07:16 AM
rw-r--r--
📄
send_log.txt
68.41 KB
04/10/2025 05:52:23 AM
rwxrwxrwx
📄
webhook_post_log.txt
272.88 KB
04/09/2025 09:25:07 AM
rwxrwxrwx
📄
whatsappAPI.php
22 KB
05/19/2025 10:07:16 AM
rw-r--r--
📄
whatsapp_messages.log
9.53 KB
04/10/2025 05:52:22 AM
rw-rw-rw-
Editing: whatsappAPI.php
Close
<?php // Define configuration settings at the beginning $config = [ 'verify_token' => 'knoblywaapi', 'access_token' => 'EAAUOqGZCvgXABO89X72FOqDC6UCJ7NEG0JFZBwdZCu21dfQy8r2JvKdifIZCkuCAI8VVBMEkExHpHSxyQhxpYStH254CmhjIwM1f4iNaVM7yhL9d4bZArGmvZCJ3vx5uyjrrPtzB1VNNue0XLGi10uyLysBejVd9dFBYP6LkhhAtNRd7LMPZATP7h4MIifOHkgchgZDZD', 'phone_number_id' => '542877718919663', 'app_secret' => 'a381b107387ef1357b5bc7973d80287f' ]; // Handle webhook verification if ($_SERVER['REQUEST_METHOD'] === 'GET') { $mode = $_GET['hub_mode'] ?? ''; $token = $_GET['hub_verify_token'] ?? ''; $challenge = $_GET['hub_challenge'] ?? ''; if ($mode === 'subscribe' && $token === $config['verify_token']) { // Return the challenge code to verify webhook echo $challenge; exit; } else { // Failed verification http_response_code(403); exit; } } /** * Fetch news articles from the API */ function fetchNews() { $url = 'https://knoblycream.com/api/articles.php?rss_id=9'; $curl = curl_init($url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { error_log("cURL Error fetching news: " . $err); return false; } return json_decode($response, true); } function fetchPosts() { $url = 'https://knoblycream.com/api/stream.php'; $curl = curl_init($url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { error_log("cURL Error fetching posts: " . $err); return false; } return json_decode($response, true); } function sendWhatsAppImage($to, $imageUrl, $caption, $config) { $url = "https://graph.facebook.com/v17.0/{$config['phone_number_id']}/messages"; $data = [ 'messaging_product' => 'whatsapp', 'recipient_type' => 'individual', 'to' => $to, 'type' => 'image', 'image' => [ 'link' => $imageUrl, 'caption' => $caption ] ]; $headers = [ 'Authorization: Bearer ' . $config['access_token'], 'Content-Type: application/json' ]; $curl = curl_init($url); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { error_log("cURL Error: " . $err); return false; } file_put_contents('send_log.txt', "Sent Image to: " . $to . " Response: " . $response . PHP_EOL, FILE_APPEND); return $response; } function formatNewsMessage($articles, $limit = 3) { if (!$articles || empty($articles)) { return "Sorry, I couldn't retrieve any news articles at the moment."; } $message = "📰 *Latest News* 📰\n\n"; // Limit the number of articles to display $count = 0; foreach ($articles as $article) { if ($count >= $limit) break; $message .= "*" . $article['title'] . "*\n"; $message .= $article['description'] . "\n"; $message .= "Read more: " . $article['url'] . "\n\n"; $count++; } $message .= "Reply with 'more news' to see additional articles."; return $message; } function formatPostMessage($posts, $limit = 3) { if (!$posts || empty($posts)) { return "Sorry, I couldn't retrieve any social posts at the moment."; } $message = "📱 *Latest Social Posts* 📱\n\n"; // Limit the number of posts to display $count = 0; $displayedPosts = 0; while ($displayedPosts < $limit && $count < count($posts)) { $post = $posts[$count]; $count++; // Skip posts with null chat content if (empty($post['chat'])) continue; $message .= "*" . $post['full_name'] . "*\n"; // Strip quotes if present and limit text length $chatText = $post['chat']; if (substr($chatText, 0, 1) === '"' && substr($chatText, -1) === '"') { $chatText = substr($chatText, 1, -1); } // If chat text is too long, truncate it if (strlen($chatText) > 150) { $chatText = substr($chatText, 0, 147) . "..."; } $message .= $chatText . "\n"; // Extract URL from chat if present if (preg_match('/https?:\/\/[^\s]+/i', $post['chat'], $matches)) { $message .= "Link: " . $matches[0] . "\n"; } $message .= "Posted on: " . date('M d, Y', strtotime($post['postedOn'])) . "\n\n"; $displayedPosts++; } $message .= "Reply with 'more posts' to see additional posts."; return $message; } function processMessage($messageText) { $messageText = strtolower($messageText); // News-related queries if (strpos($messageText, 'news') !== false || strpos($messageText, 'headlines') !== false) { $articles = fetchNews(); return formatNewsMessage($articles); } // Handle request for more news else if (strpos($messageText, 'more news') !== false) { $articles = fetchNews(); // Skip first 3 articles and show the next 3 $slicedArticles = array_slice($articles, 3, 3); return formatNewsMessage($slicedArticles); } // Posts-related queries else if (strpos($messageText, 'posts') !== false) { $posts = fetchPosts(); return formatPostMessage($posts); } // Handle request for more posts else if (strpos($messageText, 'more posts') !== false) { $posts = fetchPosts(); // Skip first 3 posts and show the next 3 $slicedPosts = array_slice($posts, 3, 3); return formatPostMessage($slicedPosts); } // Existing chatbot logic else if (strpos($messageText, 'hello') !== false || strpos($messageText, 'hi') !== false) { return "Hello! Welcome to Knobly Cream. How can I help you?\n\n" . "Please reply with a number:\n" . "1. Latest News\n". "2. Latest Social Posts\n" . "3. Product Information\n" . "4. Business Hours\n" . "5. Contact Support" ; } else if ($messageText === '1') { $articles = fetchNews(); return formatNewsMessage($articles); } else if ($messageText === '2') { $posts = fetchPosts(); return formatPostMessage($posts); }else if ($messageText === '3') { return "Our products include high-quality widgets designed for both personal and professional use. Would you like to know more about a specific product line?"; }else if ($messageText === '4') { return "Our business hours are:\nMonday-Friday: 9am-6pm\n Weakend: Closed"; }else if ($messageText === '5') { return "Our support team is ready to assist you. Please describe your issue, and a representative will follow up shortly."; }else { return "I didn't understand your request. Please send hi or hello to get options."; } } // } else if ($messageText === '3') { // return "Our products include high-quality widgets designed for both personal and professional use. Would you like to know more about a specific product line?"; // } else if ($messageText === '4') { // return "Our business hours are:\nMonday-Friday: 9am-6pm\n Weakend: Closed"; // } else if ($messageText === '5') { // return "Our support team is ready to assist you. Please describe your issue, and a representative will follow up shortly."; // } else if ($messageText === '1') { // $articles = fetchNews(); // return formatNewsMessage($articles); // } else if ($messageText === '2') { // $posts = fetchPosts(); // return formatPostMessage($posts); // } else { // return "I didn't understand your request. Please send hi or hello to get options."; // } // } function sendWhatsAppMessage($to, $message, $config) { $url = "https://graph.facebook.com/v17.0/{$config['phone_number_id']}/messages"; $data = [ 'messaging_product' => 'whatsapp', 'recipient_type' => 'individual', 'to' => $to, 'type' => 'text', 'text' => [ 'body' => $message ] ]; $headers = [ 'Authorization: Bearer ' . $config['access_token'], 'Content-Type: application/json' ]; $curl = curl_init($url); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { error_log("cURL Error: " . $err); return false; } file_put_contents('send_log.txt', "Sent Response to: " . $to . " Response: " . $response . PHP_EOL, FILE_APPEND); return $response; } function verifySignature($payload, $signature, $appSecret) { if (empty($signature)) { return false; } $expectedSignature = 'sha256=' . hash_hmac('sha256', $payload, $appSecret); return hash_equals($expectedSignature, $signature); } function logMessage($sender, $message) { // Example: Append to a log file $logEntry = date('Y-m-d H:i:s') . " - From: $sender, Message: $message" . PHP_EOL; file_put_contents('whatsapp_messages.log', $logEntry, FILE_APPEND); // In a production environment, you might want to log to a database instead } // Handle incoming webhook messages if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Get request headers and body $headers = getallheaders(); $input = file_get_contents('php://input'); $body = json_decode($input, true); // Verify the request is from Meta using x-hub-signature-256 // Uncomment this code once you've properly set up your app secret /* $signature = $headers['x-hub-signature-256'] ?? ''; file_put_contents('signature_log.txt', "Received Signature: " . $signature . PHP_EOL, FILE_APPEND); if (!verifySignature($input, $signature, $config['app_secret'])) { http_response_code(403); exit('Invalid signature'); } */ // Process WhatsApp messages if (isset($body['object']) && $body['object'] === 'whatsapp_business_account') { try { // Check if this is a message notification if (isset($body['entry'][0]['changes'][0]['value']['messages'])) { $message = $body['entry'][0]['changes'][0]['value']['messages'][0]; $from = $message['from']; $messageText = $message['text']['body'] ?? ''; // Log the message (optional) logMessage($from, $messageText); // Check if it's a news-related request if ( strpos(strtolower($messageText), 'news') !== false || strpos(strtolower($messageText), 'headlines') !== false || $messageText === '1' ) { // Fetch news articles $articles = fetchNews(); if (!empty($articles)) { // Track user's pagination state using a simple file-based approach $paginationFile = 'news_pagination.json'; $pagination = []; if (file_exists($paginationFile)) { $paginationData = file_get_contents($paginationFile); $pagination = json_decode($paginationData, true) ?: []; } // Determine the starting point for articles $start = 0; $limit = 3; // Check if this is a "more news" request if (strpos(strtolower($messageText), 'more news') !== false) { // Get current page for this user, default to 0 $currentPage = $pagination[$from] ?? 0; // Increment the page counter $currentPage++; $start = $currentPage * $limit; // Save the updated page counter $pagination[$from] = $currentPage; file_put_contents($paginationFile, json_encode($pagination)); } else { // Reset pagination for new news requests $pagination[$from] = 0; file_put_contents($paginationFile, json_encode($pagination)); } // Get the subset of articles to display $displayArticles = array_slice($articles, $start, $limit); if (empty($displayArticles)) { // No more articles to show sendWhatsAppMessage($from, "No more news articles available at this time.", $config); } else { // Send each article with its image if available foreach ($displayArticles as $article) { // Create a message for this specific article $articleText = "*" . $article['title'] . "*\n" . // $article['description'] . "\n\n" . "*Read more:* " . $article['url']; // If article has an image, send as image with caption if (!empty($article['image'])) { sendWhatsAppImage($from, $article['image'], $articleText, $config); } else { // No image, send as text only sendWhatsAppMessage($from, $articleText, $config); } // Add a small delay to prevent rate limiting usleep(500000); // 0.5 second delay } // Check if there are more articles available if (count($articles) > ($start + $limit)) { sendWhatsAppMessage($from, "Reply with 'more news' to see additional articles.", $config); } } } else { // No articles available sendWhatsAppMessage($from, "Sorry, I couldn't retrieve any news articles at the moment.", $config); } } else if ( strpos(strtolower($messageText), 'posts') !== false || $messageText === '2' ) { // Fetch posts $posts = fetchPosts(); if (!empty($posts)) { // Track user's pagination state using a simple file-based approach $postpaginationFile = 'posts_pagination.json'; $pagination = []; if (file_exists($postpaginationFile)) { $paginationData = file_get_contents($postpaginationFile); $pagination = json_decode($paginationData, true) ?: []; } // Determine the starting point for posts $start = 0; $limit = 3; // Check if this is a "more posts" request if (strpos(strtolower($messageText), 'more posts') !== false) { // Get current page for this user, default to 0 $currentPage = $pagination[$from] ?? 0; // Increment the page counter $currentPage++; $start = $currentPage * $limit; // Save the updated page counter $pagination[$from] = $currentPage; } else { // This is a fresh request (clicked "5"), so reset the pagination $pagination[$from] = 0; } // Always save the pagination state file_put_contents($postpaginationFile, json_encode($pagination)); // Get the subset of posts to display $displayPosts = array_slice($posts, $start, $limit); // Keep track of how many valid posts we've sent $sentPostCount = 0; if (empty($displayPosts)) { // No more posts to show sendWhatsAppMessage($from, "No more social posts available at this time.", $config); } else { // Send each post with its image if available foreach ($displayPosts as $post) { // Don't immediately skip posts with null chat // Only skip if both chat AND image are empty if (empty($post['chat']) && empty($post['imgurl'])) continue; // Create a message for this specific post $postText = "*" . $post['full_name'] . "*\n"; // Process chat text if it exists if (!empty($post['chat'])) { // Strip quotes if present and clean up the text $chatText = $post['chat']; if (substr($chatText, 0, 1) === '"' && substr($chatText, -1) === '"') { $chatText = substr($chatText, 1, -1); } // Remove any URLs from the chat text $chatText = preg_replace('/https?:\/\/[^\s]+/i', '', $chatText); // Clean up any extra spaces left after removing URLs $chatText = trim(preg_replace('/\s+/', ' ', $chatText)); // Limit text length if (strlen($chatText) > 150) { $chatText = substr($chatText, 0, 147) . "..."; } $postText .= $chatText . "\n\n"; } $postText .= "*Post Link*:" . $post['postUrl'] . "\n"; $postText .= "*Posted On:* " . date('M d, Y', strtotime($post['postedOn'])); // If post has an image, send as image with caption if (!empty($post['imgurl'])) { sendWhatsAppImage($from, $post['imgurl'], $postText, $config); } else { // No image, send as text only // Extract URL from chat if present if (!empty($post['chat']) && preg_match('/https?:\/\/[^\s]+/i', $post['chat'], $matches)) { $postText .= "\n*Link:* " . $matches[0]; } // No image, send as text only sendWhatsAppMessage($from, $postText, $config); } $sentPostCount++; // Add a small delay to prevent rate limiting usleep(500000); // 0.5 second delay } // Check if there are more posts available if (count($posts) > ($start + $sentPostCount)) { sendWhatsAppMessage($from, "Reply with 'more posts' to see additional social posts.", $config); } } } else { // No posts available sendWhatsAppMessage($from, "Sorry, I couldn't retrieve any social posts at the moment.", $config); } } else { // For non-news/posts responses, process as usual $response = processMessage($messageText); sendWhatsAppMessage($from, $response, $config); } } // Return 200 OK to acknowledge receipt http_response_code(200); echo 'OK'; exit; } catch (Exception $e) { // Log the error error_log('Error processing webhook: ' . $e->getMessage()); http_response_code(500); exit('Error processing webhook'); } } // Not a WhatsApp message http_response_code(400); exit('Invalid request'); } ?>