Hey there, fellow developer! Ready to dive into the world of Facebook Messenger bots? You're in for a treat. We'll be using the awesome tgallice/fb-messenger-sdk package to make our lives easier. Let's get cracking!
Before we jump in, make sure you've got:
First things first, let's get our project set up:
composer require tgallice/fb-messenger-sdk
Now, head over to the Facebook Developer portal and create a new app. Easy peasy!
Time to set up your webhook:
Let's get our hands dirty with some code:
<?php use Tgallice\FBMessenger\Messenger; $messenger = new Messenger('PAGE_TOKEN'); // Your webhook endpoint $app->post('/webhook', function (Request $request, Response $response) use ($messenger) { $body = json_decode($request->getBody(), true); foreach ($body['entry'] as $entry) { foreach ($entry['messaging'] as $event) { // Handle the event $this->handleEvent($messenger, $event); } } return $response->withStatus(200); }); private function handleEvent(Messenger $messenger, array $event) { if (isset($event['message'])) { $senderId = $event['sender']['id']; $messageText = $event['message']['text']; // Echo the message back $messenger->sendMessage($senderId, $messageText); } }
Now for the fun part - sending messages!
// Send a simple text message $messenger->sendMessage($recipientId, 'Hello, World!'); // Send an image $messenger->sendImage($recipientId, 'https://example.com/image.jpg'); // Send a button template $messenger->sendTemplate($recipientId, new ButtonTemplate('What do you want to do next?', [ new PostbackButton('Start over', 'START_OVER'), new WebUrlButton('Visit our website', 'https://example.com'), ]));
Let's make our bot interactive:
private function handleEvent(Messenger $messenger, array $event) { if (isset($event['postback'])) { $senderId = $event['sender']['id']; $payload = $event['postback']['payload']; switch ($payload) { case 'START_OVER': $messenger->sendMessage($senderId, "Let's start over!"); break; // Handle other postbacks } } // Handle quick replies similarly }
Want to take your bot to the next level? Try these:
// Get user profile $userProfile = $messenger->getUserProfile($userId); // Set up a persistent menu $messenger->setPersistentMenu([ new PostbackButton('Help', 'HELP_PAYLOAD'), new WebUrlButton('Visit website', 'https://example.com'), ]); // Set up a get started button $messenger->setGetStartedButton('GET_STARTED_PAYLOAD');
Testing is crucial, folks! Use Facebook's test users to put your bot through its paces. And don't forget about the handy debugging tools in the Facebook Developer portal.
As you prepare to unleash your bot on the world, keep these in mind:
And there you have it! You're now armed with the knowledge to create your very own Facebook Messenger bot. Remember, the key to a great bot is continuous improvement, so keep iterating and have fun with it!
For more advanced features and detailed documentation, check out the tgallice/fb-messenger-sdk GitHub page.
Now go forth and bot! 🚀