Slack is printing raw JSON instead of styled message - php

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.

Related

file_get_contents() always returns bool(false) while URL returns a value during recapctha V2 upgrade in PHP

I am currently updating recaptchalib.php to upgrade captcha from V1 to V2.
I have done the client integration successfully. But at the server side facing issues. In my below code snippet if I hit the URL directly in browser I either get
"success" : false with "error-codes" as "timeout-or-duplicate" OR
"success" :true but in both the above cases file_get_contents() returns the value as bool(false). Ultimately, always I get the error as "reCaptcha not enetered correctly" .Please suggest why file_get_content() is always returning bool(false)? What correction can be done in code so that we get response in correct format and then do json_decode successfully i.e hit 'true' case .
Below is the code snippet
$postdata = http_build_query(
array(
'secret' => $privkey,
'response' => $response,
'remoteip' => $remoteip
)
);
$url = 'https://www.google.com/recaptcha/api/siteverify?'.$postdata;
print "URL is " . $url . "<br>";
$response = file_get_contents($url);
var_dump($response) ;
$responses = json_decode($response, true);
if($responses["success"] === TRUE){
echo "true";
}else{
echo "false";
}
For file_get_contents() to work, the URL that is passed must not conatin any special characters. To obtain the sanitized version of the URL, use urlencode() as mentioned here. Looks like your URL might have special characters (private key etc.).
Try this:
$url = 'https://www.google.com/recaptcha/api/siteverify?'.$postdata;
$url = urlencode($url);
$response = file_get_contents($url);

How to execute URL in codeigniter?

I want to send the SMS to the user using the third party API key in codeigniter. For that I used the file_get_content() But when file runs it takes the more execution time and after display blank page.
I also use CURL but same error in codeignator.
This code runs another PHP script only error in codeigniter
Following my code:
$to = "thisisprashantkumbhar";
$username ='puretechnology';
$numbers = '9326447272';
$messagenew=rawurlencode($to);
$apikey = 'gdfgrte5-er54-h57f-4rgt-0a7215d15abc';
$url = "http://sms1.businesslead.co.in/sendSMS?username=$username&message=$messagenew&sendername=CMISAM&smstype=TRANS&numbers=$numbers&apikey=$apikey";
$response = file_get_contents($url);
return $response;
$stream_options = array(
'http' => array(
'method' => 'GET',
),
);
$context = stream_context_create($stream_options);
$response = file_get_contents("http://api.smsbrain.in/1.2/appsms/send.php?user=username&passwd=141414&senderId=SATISH&recipients=9723613143&message=Hello", null, $context);
echo json_encode($response);
echo $url and it will show you the complete url then execute url you will get the error. e.g invalid key check your details as well.

How do you decode the tweets.json string returned from a twitter search API request?

How do you decode the tweets.json string returned from a twitter search API request?
I have looked through answers to similar questions. Those answers do show how to make a call, and how to display the data returned, but those don't deal with the issue of dealing with the structure of the data that is returned from the tweets.json API call.
Here's the code - it uses the twitter API. It requests search results.
<?php
require_once('../TwitterAPIExchange.php');
$settings = array(
'oauth_access_token' => "......",
'oauth_access_token_secret' => "......",
'consumer_key' => "......",
'consumer_secret' => "......"
);
$requestMethod = 'GET';
//$url = "https://api.twitter.com/1.1/statuses/user_timeline.json"; // I can decode output from this
//$getfield = "?screen_name=J7mbo&count=5"; // I can decode output from this
$url = "https://api.twitter.com/1.1/search/tweets.json"; // I can NOT decode output from this
$getfield = "?q=%23J7mbo&result_type=recent"; // I can NOT decode output from this
$twitter = new TwitterAPIExchange($settings);
$string = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(); // from stackOverflow
$string = json_decode($string, $assoc = TRUE); // seems i cannot use json_decode for output from tweets.json
if ($string["errors"][0]["message"] != "")
{
echo "twitter error message:" . $string[errors][0]["message"];
exit();
}
foreach ($string as $items)
{
echo "tweet text =[". $items['text']."]<br />";
}
?>
If I was using a twitter API timeline call, I could use json_decode and access $items['text'] for each of the returned tweets
But I want to use the twitter API search call (tweets.json). json_decode does not properly decode the data from this search call, it only returns two empty $items['text']
So what's the best way to decode the tweets.json string returned from a twitter API request?
You need to iterate through the $items array and get the text property off of there.
foreach ($items as $item) {
echo "tweet text =[". $item['text']."]<br />";
}
After examining the data I noticed that is consisted of two JSON encoded strings, named statuses and search_metadata. I extracted the statuses string and was able to decode it using json_decode.

