get_error_message(); } else { $body = wp_remote_retrieve_body($response); $json = json_decode($body, true); if (isset($json['ok']) && $json['ok'] === true) { $status = 'success'; $message = __('Webhook registered successfully.', 'aiutoma'); } else { $message = isset($json['description']) ? $json['description'] : __('Unknown Telegram API error.', 'aiutoma'); } } } set_transient('aiutoma_im_admin_notice', ['status' => $status, 'message' => $message], 45); wp_safe_redirect(admin_url('admin.php?page=aiutoma-im')); exit; } public function clear_im_history_action() { if (!current_user_can('manage_options')) { wp_die(esc_html__('You do not have permission to perform this action.', 'aiutoma')); } check_admin_referer('aiutoma_clear_im_history'); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verified above via check_admin_referer. $platform_to_clear = isset($_GET['platform']) ? sanitize_key(wp_unslash($_GET['platform'])) : ''; $conv_id = ''; if ($platform_to_clear === 'whatsapp') { $t_num = get_option('aiutoma_wa_target_number'); if (!empty($t_num)) { $conv_id = 'whatsapp_' . preg_replace('/[^0-9]/', '', $t_num); } } elseif ($platform_to_clear === 'telegram') { $c_id = get_option('aiutoma_tg_allowed_chat_id'); if (!empty($c_id)) { $conv_id = 'telegram_' . $c_id; } } if (!empty($conv_id)) { delete_transient($conv_id); $file_path = \Aiutoma\Modules\Ai\Ai::get_storage_dir() . '/logs/sessions/' . sanitize_file_name($conv_id) . '.json'; if (file_exists($file_path)) { wp_delete_file($file_path); } /* translators: %s: Platform name */ $notice_msg = sprintf(__('AI Memory wiped for %s. You can now start fresh!', 'aiutoma'), ucfirst($platform_to_clear)); set_transient('aiutoma_im_admin_notice', ['status' => 'success', 'message' => $notice_msg], 45); } wp_safe_redirect(admin_url('admin.php?page=aiutoma-im')); exit; } public function aiutoma_im_page_html() { if (!current_user_can('manage_options')) return; // WhatsApp Saving if (isset($_POST['aiutoma_wa_settings_nonce'])) { check_admin_referer('aiutoma_wa_settings_action', 'aiutoma_wa_settings_nonce'); if (isset($_POST['aiutoma_wa_phone_number_id'])) { update_option('aiutoma_wa_phone_number_id', sanitize_text_field(wp_unslash($_POST['aiutoma_wa_phone_number_id']))); } if (isset($_POST['aiutoma_wa_access_token'])) { update_option('aiutoma_wa_access_token', sanitize_text_field(wp_unslash($_POST['aiutoma_wa_access_token']))); } if (isset($_POST['aiutoma_wa_target_number'])) { update_option('aiutoma_wa_target_number', sanitize_text_field(wp_unslash($_POST['aiutoma_wa_target_number']))); } if (isset($_POST['aiutoma_wa_app_secret'])) { update_option('aiutoma_wa_app_secret', sanitize_text_field(wp_unslash($_POST['aiutoma_wa_app_secret']))); } echo '

' . esc_html__('WhatsApp Settings saved.', 'aiutoma') . '

'; } // Telegram Saving if (isset($_POST['aiutoma_tg_settings_nonce'])) { check_admin_referer('aiutoma_tg_settings_action', 'aiutoma_tg_settings_nonce'); $new_token = isset($_POST['aiutoma_tg_bot_token']) ? sanitize_text_field(wp_unslash($_POST['aiutoma_tg_bot_token'])) : ''; if (!empty($new_token) && !preg_match('/^[0-9]+:[a-zA-Z0-9_-]+$/', $new_token)) { echo '

' . esc_html__('Error: Invalid Telegram Bot Token format. It must look like: 123456789:ABCdefGHIjkl...', 'aiutoma') . '

'; } else { $is_valid = true; if (!empty($new_token)) { $response = wp_remote_get("https://api.telegram.org/bot{$new_token}/getMe"); if (!is_wp_error($response)) { $body = wp_remote_retrieve_body($response); $json = json_decode($body, true); if (isset($json['ok']) && $json['ok'] === true) { update_option('aiutoma_tg_bot_info', [ 'name' => $json['result']['first_name'], 'username' => $json['result']['username'] ]); } else { $is_valid = false; delete_option('aiutoma_tg_bot_info'); echo '

' . esc_html__('Telegram API Error: Token format is correct, but Telegram rejected it as invalid.', 'aiutoma') . '

'; } } } else { delete_option('aiutoma_tg_bot_info'); } if ($is_valid) { update_option('aiutoma_tg_bot_token', $new_token); if (isset($_POST['aiutoma_tg_allowed_chat_id'])) { update_option('aiutoma_tg_allowed_chat_id', sanitize_text_field(wp_unslash($_POST['aiutoma_tg_allowed_chat_id']))); } echo '

' . esc_html__('Telegram Settings saved.', 'aiutoma') . '

'; } } } // Global Settings Saving if (isset($_POST['aiutoma_im_global_nonce'])) { check_admin_referer('aiutoma_im_global_action', 'aiutoma_im_global_nonce'); if (isset($_POST['aiutoma_im_model'])) { update_option('aiutoma_im_model', sanitize_text_field(wp_unslash($_POST['aiutoma_im_model']))); } if (isset($_POST['aiutoma_im_system_prompt'])) { update_option('aiutoma_im_system_prompt', sanitize_textarea_field(wp_unslash($_POST['aiutoma_im_system_prompt']))); } if (isset($_POST['aiutoma_im_acting_user'])) { update_option('aiutoma_im_acting_user', intval(wp_unslash($_POST['aiutoma_im_acting_user']))); } echo '

' . esc_html__('Global Settings saved.', 'aiutoma') . '

'; } // Display transient notice if available $im_notice = get_transient('aiutoma_im_admin_notice'); if (!empty($im_notice) && is_array($im_notice)) { delete_transient('aiutoma_im_admin_notice'); $notice_status = $im_notice['status'] ?? 'info'; $notice_msg = $im_notice['message'] ?? ''; $notice_class = ($notice_status === 'success') ? 'notice-success' : 'notice-error'; echo '

' . esc_html($notice_msg) . '

'; } // Global Options $im_model = get_option('aiutoma_im_model', ''); $im_system_prompt = get_option('aiutoma_im_system_prompt', ''); $saved_im_acting_user = (int) get_option('aiutoma_im_acting_user', 0); $current_user_id = get_current_user_id(); $selected_im_user_id = (int) apply_filters('aiutoma_im_selected_user_id', $saved_im_acting_user ?: $current_user_id); $selected_user = get_userdata($selected_im_user_id); $current_user = wp_get_current_user(); $selected_user_login = ($selected_user && !empty($selected_user->user_login)) ? $selected_user->user_login : (($current_user && !empty($current_user->user_login)) ? $current_user->user_login : 'admin'); // WA Options $phone_number_id = get_option('aiutoma_wa_phone_number_id', ''); $access_token = get_option('aiutoma_wa_access_token', ''); $target_number = get_option('aiutoma_wa_target_number', ''); $app_secret = get_option('aiutoma_wa_app_secret', ''); $wa_verify_token = get_option('aiutoma_wa_verify_token', ''); if (empty($wa_verify_token)) { $wa_verify_token = wp_generate_password(32, false, false); update_option('aiutoma_wa_verify_token', $wa_verify_token); } // TG Options $tg_bot_token = get_option('aiutoma_tg_bot_token', ''); $tg_allowed_chat_id = get_option('aiutoma_tg_allowed_chat_id', ''); $tg_bot_info = get_option('aiutoma_tg_bot_info', []); $mcp_token = get_option('aiutoma_mcp_token', ''); // Enqueue Select2 for the models dropdown wp_enqueue_style('aiutoma-select2'); wp_enqueue_script('aiutoma-select2'); ?>

esc_url(rest_url('aiutoma/v1/ai-models')), 'nonce' => wp_create_nonce('wp_rest') ]); ?>


  1. Go to the Meta for Developers portal, log in, click "My Apps".
  2. Click "Create App", select "Other" then "Business". Name it and proceed.
  3. Scroll down to find "WhatsApp" and click "Set Up".
  4. Expand "WhatsApp" → "API Setup". Copy the Phone Number ID to the field above.
  5. Go to Meta Business Settings → System Users. Create a system user, assign your App, click "Generate New Token" with whatsapp_business_messaging and whatsapp_business_management. Paste token above.
  6. Under "WhatsApp" → "Configuration", edit the Webhook:
    • Callback URL:
    • Verify Token: Copy your global MCP token from the field above.
  7. Click "Manage" under Webhook fields and "Subscribe" to the "messages" event.
  8. Send a message from your target number to the Meta number to test!

