ChatGPT Gadget Helper



‘Invalid request’]);
}

$user_message = sanitize_text_field($_POST[‘user_message’]);

// OpenAI API call (Replace ‘YOUR_OPENAI_API_KEY’ with an actual API key)
$response = wp_remote_post(‘https://api.openai.com/v1/chat/completions’, array(
‘headers’ => array(
‘Content-Type’ => ‘application/json’,
‘Authorization’ => ‘Bearer YOUR_OPENAI_API_KEY’,
),
‘body’ => json_encode(array(
‘model’ => ‘gpt-4’,
‘messages’ => array(
array(‘role’ => ‘system’, ‘content’ => ‘You are a helpful assistant for troubleshooting electronics.’),
array(‘role’ => ‘user’, ‘content’ => $user_message),
),
)),
));

if (is_wp_error($response)) {
wp_send_json_error([‘message’ => ‘API request failed’]);
}

$body = json_decode(wp_remote_retrieve_body($response), true);
$reply = $body[‘choices’][0][‘message’][‘content’] ?? ‘Sorry, I could not process your request.’;

// Check for product recommendation
$product_links = [
‘hdmi cable’ => ‘https://www.amazon.com/dp/YOUR_HDMI_CABLE_AFFILIATE_LINK’,
‘rca cable’ => ‘https://www.amazon.com/dp/YOUR_RCA_CABLE_AFFILIATE_LINK’,
];

foreach ($product_links as $keyword => $link) {
if (stripos($user_message, $keyword) !== false) {
$reply .= “\nYou can buy it here: $keyword.”;
}
}

wp_send_json_success([‘message’ => nl2br($reply)]);
}
add_action(‘wp_ajax_chatgpt_gadget_helper’, ‘chatgpt_gadget_helper_ajax’);
add_action(‘wp_ajax_nopriv_chatgpt_gadget_helper’, ‘chatgpt_gadget_helper_ajax’);