slack: Delete all messages with php - php

I'm trying to delete all message of a slack channel
i tried to add the required scopes to the app but this two scopes aren't available
chat:write:user
chat:write:bot
i tried with the bot and the user token after reinstall the workspace
the function getAllMessagesFromChannel() i wrote works and i get all the timestamps correctly
public function clearChannel()
{
$jsonData = $this->getAllMessagesFromChannel();
foreach ($jsonData->messages as $message) {
$this->deleteMessage($message->ts);
}
}
private function deleteMessage($ts)
{
$data = json_encode(array("channel" => $this->channel, "ts" => $ts));
$ch = curl_init("https://slack.com/api/chat.delete");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8', "Authorization: Bearer " . $this->token));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo $result . "\n";
curl_close($ch);
}
i get this error for every message:
{"ok":false,"error":"cant_delete_message"}
enter image description here
any idea how to fix this?

Related

Issuing with making a post request with php curl

I'm trying to make a post request with php using curl however the json is not getting delivered to the REST API. Here is my code. In the webservice all I get is null value. I'm not sure where I'm going wrong.
$email_json_data = json_encode($email_data);
$header[] = "Content-type: application/json";
$ch = curl_init($api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $email_json_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
return $response;
Webservice code:
$email_json_data = $this->post('email_json_data');
$email_data = json_decode($email_json_data);
Check PHP: curl_errno
There's probably a problem connecting to the server, and it's probably in one of your $header. To find out more, you need to show (in production, LOG it) the curl error.
In the future, please try to include a complete code sample, rather than just snippets
Code added from PHP: curl_strerror
class CurlAdapter
{
private $api_url = 'www.somewhere.com/api/server.php';
private $error = "";
private function jsonPost($data)
{
// init curl
$ch = curl_init($this->api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl header
$header[] = "Content-type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
// build post data
$post_data = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
// execute
if (empty($response = curl_exec($ch)) {
// Check for errors and display the error message
if($errno = curl_errno($ch)) {
$error_message = curl_strerror($errno);
$this->error = "cURL error ({$errno}):\n {$error_message}";
// #todo log curl error
}
}
// Close the handle
curl_close($ch);
return $response;
}
public function post( mixed $data )
{
if (empty($this->jsonPost($data))) {
return $this->error;
}
return $response;
}
}
$ca = new CurlAdapter();
echo $ca->post(['data' => 'testdata']);
Figured out a way to make this work.
Replaced $email_json_data = $this->post('email_json_data');
with $email_json_data = file_get_contents("php://input");

Update Cell SmartSheet 2.0 with PHP Script

I have found this piece of code to update cell in SmartSheet website. But I I don't understand what are the values in the fields variable. Is anyone has the working example of PHP code to do this?
curl https://api.smartsheet.com/2.0/sheets/{sheetId}/rows?include=objectValue \
-H "Authorization: Bearer ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-X PUT \
-d '[{"id": "6572427401553796", "cells": [{"columnId": 7518312134403972,"objectValue": {"objectType": "PREDECESSOR_LIST","predecessors": [{"rowId": 567735454328708,"type": "FS","lag": {"objectType": "DURATION","days": 2,"hours": 4}}]}}]}]'
My current php code is as follow and I just want to update some value into the sheet.I don't know what to put in the field varaible. Thanks.
<?php
$baseURL = "https://api.smartsheet.com/2.0";
$getSheetURL = $baseURL. "/sheets/4925037959505xxx/rows?include=objectValue";
$accessToken = "34ouqtkxp0sutdv6tjbwtsxxxx";
$headers = array("Authorization: Bearer ". $accessToken , "Content-Type: application/json");
$fields='[????]';
$ch = curl_init($getSheetURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
$result = curl_exec($ch);
print_r($result);
?>
Thanks
This is a function I created to update a SmartSheet
$ssID: is the Smart Sheet ID
$ssRowID: is the Smart Sheet row id I
want to update
$values: is an array of column values
$columArray: is
an array of the column IDs
$config: is an array I use to hold all
auth information
Breaking down the Json Data which is the way you communicate which columns you want to update and the values
{"id": "'.$ssRowID.'",
"cells":
[
{"columnId": '.$columnArray['go'].',"value": "'.$values['go'].'"},
{"columnId": '.$columnArray['comments'].',"value": "'.$values['comment'].'"},
{"columnId": '.$columnArray['data center'].',"value": "'.$values['datacenter'].'"}
]
}
ID represents the row you want to update
ColumnID represents each column you want to update must provide the column ID and value represents the value you want to insert
{"columnId": 'your column id here',"value": 'your value here'}
function ssUpdate($ssID, $ssRowID, $values, $columnArray, $config){
/*
* update the Smart Sheet using the passed in sheet ID, Row ID and VALUES
*
*/
$sheetID = $ssID;
$SSAPIToken = $config['smartsheets']['SSAPIToken'];
$sheetsURL = "https://api.smartsheet.com/2.0/sheets/".$sheetID."/rows";
$data_json = '[{"id": "'.$ssRowID.'", "cells": [{"columnId": '.$columnArray['go'].',"value": "'.$values['go'].'"}, {"columnId": '.$columnArray['comments'].',"value": "'.$values['comment'].'"}, {"columnId": '.$columnArray['data center'].',"value": "'.$values['datacenter'].'"}]}]';
//echo $data_json."<br />";
// Create Headers Array for Curl
$headers = array(
"Authorization: Bearer " .$SSAPIToken,
'Content-Type: application/json',
'Content-Length: ' . strlen($data_json)
);
/*
* connect to SS and update Sheet
*/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$sheetsURL );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0);
curl_setopt($ch, CURLOPT_TIMEOUT, 400); //timeout in seconds
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
$data = curl_exec($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); //get status code
$curl_errno = curl_errno($ch);
$curl_error = curl_error($ch);
$information = curl_getinfo($ch);
curl_close($ch);
$ssArray = json_decode ($data, true); // make an XML object
/*
* did connection work
*/
if ($status_code != 200) {
echo "Oh No! Update Error: (". $ssArray['errorCode'] .") ". $ssArray['message'] ."\n";
} else {
//var_dump($ssArray);
if ($ssArray['resultCode'] == 0){
echo "Updated: ".$values['store'];
}else{
echo "Oh No! Update Error: (". $ssArray['errorCode'] .") ". $ssArray['message'] ."\n";
}
}
}
More details: http://smartsheet-platform.github.io/api-docs/#add-row-s
$fields is the JSON payload for the PUT request. Details are documented here: http://smartsheet-platform.github.io/api-docs/#update-row-s
I suggest you test using Postman or the Advanced Rest Client before you begin coding.
Also, include=objectValue only makes sense for a GET so there is no point including it for a PUT request.

Google Cloud Storage - Upload an 'Object' without using Google Client

I've been looking around for the past few days for an answer to this question, but I haven't been able to find the solution I'm after.
I have a fully working version of doing this task using Google_Client, however I want to be able to do this without using the Google_Client. I can create buckets without using it, but not Objects. I cannot understand the Google Documentation on this at all (it's pretty poor).
So, I have a function below which takes in several parameters to try and upload a file. I'm not sure what needs to go in $authheaders, $post_fields (the body of the post) or the url.
public function upload_file($bucket, $fileName, $file, $fileType) {
// Check if we have auth token
if(empty($this->authtoken)) {
echo "Please login to Google";
exit;
}
// Prepare authorization headers
$authheaders = array(
"Authorization: Bearer " . $this->authtoken
);
$postbody = array();
//Http call for creating a file
$response = $this->http_call(self::FILE_UPLOAD_URL.$bucket.'/o?uploadType=multipart&name='.$fileName, $postbody, $authheaders);
// Has the file been created successfully?
if($response->success=="1") {
return array('status' => 'success', 'errorcode' =>'', 'errormessage'=>"", 'id' => $response->job->id);
}
else {
return $response;
}
}
The http_call function:
public function http_call($url, $post_fields, $authheaders) {
// Make http call
$this->httpRequest->setUrl($url);
$this->httpRequest->setPostData(json_encode($post_fields));
$this->httpRequest->setHeaders($authheaders);
$this->httpRequest->send();
$response = json_decode($this->httpRequest->getResponse());
return $response;
}
Any help on this would be greatly appreciated.
If anyone else is looking to do this without using the API, here is how I solved my question using curl.
// Prepare authorization headers
$authheaders = array(
"Authorization: Bearer " . $this->authtoken,
"Content-Type: application/pdf"
);
$url = self::FILE_UPLOAD_URL.$bucket.'/o/?uploadType=multipart&name='.$fileName.'';
$curl = curl_init();
curl_setopt($curl, CURLOPT_POSTFIELDS, $file);
curl_setopt($curl, CURLOPT_HTTPHEADER, $authheaders);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_USERAGENT, "Goole Cloud Storage PHP Starter Application google-api-php-client/1.1.5");
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
// 1 is CURL_SSLVERSION_TLSv1, which is not always defined in PHP.
curl_setopt($curl, CURLOPT_SSLVERSION, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
$response = curl_exec($curl);

Airbnb Login Script through the command line using PHP

Is there a way to programmatically login to Airbnb with email/password through a CLI PHP script? and get a response back?
Thanks.
If you're looking to remotely log in to Airbnb and return information, you can use cURL to post data to Airbnb and return the results.
Examples on how to post form data can be found all over the web, however, a very reputable tutorial can be found here. Essentially, you want to cURL the login page, and include the login information with POST.
<?php
// A very simple PHP example that sends a HTTP POST to a remote site
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://www.airbnb.com/login");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"email=" . $email . "&password=" . $password);
// in real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('email' => $email, 'password' => $password)));
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
// further processing ....
if ($server_output == "OK") { ... } else { ... }
?>
Make sure you check out this answer on SO, as well as the tutorials here.
Yes, there is. Airbnb's API isn't open to the general public, but if you sniff the traffic from your phone, you can see what requests are being sent to which endpoints. I experimented a little bit with their API and it follows as such for logging in
<?php
class AirBnB {
// Define the properties
public $currency = 'USD';
public $language = 'en';
public $country = 'us';
public $network = 'AT&T';
public $apiKey = '915pw2pnf4h1aiguhph5gc5b2';
public $adId = '911EBF1C-7C1D-46D5-A925-2F49ED064C92';
public $deviceId = 'a382581f36f1635a78f3d688bf0f99d85ec7e21f';
public function SendRequest($endpoint, $token, $post, $data, $cookies) {
$headers = array(
'Host: api.airbnb.com',
'Accept: application/json',
'Accept-Language: en-us',
'Connection: keep-alive',
'Content-Type: application/json',
'Proxy-Connection: keep-alive',
'X-Airbnb-Carrier-Country: '.$this->country,
'X-Airbnb-Currency: '.$this->currency,
'X-Airbnb-Locale: '.$this->language,
'X-Airbnb-Carrier-Name: '.$this->network,
'X-Airbnb-Network-Type: wifi',
'X-Airbnb-API-Key: '.$this->apiKey,
'X-Airbnb-Device-ID: '.$this->deviceId,
'X-Airbnb-Advertising-ID: '.$this->adId,
);
// Add the new custom headers
if($token) {
$header = 'X-Airbnb-OAuth-Token: '.$token;
array_push($headers, $header);
}
// Add the query string
if(!$post && is_array($data)) {
$endpoint .= '?'.http_build_query($data);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.airbnb.com/'.$endpoint);
curl_setopt($ch, CURLOPT_USERAGENT, 'Airbnb/15.50 iPhone/9.2 Type/Phone');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
if($post) {
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
if($cookies) {
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
} else {
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
}
$response = curl_exec($ch);
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return array(
'http' => $http,
'response' => $response
);
}
public function Authorize($username, $password) {
$data = array(
'username' => $username,
'password' => $password,
'prevent_account_creation' => TRUE,
);
$data = $this->SendRequest('v1/authorize', FALSE, TRUE, $data, FALSE);
if($data['http'] == 200) {
$json = #json_decode($data['response'], TRUE);
return $json['access_token'];
} else {
return FALSE;
}
}
}
// Call a new instance of AirBnB
$airbnb = new AirBnB;
// Get the OAuth token
$token = $airbnb->Authorize('my#email.com', 'password');
?>
You can find out more about their API here.

Yammer - How to post via api to activity stream? (php)

I am able to "GET" the activity stream but not "POST" to it. It seems its a technical error.
This is the code which works for getting the activity stream:
function getActivityStream()
{
$as=$this->request('https://www.yammer.com/api/v1/streams/activities.json');
var_dump($as);
}
function request($url, $data = array())
{
if (empty($this->oatoken)) $this->getAccessToken();
$headers = array();
$headers[] = "Authorization: Bearer " . $this->oatoken['token'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . '?' . http_build_query($data) );
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
return json_decode($output);
}
ok so that works fine...
the code below, returns a Yammer "oops this page could not be found" message:
function putActivityStream()
{
$data=array('type'=>'text', 'text'=>'hello from api test call');
$json=json_encode($data);
$res=$this->post('streams/activites.json',$json);
}
function post($resource, $data)
{
if (empty($this->oatoken)) $this->getAccessToken();
$ch = curl_init();
$headers = array();
$headers[] = "Authorization: Bearer " . $this->oatoken['token'];
$headers[]='Content-Type: application/json';
$url = 'https://www.yammer.com/api/v1/' . $resource;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
return $response;
}
One of the examples from:
http://developer.yammer.com/api/streams.html
POST https://www.yammer.com/api/v1/streams/activities.json
Requests must be content-type: application/json.
{
"type": "text",
"text": "The build is broken."
}
You're going to kick yourself. You have a typo in your code. :)
Change:
$res=$this->post('streams/activites.json',$json);
to
$res=$this->post('streams/activities.json',$json);
Simples.

Categories