Google app scrips Slack API Get pins:list - json

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"
}

Related

How to make GET requests works in Postman and Google Apps script

The following works in Postman:
GET https://mainnet.incognito.org/fullnode
with Body -> raw of:
{
"id": 1,
"jsonrpc": "1.0",
"method": "getbeaconbeststatedetail",
"params": []
}
The following doesn't work in Google app scripts:
function getBeaconState() {
const mainnet = "https://mainnet.incognito.org/fullnode";
var raw = JSON.stringify({ "id": 1,"jsonrpc": "1.0","method": "getbeaconbeststatedetail","params": []});
var requestOptions = {
"method": "get",
"headers": {"Content-Type": "application/json"},
"body": raw,
"redirect": "follow"
};
var beaconState = UrlFetchApp.fetch(mainnet, requestOptions);
Logger.log("I set the beaconState variable.");
}
It gets a 400 error, so it must be something I'm doing wrong but poking around hasn't gotten me very far.

How can I get a specific response value from response body in postman

{
"Group": "4r3rwee",
"EventType": "string",
"EventId": "string",
"Payload": "{\"Id\":\"6fd04f93e22e44c98752e209c1b74b03\",\"Name\":\"Md. Sakibur Rahman\",\"Email\":\"sakibur.rahmandd773661#orbitax.com \",\"Phone\":\"string\",\"Title\":\"Add Contact\",\"Status\":1,\"ContactType\":0,\"CompanyId\":\"automation\",\"ProjectId\":\"\"}",
"Status": 1,
"Id": "57c9c52a645a40f5bed0562dbee7d13b"
}
How can I get Id value from the payload?
I am using this command, but it's not working
pm.test("Set Contacts ID", function () {
var jsonData = pm.response.json();
//console.log("Response Payload : " + jsonData.Payload.{jsonData.Id});
pm.environment.set("contactIds", jsonData.Payload.Id);
});
As per the request data shown in the question, param. Payload contains JSON string. So, you'd need to parse it first, to access the property as follows,
pm.test("Set Contacts ID", function () {
var jsonData = pm.response.json();
var payloadData = JSON.parse(jsonData.Payload); //parsed payload
console.log(payloadData.Id);
pm.environment.set("contactIds", payloadData.Id);
});

Google Apps Script to Create Confluence Page -- Results in Status Code 500

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.

Status code error while posting json data using google script

I was writing an app script to send an sms. In the sms api document section, it's written that with the following, sms can be sent:
POST http://clients.muthofun.net/api/v3/sendsms/json
Host: http://clients.muthofun.net
Content-Type: application/json
Accept: */*
{
"authentication":{
"username":"test",
"password":"test"
},
"messages":[
{
"sender":"044XXXXXXXX",
"text":"Hello",
"recipients":[
{
"gsm":"88017XXXXXXXX"
}
]
}
]
}
So I write the following script code,
modified as #Tanaike said
function myFunction() {
var _auth = {
"username": "*****",
"password": "*****"
};
var rec = {
"gsm": "xxxxxxxxxxx"
};
var msg = {
"sender": "xxxxxxxxxxx",
"text": "Hello",
"recipients": [rec]
};
var payload = {
"authentication": _auth,
"messages": [msg]
};
_payload = JSON.stringify(payload)
var options = {
'method' : 'POST',
'contentType': 'application/json',
"accept": "*/*",
"payload": _payload
};
var url = "http://clients.muthofun.net/api/v3/sendsms/json";
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}
But the actual response is:
{
"results":[
{
"status":"0",
"messageid":"10210011344550330860",
"destination":"88017XXXXXXXX"
}
]
}
but from the Logger function I get the following response
{
"results":[
{
"status":"-5",
"messageid":"",
"destination":"8801552555645"
}
]
}
Is it because I missed out a square bracket in the recipients and messages section? Or I am doing something wrong while sending the post request to the url?
How about this modification? In your sample request body, messages is as follows.
{
"authentication": {
"username": "test",
"password": "test"
},
"messages": [
{
"sender": "044XXXXXXXX",
"text": "Hello",
"recipients": [
{
"gsm": "88017XXXXXXXX"
}
]
}
]
}
In your script, it is as follows.
{
"authentication": {
"username": "*****",
"password": "*****"
},
"messages": {
"sender": "xxxxxxxxxxx",
"text": "Hello",
"recipients": {
"gsm": "xxxxxxxxxxx"
}
}
}
In your script, the values of messages and recipients are not array. So how about this modification?
Modified script :
From :
var msg = {
"sender": "xxxxxxxxxxx",
"text": "Hello",
"recipients": rec
};
var payload = {
"authentication": _auth,
"messages": msg
};
To :
var msg = {
"sender": "xxxxxxxxxxx",
"text": "Hello",
"recipients": [rec] // Modified
};
var payload = {
"authentication": _auth,
"messages": [msg] // Modified
};
And accept should be included in headers.
I'm not sure whether this modification resolves your issue, because I cannot test it. If this was not useful for you, can you provide the detail situation of the error?
Edit :
In this modification, option was modified.
var options = {
"method" : "POST",
"contentType": "application/json",
"headers": {"accept": "*/*"}, // Modified
"payload": payload // Modified
};
Rather than doing json request I made a http request to send sms.
Here is the code:
function myFunction() {
var username = "*****";
var password = "****";
var msg = "Harry kane didn't score!!! why!!!! why on August!!! :'(";
var phone = "xxxxxxxxxxx";
var url = "http://clients.muthofun.com:8901/esmsgw/sendsms.jsp?user="+username+"&password="+password+"&mobiles="+phone+"&sms="+msg;
Logger.log(url)
var response = UrlFetchApp.fetch(url);
Logger.log(response);
}

How to Retrieve (not create) Tasks from Asana using Apps Script & Personal Access Token

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.