使用PHP从twitter检索直接消息?

时间:2017-03-06 08:14:51

标签: php twitter

我正在尝试检索实时发送到我帐户的直接消息。但是,我的脚本工作的方式是,当有人给我发消息时,我必须刷新脚本以获取最新消息。我想让它成为实时的,每当有人给我发消息时,我立即得到它。我该怎么办呢?任何帮助/建议都非常感谢。

<?php
ini_set('display_errors', 1);
require_once('twitterapiexchange.php'); 
require_once("twitteroauth.php");
$settings = array( 
    'oauth_access_token' => "*********",
    'oauth_access_token_secret' => "*********",
    'consumer_key' => "*********",
    'consumer_secret' => "*********");
$url = 'https://api.twitter.com/1.1/direct_messages.json';
$getfield = '?since_id=240136858829479935&count=1';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$string = json_decode($twitter->setGetfield($getfield)
                      ->buildOauth($url, $requestMethod)
                      ->performRequest(),$assoc = TRUE);
foreach($string as $items)
{
    $url = 'https://api.twitter.com/1.1/direct_messages/show.json?';
    $requestMethod = 'GET';
    $getfields = array('id' => $items['id']);
    $twitter = new TwitterAPIExchange($settings);           
    $do = $twitter->setGetfield($getfield)
        ->buildOauth($url, $requestMethod)                         
        ->performRequest();
    echo "<strong>Teet:</strong> ".$items['text']."<br />";
    $senderId = $items['sender_id'];
    $messageText = $items['text'];
    $timeStamp = $items['created_at'];
    $recipentId = $items['recipient_id'];
    $messageId = $items['id'];
    $screenname=$items['sender_screen_name'];
    if(!empty($messageText)) {
        // $data = file_get_contents('https://fb.craftsilicon.com/testphpbot/core.php??username=".$senderId."&tweetid=".$messageId."&tweettext=".$messageText."&tweettime="$timeStamp."&source=facebook&receiver=".$recipentId."');
        $json = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452');
        $obj = json_decode($json);
        //var_dump($obj->results[0]->formatted_address);
        $addr = $obj->results[0]->formatted_address;
        $answer = "You said ".$messageText . " " .$addr;
        echo "<strong>Answer:</strong> ".$answer."<br />";
        $api_key='*********' ;
        $api_secret= '*********' ;
        $access_token = '*********';
        $access_token_key='*********' ;
        $connection = new TwitterOAuth($api_key,$api_secret, $access_token, $access_token_key);
        $connection->post('direct_messages/new', array('user_id' => $senderId, 'text' => $messageText));
    }
    //var_dump(json_encode($items, true));
}?>

1 个答案:

答案 0 :(得分:1)

您需要使用流媒体API并保持与user stream的持续连接,然后过滤掉来自回复的直接消息。