Set Up a Webhook for Receiving Messages
- Facebook requires your server to be set up with a webhook to receive messages. Use a publicly accessible HTTPS server.
- Facebook will send HTTP POST requests to your webhook containing messages sent by users to your page. Your webhook should be able to respond to verification requests from Facebook during setup.
<?php
// Verifies requests to ensure they're from Facebook
$hub_verify_token = 'your_verification_token';
if ($_REQUEST['hub_verify_token'] === $hub_verify_token) {
echo $_REQUEST['hub_challenge'];
exit;
}
// Handle incoming POST data
$input = json_decode(file_get_contents('php://input'), true);
if (isset($input['entry'][0]['messaging'][0])) {
$message_event = $input['entry'][0]['messaging'][0];
// You can process the message here
}
echo "OK";
?>
Handle Incoming Messages
- Parse the incoming event data to extract the sender's ID and message content.
- Decide on the response logic based on the message content, which could involve calling other APIs or services to form a response.
<?php
// Assume $message_event is assigned from your webhook script
$sender_id = $message_event['sender']['id'];
$message_text = $message_event['message']['text'];
// Example: simple echo response
$response_text = "You said: " . $message_text;
// Send the message
sendTextMessage($sender_id, $response_text);
Create a Function to Send Messages
- Facebook Messenger API has a Send API that you can use to send messages to users. Implement a function to send text messages as a starting point.
- The function will call the Send API endpoint with appropriate headers and payload, using cURL or a similar library for making HTTP requests.
<?php
function sendTextMessage($recipient_id, $message_text) {
$accessToken = "your_page_access_token"; // You get this from your Facebook app settings
$url = "https://graph.facebook.com/v2.6/me/messages?access_token=$accessToken";
$ch = curl_init($url);
$jsonData = '{
"recipient": {
"id": "' . $recipient_id . '"
},
"message": {
"text": "' . $message_text . '"
}
}';
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
?>
Handle Various Message Types
- Enhance your chatbot to handle different message types like images, videos, and attachments.
- You can parse these based on the structure of the incoming webhook event and decide the appropriate response or action.
Implement Conversational Logic
- For more advanced chatbots, implement state management to handle different conversation stages or intents.
- You might need a storage mechanism to remember user preferences or previous interactions.
Secure and Optimize Your Bot
- Ensure your webhook validates requests properly to only process legitimate messages from Facebook.
- Implement logging and error handling to monitor your bot's performance and troubleshoot issues.
<?php
// Example: Basic Logging
function logMessage($message) {
file_put_contents('bot.log', date('Y-m-d H:i:s') . " - " . $message . PHP_EOL, FILE_APPEND);
}
logMessage("Received message from $sender_id: $message_text");
?>
Test and Iterate
- Test your bot extensively to ensure it handles different types of messages and edge cases robustly.
- Gather feedback from users and make iterative improvements to the bot’s functionality and conversation flow.