Connecting Google spreadsheet to Atlassian JIRA - google-apps-script

I want to display my JIRA issues in a Google spreadsheet using Google Apps script but first i need to establish a connection with JIRA, so i went through these tutorials only to find out that the opposit is possible (JIRA connects to other applications), therefore i want to ask if there's a way to connect Google Sheets to JIRA and in that case how to get the Authentication Token ?

Request token from JIRA:
Code.gs
function requestJIRA_Token() {
var baseUrl = 'Put Base URL to JIRA here';
var theUrl = baseUrl + "/plugins/servlet/oauth/request-token";
var response = UrlFetchApp.fetch(theUrl);
Logger.log('response: ' + response);
};
JIRA OAUTH

Please find sample code to connect to JIRA and get the response as an Json Load
function seachIssuesR(j_query, maxresult) {
if (!j_query) {
Browser.msgBox("Null Query :: " + j_query);
}
var url = "https://<jiraServerName>.jira.com/rest/api/2/search?jql=" + j_query + "&startAt=0&maxResults=" + maxresult;
Logger.log(url);
if (!PropertiesService.getScriptProperties().getProperty("digest")) {
var userAndPassword = Browser.inputBox("Enter your Jira On Demand User id and Password in the form User:Password. e.g. javarohit#gmail.com:mypassword#123 (Note: This will be base64 Encoded and saved as a property on the spreadsheet)", "Userid:Password", Browser.Buttons.OK_CANCEL);
var x = Utilities.base64Encode(userAndPassword);
PropertiesService.getScriptProperties().setProperty("digest", "Basic " + x);
}
var digestfull = PropertiesService.getScriptProperties().getProperty("digest");
var headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"method": "GET",
"headers": {
"Authorization": digestfull
},
"muteHttpExceptions": true
};
var resp = UrlFetchApp.fetch(url, headers);
if (resp.getResponseCode() != 200) {
Browser.msgBox("Error retrieving data for url" + url + ":" + resp.getContentText());
return "";
} else {
json = resp.getContentText();
}
pri_list = JSON.parse(json);
return pri_list;
}

Related

can I be shown how to fix my syntax error : "unexpected token var line 65"?

(1:) I am writing a webhook script. (2:) Using "google sheets" and it's script editor. It is not liking how I used the below syntax.
`function sendMessage(message, channel)
{
if(webhooks(channel))
var url = webhooks[channel];
else {
Logger.log("Error Sending Message to Channel " + channel);
return "NoStoredWebhookException";
}
var payload = JSON.stringify({content: message});
Logger.log(options, null, 2);
UrlFetchApp.fetch("https://discord.com/api/webhooks/1069728124704653413/_h9KQdxqenUWGSSE5xR91QgBU28bdcUcY2yGslu83KezXvUTEv7BlJzvYo-mVTBv5_ye", options);
var webhooks = {
test: "Obtain a webhook for the channel you'd like and put it here."
var params = {
headers: {"Content-Type": "application/x-www-form-urlencoded"},
method: "POST",
payload: payload,
muteHttpExceptions: true
};
var res = UrlFetchApp.fetch(url, params);
Logger.log(res.getContentText());
}`
You didn't close the second brace on the webhooks object
var webhooks = {
test: "Obtain a webhook for the channel you'd like and put it here."
}

Changing json file creation destination from dropbox to google drive

