How can you get all the smartsheet attachments with one request - php

Using my current code I need to make a separate curl request for on each row of the smartsheet to get the attachment id, then send another request with that id to get the download url.
This will occur for each row of the smartsheet and is very inefficient for sheets with lots of rows.
Is there a way to get all the attachment id's / url's from a sheet with one request?
class Sheet_request{
private $urlMain = "https://api.smartsheet.com/2.0/users/me";
private $url_food_sheet = "https://api.smartsheet.com/2.0/sheets/3650210866XXXX/?include=attachments";
private $url_food_main= "https://api.smartsheet.com/2.0/sheets/36502108669XXX";
private function curl($url) {
$ch = curl_init($url);
$request_headers = array();
$request_headers[] = "Authorization: Bearer XXXXXXXXXXXXXXXX";
$request_headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if ($response === false) {
die(curl_error($ch));
}
curl_close($ch);
return $response;
}
function get_attachments() {
$response = $this -> curl($this -> url_food_sheet);
$sheetObj = json_decode($response);
foreach ($sheetObj->rows as $row) {
if (isset($row->attachments)){
$rowAttachmentsURL = $this -> url_food_main . "/rows/" . number_format($row -> id, 0, "", "") . "/attachments";
$getAttachmentsResponse = $this->curl($rowAttachmentsURL);
$attachment = json_decode($getAttachmentsResponse);
$attachmentURL = $this->url_food_main . "/attachments/".number_format($attachment->data[0]->id, 0, "", "");
$attachmentInfo = $this->curl($attachmentURL);
$attachmentInfo = json_decode($attachmentInfo);
file_put_contents("pictures/".$attachmentInfo->name, file_get_contents($attachmentInfo->url));
}
}
}
}
$foo = new Sheet_request();
$foo->get_attachments();

You can use the Get All Attachments operation to retrieve all attachments (Ids) in a single request for the specified sheet. As the documentation shows, the Request URI is: https://api.smartsheet.com/2.0/sheets/{sheetId}/attachments.
Please note that Attachments can exist in Smartsheet at 3 different levels: Sheet, Row, Comment. The Get All Attachments response will contain an all attachments in the sheet (at any/all levels: Sheet, Row, Comment) -- so if you're just interested in Row attachments, you'll want to only process items in the response where the parentType attribute has a value of "ROW".
Once you have access to the attachment Ids in the "Get All Attachments" response, you'll still need to subsequently use the Get Attachment operation for each attachment to retrieve the URLs one at a time. (There's currently no way to get these in bulk.)

At the sheet or row level, I believe you can now add the 'include' query parameter to force inclusion of attachments at .sheet. and .row. level, to ensure .comment. level attachments, need to add discussions to the include values:
https://api.smartsheet.com/2.0/sheets/{sheetId}?include=attachments,discussions

Related

get Full message from telegram bot

I want to get the full message sent by the person's ID in telegram bot , including all the attached files, such as a photo , audio, image, or a caption and photo ... , and send it to another person's ID. I don't want it to be forward , I want to be sent!
I receive all updates this way:
$data=json_decode(file_get_contents("php://input"));
my code :
<?php
const apiKey='112';
$channels=[
'1'=>'-1001233909561',
'2'=>'-1001198102700',
];
const admin='668400001';
//-------------------------------------------------------- End Channels and ADMIN Info
$data=json_decode(file_get_contents("php://input"));
$json_data=json_encode($data);
file_put_contents('data.json', $json_data);
function bot($method, $datas = [])
{
$url = "https://api.telegram.org/bot" . apiKey . "/" . $method;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($datas));
$res = curl_exec($ch);
if (curl_error($ch))
{
var_dump(curl_error($ch));
}
else
{
return json_decode($res);
}
}
function forwardMessage($messageId)
{
bot('forwardMessage',[
'chat_id'=>backupChannelId,
'from_chat_id'=>firstChannelId,
'message_id'=>$messageId,
]);
}
function sendMessage($toChannel,$message)
{
}
?>
If I understand correctly, you want to get the text and all the attachments of all messages sent to the bot. For example, the text of the message is in update->message-> text.
$text = $data['message']['text'];
$audio = $data['message']['audio'];
The easiest way to send the exact same massage to another chat is by forwarding it, otherwise you have to search for all the possible attachments in the message object and, if present, send them to the other chat with the corrisponding method (sendPhoto, sendAudio etc.).
Tip:
use
$data = json_decode(file_get_contents("php://input"), true);
instead of
$data = json_decode(file_get_contents("php://input"));
More details here