@
→


  1. Open Telegram and search for @BotFather.
  2. Send the command /newbot and follow instructions to choose a name and username.
  3. Copy the Bot Token (e.g. 123456789:ABCdef...) into the field above.
  4. To find your personal Allowed Chat ID, search for @userinfobot on Telegram and send a message. It replies with your ID. Copy it to the field above to secure your bot.
  5. Save the settings using the button above.
  6. Click Register Webhook via API to automatically tell Telegram to send messages to your site.
  7. Done! You can now chat with your bot directly on Telegram.
'GET', 'callback' => [$this, 'whatsapp_webhook_verify'], 'permission_callback' => [$this, 'whatsapp_webhook_verify_permission_check'] ], [ 'methods' => 'POST', 'callback' => [$this, 'whatsapp_webhook_receive'], 'permission_callback' => [$this, 'whatsapp_webhook_permission_check'] ] ]); // Telegram Webhook register_rest_route('aiutoma/v1', '/telegram-webhook', [ [ 'methods' => 'POST', 'callback' => [$this, 'telegram_webhook_receive'], 'permission_callback' => [$this, 'telegram_webhook_permission_check'] ] ]); } // --- WhatsApp Methods --- public function whatsapp_webhook_verify_permission_check(\WP_REST_Request $request) { $mode = (string) $request->get_param('hub_mode'); $token = (string) $request->get_param('hub_verify_token'); $verify_token = (string) get_option('aiutoma_wa_verify_token', ''); if (empty($verify_token)) { $verify_token = (string) get_option('aiutoma_mcp_token', ''); } if ($mode === 'subscribe' && !empty($verify_token) && hash_equals($verify_token, $token)) { return true; } return new \WP_Error('rest_forbidden', __('Forbidden: Invalid verify token.', 'aiutoma'), ['status' => 403]); } public function whatsapp_webhook_verify(\WP_REST_Request $request) { $challenge = (string) $request->get_param('hub_challenge'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Plain text numeric/alphanumeric challenge token required by Meta Webhooks. echo esc_html($challenge); exit; } public function whatsapp_webhook_permission_check(\WP_REST_Request $request) { $raw_body = $request->get_body(); $signature = $request->get_header('x_hub_signature_256'); $app_secret = (string) get_option('aiutoma_wa_app_secret', ''); if ($app_secret === '' || !is_string($signature)) { return new \WP_Error('rest_forbidden', __('Unauthorized: Missing signature or app secret.', 'aiutoma'), ['status' => 401]); } $expected = 'sha256=' . hash_hmac('sha256', $raw_body, $app_secret); if (!hash_equals($expected, $signature)) { return new \WP_Error('rest_forbidden', __('Unauthorized: Invalid webhook signature.', 'aiutoma'), ['status' => 401]); } $acting_user_id = (int) apply_filters('aiutoma_im_acting_user_id', (int) get_option('aiutoma_im_acting_user', 0)); $user = get_userdata($acting_user_id); if (!$user || !$user->has_cap('manage_options')) { return new \WP_Error('rest_forbidden', __('Service Unavailable: Missing or demoted acting user.', 'aiutoma'), ['status' => 503]); } return true; } public function whatsapp_webhook_receive(\WP_REST_Request $request) { $body = $request->get_json_params(); if (isset($body['entry'][0]['changes'][0]['value']['messages'][0])) { $message_data = $body['entry'][0]['changes'][0]['value']['messages'][0]; $from = $message_data['from']; $target_number = get_option('aiutoma_wa_target_number', ''); $clean_from = preg_replace('/[^0-9]/', '', $from); $clean_target = preg_replace('/[^0-9]/', '', $target_number); if (!empty($clean_target) && $clean_from === $clean_target) { ignore_user_abort(true); if (function_exists('set_time_limit')) { @set_time_limit(120); } if (function_exists('fastcgi_finish_request')) { status_header(200); header('Content-Type: application/json'); echo wp_json_encode(['success' => true]); fastcgi_finish_request(); } else { status_header(200); header('Connection: close'); header('Content-Type: application/json'); ob_start(); echo wp_json_encode(['success' => true]); $size = ob_get_length(); header("Content-Length: {$size}"); ob_end_flush(); @ob_flush(); flush(); } $text = ''; if (isset($message_data['text']['body'])) { $text = $message_data['text']['body']; } elseif (isset($message_data['type']) && $message_data['type'] === 'image') { $text = "User sent an image."; if (isset($message_data['image']['caption'])) { $text .= " Caption: " . $message_data['image']['caption']; } } if (!empty($text)) { $this->process_im_message($text, 'whatsapp'); } } } return new \WP_REST_Response(['success' => true], 200); } // --- Telegram Methods --- public function telegram_webhook_permission_check(\WP_REST_Request $request) { $secret_token = (string) get_option('aiutoma_tg_webhook_secret', ''); $incoming_token = $request->get_header('x_telegram_bot_api_secret_token'); if (empty($secret_token) || !is_string($incoming_token) || !hash_equals($secret_token, $incoming_token)) { return new \WP_Error('rest_forbidden', __('Forbidden: Invalid Telegram secret token.', 'aiutoma'), ['status' => 403]); } $acting_user_id = (int) apply_filters('aiutoma_im_acting_user_id', (int) get_option('aiutoma_im_acting_user', 0)); $user = get_userdata($acting_user_id); if (!$user || !$user->has_cap('manage_options')) { return new \WP_Error('rest_forbidden', __('Service Unavailable: Missing or demoted acting user.', 'aiutoma'), ['status' => 503]); } return true; } public function telegram_webhook_receive(\WP_REST_Request $request) { $body = $request->get_json_params(); if (isset($body['message'])) { $message = $body['message']; $chat_id = $message['chat']['id'] ?? ''; $allowed_chat_id = get_option('aiutoma_tg_allowed_chat_id', ''); if (!empty($allowed_chat_id) && (string)$chat_id === (string)$allowed_chat_id) { ignore_user_abort(true); if (function_exists('set_time_limit')) { @set_time_limit(120); } if (function_exists('fastcgi_finish_request')) { status_header(200); header('Content-Type: application/json'); echo wp_json_encode(['success' => true]); fastcgi_finish_request(); } else { status_header(200); header('Connection: close'); header('Content-Type: application/json'); ob_start(); echo wp_json_encode(['success' => true]); $size = ob_get_length(); header("Content-Length: {$size}"); ob_end_flush(); @ob_flush(); flush(); } $text = ''; if (isset($message['text'])) { $text = $message['text']; } elseif (isset($message['photo'])) { $text = "User sent an image."; if (isset($message['caption'])) { $text .= " Caption: " . $message['caption']; } } elseif (isset($message['voice'])) { $text = "User sent a voice message."; } elseif (isset($message['document'])) { $text = "User sent a document."; } if (!empty($text)) { $this->process_im_message($text, 'telegram', $chat_id); } } } return new \WP_REST_Response(['success' => true], 200); } // --- Shared Processing Methods --- private function process_im_message($text, $platform, $telegram_chat_id = null) { if (!class_exists('\WordPress\AiClient\AiClient')) return; if (trim($text) === '/clear') { $conversation_id = ''; if ($platform === 'whatsapp') { $target_number = get_option('aiutoma_wa_target_number'); if (!empty($target_number)) { $conversation_id = 'whatsapp_' . preg_replace('/[^0-9]/', '', $target_number); } } else if ($platform === 'telegram') { $conversation_id = 'telegram_' . $telegram_chat_id; } if (!empty($conversation_id)) { delete_transient($conversation_id); $upload_dir = wp_upload_dir(); $file_path = \Aiutoma\Modules\Ai\Ai::get_storage_dir() . '/logs/sessions/' . sanitize_file_name($conversation_id) . '.json'; if (file_exists($file_path)) wp_delete_file($file_path); if ($platform === 'telegram') { $this->send_telegram_message($telegram_chat_id, "Conversation history cleared. We can start fresh!"); } else if ($platform === 'whatsapp') { $this->send_whatsapp_message("Conversation history cleared. We can start fresh!"); } } return; } // Authenticate the webhook request as the configured user to allow AI abilities to function if (get_current_user_id() === 0) { $acting_user_id = (int) apply_filters('aiutoma_im_acting_user_id', (int) get_option('aiutoma_im_acting_user', 0)); if ($acting_user_id) { add_filter('determine_current_user', function() use ($acting_user_id) { return $acting_user_id; }, 20); global $current_user; $current_user = null; wp_get_current_user(); } } $conversation_id = ''; if ($platform === 'whatsapp') { $target_number = get_option('aiutoma_wa_target_number'); if (empty($target_number)) return; $conversation_id = 'whatsapp_' . preg_replace('/[^0-9]/', '', $target_number); $prompt_prefix = "User via WhatsApp: "; } else if ($platform === 'telegram') { $conversation_id = 'telegram_' . $telegram_chat_id; $prompt_prefix = "User via Telegram: "; } else { return; } $chat_request = new \WP_REST_Request('POST', '/aiutoma/v1/ai-chat'); $chat_request->set_param('conversation_id', $conversation_id); $chat_request->set_param('prompt', $prompt_prefix . $text); $im_model = get_option('aiutoma_im_model', ''); $im_system_prompt = get_option('aiutoma_im_system_prompt', ''); if (!empty($im_model)) { $chat_request->set_param('model', $im_model); } if (!empty($im_system_prompt)) { $chat_request->set_param('session_context', $im_system_prompt); } if (!method_exists($this, 'handle_chat_request')) return; $response = $this->handle_chat_request($chat_request); $iterations = 0; $max_iterations = 5; $final_text = ''; while ($iterations < $max_iterations && !is_wp_error($response) && $response instanceof \WP_REST_Response) { $data = $response->get_data(); $last_action = $data['action'] ?? ''; if (isset($data['success']) && $data['success'] === false) { $final_text = "Error: " . ($data['message'] ?? 'Unknown error occurred.'); break; } if ($last_action === 'tool_calls') { $iterations++; $exec_request = new \WP_REST_Request('POST', '/aiutoma/v1/ai-chat'); $exec_request->set_param('conversation_id', $conversation_id); $exec_request->set_param('execute_tools', true); if (!empty($im_model)) { $exec_request->set_param('model', $im_model); } // Add a short delay to prevent hitting strict rate limits on the API proxy sleep(2); $response = $this->handle_chat_request($exec_request); } else { if (isset($data['response']['text'])) { $final_text = $data['response']['text']; } elseif (isset($data['response']) && is_string($data['response'])) { $final_text = $data['response']; } elseif (isset($data['message'])) { $final_text = $data['message']; } break; } } if (is_wp_error($response)) { $final_text = "Error: " . $response->get_error_message(); } if (!empty($final_text)) { $media_url = ''; if (preg_match('/(https?:\/\/[^\s]+(?:jpg|jpeg|png|webp|pdf|docx|xlsx|mp4))/i', $final_text, $matches)) { $media_url = $matches[1]; $final_text = trim(str_replace($media_url, '', $final_text)); } $display_text = $final_text; if (class_exists('\League\CommonMark\CommonMarkConverter')) { if (class_exists('\League\CommonMark\GithubFlavoredMarkdownConverter')) { $converter = new \League\CommonMark\GithubFlavoredMarkdownConverter(['html_input' => 'allow', 'allow_unsafe_links' => false]); } else { $converter = new \League\CommonMark\CommonMarkConverter(['html_input' => 'allow', 'allow_unsafe_links' => false]); } $display_text = trim($converter->convert($final_text)->getContent()); // Add newlines around block elements so they don't squash together when stripped $display_text = preg_replace('/<\/?(p|br|div|h[1-6]|tr|ul|ol)[^>]*>/i', "\n$0\n", $display_text); $display_text = preg_replace('/]*>/i', "\n- $0", $display_text); } if ($platform === 'whatsapp') { $this->send_whatsapp_message($final_text, $media_url); // WhatsApp handles markdown natively better } else if ($platform === 'telegram') { // Remove unsupported HTML tags for Telegram $display_text = strip_tags($display_text, '
');
                $display_text = trim(preg_replace("/[\r\n]{3,}/", "\n\n", $display_text));
                $this->send_telegram_message($telegram_chat_id, $display_text, $media_url);
            }
            
            // Save Session for Playground History
            $upload_dir = wp_upload_dir();
            $log_dir = \Aiutoma\Modules\Ai\Ai::get_storage_dir() . '/logs/sessions';
            if (!is_dir($log_dir)) wp_mkdir_p($log_dir);
            $session_id = sanitize_file_name($conversation_id);
            $file_path = $log_dir . '/' . $session_id . '.json';
            
            $sess_data = [];
            if (file_exists($file_path)) {
                $sess_data = json_decode(file_get_contents($file_path), true);
            }
            if (empty($sess_data)) {
                $sess_data = [
                    'is_full_state' => true,
                    'id' => $session_id,
                    'user' => 'IM User (' . ucfirst($platform) . ')',
                    'first_prompt' => $text,
                    'html' => '',
                    'conversation_id' => $conversation_id,
                    'session_prompts' => []
                ];
            }
            
            $sess_data['date'] = current_time('mysql');
            $sess_data['session_prompts'][] = $text;
            
            $transient_data = get_transient($conversation_id);
            if ($transient_data) {
                $json_data = json_decode($transient_data, true);
                if (is_array($json_data)) {
                    $messages = [];
                    foreach ($json_data as $msg_array) {
                        if (is_array($msg_array) && isset($msg_array['role'])) {
                            $messages[] = \WordPress\AiClient\Messages\DTO\Message::fromArray($msg_array);
                        }
                    }
                }
                if (isset($messages) && is_array($messages)) {
                    $html = '';
                    foreach ($messages as $msg) {
                        $role_obj = method_exists($msg, 'getRole') ? $msg->getRole() : '';
                        $role = (is_object($role_obj) && property_exists($role_obj, 'value')) ? $role_obj->value : (string) $role_obj;
                        $content_html = '';
                        $raw_text = '';
                        if (method_exists($msg, 'getParts')) {
                            $parts = $msg->getParts();
                            foreach ($parts as $part) {
                                if (method_exists($part, 'getText') && (string)$part->getText() !== '') {
                                    if ($role === 'model') {
                                        $raw_text .= (string) $part->getText() . "\n";
                                    } else {
                                        $content_html .= nl2br(esc_html((string) $part->getText())) . "
"; } } elseif (method_exists($part, 'getFunctionCall') && $part->getFunctionCall()) { $func = $part->getFunctionCall(); $name = method_exists($func, 'getName') ? $func->getName() : ''; $args = method_exists($func, 'getArgs') ? wp_json_encode($func->getArgs(), JSON_PRETTY_PRINT) : ''; $content_html .= "🛠️ [Tool Execution]: " . esc_html($name) . "
" . esc_html($args) . "
"; } elseif (method_exists($part, 'getFunctionResponse') && $part->getFunctionResponse()) { $resp = $part->getFunctionResponse(); $name = method_exists($resp, 'getName') ? $resp->getName() : ''; $res = method_exists($resp, 'getResponse') ? wp_json_encode($resp->getResponse(), JSON_PRETTY_PRINT) : ''; $content_html .= "✅ [Tool Response]: " . esc_html($name) . "
" . esc_html($res) . "
"; } } } if ($role === 'model' && !empty($raw_text)) { if (class_exists('\League\CommonMark\CommonMarkConverter')) { if (class_exists('\League\CommonMark\GithubFlavoredMarkdownConverter')) { $converter = new \League\CommonMark\GithubFlavoredMarkdownConverter(['html_input' => 'allow', 'allow_unsafe_links' => false]); } else { $converter = new \League\CommonMark\CommonMarkConverter(['html_input' => 'allow', 'allow_unsafe_links' => false]); } $content_html = wp_kses_post($converter->convert($raw_text)->getContent()) . $content_html; } else { $content_html = nl2br(esc_html($raw_text)) . $content_html; } } if ($role === 'user') { $html .= '
You (' . ucfirst($platform) . '):
' . $content_html . '
'; } elseif ($role === 'model') { $html .= '
AI:
' . $content_html . '
'; } elseif ($role === 'tool' || $role === 'function') { $html .= '
Tool Response:
' . $content_html . '
'; } } if (is_wp_error($response)) { $html .= '
Error:
' . esc_html($response->get_error_message()) . '
'; } else if ($response instanceof \WP_REST_Response) { $data = $response->get_data(); if (isset($data['success']) && $data['success'] === false) { $html .= '
Error:
' . esc_html($data['message'] ?? 'Unknown API Error') . '
'; } } $sess_data['html'] = $html; $sess_data['raw_messages'] = base64_encode(wp_json_encode($messages)); } } $sess_data['date'] = current_time('mysql'); file_put_contents($file_path, json_encode($sess_data)); } } public function send_im_admin_notification($message_text, $media_url = '', $buttons = []) { $wa_sent = false; $tg_sent = false; $target_number = get_option('aiutoma_wa_target_number'); if (!empty($target_number)) { $this->send_whatsapp_message($message_text, $media_url, $buttons); $wa_sent = true; } $tg_chat_id = get_option('aiutoma_tg_allowed_chat_id'); if (!empty($tg_chat_id)) { $this->send_telegram_message($tg_chat_id, $message_text, $media_url, $buttons); $tg_sent = true; } return $wa_sent || $tg_sent; } private function send_whatsapp_message($message_text, $media_url = '', $buttons = []) { $phone_number_id = get_option('aiutoma_wa_phone_number_id'); $access_token = get_option('aiutoma_wa_access_token'); $target_number = get_option('aiutoma_wa_target_number'); if (empty($phone_number_id) || empty($access_token) || empty($target_number)) { return false; } if (!empty($buttons)) { foreach ($buttons as $btn) { if (!empty($btn['url']) && !empty($btn['text'])) { $message_text .= "\n\n" . $btn['text'] . ": " . $btn['url']; } } } // Convert HTML to WhatsApp formatting $message_text = str_replace(['
', '
', '
', '

'], "\n", $message_text); $message_text = str_ireplace(['', '', '', ''], '*', $message_text); $message_text = preg_replace('/]*href=["\'](.*?)["\'][^>]*>(.*?)<\/a>/i', '$2: $1', $message_text); $message_text = wp_strip_all_tags($message_text); $message_text = html_entity_decode($message_text, ENT_QUOTES | ENT_HTML5, 'UTF-8'); $clean_target = preg_replace('/[^0-9]/', '', $target_number); $url = "https://graph.facebook.com/v18.0/{$phone_number_id}/messages"; $body = [ 'messaging_product' => 'whatsapp', 'to' => $clean_target, ]; if (!empty($media_url)) { $ext = strtolower(pathinfo(wp_parse_url($media_url, PHP_URL_PATH), PATHINFO_EXTENSION)); $is_image = in_array($ext, ['jpg', 'jpeg', 'png', 'webp']); if ($is_image) { $body['type'] = 'image'; $body['image'] = [ 'link' => $media_url ]; if (!empty($message_text)) { $body['image']['caption'] = mb_strimwidth($message_text, 0, 1024, '...'); } } else { $body['type'] = 'document'; $body['document'] = [ 'link' => $media_url ]; if (!empty($message_text)) { $body['document']['caption'] = mb_strimwidth($message_text, 0, 1024, '...'); } } } else { $body['type'] = 'text'; $body['text'] = [ 'body' => $message_text ]; } $args = [ 'body' => wp_json_encode($body), 'headers' => [ 'Authorization' => 'Bearer ' . $access_token, 'Content-Type' => 'application/json', ], 'timeout' => 15, 'data_format' => 'body', ]; return wp_remote_post($url, $args); } private function send_telegram_message($chat_id, $message_text, $media_url = '', $buttons = []) { $bot_token = get_option('aiutoma_tg_bot_token'); if (empty($bot_token) || empty($chat_id)) return false; $api_url = "https://api.telegram.org/bot{$bot_token}/"; $reply_markup = ''; if (!empty($buttons)) { $inline_keyboard = []; foreach ($buttons as $btn) { if (!empty($btn['url']) && !empty($btn['text'])) { $parsed_host = wp_parse_url($btn['url'], PHP_URL_HOST); if (in_array($parsed_host, ['localhost', '127.0.0.1'])) { // Telegram blocks localhost in buttons. Append to text instead. $message_text .= "\n\n" . $btn['text'] . ": " . $btn['url']; } else { $inline_keyboard[] = [['text' => $btn['text'], 'url' => $btn['url']]]; } } } if (!empty($inline_keyboard)) { $reply_markup = json_encode(['inline_keyboard' => $inline_keyboard]); } } if (!empty($media_url)) { $ext = strtolower(pathinfo(wp_parse_url($media_url, PHP_URL_PATH), PATHINFO_EXTENSION)); $is_image = in_array($ext, ['jpg', 'jpeg', 'png', 'webp']); $endpoint = $is_image ? 'sendPhoto' : 'sendDocument'; $media_field = $is_image ? 'photo' : 'document'; $body = [ 'chat_id' => $chat_id, $media_field => $media_url, 'caption' => mb_strimwidth($message_text, 0, 1024, '...'), 'parse_mode' => 'HTML' ]; } else { $endpoint = 'sendMessage'; $body = [ 'chat_id' => $chat_id, 'text' => $message_text, 'parse_mode' => 'HTML' ]; } if ($reply_markup) { $body['reply_markup'] = $reply_markup; } $args = [ 'body' => $body, 'timeout' => 15 ]; $response = wp_remote_post($api_url . $endpoint, $args); if (defined('WP_DEBUG') && WP_DEBUG && (is_wp_error($response) || wp_remote_retrieve_response_code($response) != 200)) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log, WordPress.PHP.DevelopmentFunctions.error_log_print_r error_log('Telegram API Error: ' . print_r($response, true)); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log, WordPress.PHP.DevelopmentFunctions.error_log_print_r error_log('Telegram Payload: ' . print_r($body, true)); } return $response; } }