i need to have this code have the create the json file inside of google drive instead of drop box
I have experimented with a few things but i am not quite knowledgeable enough to make this change, i would show less code but i do not know where the problem lies
function main(spreadsheet_id) {
var json_dict = fillDict(spreadsheet_id)
var json_obj = convertDictToJSON(json_dict)
sendJSONToDropbox(json_obj)
};
function sendJSONToDropbox(json_object) {
var timestamp = timeStamp()
var parameters = {
"path": "/json_jobs/rhino" + "-" + timestamp + ".json",
"mode": "add", // do not overwrite
"autorename": true,
"mute": false // notify Dropbox client
};
var headers = {
"Content-Type": "application/octet-stream",
'Authorization': 'Bearer ' + 'dropbox_access_token',
"Dropbox-API-Arg": JSON.stringify(parameters)
};
var options = {
"method": "POST",
"headers": headers,
"payload": json_object
};
var API_url = "https://content.dropboxapi.com/2/files/upload";
var response = JSON.parse(UrlFetchApp.fetch(API_url, options).getContentText());
Using the DriveApp class, it is not too difficult:
function sendJSONToGDrive(json_object) {
var timestamp = timeStamp();
var fileName = "rhino" + "-" + timestamp + ".json";
var fileContent = JSON.stringify(json_object);
var myFolder = DriveApp.getFolderById('YOUR_FOLDER_ID');
myFolder.createFile(fileName, fileContent, 'application/json');
}
You just have to replace YOUR_FOLDER_ID for your actual destination folder's id.
For more information on how to use the Drive API from Google Apps Script, I recommend you check out the following link: https://developers.google.com/apps-script/reference/drive

Spotify API authorisation via Google Apps Script

I am using the following code to make requests to the Spotify API via Google Apps Script:
function search() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var artist = sheet.getRange(1,1).getValue();
artist = encodeURIComponent(artist.trim());
var result = searchSpotify(artist);
Logger.log(result);
}
function searchSpotify(artist) {
//searches spotify and returns artist ID
var response = UrlFetchApp.fetch("https://api.spotify.com/v1/search?q=" + artist + "&type=artist&limit=1",
{ method: "GET",
headers:{
"contentType": "application/json",
'Authorization': "Bearer BQBnpSUdaEweirImw23yh2DH8OGhTwh5a_VnY_fgb2BPML0KvFvYd04CaEdUhQN9N4ZUXMIVfJ1MjFe1_j0Gl0UoHDhcoC_dklluZyOkq8Bo6i2_wfxSbGzP3k5EUjUKuULAnmTwCdkdZQnl-SNU0Co"
},
});
json = response.getContentText();
var data = JSON.parse(json);
var uri = data.artists.items[0].uri.slice(15);
var getArtists = getRelatedArtists(uri);
Logger.log(getArtists);
return getArtists;
}
function getRelatedArtists(uri) {
//searches related artists with the returned ID
var response = UrlFetchApp.fetch("https://api.spotify.com/v1/artists/" + uri + "/related-artists",
{ method: "GET",
headers:{
"contentType": "application/json",
'Authorization': "Bearer BQBnpSUdaEweirImw23yh2DH8OGhTwh5a_VnY_fgb2BPML0KvFvYd04CaEdUhQN9N4ZUXMIVfJ1MjFe1_j0Gl0UoHDhcoC_dklluZyOkq8Bo6i2_wfxSbGzP3k5EUjUKuULAnmTwCdkdZQnl-SNU0Co"
},
});
json = response.getContentText();
var data = JSON.parse(json);
var listArtists = [];
for(var i = 0, len = data.artists.length; i < len; i++){
listArtists.push(data.artists[i].name);
}
return listArtists;
}
This works fine using the temporary Authorisation token from the Spotify website but this token refreshes every hour and so is obviously useless.
I am trying to use my own Authorisation token and ID which I have setup on Spotify however I'm struggling to make this work. As I understand it I may need to add an extra step at the beginning to start the authorisation process but I've tried all methods suggested but keep receiving server errors.
From the document, it seems that "Client Credentials Flow" uses the basic authorization.
In order to use this, at first, you are required to retrieve "client_id" and "client_secret".
Sample script:
var clientId = "### client id ###"; // Please set here.
var clientSecret = "### client secret ###"; // Please set here.
var url = "https://accounts.spotify.com/api/token";
var params = {
method: "post",
headers: {"Authorization" : "Basic " + Utilities.base64Encode(clientId + ":" + clientSecret)},
payload: {grant_type: "client_credentials"},
};
var res = UrlFetchApp.fetch(url, params);
Logger.log(res.getContentText())
From curl sample, grant_type is required to send as form.
Result:
The document says that the response is as follows.
{
"access_token": "NgCXRKc...MzYjw",
"token_type": "bearer",
"expires_in": 3600,
}
Note:
This is a simple sample script. So please modify this for your situation.
I prepared this sample script by the sample curl in the document.
Reference:
Client Credentials Flow
Edit:
As your next issue, you want to retrieve the access token from the returned value. If my understanding is correct, how about this modification? Please modify my script as follows.
From:
Logger.log(res.getContentText())
To:
var obj = JSON.parse(res.getContentText());
Logger.log(obj.access_token)
When the value is returned from API, it returns as a string. So it is required to parse it as an object using JSON.parse().

