革新对话:使用PHP将WhatsApp Chatbot与Meta和ChatGPT Turbo集成

介绍:在快速发展的对话型人工智能世界中,我们踏上了一段旅程,通过一个完全集成的 WhatsApp 聊天机器人来增强用户互动。这个项目利用 PHP 实现了与 Meta(前身为 Facebook)和强大的 ChatGPT Turbo 聊天机器人的无缝集成,用于自然语言处理。

使用的技术:我们的技术栈包括用于服务器端脚本的PHP,用于WhatsApp集成的Meta API以及用于高级语言理解的ChatGPT Turbo。

关键成就:成功整合Meta API for WhatsApp以实现与用户的互动和动态对话。无缝集成ChatGPT Turbo以增强聊天机器人的自然语言处理能力。克服身份验证、消息处理等挑战,确保用户体验顺畅。 功能和演示: 丰富的多媒体支持:通过聊天机器人发送图片、视频和其他媒体。 动态回应:聊天机器人根据用户输入和上下文自适应回应。 多步对话:通过一系列消息处理复杂的互动。 用户体验和反馈: 用户报告了显著改善的体验,称赞聊天机器人在理解和上下文响应方面的能力。真实场景展示了集成解决方案的有效性。

测试和性能:为确保聊天机器人的可靠性和性能,进行了严格的测试。性能指标显示优化的响应时间和高效的资源利用。

未来发展:整合额外功能,如个性化用户交互和第三方API集成。持续优化聊天机器人的语言理解和响应生成。

完整代码

配置Webhook

// Set your verify token
$verifyToken = "YOUR_KEY"; // Replace with your actual verify token

// Get the hub challenge, mode, and verify token from the request
$hubChallenge = isset($_GET['hub_challenge']) ? $_GET['hub_challenge'] : null;
$hubMode = isset($_GET['hub_mode']) ? $_GET['hub_mode'] : null;
$hubVerifyToken = isset($_GET['hub_verify_token']) ? $_GET['hub_verify_token'] : null;

// Check if the hub mode is 'subscribe' and the verify token matches
if ($hubMode === 'subscribe' && $hubVerifyToken === $verifyToken) {
// Respond with the hub challenge to complete the verification
echo $hubChallenge;
} else {
// Respond with an error or log the issue
echo "Verification failed.";
}

// Exit the script after verification
exit();

完整PHP代码

<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);

// Specify the path to the log file
$logFilePath = 'PATH/TO/LOG/FILE';

// Set the default timezone
date_default_timezone_set('Africa/Nairobi');

// Decode incoming JSON data from WhatsApp webhook
$data = json_decode(file_get_contents('php://input'), true);

// Check if the data is from a WhatsApp Business Account and contains messages
if ($data['object'] == 'whatsapp_business_account' && isset($data['entry'][0]['changes'][0]['value']['messages'])) {

// Decode JSON data again for better readability
$data_json = file_get_contents('php://input');
$data_array = json_decode($data_json, true);

// Extract relevant information from the incoming data
$entry = $data_array['entry'];
$message_id = $entry[0]['id'];

$from = $entry[0]['changes'][0]['value']['messages'][0]['from'];
$to = $entry[0]['changes'][0]['value']['metadata']['display_phone_number'];

$senderName = $entry[0]['changes'][0]['value']['contacts'][0]['profile']['name'];

$type = $entry[0]['changes'][0]['value']['messages'][0]['type'];

// Determine the message type and extract the text
if ($type == 'text') {
$text = $entry[0]['changes'][0]['value']['messages'][0]['text']['body'];
} else if ($type == 'interactive') {
$interactive = $entry[0]['changes'][0]['value']['messages'][0]['interactive'];
$interactive_type = $entry[0]['changes'][0]['value']['messages'][0]['interactive']['type'];

if ($interactive_type == 'button_reply') {
$button_reply = $interactive['button_reply'];
$text = $button_reply['title'];
} else {
$list_reply = $interactive['list_reply'];
$text = $list_reply['title'];
}
} else {
// Default message if type is neither 'text' nor 'interactive'
$text = "Hello";
}

// Check if products have already been fetched for this user
getChatGPTResponse($text, $from);
}

