Facebook Messenger API Messenge Attachments example does not work - facebook

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

Related

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

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.

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

Salesforce Bulk Job CSV Upload via Google Apps Script UrlFetchApp

I'm attempting to use Google Apps Script to access Salesforce's Bulk API 2.0 and upload the CSV data to a job, however Salesfore is returning
[{"errorCode":"METHOD_NOT_ALLOWED","message":"HTTP Method 'GET' not allowed. Allowed are PUT"}]
Given my experience with the Salesforce API, I highly doubt the issue is actually with the method type, but that there is some other validation which is causing this error. However, upon inspection of the request body and comparing it to what I successfully submit through cURL, I don't see what I can do to resolve.
The request code:
var headers = {
"Authorization": "Bearer TOKEN"
};
var options = {
"method": "put",
"contentType": "text/csv",
"headers": headers,
"payload": "Id,Entity_Name__c\n001,One\n002,Two\n003,Three"
};
var url = INSTANCE + "/services/data/v44.0/jobs/ingest/" + JOB_ID + "/batches";
UrlFetchApp.fetch(url, options);
Google Apps Script request as returned via getRequest():
{
"headers": {
"Authorization": "Bearer TOKEN"
},
"method": "put",
"payload": "Id,Entity_Name__c\n001,One\n002,Two\n003,Three",
"followRedirects": true,
"validateHttpsCertificates": true,
"useIntranet": false,
"contentType": "text/csv",
"url": "INSTANCE/services/data/v44.0/jobs/ingest/JOB_ID/batches"
}
cURL request:
curl --request PUT \
--url INSTANCE/services/data/v44.0/jobs/ingest/JOB_ID/batches \
--header 'authorization: Bearer TOKEN' \
--header 'content-type: text/csv' \
--data '"Id,Entity_Name__c\n001,One\n002,Two\n003,Three"'
How can I resolve this?

Copy a public gdrive file to my account with curl

I tried to copy public gdrive files to my account by Gdrive API with a simple ps1 script and unix-tools for windows. (curl).
Worked out all required tokens and started to copy,download,delete files that I copied before.
The problem is, I found out that public shared files have different permissions
"capabilities": { "canCopy": true, "canEdit": false },
"editable": false, "copyable": true,
like this link for example:
drive.google.com/open?id=1ArIfiMSmBdlZQUm1cgHi8RRjhSCh8Rym
This is working fine by api request, but if I try to copy files with this permissions
"capabilities": { "canCopy": false, "canEdit": false },
"editable": false, "copyable": false,
drive.google.com/open?id=1cHAsF0D8zEp3LbVB4LmEQbJ3LdU8Cj7i
I get:
"reason": "forbidden",
"message": "Insufficient permissions for the specified parent.",
"locationType": "other",
"location": "parent.permissions" }],
"code": 403,
"message": "Insufficient permissions for the specified parent."
}
}
But in my browser I can rightclick taht file and simply make a copy.
So it seems just not possible by api requests.
But how can I do that by curl/http requests (with stored cookie or someting) ?
$UID = 'clientID.apps.googleusercontent.com'
$skey = 'clientsecret'
$readtoken = (Get-Content "$PSScriptRoot\refreshtoken.txt")
This is to create a fresh accesstoken from stored refreshtoken
$token = curl -d
"client_id=$UID&client_secret=$skey&refresh_token=$readtoken&grant_type=refresh_token"
https://accounts.google.com/o/oauth2/token | grep access_token
$string = $token.TrimStart(""access_token": `"")
$cleantoken = $string.TrimEnd("`",")
$drivefile = Read-Host -Prompt 'Put your Link here'
$driveID =
$drivefile.Substring(33)
$LINKS = curl --request POST
"https://www.googleapis.com/drive/v2/files/$driveID/copy" --header
"Authorization: Bearer $cleantoken" --header "Accept:
application/json" --header "Content-Type: application/json" --data
"{}" --compressed

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.