Trying to fetch data from the ConvertAPI's web to jpg but the program throws an error for a Bad Value. Here's my code :
const url = 'https://v2.convertapi.com/convert/web/to/png?Secret=...'
const prams = [
{
"Name": "Url",
"Value": "..."
}
];
Logger.log(UrlFetchApp.getRequest(url, prams));
I believe your goal is as follows.
From your provided document, you want to convert the following HTTP request to Google Apps Script.
POST https://v2.convertapi.com/convert/web/to/jpg?Secret=<YOUR SECRET HERE>
Content-Type: application/json
{
"Parameters": [
{
"Name": "Url",
"Value": ""
},
{
"Name": "StoreFile",
"Value": true
}
]
}
Unfortunately, your prams cannot be directly used for UrlFetchApp. And, UrlFetchApp.getRequest doesn't request. And also, your prams is different from the sample of the document you provided.
When these points are reflected in Google Apps Script, how about the following modification?
Modified script:
function myFunction() {
const url = 'https://v2.convertapi.com/convert/web/to/jpg?Secret=<YOUR SECRET HERE>';
const prams = {
"Parameters": [
{
"Name": "Url",
"Value": ""
},
{
"Name": "StoreFile",
"Value": true
}
]
};
const options = {
contentType: "application/json",
payload: JSON.stringify(prams),
};
const res = UrlFetchApp.fetch(url, options);
console.log(res.getContentText());
}
If an error occurs, please confirm your Secret and the values of prams again.
Note:
In the document, there is a sample curl command of curl -F "Url=" -F "StoreFile=true" https://v2.convertapi.com/convert/web/to/jpg?Secret=<YOUR SECRET HERE>. When this is converted to Google Apps Script, it becomes as follows.
const url = "https://v2.convertapi.com/convert/web/to/jpg?Secret=<YOUR SECRET HERE>";
const options = { payload: { "StoreFile": "true", "Url": "" } };
const res = UrlFetchApp.fetch(url, options);
console.log(res.getContentText());
Please test the above 2 patterns.
References:
WEB to JPG API
fetch(url, params)
Related
Using Google app script as serverless for a slack bot. Having an issue returning specific values from slack API. I'm using the pins:list call. I am able to get the JSON in response and items calls but get null when trying to get the next set of values. I am looking to return "permalinks" so I can then post back into slack what items are pinned to a room. here is my script:(without giving away company details)
function GetPinns() {
const ss = SpreadsheetApp.getActiveSpreadsheet()
let url = "https://slack.com/api/pins.list?channel=C0XXXXXXXXX&pretty=1";
let payload = {
"ok": true,
"channel": "C0XXXXXXXXX"
"type": "message",
}
var options = {
"method": "get",
"payload": JSON.stringify(payload),
"headers": {
"Content-type": "application/json; charset=utf-8",
"Authorization": "Bearer xoxb-"}}
var response = UrlFetchApp.fetch(url, options)
var json = response.getContentText();
var data = JSON.parse(json);
var items = data.item.permalinks;
Logger.log(items);
}
Thank you!!
SUGGESTION
Upon reviewing Slack's official docs for pins.list method, I suppose that this sample JSON response below is the same as the actual JSON response that you're getting:
Sample JSON response:
{
"items": [
{
"channel": "C2U86NC6H",
"created": 1508881078,
"created_by": "U2U85N1RZ",
"message": {
"permalink": "https://hitchhikers.slack.com/archives/C2U86NC6H/p1508197641000151",
"pinned_to": [
"C2U86NC6H"
],
"text": "What is the meaning of life?",
"ts": "1508197641.000151",
"type": "message",
"user": "U2U85N1RZ"
},
"type": "message"
},
{
"channel": "C2U86NC6H",
"created": 1508880991,
"created_by": "U2U85N1RZ",
"message": {
"permalink": "https://hitchhikers.slack.com/archives/C2U86NC6H/p1508284197000015",
"pinned_to": [
"C2U86NC6H"
],
"text": "The meaning of life, the universe, and everything is 42.",
"ts": "1503289197.000015",
"type": "message",
"user": "U2U85N1RZ"
},
"type": "message"
}
],
"ok": true
}
You can try iterating though the items array via looping in the JSON response to get each permalinks data, as seen on this quick test below:
Quick Test
function GetPinns() {
//This sample JSON String response was from https://api.slack.com/methods/pins.list#examples
var json =
"{\"items\": [{\"channel\": \"C2U86NC6H\",\"created\": 1508881078,\"created_by\": \"U2U85N1RZ\",\"message\": {\"permalink\": \"https://hitchhikers.slack.com/archives/C2U86NC6H/p1508197641000151\",\"pinned_to\": [\"C2U86NC6H\"],\"text\": \"What is the meaning of life?\",\"ts\": \"1508197641.000151\",\"type\": \"message\",\"user\": \"U2U85N1RZ\"},\"type\": \"message\"},{\"channel\": \"C2U86NC6H\",\"created\": 1508880991,\"created_by\": \"U2U85N1RZ\",\"message\": {\"permalink\": \"https://hitchhikers.slack.com/archives/C2U86NC6H/p1508284197000015\",\"pinned_to\": [\"C2U86NC6H\"],\"text\": \"The meaning of life, the universe, and everything is 42.\",\"ts\": \"1503289197.000015\",\"type\": \"message\",\"user\": \"U2U85N1RZ\"},\"type\": \"message\"}],\"ok\": true}";
var data = JSON.parse(json);
//Iterate through the items via looping
data.items.forEach(item => {
Logger.log(item.message.permalink)
});
}
Result
Your script will look like this:
function GetPinns() {
const ss = SpreadsheetApp.getActiveSpreadsheet()
let url = "https://slack.com/api/pins.list?channel=C0XXXXXXXXX&pretty=1";
let payload = {
"ok": true,
"channel": "C0XXXXXXXXX"
"type": "message",
}
var options = {
"method": "get",
"payload": JSON.stringify(payload),
"headers": {
"Content-type": "application/json; charset=utf-8",
"Authorization": "Bearer xoxb-"
}
}
var data = JSON.parse(json);
//Iterate through the items via looping
data.items.forEach(item => {
Logger.log(item.message.permalink)
});
}
Reference
https://www.sitepoint.com/loop-through-json-response-javascript/
Thank you!!
I wound up with this in the end
var response = UrlFetchApp.fetch(url, options);
var json = JSON.parse(response.getContentText());
var items = json.items
var linkList = ""
for(var x in items) {
var link = items[x]["message"]["permalink"]
var text = items[x]["message"]["text"]
linkList += "<" + link +"|" + text +">" + "\n"
}
I trying to use doPost in google script to get parameter from source A and get twilio to send sms.
Currently, by using the code given by twilio, I can send whatever detail in google script.
I have created the webapp exec url to put in source A so now source A and google script can communicating.
I just do not know how to do a proper script in google script to get the parameters from source A.
Can anyone help me.. thank you in advance !
I am new to coding, not sure even source A code/format is correct -_-"
Source A:(json)
data input field
output result
{
"$type": "Nirvana.Data.TaskResultWebhook, V2API",
"Headers": {
"$type": "System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.String, mscorlib]], mscorlib",
"Authorization": "Basic xxxxxxxxxxxxxxxxxx=="
},
"Payload": "{\"To\": \"+8888888888\",\"Body\": \"testing\",\"From\" : \"business\"}",
"Url": "https://script.google.com/macros/s/xxxxxxxxxx/exec",
"Verb": "Post",
"ContentType": "JSON",
"MimeType": "application/json",
"TimeoutSeconds": 180,
"MaxRetryCount": 3,
"AsyncExec": false,
"AppErrors": {
"$type": "Jeenee.DataTypes.AppErrors, Jeenee.DataTypes",
"RecordInfo": false,
"RecordWarning": true,
"AnnotateErrors": false,
"Errors": []
},
"TaskType": "Webhook",
"TaskName": "New Task"
}
Google script (code from twilio)
function doPost(e) {
var messages_url = "https://api.twilio.com/2010-04-01/Accounts/ACxxxxxxxxxxxx/Messages.json";
var payload = {
"To": "+1111111111",
"Body" : "AAAAAAAAAA",
"From" : "BBBBBBBBBB"
};
var options = {
"method" : "post",
"payload" : payload
};
options.headers = {
"Authorization" : "Basic " + Utilities.base64Encode("ACxxxxxxxxxx:xxxxxxxxxxxx")
};
UrlFetchApp.fetch(messages_url, options);
}
Step 3 (twilio)
send sms
Not sure who's calling your script. If you're using it as a webhook you can get the parameters in the object passed into your doPost function when it is called.
function doPost(e) {
var params = e.parameter;
var from = params.From;
var to = params.To;
var body = params.Body;
var messages_url = "https://api.twilio.com/2010-04-01/Accounts/ACxxxxxxxxxxxx/Messages.json";
var payload = {
"To": to,
"Body" : body,
"From" : from
};
var options = {
"method" : "post",
"payload" : payload
};
options.headers = {
"Authorization" : "Basic " + Utilities.base64Encode("ACxxxxxxxxxx:xxxxxxxxxxxx")
};
UrlFetchApp.fetch(messages_url, options);
}
I am attempting to retrieve, but not create, tasks from Asana using Google Apps Script.
Using the Asana API Explore, I have constructed a URL that returns the data I desire: https://app.asana.com/api/1.0/tasks?opt_fields=name,assignee_status&assignee=987654321987654&completed_since=2018-02-22&limit=100&workspace=456789123456
This URL returns the desired data, in the following format:
{
"data": [
{
"id": 147258369147258,
"assignee_status": "inbox",
"name": "An example task name"
},
{
"id": 963852741963852,
"assignee_status": "upcoming",
"name": "And second example task name."
},
//etc...
]
}
With that URL as a model, I have created a Personal Access Token and executed the following function within Apps Script:
function getTasks5() {
// Asana Personal Token
var bearerToken = "Bearer " + "asdf123456789asdf456789456asdf";
//Request
var request = {
data: {
opt_fields: ["name", "assignee_status"],
assignee: "987654321987654",
completed_since: "2018-02-22",
limit: "100",
workspace: "456789123456"
}
};
// Request options
var options = {
method: "GET",
headers: {
"Authorization": bearerToken
},
contentType: "application/json",
payload: JSON.stringify(request)
};
var url = "https://app.asana.com/api/1.0/tasks";
var result = UrlFetchApp.fetch(url, options);
var reqReturn = result.getContentText();
Logger.log(reqReturn);
}
Instead of returning the desired data as the aforementioned URL does, the function creates an unnamed task in Asana, which is undesirable. It also returns this response containing undesired data:
{
"data": {
"id": 123456789123456,
"created_at": "2018-02-22T20:59:49.642Z",
"modified_at": "2018-02-22T20:59:49.642Z",
"name": "",
"notes": "",
"assignee": {
"id": 987654321987654,
"name": "My Name Here"
},
"completed": false,
"assignee_status": "inbox",
"completed_at": null,
"due_on": null,
"due_at": null,
"projects": [],
"memberships": [],
"tags": [],
"workspace": {
"id": 456789123456,
"name": "Group Name Here"
},
"num_hearts": 0,
"num_likes": 0,
"parent": null,
"hearted": false,
"hearts": [],
"followers": [
{
"id": 987654321987654,
"name": "My Name Here"
}
],
"liked": false,
"likes": []
}
}
Is it possible to simply GET a list of tasks in the manner exemplified by my first JSON example above without creating a task, and without resorting to using OAuth? If so, what changes to the Apps Script function need to be made?
Alright, the problem was with the approach I was taking. Rather than format the request with a payload (which infers a POST request), I needed to structure it more traditionally as a GET request, like so:
var requestUrl = "https://app.asana.com/api/1.0/tasks?opt_fields=name,assignee_status&assignee=123456789123&completed_since=2018-02-22&limit=100&workspace=987654321987";
var headers = {
"Authorization" : "Bearer " + AUTH_TOKEN
};
var reqParams = {
method : "GET",
headers : headers,
muteHttpExceptions: true
};
Then I was able to perform:
UrlFetchApp.fetch(requestUrl, reqParams);
And obtain the data I was after.
I want to use mandrill email sending api in my google apps script. In google script I have to use JSON code but I am not getting how I will use it. I am very new in Google apps script.
var m = new mandrill.Mandrill('XXXXXXXXXXX');
var from_email = "user4#gmail.com";
var to = '[
{
"email": "recipient.email#example.com",
"name": "Recipient Name"
}
],';
// create a variable for the API call parameters
var params = {
"message": {
"from_email":from_email,
"to":[{"email":to}],
"subject": "Sending a text email from the Mandrill API",
"text": "I'm learning the Mandrill API at Codecademy, it's very difficult."
}
};
function sendTheMail() {
// Send the email!
alert('this is a mail script');
m.messages.send(params, function(res) {
log(res);
}, function(err) {
log(err);
});
}
I am not getting how to use this code in Google Apps Script.
You'd need to use the urlfetchapp.
var url = "https://mandrillapp.com/api/1.0/messages/send.json";
var your_key = "xxxxxxxxxxxxx";
var from_email = "user4#gmail.com";
var to = [{
"email": "recipient.email#example.com",
"name": "Recipient Name"
}];
var params = {
"key": your_key,
"message": {
"from_email":from_email,
"to":[{"email":to}],
"subject": "Sending a text email from the Mandrill API",
"text": "I'm learning the Mandrill API at Codecademy, it's very difficult."
}
};
var payload = JSON.stringify(params);
var options = {
'method': 'post',
'payload': payload,
'contentType' : 'application/json'
};
var response = UrlFetchApp.fetch(url, options);
Haven't tested this code, but should be something like that.
I paste sample code example to send email by Mandrill with attachment file from Google Drive.
function sendEmail() {
var MANDRILL_API_KEY = "<<your key here>>";
var files = [
"<<Google Drive File ID 1>>",
"<<Google Drive File ID 2>>",
"<<Google Drive File ID 3>>"
];
var recipients = [
{
"email": "ctrlq+to#labnol.org",
"name": "Amit Agarwal",
"type": "to"
}, {
"email": "ctrlq+cc#labnol.org",
"type": "cc"
}, {
"email": "ctrlq+bcc#gmail.com",
"type": "bcc"
}
];
var attachments = [];
for (var f in files) {
var file = DriveApp.getFileById(files[f]);
attachments.push({
"type": file.getMimeType(),
"name": file.getName(),
"content": Utilities.base64Encode(file.getBlob().getBytes())
});
}
var params = {
"key": MANDRILL_API_KEY,
"message": {
"from_email": "<<Sender's Email Address>>",
"from_name": "<<Sender Name>>",
"to": recipients,
"attachments": attachments,
"headers": {
"Reply-To": "reply#example.com"
},
"subject": "Enter email subject",
"text" : "Enter email body in plain text",
"html" : "Enter HTML content with <b>tags</b>"
}
};
var response = UrlFetchApp.fetch(
"https://mandrillapp.com/api/1.0/messages/send.json", {
'method': 'POST',
'payload': JSON.stringify(params),
'contentType': 'application/json'
});
Logger.log(response.getContentText());
}
Sample code is extracted from website ctrlq of Amit Agarwal
hi all iam trying insert post using GAS but failed.. can you tell me what im wrong... thx in advance....
here my code
`function sendHttpPost() {
var API_KEY = 'my api key';
var scope = "http://www.blogger.com/feeds/";
var oAuthConfig = UrlFetchApp.addOAuthService("blogger");
oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig.setConsumerKey("anonymous");
oAuthConfig.setConsumerSecret("anonymous");
var payload =
{
"kind": "blogger#post",
"blog": {
"id": "486683248036684073"
},
"title": "A new post",
"content": "With <b>exciting</b> content..."
}
var options =
{
"contentType":"application/json",
"oAuthServiceName" : "blogger",
"oAuthUseToken" : "always",
"method" : "POST",
"payload" : payload
};
var respon = UrlFetchApp.fetch("https://www.googleapis.com/blogger/v3/blogs/486683248036684073/posts?key="+API_KEY, options);
and here is error message
Request failed for returned code 400. Server response: { "error": {
"errors": [ { "domain": "global", "reason": "parseError", "message":
"Parse Error" } ], "code": 400, "message": "Parse Error" } }
I believe you are trying to use oauth1 when oauth2 is required.
there already is a unanswered request about that here.
Implementing oauth 2 with Google app script is really a pain, so I made an attempt to build a library that could answer the need (dioxygen library) - it work a little bit like the oauth2 playground but it's less pretty.
With a little work you should be able to adapt it to your need with blogger.
I tried Harold's library, but after successfully retrieving OAuth token, I ended up with the same error.
But, when I issued the same JSON request as in my script through the API Explorer, it was processed:
https://developers.google.com/blogger/docs/3.0/reference/posts/insert
[UPDATE]
I am taking it back. This code works. I just replaced the payload variable and put the JSON request straight into URL fetch options. So there was some problem with passing that payload variable into options variable.
function testBlogger() {
var payload =
{
"kind": "blogger#post",
"blog": {
"id": "YOUR_BLOG_ID"
},
"title": "New post",
"content": "With content..."
};
var options =
{
"method" : "post",
"headers" : { "Authorization" : "Bearer YOUR_ACTIVE_TOKEN"},
"contentType" : "application/json",
"payload" : '{ "kind": "blogger#post", "blog": { "id": "YOUR_BLOG_ID" }, "title": "New post", "content": "With content..." }'
};
try {
var result = UrlFetchApp.fetch(
"https://www.googleapis.com/blogger/v3/blogs/YOUR_BLOG_ID/posts",
options);
Logger.log(result);
} catch (e) {
Logger.log(e);
}
}