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);
}
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 developed an Apps Script called "sudofunctions" which execute sensitive commands using an elevated account. It is shared with the entire domain and executes as the author.
I then developed "clientFunctions" which can be run by any authenticated user and needs to invoke funcntions in sudofunctions.
sudofunctions has 2 functions so far
function test()
{
createUser("email#domain.com", "Full name")
}
function createUser(email, name)
{
console.log("Checkpoint Alpha")
}
clientFunctions then tries to call both these functions, calling test() works perfectly
var token = ScriptApp.getOAuthToken();
var options = {
"method" : "POST",
"headers": {"Authorization": "Bearer "+ token },
"payload" : {
"function": "test",
"devMode": "true"
},
muteHttpExceptions:true
}
var rest = UrlFetchApp.fetch("https://script.googleapis.com/v1/scripts/ABCXYZ:run", options)
However, calling createUser fails
var token = ScriptApp.getOAuthToken();
var options = {
"method" : "POST",
"headers": {"Authorization": "Bearer "+ token },
"payload" : {
"function": "createUser",
"parameters":["john#domain.com", "John Doe"],
"devMode": "true"
},
muteHttpExceptions:true
}
var rest = UrlFetchApp.fetch("https://script.googleapis.com/v1/scripts/ABCXYZ:run", options)
With the error:
{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"parameters\": Cannot bind query parameter. 'parameters' is a message type. Parameters can only be bound to primitive types.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": "Invalid JSON payload received. Unknown name \"parameters\": Cannot bind query parameter. 'parameters' is a message type. Parameters can only be bound to primitive types."
}
]
}
]
}
}
According to the documentation, it should work.
https://developers.google.com/apps-script/api/reference/rest/v1/scripts/run#request-body
Any ideas where I am going wrong?
Thanks for the help.
In your script, from your error message, how about the following modification?
From:
var options = {
"method" : "POST",
"headers": {"Authorization": "Bearer "+ token },
"payload" : {
"function": "createUser",
"parameters":["john#domain.com", "John Doe"],
"devMode": "true"
},
muteHttpExceptions:true
}
To:
var options = {
"method": "POST",
"headers": { "Authorization": "Bearer " + token },
"contentType": "application/json",
"payload": JSON.stringify({
"function": "createUser",
"parameters": ["john#domain.com", "John Doe"],
"devMode": "true"
}),
"muteHttpExceptions": true
}
Reference:
Method: scripts.run
I confirmed authorization with service account on GAS. "list" is work, but "run" method never work. Error msg is "source must not be empty". What kind of json should I attach?
This is on standalone GAS using GSApp library. (Apps-Script-GSApp-Library : MJ5317VIFJyKpi9HCkXOfS0MLm9v2IJHf)
function deploy() {
var jsonKey = JSON.parse(PropertiesService.getScriptProperties().getProperty("jsonKey"));
var serverToken = new GSApp.init(jsonKey.private_key, ["https://www.googleapis.com/auth/cloud-platform"], jsonKey.client_email);
var tokens = serverToken.addUser(jsonKey.client_email).requestToken().getTokens();
var url = "https://cloudbuild.googleapis.com/v1/projects/{ProjectId}/triggers/{TriggerId}:run";
var options = {
"muteHttpExceptions": true,
"method": "POST",
"headers": {
"Authorization":"Bearer "+tokens[jsonKey.client_email].token,
},
"source": {
"projectId": "{ProjectId}",
"branchName": "master",
"repoName": "repo"
}
}
Logger.log(UrlFetchApp.fetch(url,options));
}
{
"error": {
"code": 400,
"message": "source must not be empty",
"status": "INVALID_ARGUMENT"
}
}
UrlFetchApp.fetch() does not recognize "source" as a valid property. Use "payload" instead. Also you'll need to JSON.stringify() your payload and set the contentType property as application/json as follows:
var options = {
"muteHttpExceptions": true,
"method": "POST",
"contentType":"application/json",
"headers": {
"Authorization":"Bearer "+tokens[jsonKey.client_email].token,
},
"payload": JSON.stringify({
"projectId": "{ProjectId}",
"branchName": "master",
"repoName": "repo"
})
};
Note: I also posted this question on the Atlassian forum here:
https://community.atlassian.com/t5/Confluence-questions/Google-Apps-Script-to-Create-Confluence-Page-HTTP-500-Error/qaq-p/1039040#M66094
I'm reaching out to a larger audience here on SO.
I'm using the following google apps script code in a Google Sheet to create a Confluence page:
headers = {"Authorization" : "Basic " + Utilities.base64Encode(user + ':' +
pswd), "Content-Type": "application/json"};
url = "https://confluence.asdf.com/rest/api/content/";
var params = {
"method":"POST",
"headers":headers,
"muteHttpExceptions": false,
"type":"page",
"title":newTitle,
"space":{"key":"DOC"},
"body":{"storage":{"value": "<p>This is <br/> a new page</p>" },
"representation":"storage"}
};
var createResponse = UrlFetchApp.fetch(url, params);
However, when I submit the request, I receive this response:
Request failed for https://confluence.atlas.asdf.com/rest/api/content/
returned code 500.
Truncated server response: {"statusCode":500,"
message":"<?> No content to map to Object due to end of
input","reason":"Internal Server Error"} (use muteHttpExceptions option to
examine full response)
I realize there are curl samples out there which I've seen but do not help me.
What am I doing wrong?
Edit: 25-March
#Tanaike
I modified the code as you suggested:
headers = {"Authorization" : "Basic " + Utilities.base64Encode(user + ':' + pswd) };
var payload = {
"type": "page",
"title": newTitle,
"space": {"key": "DOC"},
"body": {
"storage": {
"value": "<p>This is <br/> a new page</p>"
},
"representation": "storage"
}
};
var params = {
"method": "POST",
"headers": headers,
"muteHttpExceptions": false,
"payload": JSON.stringify(payload),
"contentType": "application/json"
};
var createResponse = UrlFetchApp.fetch(url, params);
I receive the same error as before.
How about this modification?
Modified script:
Please modify params as follows and test again. From the error message in your question, the request body was put in the property of payload.
var payload = {
"type": "page",
"title": newTitle,
"space": {"key": "DOC"},
"body": {
"storage": {
"value": "<p>This is <br/> a new page</p>"
},
"representation": "storage"
}
};
var params = {
"method": "POST",
"headers": headers,
"muteHttpExceptions": false,
"payload": JSON.stringify(payload)
};
Note:
This modification supposes that each value in payload and headers is correct.
"Content-Type": "application/json" in headers can be also put in params as "contentType": "application/json".
References:
UrlFetchApp
Confluence REST API examples
I cannot test this modification. So if this didn't work, can you provide the error message? I would like to think of about the issue.
Edit:
From the official document, it seems that the property of body is "body":{"storage":{"value":"<p>This is a new page</p>","representation":"storage"}}}. So please modify as follows.
Modified script:
headers = {"Authorization" : "Basic " + Utilities.base64Encode(user + ':' + pswd) };
var payload = {
"type": "page",
"title": newTitle,
"space": {"key": "DOC"},
"body": {
"storage": {
"value": "<p>This is <br/> a new page</p>",
"representation": "storage" // Modified
}
}
};
var params = {
"method": "POST",
"headers": headers,
"muteHttpExceptions": false,
"payload": JSON.stringify(payload),
"contentType": "application/json"
};
var createResponse = UrlFetchApp.fetch(url, params);
Note:
In my environment, I could confirm that the result was the same with the result from the official sample script. If this didn't work, please confirm each value of payload and headers, again.
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