How to decode twitter JSON when adding a new Tweet? - php

I hope that you can help me with this one. Basically what I am doing, is adding tweets to my twitter account through api from my website administration panel.
It all works fine, BUT I cannot store the info to database because the json_decode variable that I have returns a NULL. I do not understand what is the appropriate way to get the info from twitter json.
Here is my code:
$settings = array(
'oauth_access_token' => $oauth_access_token,
'oauth_access_token_secret' => $oauth_access_token_secret,
'consumer_key' => $consumer_key,
'consumer_secret' => $consumer_secret
);
$connection = new TwitterAPIExchange($settings);
$url = 'https://api.twitter.com/1.1/statuses/update.json';
$requestMethod = "POST";
$user = $twitter_user;
$postfields = array(
'screen_name' => $user,
'status' => $twit );
$connection->buildOauth($url, $requestMethod)
->setPostfields($postfields)
->performRequest();
// get the contents of the JSON file
$jsonCont = file_get_contents($connection);
//decode JSON data to PHP array
$content = json_decode($jsonCont, true);
$conn = new mysqli($server, $username, $password, $database);
$id = $content['id'];
$created = $content['created_at'];
$tweet = $content['text'];
$by = $content['user']['name'];
$sql = "INSERT INTO `twitter` (`idtwit`, `tweet`, `tweetedby`, `datet`) VALUES ('".$id."', '".$tweet."', '".$by."', '".$created."')";
$conn->query($sql);
echo "<br /><div class='alert alert-info'>New record updated successfully</div>";
$conn->close();
How to use json_decode properly with this ?!
I have also tried to wrap it around the $connection request like so, eliminating my variable, but then, it will not post to twitter anymore.
$connection->json_decode(buildOauth($url, $requestMethod)
->setPostfields($postfields)
->performRequest(),$assoc = TRUE);

Related

Php Twitter Post tweet with media

With this code, I can upload image and print Media ID but I can't post a tweet with image. Could you help me?
Thanks
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
set_include_path('/home/.....');
require_once('TwitterAPIExchange.php');
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'oauth_access_token' => "...",
'oauth_access_token_secret' => "...",
'consumer_key' => "...",
'consumer_secret' => "..."
);
$twitter = new TwitterAPIExchange($settings);
$file = file_get_contents('aaa.jpg');
$data = base64_encode($file);
// Upload image to twitter
$url = "https://upload.twitter.com/1.1/media/upload.json";
$method = "POST";
$params = array(
"media_data" => $data,
);
$json = $twitter
->buildOauth($url, $method)
->setPostfields($params)
->performRequest();
// Result is a json string
$res = json_decode($json);
// Extract media id
$id = $res->media_id_string;
print_r($id);
////// Code is working to this line and can print media id like 213213214123123
$url = "https://api.twitter.com/1.1/statuses/update.json";
$twitter = new TwitterAPIExchange($settings);
$requestMethod = 'POST';
$response = $twitter->setPostfields(
array('status' => '', 'media_ids' => $id)
)
->buildOauth($url, $requestMethod)
->performRequest();
The media_id value can be used to create a Tweet with an attached photo using the statuses/update endpoint. Use your media_id as a parameter in the Statuses/update

PHP error empty response

The php code below should work however, I receive an error, empty response, from my server. Ive tried shutting down firewall but no luck. Can you please help me I have been trying different methods for ages I have no idea whats wrongs. Thank you.
<?php
require_once('TwitterAPIExchange.php');
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'oauth_access_token' => "",
'oauth_access_token_secret' => "",
'consumer_key' => "",
'consumer_secret' => ""
);
$url = "https://api.twitter.com/1.1/search/tweets.json";
$requestMethod = "GET";
$getfield = '?q=cloud%20computing&count=5&result_type=popular';
$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
?>
you need to use json_decode : http://php.net/manual/en/function.json-decode.php
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once('TwitterAPIExchange.php');
$settings = array(
'oauth_access_token' => "xxx",
'oauth_access_token_secret' => "xxx",
'consumer_key' => "xxx",
'consumer_secret' => "xxx"
);
$url = "https://api.twitter.com/1.1/search/tweets.json";
$requestMethod = "GET";
$getfield = '?q=cloud%20computing&count=5&result_type=popular';
$twitter = new TwitterAPIExchange($settings);
$response = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
$string = json_decode($response, true); // there you handle twitter response
print_r($string); // here is the echo'd result, not needed after
// from here, you have access to the data
// then, a foreach loop will give you access to whatever you want to echo
foreach($string['statuses'] as $tweets) {
$tweet = $tweets['text'];
echo "<p>Tweet: $tweet </p>";
}
?>
updated with the loop example

Retrieving direct messages from twitter using PHP?

I am trying to retrieve direct messages sent to my account real time. But the way, my script is working is that when someone sends me a message, I have to refresh the script to get the latest message. I would like to make it real time such that whenever someone sends me a message, I get it instantly. How do I go about it? Any help/suggestions is highly appreciated.
<?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));
}?>
You'd need to use the streaming API and maintain a continuous connection to a user stream, then filter out direct messages from the responses.

Twitter bot issues with real time direct message streaming Php?

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.

var_dump(tweet->id); gives int(198231293) int(123981623) how to i retrieve one and store it on a variable?

So i am trying to get that tweet id of a retweeted id and since twitter recently allows you to retweet your own tweet, when i try to get the retweeted tweet's id of my own tweet, it gives me two variables when i use var_dump i want only one of it how do i extract?
i used
var_dump(tweet->id);
in the code and when i execute it, it shows like int(12381239) int(29384121)
i want to take the first int variable that is 12381239 and store it in a variable, i tried all i can but failed can anyone help me?
UPDATE : Here is the code
<?php
require_once('TwitterAPIExchange.php');
$settings = array(
'oauth_access_token' => "xxxxxx-asdsaldjasd",
'oauth_access_token_secret' => "xxxxxx",
'consumer_key' => "xxxxxxx",
'consumer_secret' => "xxxxxxxxxx"
);
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$requestMethod = "GET";
$getfield = '?screen_name=username';
$twitter = new TwitterAPIExchange($settings);
$response = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
$tweets = json_decode($response);
foreach($tweets as $tweet)
{
if ($tweet->retweeted) // here is the part where i did var_dump
{
$url = "https://api.twitter.com/1.1/statuses/destroy/$tweet->id.json";
$requestMethod = 'POST';
$postfields = array(
'id' => '$tweet->id'
);
$twitter = new TwitterAPIExchange($settings);
$response = $twitter->buildOauth($url, $requestMethod)
->setPostfields($postfields)
->performRequest();
$response;
}
}
what i'm trying to do is undo the retweets, which was working fine until twitter let the accs rt themselves.

Categories