Posting to Tumblr with php & Tumblr API

I am trying to post messages automatically to my Tumblr Blog (which will run daily via Cron)
I am using the Official Tumblr PHP library here:
https://github.com/tumblr/tumblr.php
And using the Authentication method detailed here :
https://github.com/tumblr/tumblr.php/wiki/Authentication
(or parts of this, as I don't need user input!)
I have the below code
require_once('vendor/autoload.php');
// some variables that will be pretttty useful
$consumerKey = 'MY-CONSUMER-KEY';
$consumerSecret = 'MY-CONSUMER-SECRET';
$client = new Tumblr\API\Client($consumerKey, $consumerSecret);
$requestHandler = $client->getRequestHandler();
$blogName = 'MY-BLOG-NAME';
$requestHandler->setBaseUrl('https://www.tumblr.com/');
// start the old gal up
$resp = $requestHandler->request('POST', 'oauth/request_token', array());
// get the oauth_token
$out = $result = $resp->body;
$data = array();
parse_str($out, $data);
// set the token
$client->setToken($data['oauth_token'], $data['oauth_token_secret']);
// change the baseURL so that we can use the desired Methods
$client->getRequestHandler()->setBaseUrl('http://api.tumblr.com');
// build the $postData into an array
$postData = array('title' => 'test title', 'body' => 'test body');
// call the creatPost function to post the $postData
$client->createPost($blogName, $postData);
However, this gives me the following error:
Fatal error: Uncaught Tumblr\API\RequestException: [401]: Not
Authorized thrown in
/home///*/vendor/tumblr/tumblr/lib/Tumblr/API/Client.php
on line 426
I can retrieve blog posts and other data fine with (example):
echo '<pre>';
print_r( $client->getBlogPosts($blogName, $options = null) );
echo '</pre>';
So it seems it is just making a post that I cant manage.
In all honesty, I don't really understand the OAuth Authentication, so am using code that more worthy coders have kindly provided free :-)
I assume I am OK to have edited out parts of the https://github.com/tumblr/tumblr.php/wiki/Authentication as I don't need user input as this is just going to be code ran directly from my server (via Cron)
I have spent days looking around the internet for some answers (have gotten a little further), but am totally stuck on this one...
Any advice is much appreciated!
It looks like the parts that you removed in the code pertained to a portion of the OAuth process that was necessary for the desired action.
// exchange the verifier for the keys
You might try running the Authentication Example itself and removing the parts of the code that you've removed until it no longer works. This will narrow down what's causing the issue. I'm not very familiar with OAuth personally, but this looks as though it would be apart of the problem as one of the main portions you took out was surrounding the OAuth process exchanging the verifier for the OAuth keys.
function upload_content(){
// Authorization info
$tumblr_email = 'email-address#host.com';
$tumblr_password = 'secret';
// Data for new record
$post_type = 'text';
$post_title = 'Host';
$post_body = 'This is the body of the host.';
// Prepare POST request
$request_data = http_build_query(
array(
'email' => $tumblr_email,
'password' => $tumblr_password,
'type' => $post_type,
'title' => $post_title,
'body' => $post_body,
'generator' => 'API example'
)
);
// Send the POST request (with cURL)
$c = curl_init('api.tumblr.com/v2/blog/gurjotsinghmaan.tumblr.com/post');
//api.tumblr.com/v2/blog/{base-hostname}/post
//http://www.tumblr.com/api/write
//http://api.tumblr.com/v2/blog/{base-hostname}/posts/text?api_key={}
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $request_data);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($c);
$status = curl_getinfo($c, CURLINFO_HTTP_CODE);
curl_close($c);
// Check for success
if ($status == 201) {
echo "Success! The new post ID is $result.\n";
} else if ($status == 403) {
echo 'Bad email or password';
} else {
echo "Error: $result\n";
}
}
https://howtodofor.com/how-to-delete-tumblr-account/

JSON full circle (PHP)

