G-Sheet script to post a message on Guilded using its API - api

I am trying to create a script to post a text message in a chat on Guilded, but so far I get a "POST is not allowed"
Message should be "inPrivate" so a mention of the targeted member is required.
Google sheet test file
my script:
function message () {
var url = "https://www.guilded.gg/api/v1/channels/";
var channelid = "d2ba*****";
var key = "Bearer gapi_*****"; //Q-P API temp-bot
const message = {
content : "It's alive!",
embeds :[{
author:"API",
mentions:"Raven_test",
}],
isPrivate : true,
}
const params = {
method: "POST",
headers: { Authorization: key },
contentType: "application/json",
payload: JSON.stringify(message),
muteHttpExceptions: true,
};
Logger.log(JSON.stringify(params));
const response = UrlFetchApp.fetch(url + channelid + "/messages/", params);
var data = JSON.parse(response);
Logger.log(data);
}
Guilded's API
I don't understand what I'm doing wrong (but I'm a newbie, so it makes sens)

POST is still not working, with the same answer, however, if I use the PUT method, I can update a message if written by the same bot (I just need to add the messageid in the url after /messages/
function postmessage () {
var url = "https://www.guilded.gg/api/v1/channels/";
var channelid = "d2bac803-****-****-****-a609ab9c58c4";
var key = "Bearer gapi_******"; //Q-P API temp-bot
var server = "wlVKV***"
var messageid = "ae6f1693-****-****-****-c9984d4142de";
var author = "****";
const message = {
"type": "default",
"serverId":server,
"channelId":channelid,
"content" : "test #Aaron Raven ",
"mentions":{
"users" : [{"id":author}]
},
"isPrivate":false,
"isSilent":false
};
const params = {
method: "put",
headers: { Authorization: key },
contentType: "application/json",
payload: JSON.stringify(message),
muteHttpExceptions: true,
};
Logger.log(JSON.stringify(params));
// const response = UrlFetchApp.fetch(url + channelid + "/messages/" + messageid, params);
const response = UrlFetchApp.fetch(url + channelid + "/messages/" params);
var data = JSON.parse(response);
Logger.log(response);
Logger.log(data);
Logger.log(params);
}
Another issue (aside POST method) is that "mentions" doesn't work; it appears as basic text, and not as a user tag/link
Kind regards,

Related

How to use Nuxt 3 server as a passthrough API with FormData to hide external endpoints

I'm trying to get my head around the Nuxt /server API and can't seem to figure out how to send a POST request with form-data (ie files) to Nuxt server to forward on to an external service:
In my pages.vue file I have this method:
async function onSubmit() {
const formData = new FormData();
for (let file of form.files) {
await formData.append("image", file);
}
await $fetch("/api/send", {
method: "POST",
body: formData
});
}
and then in /server/api/send.js I have:
export default defineEventHandler(async (event) => {
const { method } = event.node.req;
// I THINK THE ISSUE IS HERE
const body =
method !== "GET" && method !== "HEAD"
? await readMultipartFormData(event)
: undefined;
const response = await $fetch.raw(https://*******, {
method,
baseURL: *********,
headers: {
},
body: body
});
return response._data;
}
I'm effectively creating a passthrough API using Nuxt so that the external endpoint isn't exposed to the end user. Just can't figure out how to access the formData in the correct format to pass through on the server side. I don't think I am supposed to use readMultipartFormData() because that seems to be parsing the data somehow whereas I just want to pass the formData straight through to the external API. Any tips?
I've tried using both readMultipartFormData() and readBody() and neither seem to work. I don't actually need to read the body but rather get it and pass it through without any formatting...
If you want to pass the data with formdata to the endpoint try this library:
https://www.npmjs.com/package/object-to-formdata
code:
import { serialize } from 'object-to-formdata';
const formData = serialize(body);
const response = await $fetch.raw(https://*******, {
method,
baseURL: *********,
headers: {
},
body: formData
});
I managed to make it work with ugly solution, first you have to update nuxt to version 3.2.0 min then here my front side
let jobApplicationDTO = {
firstName: values.firstName,
lastName: values.lastName,
email: values.email,
phoneNumber: values.phoneNumber,
company: values.company,
shortDescription: values.shortDescription
};
const formData = new FormData();
formData.append("application", new Blob([JSON.stringify(jobApplicationDTO)], {type: "application/json"}));
formData.append("file", values.file) ;
//formData.append("file", values.file );
await useFetch("/api/application", {
method: "POST",
body: formData,
onResponse({request, response, options}) {
// Process the response data
if (response.status === 200) {
errorMessage.value = "";
successMessage.value = "Your application wa sent successfully, you will be contacted soon !";
}
},
onResponseError({request, response, options}) {
console.debug(response);
if (response.status === 400) {
successMessage.value = "";
errorMessage.value = "There may be an issue with our server. Please try again later, or send an email to support#mantiq.com";
} else {
successMessage.value = "";
errorMessage.value = "Sorry we couldn’t send the message, there may be an issue with our server. Please try again later, or send an email to support#mantiq.com";
}
},
});
}
and server side
import {FormData} from "node-fetch-native";
export default defineEventHandler(async (event) => {
const {BACKEND_REST_API, ENQUIRY_TOKEN} = useRuntimeConfig();
//retrieve frontend post formData
const form = await readMultipartFormData(event);
const applicationUrl = BACKEND_REST_API + '/job/apply'
console.log("url used for enquiry rest call :" + applicationUrl);
console.log("Job application token :" + ENQUIRY_TOKEN);
const formData = new FormData();
console.log(form);
if (form) {
formData.append(form[0].name, new Blob([JSON.stringify(JSON.parse(form[0].data))], {type: form[0].type}));
formData.append(form[1].name, new Blob([form[1].data], {type: form[1].type}), form[1].filename);
}
console.log(formData.values);
return await $fetch(applicationUrl, {
method: "POST",
body: formData,
headers: {
Authorization: ENQUIRY_TOKEN,
},
});
})
What is funny is on frontend you have to create a formData , then to get content and to recreate a formData from your previous formData converted in MultiFormPart[], i created a ticket on nuxt to see how to do it properly