function getChatGPTResponse($inputText, $from) {
// Log the user's input
logMessage("GPT |: ", $inputText, $from);

// Load the conversation context from a file (you may replace this with a database or cache)
$conversationContext = loadConversationContext($from);

// Add the user's message to the conversation context
$conversationContext[] = ['role' => 'user', 'content' => $inputText];

// Set parameters for ChatGPT API request
$data = [
'messages' => $conversationContext,
'model' => 'CHAT_GPT_MODEL',
'temperature' => 'TEMPERATURE',
'max_tokens' => 'MAX_TOKENS'
];

// Set headers for the ChatGPT API request
$headers = [
'Content-Type: application/json',
'Authorization: Bearer ' . 'CHAT_GPT_API_KEY'
];

// Use cURL to make a request to ChatGPT API
$ch = curl_init("https://api.openai.com/v1/chat/completions");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

// Execute the cURL session and fetch result
$response = curl_exec($ch);

// Close the cURL session
curl_close($ch);

// Decode the API response
$responseArr = json_decode($response, true);

// Extract the model's reply
$reply = $responseArr['choices'][0]['message']['content'];

// Add the model's reply to the conversation context
$conversationContext[] = ['role' => 'system', 'content' => $reply];

// Save the updated conversation context to the file
saveConversationContext($from, $conversationContext);

// Send the WhatsApp message with the model's reply
sendWhatsAppMessage($from, $reply);

// Log the model's reply
logMessage("OUT |: ", $reply, $from);
}

// Load the conversation context from the specified directory for the given user
function loadConversationContext($userId) {
$filePath = "PATH/TO/conversations/$userId.json";
if (file_exists($filePath)) {
$contextJson = file_get_contents($filePath);
return json_decode($contextJson, true);
}
return [];
}

// Save the conversation context to the specified directory for the given user
function saveConversationContext($userId, $context) {
$filePath = "PATH?TO/conversations/$userId.json";
if (!file_exists(dirname($filePath))) {
mkdir(dirname($filePath), 0755, true);
}
file_put_contents($filePath, json_encode($context));
}

// Send a WhatsApp message
function sendWhatsAppMessage($recipientNumber, $message) {
$accessToken = 'META_ACCESS_TOKEN';
$url = 'https://graph.facebook.com/VERION_NUMBER/PHONE_NUMBER_ID/messages';

$_message = " *Ubuni AI*\n\n" . $message;

$data = [
'messaging_product' => 'whatsapp',
'to' => 'whatsapp:' . $recipientNumber,
'type' => 'text',
'text' => [
'body' => $_message,
],
];

$headers = [
'Content-Type: application/json',
'Authorization: Bearer ' . $accessToken,
];

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

curl_close($ch);

$responseData = json_decode($response, true);

// Print the message status
if (isset($responseData['messages'][0]['message_status'])) {
$messageStatus = $responseData['messages'][0]['message_status'];
echo 'Message Status: ' . $messageStatus;
} else {
echo 'Unable to retrieve message status.';
}
}

// Log a message with timestamp
function logMessage($type, $message, $phone_number) {
global $logFilePath;
$logMessage = date('Y-m-d H:i:s') . ' | ' . $type . ' | ' . $phone_number . ' | ' . $message . PHP_EOL;
file_put_contents($logFilePath, $logMessage, FILE_APPEND);
}

?>

结论:通过使用PHP将WhatsApp聊天机器人与Meta和ChatGPT Turbo成功集成,为互动和有趣的对话打开了新的可能性。这一旅程展示了将强大技术相结合以创建智能和用户友好的聊天机器人体验的潜力。

要试一下在WhatsApp上聊天,发送+254748406509。

2024-02-15 04:27:17 AI中文站翻译自原文