Stackdriver Logging API returns response code 200, but response is empty

I'm trying to fetch stackdriver logs via Stackdriver Logging API v2. I do this by making a POST request from google apps script project, in particular using UrlFetchApp. The thing is, it runs successfully, but the response shown in log is empty. However, when I made the same request using apirequest.io, curl and Google API explorer, I got the necessary response.
I searched extensively, but to no avail. Tried experimenting with header, url, but nothing.
function exportLogs () {
var options = {
"method" : "post",
"headers": {Authorization: 'Bearer ' + ScriptApp.getOAuthToken()},
"resourceNames": [
"projects/MyProject"
],
"pageSize": 1,
}
var response = UrlFetchApp.fetch('https://logging.googleapis.com/v2/entries:list?key=MyApiKey', options)
Logger.log(response)
}
What I want to get is some logs, but I'm only getting {}
Issue:
Unacceptable keys are used in options object.
Solution:
payload is the only acceptable parameter for including request body.
Code:
function exportLogs() {
var options = {
method: "post",
headers: { Authorization: 'Bearer ' + ScriptApp.getOAuthToken() }, //Include https://www.googleapis.com/auth/cloud-platform in scopes
payload: JSON.stringify({
resourceNames: ['projects/[PROJECT_ID]'],
pageSize: 1,
}),
};
var response = UrlFetchApp.fetch(
'https://logging.googleapis.com/v2/entries:list?key=MyApiKey',
options
);
Logger.log(response);
}
To Read:
Urlfetch#params
Logging api#entriesList
Setting scopes
For some strange reason, adding an orderBy sort property in the request body object is the only way I could get results to be retrieved.
Also, a filter should be added to get only Apps Script logs.
load.filter = 'resource.type="app_script_function"';//Only from Apps Script
See example code at GitHub:
Apps Script Download Stackdriver Logs
Code:
function exportStackdriverLogs() {
var id,load,options,param,response;
id = 'Enter your Cloud Project ID here';//See your console at:
//https://console.cloud.google.com/iam-admin/settings
param = "projects/" + id;
load = {};
load.resourceNames = [param];
load.orderBy = "timestamp desc";
load.filter = 'resource.type="app_script_function"';//Only get logs that
//came from Apps Script
load.pageSize = 1;//You will probably want more than 1 but this is for an example
options = {};
options.method = "post";
options.headers = { Authorization: 'Bearer ' + ScriptApp.getOAuthToken() };
options.payload = JSON.stringify(load);
options.muteHttpExceptions = true;
options.contentType = "application/json";
response = UrlFetchApp.fetch('https://logging.googleapis.com/v2/entries:list',options);
//Logger.log('response: ' + response.getResponseCode())
//Logger.log('content: ' + response.getContentText())
}

Basecamp json api post todo

Tried to learn the json api for Basecamp.
Get requests are working fine for me, but I cant seem to get the post requests to work.
Using Google Script.
Can anyone see the bug? I keep getting a 403, even though I am owner of the account and the project
function createBaseCampTodo(user, pw, email, appName, accountNumber,
projectNumber,todolistNumber) {
var url = "https://basecamp.com/"+accountNumber+"/api/v1/projects/"
+projectNumber+"/todolists/"+todolistNumber+"/todos.json";
var headers = {
"User-Agent": appName + " ("+email+")",
"contentType": "application/json",
"Authorization": "Basic " +
Utilities.base64Encode(user + ":" + pw)
};
var data = {
"content": "This is my new thing!",
"due_at": "2015-03-27"
};
var params = {
"method":"post",
"headers":headers,
"validateHttpsCertificates" :false,
//"muteHttpExceptions" : true,
"payload" : JSON.stringify(data)
};
var response = UrlFetchApp.fetch(url, params);
var text = response.getContentText();
Logger.log(text);
}
Buddy of mine found the bug. It should say Content-Type instead of contentType.
Points to him for his sharp mind and eyes.