Google Sheets Sentiment Analysis error over API key

Hi I've been trying to do some sentiment analysis from google sheets. Here is my code:
function getSentiment(text) {
var apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
var url = "https://language.googleapis.com/v1/documents:analyzeSentiment?key=" + apiKey;
var data = {
document: {
type: "PLAIN_TEXT",
content: text
}
};
var options = {
method: "post",
contentType: "application/json",
headers: {
"Authorization": "Bearer " + apiKey
},
payload: JSON.stringify(data)
};
var response = UrlFetchApp.fetch(url, options);
var result = JSON.parse(response.getContentText());
return result.documentSentiment.score;
}
Here is what comes up:
Error
Exception: Request failed for https://language.googleapis.com returned code 401. Truncated server response: { "error": { "code": 401, "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or othe... (use muteHttpExceptions option to examine full response) (line 18).
I think the key is right (changed here for obvious reasons) and enabled so I'm not sure where I go from here. Any ideas? Thanks

Getting error while framing request URL using appscript

I am trying to frame request for API using appscript.
var url_string = "https://*.cognitiveservices.azure.com/vision/v3.2/describe"
let body = {
'"url"':'"https://www.khwaahish.com/wp-content/uploads/2022/01/khwaahish-white-bg-logo.jpg"'
};
const headers = {
'method' : 'POST',
'Host':'imagealttextcreation.cognitiveservices.azure.com',
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key':'###',
'payload': body
};
var response = UrlFetchApp.fetch(url_string,headers)
Logger.log(response)
I am getting invalid request error. But the same thing is working when i try manually(attached image for same).
Am I missing something while forming this request in the appscript?
When tried manually using the browser the functionality works. i want help in correcting the request using appscript.
From the official document, in your script, how about the following modification?
Modified script:
var url_string = "https://*.cognitiveservices.azure.com/vision/v3.2/describe";
let body = { url: "https://www.khwaahish.com/wp-content/uploads/2022/01/khwaahish-white-bg-logo.jpg" };
const options = {
headers: { "Ocp-Apim-Subscription-Key": "###" }, // Please set your value.
payload: JSON.stringify(body),
contentType: "application/json"
};
var response = UrlFetchApp.fetch(url_string, options);
Logger.log(response.getContentText())
Reference:
fetch(url, params)

Rally API create ConversationPost

