I am working on a Slack slash command in PHP that takes a Twitter username and returns that person's latest tweet.
I can't figure out how to display the user's profile image to make it look as nice as Slack's Twitter integration.
The issue it seems to me is that I have to include 'unfurl_media: true' in JSON that gets sent back to Slack. That means I can't just use echo to print out the Twitter data I want, which is in an associative array.
I tried grabbing the Twitter data I want from the associative array, encoding it again in JSON and then printing that. But all that does is print the JSON as plain text. I checked a JSON validator and it says what gets printed to Slack is valid JSON, so I don't understand why slack isn't converting it to a styled message.
Any suggestions?
Here's the code. It's frankencode pulled from a bunch of different places that I am trying to bend to my will.
<?php
require_once('TwitterAPIExchange.php');
$command = $_POST['command'];
$text = $_POST['text'];
$token = $_POST['token'];
if($token != '[insert your Slack slash command token here]'){
$msg = ":squirrel: The token for the slash command doesn't match. We're done here until IT fixes it. Don't worry, Squirrelock is on the case.";
die($msg);
echo $msg;
}
$settings = array(
'oauth_access_token' => "[insert access token here]",
'oauth_access_token_secret' => "[insert access token secret here]",
'consumer_key' => "[insert consumer key here]",
'consumer_secret' => "[insert consumer secret here]"
);
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$requestMethod = "GET";
$getfield = '?screen_name='.$text.'&count=1';
$twitter = new TwitterAPIExchange($settings);
$string = json_decode($twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(), $assoc = TRUE);
foreach($string as $items)
{
$reply = "".$items['user']['profile_image_url']." *".$items['user'] ['name']."* ".$items['user']['screen_name']. "\n ".$items['text']."\n ".$items['created_at']."";
}
$data = json_encode(array(
"response_type" => "in_channel",
"text" => $reply,
"unfurl_media" => true,
"unfurl_links" => true
));
echo $data;
?>
Moving my comment down to an answer, since it seems to have fixed the problem:
Add header('Content-Type: application/json'); before echo $data;. The issue is that Slack is interpreting your response as text. It will interpret it as JSON only if the Content-Type is correct.
So what I'm doing is using the Twitter RestAPI to get the picture of a user and just be able to display the image on a local page. I've figured out the way to grab the URL of the image and this is what I have so far:
$url = $result->profile_image_url;
This holds the url of the profile picture of the user. Now how do I use this url to display it on the page? I know HTML allows us to do something like :
<img src = "some url">
And it will display the picture on the web page. I've looked around the internet for a while now, and still haven't figured it out. I've run into the same suggestion of the following :
<img src = "<?php echo ($url); ?>"/>
But I keep getting a parse error when I attempt loading the page. I would really appreciate if someone could guide me/help me figure out what's going on. Clearly, I'm doing something wrong which is why the PHP interpreter is not able to parse the code. Thanks!
Here is my whole code (if that helps):
<html>
<body>
<?php
require_once('TwitterAPIExchange.php');
$settings = array(
'oauth_access_token' => "N/A",
'oauth_access_token_secret' => "N/A",
'consumer_key' => "N/A",
'consumer_secret' => "N/A"
);
$url = 'https://api.twitter.com/1.1/users/show.json';
$getfield = '?screen_name=kobebryant';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$json = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
$result = json_decode($json);
$url = $result->profile_image_url;
<img src = "<?php echo ($url);?>"/> //This is the line giving me an error
?>
</body>
</html>
You closed the php tag too late. That is why it is recommended to split php from html. Try this code below:
<?php
require_once('TwitterAPIExchange.php');
$settings = array(
'oauth_access_token' => 'N/A',
'oauth_access_token_secret' => 'N/A',
'consumer_key' => 'N/A',
'consumer_secret' => 'N/A'
);
$url = 'https://api.twitter.com/1.1/users/show.json';
$getfield = '?screen_name=kobebryant';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$json = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
$result = json_decode($json);
$url = $result->profile_image_url;
?>
<html>
<head></head>
<body>
<img src="<?php echo ($url);?>"/> //This is the line giving me an error
</body>
</html>
Hint: if you've just a string without variables use ' instead of " because php tries to parse content between " and this is waste of CPU power.
So I'm making a Twitter fetch website where all the tweets from a specific hashtag will be fetched in real-time with ajax. It all works fine, I thought, until it all suddenly stops working. If I then wait for 3 minutes or so, it then starts working again. PHP is giving me errors such as
Notice: Trying to get property of non-object...
The code I'm running:
require_once '../lib/TwitterAPIExchange.php';
$settings = array(
'oauth_access_token' => "...",
'oauth_access_token_secret' => "...",
'consumer_key' => "...",
'consumer_secret' => "..."
);
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$getfield = '?q=#hashtag&result_type=recent';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$response = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
foreach(json_decode($response) as $result){
foreach($result as $post){
echo '<div class="post"><div class="header"><img src="'.$post->user->profile_image_url.'"><p class="user">'.$post->user->name.'</p></div><div class="text">'.$post->text.'</div></div>';
}
break;
}
I figured it out with help from #Uwe Allner. It turned out the Twitter API has something called API Rate Limits. So, as you may guess, they are limiting the amount of requests per x time. Under "Search", I noticed they have set a limit at 180 queries per 15 minutes. So I can make a query each 5 seconds.
180/15 = 12
60/12 = 5
I am using the Twitter Search API 1.1 to search followers_count
I have managed to get the Oauth working with the help of James Mallison at http://github.com/j7mbo/twitter-api-php.
Here my code :
require_once('TwitterAPIExchange.php');
$settings = array(
'oauth_access_token' => "xxx",
'oauth_access_token_secret' => "yyy",
'consumer_key' => "zzz",
'consumer_secret' => "vvv"
);
$url = 'https://api.twitter.com/1.1/users/lookup.json';
$getfield = '?screen_name=twitterapi';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
$response = json_decode($twitter, true);
$ed = $response->followers_count;
Here the answer :
[{"id":6253282,"id_str":"6253282","name":"Twitter API","screen_name":"twitterapi","location":"San Francisco, CA","description":"The Real Twitter API. I tweet about API changes, service issues and happily answer questions about Twitter and our API. Don't get an answer? It's on my website.","url":"http:\/\/t.co\/78pYTvWfJd","entities":{"url":{"urls":[{"url":"http:\/\/t.co\/78pYTvWfJd","expanded_url":"http:\/\/dev.twitter.com","display_url":"dev.twitter.com","indices":[0,22]}]},"description":{"urls":[]}},"protected":false,"followers_count":3402865,"friends_count":48,"listed_count":12958,"created_at":"Wed May 23 06:01:13 +0000 2007","favourites_count":27,"utc_offset":-25200,"time_zone":"Pacific Time (US & Canada)","geo_enabled":true,"verified":true,"statuses_count":3535,"lang":"en","status":{"created_at":"Thu May 21 21:12:42 +0000 2015","id":601495856353783808,"id_str":"601495856353783808","text":"RT #TwitterDev: We are excited to announce that the REST API now supports native video upload. https:\/\/t.co\/cWUrgjh8wz http:\/\/t.co\/yaenTQE9\u2026","source":"\u003ca href=\"http:\/\/twitter.com\" rel=\"nofollow\"\u003eTwitter Web Client\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"geo":null,"coordinates":null,"place":null,"contributors":null,"retweeted_status":{"created_at":"Thu May 21 20:57:40 +0000 2015","id":601492072953151488,"id_str":"601492072953151488","text":"We are excited to announce that the REST API now supports native video upload. https:\/\/t.co\/cWUrgjh8wz http:\/\/t.co\/yaenTQE95N","source":"\u003ca href=\"http:\/\/jonbulava.com\" rel=\"nofollow\"\u003eJon's Developer Testing App\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"geo":null,"coordinates":null,"place":null,"contributors":null,"retweet_count":160,"favorite_count":189,"entities":{"hashtags":[],"symbols":[],"user_mentions":[],"urls":[{"url":"https:\/\/t.co\/cWUrgjh8wz","expanded_url":"https:\/\/blog.twitter.com\/2015\/rest-api-now-supports-native-video-upload","display_url":"blog.twitter.com\/2015\/rest-api-\u2026","indices":[79,102]}],"media":[{"id":601491637433475073,"id_str":"601491637433475073","indices":[103,125],"media_url":"http:\/\/pbs.twimg.com\/ext_tw_video_thumb\/601491637433475073\/pu\/img\/XJcHkzdOR2YRMQSC.jpg","media_url_https":"https:\/\/pbs.twimg.com\/ext_tw_video_thumb\/601491637433475073\/pu\/img\/XJcHkzdOR2YRMQSC.jpg","url":"http:\/\/t.co\/yaenTQE95N","display_url":"pic.twitter.com\/yaenTQE95N","expanded_url":"http:\/\/twitter.com\/TwitterDev\/status\/601492072953151488\/video\/1","type":"photo","sizes":{"thumb":{"w":150,"h":150,"resize":"crop"},"small":{"w":340,"h":191,"resize":"fit"},"large":{"w":640,"h":360,"resize":"fit"},"medium":{"w":600,"h":337,"resize":"fit"}}}]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"lang":"en"},"retweet_count":160,"favorite_count":0,"entities":{"hashtags":[],"symbols":[],"user_mentions":[{"screen_name":"TwitterDev","name":"TwitterDev","id":2244994945,"id_str":"2244994945","indices":[3,14]}],"urls":[{"url":"https:\/\/t.co\/cWUrgjh8wz","expanded_url":"https:\/\/blog.twitter.com\/2015\/rest-api-now-supports-native-video-upload","display_url":"blog.twitter.com\/2015\/rest-api-\u2026","indices":[95,118]}],"media":[{"id":601491637433475073,"id_str":"601491637433475073","indices":[119,140],"media_url":"http:\/\/pbs.twimg.com\/ext_tw_video_thumb\/601491637433475073\/pu\/img\/XJcHkzdOR2YRMQSC.jpg","media_url_https":"https:\/\/pbs.twimg.com\/ext_tw_video_thumb\/601491637433475073\/pu\/img\/XJcHkzdOR2YRMQSC.jpg","url":"http:\/\/t.co\/yaenTQE95N","display_url":"pic.twitter.com\/yaenTQE95N","expanded_url":"http:\/\/twitter.com\/TwitterDev\/status\/601492072953151488\/video\/1","type":"photo","sizes":{"thumb":{"w":150,"h":150,"resize":"crop"},"small":{"w":340,"h":191,"resize":"fit"},"large":{"w":640,"h":360,"resize":"fit"},"medium":{"w":600,"h":337,"resize":"fit"}},"source_status_id":601492072953151488,"source_status_id_str":"601492072953151488","source_user_id":2244994945,"source_user_id_str":"2244994945"}]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"lang":"en"},"contributors_enabled":false,"is_translator":false,"is_translation_enabled":false,"profile_background_color":"C0DEED","profile_background_image_url":"http:\/\/pbs.twimg.com\/profile_background_images\/656927849\/miyt9dpjz77sc0w3d4vj.png","profile_background_image_url_https":"https:\/\/pbs.twimg.com\/profile_background_images\/656927849\/miyt9dpjz77sc0w3d4vj.png","profile_background_tile":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/2284174872\/7df3h38zabcvjylnyfe3_normal.png","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/2284174872\/7df3h38zabcvjylnyfe3_normal.png","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/6253282\/1431474710","profile_link_color":"0084B4","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"default_profile":false,"default_profile_image":false,"following":false,"follow_request_sent":false,"notifications":false}]
Warning: json_decode() expects parameter 1 to be string, object given in ...
I don't kwnow why i can't use json_decode
Any feedback or ideas on how to reach followers_count correctly would be much appreciated.
Cheers
What you need to do is:
$jsonResponse = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
$data = json_decode($jsonResponse, true);
$ed = $data[0]['followers_count'];
Here json_decode documentation.