How can I use Google Apps Script in Unity? [duplicate] - unity3d

This question is about receiving POST request from somewhere. I'm looking for a google sheet script function that can take and handle data from the POST request in JSON format. Could you suggest any example?
The POST request is here:
https://script.google.com/macros/s/BOdirjv45Dn6FHrx_4GUguuS6NJxnSEeviMHm3HerJl4UsDBnDgfFPO/
{
"p1": "writeTitle",
"p2": [[URL]],
"p3": [[PIC_A]],
"p4": [[PIC_B]],
"p5": [[TITLE]]
}
application/json
doPost() doesn't work:
doPost(e) {
var json = JSON.parse(e.postData.contents);
Logger.log(json);
}

You want to retrieve the value from the request body as an object.
You have already deployed Web Apps.
If my understanding of your situation is correct, how about this modification?
Post and retrieved object:
As a sample, I used the following curl command to POST to Web Apps.
curl -L \
-H 'Content-Type:application/json' \
-d '{"p1": "writeTitle","p2": "[[URL]]","p3": "[[PIC_A]]","p4": "[[PIC_B]]","p5": "[[TITLE]]"}' \
"https://script.google.com/macros/s/#####/exec"
When above command is run, e of doPost(e) is as follows.
{
"parameter": {},
"contextPath": "",
"contentLength": 90,
"queryString": "",
"parameters": {},
"postData": {
"type": "application/json",
"length": 90,
"contents": "{\"p1\": \"writeTitle\",\"p2\": \"[[URL]]\",\"p3\": \"[[PIC_A]]\",\"p4\": \"[[PIC_B]]\",\"p5\": \"[[TITLE]]\"}",
"name": "postData"
}
}
The posted payload can be retrieved by e.postData. From above response, it is found that the value you want can be retrieved by e.postData.contents. By the way, when the query parameter and the payload are given like as follows,
curl -L \
-H 'Content-Type:application/json' \
-d '{"p1": "writeTitle","p2": "[[URL]]","p3": "[[PIC_A]]","p4": "[[PIC_B]]","p5": "[[TITLE]]"}' \
"https://script.google.com/macros/s/#####/exec?key=value"
value can be retrieved by e.parameter or e.parameters. And the payload can be retrieved by e.postData.contents.
Modified script:
In this modified script, the result can be seen at the Stackdriver, and also the result is returned.
function doPost(e) {
var json = JSON.parse(e.postData.contents);
console.log(json);
return ContentService.createTextOutput(JSON.stringify(json));
}
Note:
When you modified your script of Web Apps, please redeploy it as new version. By this, the latest script is reflected to Web Apps. This is an important point.
Reference:
Web Apps
Stackdriver Logging
If this was not what you want, I'm sorry.

Related

Firestore REST API use with appGyver Composer Pro