with the following code I'm trying to create new conversation post for Capability. But it says
Cannot parse input stream due to I/O error as JSON document: Parse error: expected '{' but saw '￿' [ chars read = >>>￿<<< ]
function createPost(objId, post) {
objId = "313878829904";
post = "<p>MindMap:Hello from GAS.</p>"
var url = "https://rally1.rallydev.com/slm/webservice/v2.0/conversationpost/create";
var payload = {
"ConversationPost": {
"Artifact": "/portfolioitem/capability/" + objId,
"Text": post
}
}
var method = "POST";
var options = optionsPost_(method, payload);
var response = UrlFetchApp.fetch(url, optionsPost_(method, options));
var content = JSON.parse(response.getContentText());
content.CreateResult.Errors.forEach(error => Logger.log(error));
}
function optionsPost_(method, payload) {
var rallyApiKey = "";
if (rallyApiKey != "") {
PropertiesService.getScriptProperties().setProperty("RallyApiKey", rallyApiKey);
} else {
rallyApiKey = PropertiesService.getScriptProperties().getProperty("RallyApiKey");
}
if (rallyApiKey == null) return null;
return {
headers: { "ZSESSIONID": rallyApiKey },
payload: payload,
method: method
};
}
I can't spot any problem.
Could you please help?
Thank you!
Petr
I thought that from your error message, the payload might be required to be sent as JSON data. If my guessing is correct, how about the following modification?
Modified script:
From:
return {
headers: { "ZSESSIONID": rallyApiKey },
payload: payload,
method: method
};
To:
return {
headers: { "ZSESSIONID": rallyApiKey },
payload: JSON.stringify(payload),
method: method,
contentType: "application/json"
};
Note:
In this modification, it supposes that the values of payload and rallyApiKey are valid values for using the API. Please be careful this.
When above modification was not the dierct solution of your issue, can you provide the official document of API you want to use? By this, I would like to confirm it.
Reference:
fetch(url, params) of Class UrlFetchApp
Thanks for the fast response.
With the following
var payload = {"ConversationPost":{"Artifact": "/portfolioitem/capability/"+objId,"Text": post}};
var method = "POST";
var options = optionsPost_(method, payload);
and
var options={
headers: { "ZSESSIONID": rallyApiKey },
payload: payload,
method: method,
contentType:"application/json"
};
It gives me
Cannot parse input stream due to I/O error as JSON document: Parse error: expected '{' but saw 'h' [ chars read = >>>h<<< ]
If I change it to
var options={
headers: { "ZSESSIONID": rallyApiKey },
payload: JSON.stringify(payload),
method: method,
contentType:"application/json"
};
It gives me
Cannot parse input stream due to I/O error as JSON document: Parse error: expected '}' but saw ',' [ chars read = >>>{"headers":{"ZSESSIONID":"_ycHaCSd2QZSf8kbkQ0R1yhjohUvSzUYas0caApHt2A"},<<< ]
Only documentation I use is this:
https://rally1.rallydev.com/slm/doc/webservice/objectModel.sp#ConversationPost
I can't find any difference but this actually started working.
I believe the problem was caused by combination of mistakes. I removed one problem but perhaps add another one.
Here is a code which works.
function createPost(objId, post) {
objId = '313878829908';
post = "<p>MindMap:Hello from GAS.</p>"
var url = "https://rally1.rallydev.com/slm/webservice/v2.0/conversationpost/create";
var payload = {'ConversationPost':{'Artifact': '/portfolioitem/capability/'+objId,'Text': post}};
var method = 'POST';
//var options = optionsPost_(method, payload);
var response = UrlFetchApp.fetch(url, optionsPost_(method, payload));
var content = JSON.parse(response.getContentText());
content.CreateResult.Errors.forEach(error => Logger.log(error));
}
function optionsPost_(method, payload) {
var rallyApiKey = "";
if (rallyApiKey != "") {
PropertiesService.getScriptProperties().setProperty("RallyApiKey", rallyApiKey);
} else {
rallyApiKey = PropertiesService.getScriptProperties().getProperty("RallyApiKey");
}
if (rallyApiKey == null) return null;
var options={
'headers': {'ZSESSIONID': rallyApiKey },
'payload': JSON.stringify(payload),
'method': method,
'contentType':'application/json'
};
return options;
}
Thanks Tanaike for your help. I really appreciate it.

Google Apps Script API rackspace DNS

I was able to run the API from the duncio Curl.
Then try from google Apps Script.
Part of Get the token WORKED, but then I can not make any more acion.
I put the code in case it helps show where I have the problem
function Token() {
var user = "USUARIO";
var apikey= "KEY";
var Url = "https://identity.api.rackspacecloud.com/v2.0/tokens";
var payload = {"auth":{"RAX-KSKEY:apiKeyCredentials":{"username": "mvillani","apiKey": apikey}}};
var opt = {
"contentType" : "application/json",
"method" : "POST",
"payload" : Utilities.jsonStringify(payload)
};
var response = UrlFetchApp.fetch(Url,opt);
var json = JSON.parse(response.getContentText());
var token=json.access.token.id
var user="NUMERO DE USUARIO"
var Url="https://dns.api.rackspacecloud.com/v1.0/829221/domains/3715127/clone?cloneName=mvilaclone3.com" ;
var opt = {
"Content-Type": "application/json",
"method" : "POST",
"X-Auth-Token": token,
"Accept": "application/json"
};
var response1 = UrlFetchApp.fetch(Url);
var json1 =response1.getContentText();
var c=2
}
Muchas Gracias !!!!
I found the solution:
var Url="https://dns.api.rackspacecloud.com/v1.0/829221/domains/" ;
var response1 = UrlFetchApp.fetch(Url, { "headers": { 'X-Auth-Token': Token }})