I've reduced to the simplest form, and am still stumbling...I've spent more than 30 hours researching and testing. According to all of the posts which never show more than 15° of the entire circle, this is supposed to be really easy.
I want to:
Send query parameters (in JSON) from an Android Phone to a WAMP server...This may be as much as a complete dump of a local SQLite table, so query strings just won't cut it.
Have the WAMP server read the JSON data, formulate a SQL query and submit to the mySQL database
Package a response as JSON data (from a simple "OK" to a full table dump)
Return the response package to the Android phone
This is already a fully functional WAMP application, and I want to integrate Android access. For this reason, I really want to avoid AJAX, since I want to maintain consistency with what's already in place.
I've reduced this to the simplest loop and am hitting snags. I'm using send.php to post some JSON data to receive.php. At this point, I just need receive.php to read the data and send it back (slightly modified) to send.php
send.php is properly reading stock JSON sent from receive.php. I just can't get any sign of life that receive.php even recognizes the JSON sent to it.
PLEASE don't direct me towards cURL...from everything I've found regarding Android and JSON, cURL is a tangent which will send me full circle back into nonfunctionality.
APACHE 2.2.22, PHP 5.4.3
Like I said, I've reduced this to the simplest form to demonstrate a full circle...
send.php:
<?php
$url = "http://192.168.0.102:808/networks/json/receive.php";
$data = array(
'param1' => '12345',
'param2' => 'fghij'
);
$json_data = json_encode($data);
$options = array(
'http' => array(
'method' => 'POST',
'content' => $json_data,
'header'=> "Content-Type: application/json\r\n" .
"Accept: application/json\r\n" .
'Content-Length: ' . strlen($json_data) . "\r\n"
)
);
$context = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result , true);
echo '[' . $response['param1'] . "]\n<br>";
//THIS WORKS! send.php displays "Initialized"
?>
receive.php
<?php
$newparam = 'Initialized';
//HERE I NEED TO read the JSON data and do something
$data = array(
'param1' => $newparam,
'param2' => 'pqrst'
);
header('Content-type: application/json');
echo json_encode($data);
?>
It is actually easy, as stated in all the incomplete explanations...I got the full circle to work finally
I've chosen simplicity to prove I could travel full circle, and I have now done so.
send.php
<?php
//The URL of the page that will:
// 1. Receive the incoming data
// 2. Decode the data and do something with it
// 3. Package the results into JSON
// 4. Return the JSON to the originator
$url = "http://192.168.0.102:808/networks/json/receive.php";
//The JSON data to send to the page (above)
$data = array(
'param1' => 'abcde',
'param2' => 'fghij'
);
$json_data = json_encode($data);
//Prep the request to send to the web site
$options = array(
'http' => array(
'method' => 'POST',
'content' => $json_data,
'header'=> "Content-Type: application/json\r\n" .
"Accept: application/json\r\n"
)
);
$context = stream_context_create( $options );
//Make the request and grab the results
$result = file_get_contents( $url, false, $context );
//Decode the results
$response = json_decode( $result , true);
//Do something with the results
echo '[' . $response['param1'] . "]\n<br>";
?>
receive.php
<?php
//K.I.S.S. - Retrieve the incoming JSON data, decode it and send one value
//back to send.php
//Grab the incoming JSON data (want error correction)
//THIS IS THE PART I WAS MISSING
$data_from_send_php = file_get_contents('php://input');
//Decode the JSON data
$json_data = json_decode($data_from_send_php, true);
//CAN DO: read querystrings (can be used for user auth, specifying the
//requestor's intents, etc)
//Retrieve a nugget from the JSON so it can be sent back to send.php
$newparam = $json_data["param2"];
//Prep the JSON to send back
$data = array(
'param1' => $newparam,
'param2' => 'pqrst'
);
//Tell send.php what kind of data it is receiving
header('Content-type: application/json');
//Give send.php the JSON data
echo json_encode($data);
?>
AND Android integration...called with a Button.onClickListener
public void getServerData() throws JSONException, ClientProtocolException, IOException {
//Not critical, but part of my need...Preferences store the pieces to manage JSON
//connections
Context context = getApplicationContext();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String netURL = prefs.getString("NetworkURL", "");
// "http://192.168.0.102:808/networks/json"
String dataPage = prefs.getString("DataPage", "");
// "/receive.php"
//NEEDED - the URL to send to/receive from...
String theURL = new String(netURL + dataPage);
//Create JSON data to send to the server
JSONObject json = new JSONObject();
json.put("param1",Settings.System.getString(getContentResolver(),Settings.System.ANDROID_ID));
json.put("param2","Android Data");
//Prepare to commnucate with the server
DefaultHttpClient httpClient = new DefaultHttpClient();
ResponseHandler <String> resonseHandler = new BasicResponseHandler();
HttpPost postMethod = new HttpPost(theURL);
//Attach the JSON Data
postMethod.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
//Send and Receive
String response = httpClient.execute(postMethod,resonseHandler);
//Begin reading and working with the returned data
JSONObject obj = new JSONObject(response);
TextView tv_param1 = (TextView) findViewById(R.id.tv_json_1);
tv_param1.setText(obj.getString("param1"));
TextView tv_param2 = (TextView) findViewById(R.id.tv_json_2);
tv_param2.setText(obj.getString("param2"));
}

Categories