I´m trying the new appGyver Composer Pro with Google Firebase (without success). AppGyver uses REST API to get data on the database, but I can´t get it to work.
The database is very simple and has only two documents, so I´m using SoapUI and Postman to try differen uri´s to identify how to set Composer Pro:
So, using GET https://firestore.googleapis.com/v1/projects/{project}/databases/(default)/documents/{collection}/
This is the result of the request:
{"documents": [
{
"name": "projects/{project}/databases/(default)/documents/{collection}/{id}",
"fields": {
"Nombre": {"stringValue": "Cerros"},
"Resolucion": {"mapValue": {"fields": {
"Numero": {"stringValue": "22"},
"Entidad": {"stringValue": "Curaduria"},
"FechaResolucion": {"timestampValue": "2020-04-09T05:00:00Z"}
}}}
},
"createTime": "2020-04-10T13:11:35.364097Z",
"updateTime": "2020-04-10T13:11:35.364097Z"
},
{
"name": "projects/{project}/databases/(default)/documents/{collection}/{id}",
"fields": {
"Nombre": {"stringValue": "Urbanizacion Guayacanes"},
"Resolucion": {"mapValue": {"fields": {
"Numero": {"stringValue": "14"},
"Entidad": {"stringValue": "Municipio de Chinchina"},
"FechaResolucion": {"timestampValue": "2013-11-13T05:00:00Z"}
}}}
},
"createTime": "2020-04-09T14:29:09.633853Z",
"updateTime": "2020-04-09T14:29:09.633853Z"
}
]}
But if I use
https://firestore.googleapis.com/v1/projects/{project}/databases/(default)/documents/{collection}/?Nombre=Cerros
I get
{"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"Nombre\": Cannot bind query parameter. Field 'Nombre' could not be found in request message.",
"status": "INVALID_ARGUMENT",
"details": [ {
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [{"description": "Invalid JSON payload received. Unknown name \"Nombre\": Cannot bind query parameter. Field 'Nombre' could not be found in request message."}]
}]
}}
I get almost the same message (only the name of the field changes) using any of the following instead of ?Nombre=Cerros:
?"Nombre"="Cerros"
?"documents.Nombre"="Cerros"
?"documents.fields.Nombre"="Cerros"
Or using before ? any of the following:
:runQuery
search
What am I doing wrong?
I would really appreciate any help
Eduardo
P.D.
I tried on the REST API Explorer:
curl --request POST \
'https://firestore.googleapis.com/v1/projects/permisos-23395/databases/(default)/documents/Inmueble/:runQuery' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--data '{"structuredQuery":{"select":{"fields":[{"fieldPath":"Nombre"},{"fieldPath":"matInm"}]},"from":[{"collectionId":"Inmueble","allDescendants":false}],"where":{"fieldFilter":{"field":{"fieldPath":"Nombre"},"op":"EQUAL","value":{"stringValue":"Cerros"}}}}}' \
--compressed
And got
{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"structuredQuery\" at 'document': Cannot find field.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"field": "document",
"description": "Invalid JSON payload received. Unknown name \"structuredQuery\" at 'document': Cannot find field."
}
]
}
]
}
}
The endpoint you're using is meant for listing the documents of a collection, not for retrieving it's contents.
When you call https://firestore.googleapis.com/v1/projects/{project}/databases/(default)/documents/{collection}/ you're calling the method projects.databases.documents.list which as you saw returns a list of the documents belonging to that collection.
Afterwards you're trying to retrieve the document matching the restriction "Nombre=Cierros" using query parameters while pointing to the list endpoint, which is not a valid request.
If you actually want to retrieve the documents you would need to use one of the following:
To request for a single document you need to use the method projects.databases.documents.get with a get request to the endpoint https://firestore.googleapis.com/v1/projects/{project_id}/databases/{database_id}/documents/{document_path}. Where document path would be of the form {collection}/{documentId}.
To query documents based on a filter you need to use the method projects.databases.documents.runQuery supplying a request body in the format described in the documentation.
Thanks Happy-Monad. I followed your lead and got it to work:
There needs to be an Index by {collection} {query field}, created in addition to the default ones.
Never got it to work with the API EXPLORER, because it needs the collection id on the parent path, but :runQuery does not work if its in there.
:runQuery is requested with a POST call (not GET): https://firebase.google.com/docs/firestore/reference/rest#rest-resource:-v1.projects.databases.documents
The curl call that worked is as follows:
curl --request POST \
'https://firestore.googleapis.com/v1/projects/{database}/databases/(default)/documents:runQuery' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--data '{"structuredQuery":{"select":{"fields":[{"fieldPath":"Nombre"},{"fieldPath":"nicInm"}]},"from":[{"collectionId":"{collection}","allDescendants":true}],"where":{"fieldFilter":{"field":{"fieldPath":"Nombre"},"op":"EQUAL","value":{"stringValue":"Cerros"}}}}}' \
--compressed
It returns (JSON):
array [1]
0 {2}
document {4}
name : projects/{database}/databases/(default)/documents/{collection}/{document id}
fields {2}
nicInm {1}
stringValue : 17-00-01-0001
nameInm {1}
stringValue : Cerros
createTime : 2020-04-14T15:22:53.782673Z
updateTime : 2020-04-14T15:22:53.782673Z
readTime : 2020-04-14T16:04:55.392601Z

Facebook Messenger API Messenge Attachments example does not work