Make several POST CURL API in one request PHP

I am trying to do some POST with CURL in some way, I explain:
I am using the PhpExcel library, the idea is to upload an excel file that contains a table with several records and the names of the field, with a PhpExcel function I go through each record, so I save it in an array.
The next step is to make a request that sends each of the records to a URL, in this case it is an API URL to edit several products, waiting for parameters (which are each of the fields that are sent in a record) , I have already armed the function to send a single request, I just need to know how I can send several records at once in a single request.
Summary:
I upload the excel file that contains several records. (done)
I keep these records in an array through a function that collects the contents of PhpExcel (done)
Make a POST request with CURL that runs through each of the records and send them at the same time (I have only managed to send only one record)
This code is for call function send POST
private function peticion_get_post($ruta,$formdata,$tipo){
$apiurl = 'https://url/api/v1/';
$url = $apiurl.$ruta;
$postvars = '';
foreach($formdata as $key=>$value) {
$postvars .= $key . "=" . $value . "&";
}
$ch = curl_init();
if($tipo == 'GET'){
curl_setopt($ch,CURLOPT_URL,$url."?".$postvars);
}
if($tipo == 'POST'){
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
}
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch,CURLOPT_CUSTOMREQUEST, $tipo);
//curl_setopt($ch,CURLOPT_POST, $tipo);//0 for a GET request y 1 para POST
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,0);
curl_setopt($ch,CURLOPT_TIMEOUT, 20);
$respuesta = curl_exec($ch);
$resultado = json_decode($respuesta);
return $resultado;
}
This code is for call function before and sends content from form
$formdata_post = array(
'id_box' => $id_box,
'number' => $number,
'label' => $label
);
$ruta = 'edit.json';
$resultado_post = $this->peticion_get_post($ruta, $formdata_post, 'POST');
I work with Codeigniter, currently, I send the content by JSON through a form and just send a record, I just have to edit the form and send the content that is in the array that generated the PhpExcel when uploading the file.

PHP Fetch image from DM Twitter using REST API?

