【问题标题】:How to access the name of someone with messenger chat bot? (Facebook Messenger SDK)如何使用信使聊天机器人访问某人的姓名? (Facebook 信使 SDK)
【发布时间】:2016-09-27 20:19:14
【问题描述】:

您好,我是 PHP 和 Messenger Bots 编码的新手。

我想知道如何访问向我的聊天机器人发送消息的人的姓名。

【问题讨论】:

  • 您是否考虑过在这里接受任何答案?有没有人回答你的问题?

标签: php artificial-intelligence facebook-chatbot


【解决方案1】:

@Rajesh 对冲

您的代码有一个小错误:

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/v2.6/<USER_ID>?fields=first_name,last_name&access_token=<PAGE_ACCESS_TOKEN>');
$result = curl_exec($ch);
curl_close($ch);

$obj = json_decode($result); // *** here
echo 'Hi ' . $obj['first_name'] . ' ' . $obj['last_name']

$obj = json_decode($result, **true**);

$result 需要转换成关联数组才能访问它,如下所示:$obj['first_name']

详情请见http://php.net/manual/en/function.json-decode.php

【讨论】:

    【解决方案2】:

    User Profile API 可以帮助您。

    使用从 messenger bot 服务器 (/webhook) 收到的 event.sender.id,并按照以下请求进行操作

    curl -X GET "https://graph.facebook.com/v2.6/<USER_ID>?fields=first_name,last_name,profile_pic,locale,timezone,gender&access_token=<PAGE_ACCESS_TOKEN>"
    

    那么你可以在下面得到返回的json

    {
         "first_name": "Peter",
         "last_name": "Chang",
         "profile_pic": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xpf1/v/t1.0-1/p200x200/13055603_10105219398495383_8237637584159975445_n.jpg?oh=1d241d4b6d4dac50eaf9bb73288ea192&oe=57AF5C03&__gda__=1470213755_ab17c8c8e3a0a447fed3f272fa2179ce",
         "locale": "en_US",
         "timezone": -7,
         "gender": "male"
    }
    

    【讨论】:

    【解决方案3】:

    你可以使用下面的 PHP sn-p 来获取用户名

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/v2.6/<USER_ID>?fields=first_name,last_name&access_token=<PAGE_ACCESS_TOKEN>');
    $result = curl_exec($ch);
    curl_close($ch);
    
    $obj = json_decode($result);
    echo 'Hi ' . $obj['first_name'] . ' ' . $obj['last_name']
    

    【讨论】:

    • 对不起,我从未真正使用过 PHP。我应该如何使用您的 PHP sn-p(即我将它放在代码中的什么位置)?我在下面的评论中有我根据你的代码尝试过的代码。
    • if($messageText == "hi" ) { //$answer = "Hello" ; $ch = curl_init(); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_URL, 'graph.facebook.com/v2.6/…); $result = curl_exec($ch); curl_close($ch); $obj = json_decode($result); $answer = '嗨' 。 $obj['first_name'] 。 ' ' 。 $obj['last_name']; } else if ($messageText != "") { $answer = "对不起,我不明白你在说什么。试着问我别的!"; }
    • @RayyaanMustafa,您必须将此代码粘贴到您正在处理消息文本的位置。
    猜你喜欢
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    • 2017-01-17
    • 1970-01-01
    • 2011-07-09
    • 2016-10-21
    • 1970-01-01
    相关资源
    最近更新 更多