I have a problem with reproducing the second example https://developers.facebook.com/docs/messenger-platform/reference/attachment-upload-api#example_request
It is:
curl \
-F 'message={"attachment":{"type":"image", "payload":{"is_reusable":true}}}' \
-F 'filedata=#/tmp/shirt.png;type=image/png' \
"https://graph.facebook.com/v6.0/me/message_attachments?access_token=<PAGE_ACCESS_TOKEN>"
When I check the request with httpbin, I get:
{
"args": {},
"data": "",
"files": {
"filedata": ""
},
"form": {
"message": "{\"attachment\":{\"type\":\"image\", \"payload\":{\"is_reusable\"=true}}}",
"recipient": "{\"id\":\"2673203139464950\"}"
},
"headers": {
"Accept": "*/*",
"Content-Length": "474",
"Content-Type": "multipart/form-data; boundary=------------------------855a2be7cb07aa99",
"Host": "httpbin.org",
"User-Agent": "curl/7.58.0",
"X-Amzn-Trace-Id": "Root=1-5e71f6ce-edeb373f3e446e443e23f2e3"
},
"json": null,
"origin": "my.ip.ad.dr",
"url": "https://httpbin.org/post"
}
When I run it locally, I get
{
"error":{
"message":"(#100) Field message must be a valid json object with string keys",
"type":"OAuthException",
"code":100,
"fbtrace_id":"ABYTTCTcFg7DoXr8i8ySdJB"
}
}
My attempts to solve it by myself are unsuccessful, despite several days of effort.
I guess, the problem is really simple, but I need help.
By the way, in general I need python-requests way of uploading files to Facebook, thus, if I had one, I would not need curl solution.
Any help will be appreciated.
I was told to replace the equals sign with a colon and add backslashes, however, it does not seem to work:
$ curl \
> -F 'message:{\"attachment\":{\"type\":\"image\", \"payload\":{\"is_reusable\": true}}}' \
> -F 'filedata=#/tmp/shirt.png;type=image/png' \
> "https://graph.facebook.com/v6.0/me/message_attachments?access_token=<MY-TOKEN>"
Warning: Illegally formatted input field!
curl: option -F: is badly used here
You only want to replace the second equal sign with a colon, the one after is_reusable, otherwise the JSON you provide is not valid. The equal sign after message should stay, because it is required by curl. Check out the documentation for more details.
In your case you want to use the following:
-F 'message={"attachment":{"type":"image","payload":{"is_reusable":true}}}'

How to perform PATCH operation in Firebase APi?

The firebase doc sys this is how it is supposed to be done:
curl -X PATCH -d '{"last":"Jones"}' \
'https://[PROJECT_ID].firebaseio.com/users/jack/name/.json'
But I dont know how to convert this to a rest based request.
TO be clear I need to send a web request from javascript/java, hence I want to know what should be the body , and header and operation type for this request.
Can someone please help?
If you use the documentation for curl, you can figure out what that command line you showed is trying to tell you.
The HTTP method is: PATCH
The request body is: {"last":"Jones"}
The url is: https://[PROJECT_ID].firebaseio.com/users/jack/name/.json
Where PROJECT_ID is the name of your project. That's all there is to it.
You need teh following structure:
HTTP Request:
https://firestore.googleapis.com/v1/projects/*YOUPROJECT_ID*/databases/(default)/documents/users_admin/*DOCUMENT_ID*?**updateMask.fieldPaths=user_name&updateMask.fieldPaths=permisos.Administrador&updateMask.fieldPaths=user_email**
JSON Body (must be exactly the same structure and type as your database):
{
"fields": {
"user_name": { "stringValue": "Test Actualización 2" },
"permisos": {
"mapValue": {
"fields": {
"Administrador": {
"booleanValue": true
}
}
}
},
"user_email": { "stringValue": "veviboj548#eyeremind.com" }
}
}

Weird error with Facebook Messenger Platform/bot Welcome Confugration