I have problem when I want to fetch image that was sent to my DM.
So when I fetch the DM data from API, I got the media id for the image but how to fetch it?
I want to fetch the image and tweet it to my account.
So basically:
Someone send DM to me with media
I read my account DM from API
Tweet DM content to my account
Here is my code
$AMConnection = new \Twitter\OAuth(AM_CONSUMER_KEY, AM_CONSUMER_SECRET);
$AMConnection->setAccessToken($amService->token, $amService->secret);
$jsonData = json_decode(file_get_contents("./fetchDM.json"));
foreach ($jsonData as $json) {
if (!isset($json->entities->media)) continue;
$medias = $json->entities->media;
$postParam['status'] = $json->text;
foreach ($medias as $image) {
$postParam['status'] = str_replace($image->url, "", $postParam['status']);
$postParam['media_ids'][] = $image->id_str;
}
echo "SEND TWEET".PHP_EOL;
$return = $AMConnection->post('statuses/update', $postParam);
var_dump($return);
if (isset($return->errors) and count($return->errors) > 0) {
foreach ($return->errors as $error) {
if ($error->code == 89) {
$amService->token = null;
$amService->secret = null;
$amService->save();
break;
}
}
}
}
On my code, I was tried to tweet media using media_id but it doesn't work.
Sorry for bad english
Finally it's solved.
So I've been look for this one on some forums but only 2 forum has answer, 1 on twitter forum (sorry I don't have link) and another 1 StackOverflow
I'm using library and try messing out with it but deadend. The library that I've used to request REST API, use OAuth request from URL and POST data. Yeah, it's totally work (only for REST API) but this one is totally different.
To fetch image from DM, YOU MUST REQUEST USING HEADER AUTHORIZATION and no other way.
On my sample, I want to try to fetch https://ton.twitter.com/1.1/ton/data/dm/863758539021365258/863758532109246464/VSSysEvy.jpg (This one is image url from DM, so only me and someone who've sent me that image only can see it).
I'm using CURL PHP to fetch the image so the request will be like this
<?php
$this->http_info = array();
$ci = curl_init();
$url = 'https://ton.twitter.com/1.1/ton/data/dm/863758539021365258/863758532109246464/VSSysEvy.jpg';
$headerAuth = 'Authorization: OAuth oauth_version="1.0",
oauth_nonce="{autoGeneratedNonce}",
oauth_timestamp="{time()}",
oauth_consumer_key="{yourAppToken}",
oauth_token="{userToken}",
oauth_signature_method="HMAC-SHA1",
oauth_signature="{autoGeneratedSignature}"';
/* Curl settings */
curl_setopt($ci, CURLOPT_USERAGENT, 'LShaf User Agent');
curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ci, CURLOPT_HTTPHEADER, [$headerAuth]);
curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ci, CURLOPT_HEADER, FALSE);
curl_setopt($ci, CURLOPT_URL, $url);
$response = curl_exec($ci);
curl_close ($ci);
Note: You MUST use method GET and put Authorization on HEADER.
And for the last thing, I'm sorry for my bad english.

What would be the best way to collect the titles (in bulk) of a subreddit

I am looking to collect the titles of all of the posts on a subreddit, and I wanted to know what would be the best way of going about this?
I've looked around and found some stuff talking about Python and bots. I've also had a brief look at the API and am unsure in which direction to go.
As I do not want to commit to find out 90% of the way through it won't work, I ask if someone could point me in the right direction of language and extras like any software needed for example pip for Python.
My own experience is in web languages such as PHP so I initially thought of a web app would do the trick but am unsure if this would be the best way and how to go about it.
So as my question stands
What would be the best way to collect the titles (in bulk) of a
subreddit?
Or if that is too subjective
How do I retrieve and store all the post titles of a subreddit?
Preferably needs to :
do more than 1 page of (25) results
save to a .txt file
Thanks in advance.
PHP; in 25 lines:
$subreddit = 'pokemon';
$max_pages = 10;
// Set variables with default data
$page = 0;
$after = '';
$titles = '';
do {
$url = 'http://www.reddit.com/r/' . $subreddit . '/new.json?limit=25&after=' . $after;
// Set URL you want to fetch
$ch = curl_init($url);
// Set curl option of of header to false (don't need them)
curl_setopt($ch, CURLOPT_HEADER, 0);
// Set curl option of nobody to false as we need the body
curl_setopt($ch, CURLOPT_NOBODY, 0);
// Set curl timeout of 5 seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
// Set curl to return output as string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Execute curl
$output = curl_exec($ch);
// Get HTTP code of request
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close curl
curl_close($ch);
// If http code is 200 (success)
if ($status == 200) {
// Decode JSON into PHP object
$json = json_decode($output);
// Set after for next curl iteration (reddit's pagination)
$after = $json->data->after;
// Loop though each post and output title
foreach ($json->data->children as $k => $v) {
$titles .= $v->data->title . "\n";
}
}
// Increment page number
$page++;
// Loop though whilst current page number is less than maximum pages
} while ($page < $max_pages);
// Save titles to text file
file_put_contents(dirname(__FILE__) . '/' . $subreddit . '.txt', $titles);

