I have been able to build a twitter bot that receives and replies back to direct messages. But then there is this problem. I have the php script(bot script) that receives messages from twitter and replies back accordingly. Now, here is the problem- I am using cloud9 for hosting my script. When a user sends a direct message to my bot(php script), it doesnt reply until I refresh the bot script and thats when it replies back. I have used the same logic for my facebook bot and things seem to work just fine but I dont seem to make it work in twitter. How can I fix this issue? I would want my bot to be more real time and should be able to reply back to messages without having to refresh the script. Please help me out.
This is what I tried so far-
<?php
ini_set('display_errors', 1);
require_once('twitterapiexchange.php');
require_once("twitteroauth.php");
$settings = array(
'oauth_access_token' => "XXXXXXXXXXXX",
'oauth_access_token_secret' => "XXXXXXXXXXXX",
'consumer_key' => "XXXXXXXXXXXX",
'consumer_secret' => "XXXXXXXXXXXX");
$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)) {
$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='XXXXXXXXXXXX' ;
$api_secret= 'XXXXXXXXXXXX' ;
$access_token = 'XXXXXXXXXXXX';
$access_token_key='XXXXXXXXXXXX' ;
$connection = new TwitterOAuth($api_key,$api_secret, $access_token, $access_token_key);
$connection->post('direct_messages/new', array('user_id' => $senderId, 'text' => $answer));
}
//var_dump(json_encode($items, true));
}
**- My bot has to be done in php and will be hosted in a Windows platform. Thanks-- Any help/suggestions is highly appreciated.