I'm getting a weird error while configuring welcome message for my Messenger bot. I've been using the same code (as shown below) and it has just been working fine until last night. I tried it with both cURL and Postman. Neither of them works.
curl -X POST -H "Content-Type: application/json" -d '{
"setting_type":"call_to_actions",
"thread_state":"new_thread",
"call_to_actions":[
{
"message":{
"text":"Welcome to My Company!"
}
}
]
}' "https://graph.facebook.com/v2.6/<PAGE_ID>/thread_settings?access_token=<PAGE_ACCESS_TOKEN>"
Error message when executing the code above:
{"error":{"message":"(#100) Invalid keys \"message\" were found in param \"call_to_actions[0]\".","type":"OAuthException","code":100,"fbtrace_id":"Hn42Wa+hapI"}}%
I can confirm both PAGE_ID and PAGE_ACCESS_TOKEN are correct as trying to delete the welcome message with the following code works fine.
curl -X POST -H "Content-Type: application/json" -d '{
"setting_type":"call_to_actions",
"thread_state":"new_thread",
"call_to_actions":[
{
"message":{
"text":"Welcome to My Company!"
}
}
]
}' "https://graph.facebook.com/v2.6/<PAGE_ID>/thread_settings?access_token=<PAGE_ACCESS_TOKEN>"
Also, the code I'm using is exactly the same as shown on the Facebook official API doc. I don't understand why it's saying "message" is not a valid key. Is anyone experiencing the same problem? Did Facebook change their api?
Any help will be much appreciated!
The docs are now updated, you need to define your payload in payload parameter now (a UTF-8 encoded string), eg:
"call_to_actions":[
{
"payload":"USER_DEFINED_PAYLOAD"
}
]
Docs updated:
https://developers.facebook.com/docs/messenger-platform/thread-settings/greeting-text
Example:
curl -X POST -H "Content-Type: application/json" -d '{
"setting_type":"greeting",
"greeting":{
"text":"Welcome to My Company!"
}
}' "https://graph.facebook.com/v2.6/me/thread_settings?access_token=PAGE_ACCESS_TOKEN"
I get the same issue and fix it.
I think your json of request is
let messageData = {
"setting_type":"call_to_actions",
"thread_state":"new_thread",
"call_to_actions":[
{
"payload":"welcome_payload"
}
]
}
request({
url: 'https://graph.facebook.com/v2.6/me/thread_settings',
qs: {access_token:token},
method: 'POST',
json: {
messageData
}
}
but it will not work and log will say you have no "setting_type" = =a
try this one
request({
url: 'https://graph.facebook.com/v2.6/me/thread_settings',
qs: {access_token:token},
method: 'POST',
json: {
setting_type:"call_to_actions",
thread_state:"new_thread",
call_to_actions:[
{
"payload":"welcome_payload"
}
]
}
}
it work for me.
This error was due to an API change.
New call:
curl -X POST -H "Content-Type: application/json" -d '{
"setting_type":"call_to_actions",
"thread_state":"new_thread",
"call_to_actions":[{
"payload":"START"
}]
}' "https://graph.facebook.com/v2.6/<PAGE_ID>/thread_settings?access_token=<PAGE_TOKEN>"
Just add a payload like {"payload":"START"}
If a user press the "Getting started" button, you receive this payload in your messageHandler (webhook). Check if $incomingMessage == "START" and send back your structured message, or whatever you want.
Messages like before are not supported anymore.
Bug report: https://developers.facebook.com/bugs/1751749508372552/

how to create an issue in jira via rest api?

Is it possible to create an issue in jira using REST api? I didn't find this in the documentation (no POST for issues), but I suspect it's possible.
A wget or curl example would be nice.
POST to this URL
https://<JIRA_HOST>/rest/api/2/issue/
This data:
{
"fields": {
"project":
{
"key": "<PROJECT_KEY>"
},
"summary": "REST EXAMPLE",
"description": "Creating an issue via REST API",
"issuetype": {
"name": "Bug"
}
}
}
In received answer will be ID and key of your ISSUE:
{"id":"83336","key":"PROJECT_KEY-4","self":"https://<JIRA_HOST>/rest/api/2/issue/83336"}
Don't forget about authorization. I used HTTP-Basic one.
The REST API in JIRA 5.0 contains methods for creating tasks and subtasks.
(At time of writing, 5.0 is not yet released, although you can access 5.0-m4 from the EAP page. The doco for create-issue in 5.0-m4 is here).
As of the latest released version (4.3.3) it is not possible to do using the REST API. You can create issues remotely using the JIRA SOAP API.
See this page for an example Java client.
This is C# code:
string postUrl = "https://netstarter.jira.com/rest/api/latest/issue";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(postUrl);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("JIRAMMS:JIRAMMS"));
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = #"{""fields"":{""project"":{""key"": ""JAPI""},""summary"": ""REST EXAMPLE"",""description"": ""Creating an issue via REST API 2"",""issuetype"": {""name"": ""Bug""}}}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
To answer the question more direct, i.e. using cURL.
To use cURL to access JIRA REST API in creating a case, use
curl -D- -u <username>:<password> -X POST --data-binary "#<filename>" -H "Content-Type: application/json" http://<jira-host>/rest/api/2/issue/
And save this in your < Filename> (please edit the field per your Jira case) and save in the folder you call the cURL command above.
{
"fields": {
"project":
{
"key": "<PROJECT_KEY>"
},
"summary": "REST EXAMPLE",
"description": "Creating an issue via REST API",
"issuetype": {
"name": "Bug"
}
}
}
This should works. (note sometimes if it errors, possibly your content in the Filename is incorrect).
Now you can use REST + JSON to create issues.
To check which json fields you can set to create the issue use:
https://jira.host.com/rest/api/2/issue/createmeta
For more information please see the JIRA rest documentation:
https://docs.atlassian.com/jira/REST/6.2.4/
To send the issue data with REST API we need to construct a valid JSON string comprising of issue details.
A basic example of JSON string:
{“fields” : { “project” : { “key” : “#KEY#” } , “issuetype” : { “name” : “#IssueType#” } } }
Now, establish connection to JIRA and check for the user authentication.
Once authentication is established, we POST the REST API + JSON string via XMLHTTP method.
Process back the response and intimate user about the success or failure of the response.
So here JiraService being an XMLHTTP object, something like this will add an issue, where EncodeBase64 is a function which returns encrypted string.
Public Function addJIRAIssue() as String
With JiraService
.Open "POST", <YOUR_JIRA_URL> & "/rest/api/2/issue/", False
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "Accept", "application/json"
.setRequestHeader "Authorization", "Basic " & EncodeBase64
.send YOUR_JSON_STRING
If .Status <> 401 Then
addJIRAIssue = .responseText
Else
addJIRAIssue = "Error: Invalid Credentials!"
End If
End With
Set JiraService = Nothing
End Sub
You can check out a complete VBA example here
In order to create an issue, set a time estimate and assign it to yourself, use this:
Generate an Atlassian token
Generate & save a base64-encoded auth token:
export b64token="$(echo "<your_email>:<generated_token>" | openssl base64)"
Make a POST request:
curl -X POST \
https://<your_jira_host>.atlassian.net/rest/api/2/issue/ \
-H 'Accept: */*' \
-H 'Authorization: Basic $b64token \
-d '{
"fields":{
"project":{
"key":"<your_project_key (*)>"
},
"issuetype":{
"name":"Task"
},
"timetracking":{
"remainingEstimate":"24h"
},
"assignee":{
"name":"<your_name (**)>"
},
"summary":"Endpoint Development"
}
}'
Remarks:
(*) Usually a short, capitalized version of the project description such as: ...atlassian.net/projects/UP/.
(**) if you don't know your JIRA name, cURL GET with the same Authorization as above to https://<your_jira_host>.atlassian.net/rest/api/2/search?jql=project=<any_project_name> and look for issues.fields.assignee.name.
Just stumbling on this and am having issues creating an issue via the REST API.
issue_dict = {
'project': {'key': "<Key>"},
'summary': 'New issue from jira-python',
'description': 'Look into this one',
'issuetype': {'name': 'Test'},
}
new_issue = jira.create_issue(issue_dict)
new_issue returns an already existing issue and doesn't create one.