Change Output of PHP Script to use POST Method

Bear with my inexperience here, but can anyone point me in the right direction for how I can change the PHP script below to output each variable that is parsed from the XML file (title, link, description, etc) as a POST method instead of just to an HTML page?
<?php
$html = "";
$url = "http://api.brightcove.com/services/library?command=search_videos&any=tag:SMGV&output=mrss&media_delivery=http&sort_by=CREATION_DATE:DESC&token= // this is where the API token goes";
$xml = simplexml_load_file($url);
$namespaces = $xml->getNamespaces(true); // get namespaces
for($i = 0; $i < 80; $i++){
$title = $xml->channel->item[$i]->video;
$link = $xml->channel->item[$i]->link;
$title = $xml->channel->item[$i]->title;
$pubDate = $xml->channel->item[$i]->pubDate;
$description = $xml->channel->item[$i]->description;
$titleid = $xml->channel->item[$i]->children($namespaces['bc'])->titleid;
$html .= "<h3>$title</h3>$description<p>$pubDate<p>$link<p>Video ID: $titleid<p>
<iframe width='480' height='270' src='http://link.brightcove.com/services/player/bcpid3742068445001?bckey=AQ~~,AAAABvaL8JE~,ufBHq_I6FnyLyOQ_A4z2-khuauywyA6P&bctid=$titleid&autoStart=false' frameborder='0'></iframe><hr/>";/* this embed code is from the youtube iframe embed code format but is actually using the embedded Ooyala player embedded on the Campus Insiders page. I replaced any specific guid (aka video ID) numbers with the "$guid" variable while keeping the Campus Insider Ooyala publisher ID, "eb3......fad" */
}
echo $html;
?>
#V.Radev Here's another PHP script using cURL that I think will work with the API I'm trying to send data to:
<?PHP
$url = 'http://api.brightcove.com/services/post';
//open connection
$ch = curl_init($url);
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, '$title,$descripton,$url' . stripslashes($_POST['$title,$description,$url']));
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
// Enable for Charles debugging
//curl_setopt($ch,CURLOPT_PROXY, '127.0.0.1:8888');
$result = curl_exec($ch);
curl_close($ch);
print $result;
?>
My question is, how can I pass the variables from my feed parsing script (title, description, URL) to this new script?
I have this code from Brightcove, can I just output the variables from my parser script and send to this PHP script so that the data goes to the API?
<?php
// This code example uses the PHP Media API wrapper
// For the PHP Media API wrapper, visit http://docs.brightcove.com/en/video-cloud/open-source/index.html
// Include the BCMAPI Wrapper
require('bc-mapi.php');
// Instantiate the class, passing it our Brightcove API tokens (read, then write)
$bc = new BCMAPI(
'[[READ_TOKEN]]',
'[[WRITE_TOKEN]]'
);
// Create an array of meta data from our form fields
$metaData = array(
'name' => $_POST['bcVideoName'],
'shortDescription' => $_POST['bcShortDescription']
);
// Move the file out of 'tmp', or rename
rename($_FILES['videoFile']['tmp_name'], '/tmp/' . $_FILES['videoFile']['name']);
$file = '/tmp/' . $_FILES['videoFile']['name'];
// Create a try/catch
try {
// Upload the video and save the video ID
$id = $bc->createMedia('video', $file, $metaData);
echo 'New video id: ';
echo $id;
} catch(Exception $error) {
// Handle our error
echo $error;
die();
}
?>
Post is a request method to access a specific page or resource. With echo you are sending data which means that you are responding. In this page you can only add response headers and access it with a request method such as post, get, put etc.
Edit for API request as mentiond in the comments:
$curl = curl_init('your api url');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $your_data_to_send);
$result_from_api = curl_exec($curl);
curl_close($curl);

Categories