Skip to content

Commit

Permalink
Facebook Messenger component: add support for sending messages to use…
Browse files Browse the repository at this point in the history
…r IDs

This is the documentation change for home-assistant/core#9643
  • Loading branch information
mweimerskirch authored Oct 1, 2017
1 parent 6157433 commit 794fd8c
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions source/_components/notify.facebook.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,51 @@ automation:
- +919784516314
```

You can also send messages to users that do not have stored their phone number with Facebook, but this requires a bit more work. The Messenger platform uses page specific user IDs instead of a global user ID. You will need to enable a webhook for the "messages" event in Facebook's developer console. Once a user writes a message to a page, that webhook will then receive the user's page specifc ID as part of the webhook's payload. Below is a simple PHP script that reacts to the message "get my id" and sends a reply containing the user's ID:

```php
<?php
$access_token = "";
$verify_token = "";
if (isset($_REQUEST['hub_challenge'])) {
$challenge = $_REQUEST['hub_challenge'];
$hub_verify_token = $_REQUEST['hub_verify_token'];
if ($hub_verify_token === $verify_token) {
echo $challenge;
}
}
$input = json_decode(file_get_contents('php://input'), true);
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
$message = $input['entry'][0]['messaging'][0]['message']['text'];
if (preg_match('/get my id/', strtolower($message))) {
$url = 'https://graph.facebook.com/v2.10/me/messages?access_token=' . $access_token;
$ch = curl_init($url);
$jsonData = '{
"recipient":{
"id":"' . $sender . '"
},
"message":{
"text":"Your ID: ' . $sender . '"
}
}';
$jsonDataEncoded = $jsonData;
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
if (!empty($input['entry'][0]['messaging'][0]['message'])) {
$result = curl_exec($ch);
}
}
```

### {% linkable_title Rich messages %}
You could also send rich messing (cards, buttons, images, videos, etc). [Info](https://developers.facebook.com/docs/messenger-platform/send-api-reference) to which types or messages and how to build them.

Expand Down

0 comments on commit 794fd8c

Please sign in to comment.