Why `time_range` doesn't work in request to Facebook API? - facebook

I try to get some data from Facebook Marketing API. The result I get are generally correct but I have problem with data. It seems like parametr time_range doesn't work.
https://graph.facebook.com/v2.7/act_<MY_ACT>/ads?fields=name,adcreatives{object_story_id},insights{spend,unique_clicks},effective_status&params=time_range={%22since%22:%222016-11-15%22,%22until%22:%222016-11-17%22}&limit=2000&access_token=<MY_TOKEN>
Result:
{
"data": [
{
"name": "xx",
"adcreatives": {
"data": [
{
"id": "xx"
}
]
},
"effective_status": "DISAPPROVED",
"id": "xx"
},
{
"name": "xx",
"adcreatives": {
"data": [
{
"id": "xx"
}
]
},
"insights": {
"data": [
{
"spend": xx,
"unique_clicks": "34",
"date_start": "2016-10-19",
"date_stop": "2016-11-17"
}
],
"paging": {
"cursors": {
"before": "MAZDZD",
"after": "MAZDZD"
}
}
},
"effective_status": "CAMPAIGN_PAUSED",
"id": "xx"
},...}
I tried encode it, write in different way, but each time the results are from the last month, so date_start is 2016-10-19 and date_stop is 2016-10-17, not from range I put as parametr in query. How can I fix it?
Edit:
I also tried instead of &params=time_range={%22since%22:%222016-11-15%22,%22until%22:%222016-11-17%22} something like &date_preset=yesterday (yesterday or other correct value listed in documentation) but still I get exact same dates...

You can use the following to get insights within certain time_range:
/act_<ACCT_ID>/insights?level=ad&time_range={"since":"2016-11-15","until":"2016-11-17"}

Related

GA4 (Google Analytics) sessions based on UTM params

I am trying to fetch sessions from GA4 which are relevant to specific UTM params.
In GA3 we were able to use segments (sessions::condition::ga:source==X;ga:medium==Y) but I can not find a way to do this on GA4.
POST https://analyticsdata.googleapis.com/v1beta/#{property}:runReport`
Payload like this:
body = {
"metrics": [
{
"name": "sessions::condition::ga:source==X;ga:medium==Y"
}
],
"dimensions": [
{
"name": "date"
}
],
"dateRanges": [
{
"startDate": '2022-01-01',
"endDate": '2022-01-30',
"name": "current_year"
}
]
}
Returns: Field sessions::condition::ga:source==X;ga:medium==Y is not a valid metric.. Is there a way to do this via new API?
Should I use dimension filter to achieve that? I need to query on both source&medium but it is not clear how do I do this?
"dimensionFilter": {
"filter": {
"fieldName": "firstUserMedium",
"stringFilter": {
"value": "Y"
}
}
}
A dimension filter on sessionSource & sessionMedium returns sessions that have those specific utm_source & utm_medium values. See the dimensions & metrics page for a description of these and other dimensions & metrics.
The needed dimension filter is similar to the following. See Dimension Filters in Creating a Report for more info.
"dimensionFilter": {
"andGroup": {
"expressions": [
{
"filter": {
"fieldName": "sessionSource",
"stringFilter": {
"value": "X"
}
}
},
{
"filter": {
"fieldName": "sessionMedium",
"stringFilter": {
"value": "Y"
}
}
}
]
}
},
Segments are not yet available today in the GA4 Data API.
I think you should check the dimensions and metrcis list for GA4 they dont start with ga
POST https://analyticsdata.googleapis.com/v1beta/properties/GA4_PROPERTY_ID:runReport
{
"dateRanges": [{ "startDate": "2020-09-01", "endDate": "2020-09-15" }],
"dimensions": [{ "name": "country" }],
"metrics": [{ "name": "activeUsers" }]
}
Also at this time i don't think it supports segments.

Return value of ads insights in graph api

I currently don't have any campaigns that have been launched with ACTIVE status in Facebook so whenever I try to query the insights endpoint I receive an empty array of data[] which doesn't allow me to do much.
I would like to know how a response would look for an adset that has been launched with an active status and actually contains insights' data, using a query like this one:
GET graph.facebook.com/v8.0/{adset_id}/insights?date_preset=lifetime&fields=reach,unique_ctr,cpm&access_token={access_token}
I think is that it might look something like this, but I would like to get the exact response structure:
{
"data": [
{
"name": "metric_name",
"values": [
{
"end_time": "some_date_string",
"value": numeric_string,
}
]
}
]
}
I've made <adset_id>/insights?date_preset=lifetime&fields=reach,unique_ctr,cpm
Example output:
{
"data": [
{
"reach": "12739",
"unique_ctr": "1.420834",
"cpm": "13.740269",
"date_start": "2020-02-25",
"date_stop": "2021-01-28"
}
],
"paging": {
"cursors": {
"before": "MAZDZD",
"after": "MAZDZD"
}
}
}

Google Action / Dialogflow : how to ask for geolocation

I'm trying to implement a simple app for Google Assistant.
All works fine, but now I have a problem with the "permission" helper :
https://developers.google.com/actions/assistant/helpers#helper_intents
I have an intent connected with webhook to my java application. When an user types a sentence similar to "near to me", I want to ask to him his location and then use lat/lon to perform a search.
es: Brazilian restaurant near to me
my intent "searchRestaurant" is fired
I receive the webhook request and I parse it
if I find a parameter that is connected to a sentence like "near to me", so instead to response with a "Card" or a "List" I return a JSON that represent the helper request :
{
"conversationToken": "[]",
"expectUserResponse": true,
"expectedInputs": [
{
"inputPrompt": {
"initialPrompts": [
{
"textToSpeech": "PLACEHOLDER_FOR_PERMISSION"
}
],
"noInputPrompts": []
},
"possibileIntents": [
{
"intent": "actions.intent.PERMISSION",
"inputValueData": {
"#type": "type.googleapis.com/google.actions.v2.PermissionValueSpec",
"optContext": "Posso accedere alla tua posizione?",
"permission": [
"NAME",
"DEVICE_PRECISE_LOCATION"
]
}
}
]
}
]
}
but something seems to be wrong, and I receive an error:
"{\n \"responseMetadata\": {\n \"status\": {\n \"code\": 10,\n \"message\": \"Failed to parse Dialogflow response into AppResponse because of empty speech response\",\n \"details\": [{\n \"#type\": \"type.googleapis.com/google.protobuf.Value\",\n \"value\": \"{\\"id\\":\\"1cc45c5e-c398-4ea7-98a5-408f31ce142d\\",\\"timestamp\\":\\"2018-08-02T14:45:05.752Z\\",\\"lang\\":\\"it\\",\\"result\\":{},\\"alternateResult\\":{},\\"status\\":{\\"code\\":206,\\"errorType\\":\\"partial_content\\",\\"errorDetails\\":\\"Webhook call failed. Error: Failed to parse webhook JSON response: Cannot find field: conversationToken in message google.cloud.dialogflow.v2.WebhookResponse.\\"},\\"sessionId\\":\\"1533221100163\\"}\"\n }]\n }\n }\n}"
The "conversationToken" is filled, so I don't understand the error message.
Maybe I'm trying to perform the operation in a wrong way.
So, which is the correct way to call this helper?
--> I've created a second intent "askGeolocation" that have "actions_intent_PERMISSION" as "Event", and ... if I understand correctly the documentation, should be trigger if the request for helper is correct.
How can I get this working?
UPDATE :
I find some example of the json response for ask permission and seems that it should be different from the one above that i'm using :
https://github.com/dialogflow/fulfillment-webhook-json/blob/master/responses/v2/ActionsOnGoogle/AskForPermission.json
{
"payload": {
"google": {
"expectUserResponse": true,
"systemIntent": {
"intent": "actions.intent.PERMISSION",
"data": {
"#type": "type.googleapis.com/google.actions.v2.PermissionValueSpec",
"optContext": "To deliver your order",
"permissions": [
"NAME",
"DEVICE_PRECISE_LOCATION"
]
}
}
}
}
}
so, i've implemented it and now the response seems to be good (no more error on parsing it), but i still receive an error on it validation :
UnparseableJsonResponse
API Version 2: Failed to parse JSON response string with 'INVALID_ARGUMENT' error: "permission: Cannot find field."
so, a problem still persist.
Anyone know the cause?
Thanks
After some tests i found the problem.
I was returning a wrong json repsonse with "permission" instead of "permissions":
"permission**s**": [
"NAME",
"DEVICE_PRECISE_LOCATION"
]
So the steps to ask for location are correct. I report them here as a little tutorial in order to help who is facing on it for the first time:
1) In DialogFlow, add some logic to your Intent, in order to understand when is ok to ask to user his location. In my case, i've added a "parameter" that identify sentences like "nearby" and so on.
2) When my Intent is fired i receive to my java application a request like this :
...
"queryResult": {
"queryText": "ristorante argentino qui vicino",
"action": "bycategory",
"parameters": {
"askgeolocation": "qui vicino",
"TipoRistorante": ["ristorante", "argentino"]
},
...
3) If "askgeolocation" parameter is filled, instead to return a "simple message" o other type of message, i return a json for ask the permission to geolocation :
{
"payload": {
"google": {
"expectUserResponse": true,
"systemIntent": {
"intent": "actions.intent.PERMISSION",
"data": {
"#type": "type.googleapis.com/google.actions.v2.PermissionValueSpec",
"optContext": "To deliver your order",
"permissions": [
"NAME",
"DEVICE_PRECISE_LOCATION"
]
}
}
}
}
}
4) You MUST have a second Intent that is configured with "actions_intent_PERMISSION " event :
No training phrases
No Action and params
No Responses
But with Fulfillment active :
5) Once your response arrive to Google Assistant this is the message that appear :
6) Now, if user answer "ok" you receive this json on your webhook :
{
"responseId": "32cf46cf-80d8-xxxxxxxxxxxxxxxxxxxxx",
"queryResult": {
"queryText": "actions_intent_PERMISSION",
"action": "geoposition",
"parameters": {
},
"allRequiredParamsPresent": true,
"fulfillmentMessages": [{
"text": {
"text": [""]
}
}],
"outputContexts": [{
"name": "projects/xxxxxxxxxxxxxxxxxxxxx"
}, {
"name": "projects/xxxxxxxxxxxxxxxxxxxxx",
"parameters": {
"PERMISSION": true
}
}, {
"name": "projects/xxxxxxxxxxxxxxxxxxxxx"
}, {
"name": "projects/xxxxxxxxxxxxxxxxxxxxx"
}, {
"name": "projects/xxxxxxxxxxxxxxxxxxxxx"
}, {
"name": "projects/xxxxxxxxxxxxxxxxxxxxx"
}],
"intent": {
"name": "projects/xxxxxxxxxxxxxxxxxxxxx",
"displayName": "geoposition"
},
"intentDetectionConfidence": 1.0,
"languageCode": "it"
},
"originalDetectIntentRequest": {
"source": "google",
"version": "2",
"payload": {
"isInSandbox": true,
"surface": {
"capabilities": [{
"name": "actions.capability.MEDIA_RESPONSE_AUDIO"
}, {
"name": "actions.capability.SCREEN_OUTPUT"
}, {
"name": "actions.capability.AUDIO_OUTPUT"
}, {
"name": "actions.capability.WEB_BROWSER"
}]
},
"requestType": "SIMULATOR",
"inputs": [{
"rawInputs": [{
"inputType": "KEYBOARD"
}],
"arguments": [{
"textValue": "true",
"name": "PERMISSION",
"boolValue": true
}],
"intent": "actions.intent.PERMISSION"
}],
"user": {
"lastSeen": "2018-08-03T08:55:20Z",
"permissions": ["NAME", "DEVICE_PRECISE_LOCATION"],
"profile": {
"displayName": ".... full name of the user ...",
"givenName": "... name ...",
"familyName": "... surname ..."
},
"locale": "it-IT",
"userId": "xxxxxxxxxxxxxxxxxxxxx"
},
"device": {
"location": {
"coordinates": {
"latitude": 45.xxxxxx,
"longitude": 9.xxxxxx
}
}
},
"conversation": {
"conversationId": "xxxxxxxxxxxxxxxxxxxxx",
"type": "ACTIVE",
"conversationToken": "[]"
},
"availableSurfaces": [{
"capabilities": [{
"name": "actions.capability.SCREEN_OUTPUT"
}, {
"name": "actions.capability.AUDIO_OUTPUT"
}, {
"name": "actions.capability.WEB_BROWSER"
}]
}]
}
},
"session": "projects/xxxxxxxxxxxxxxxxxxxxx"
}
that contains, name/surname and latitude/longitude. This information can be saved in your application, in order to not perform again this steps.
I hope this helps.
Davide
In your intent, you can ask for a parameter with a custom Entity. This you can do like this:
entity you can define as "near"
put all the synonyms for near for which you want to trigger location permission in this entity
do not mark this parameter as "required"
do not put any prompt
in the training phrases, add some phrases with this parameter
in your webhook, keep a check on the parameter, if present ask for permission if not continue.
add a permission event to another intent
do your post permission processing in that intent
Entity
Intent
I hope you get it.
There are samples on this topic specifically that guide you through exactly what's needed for requesting permissions in Node and Java.
Note: There are helper intents samples available in Node and Java as well.

Facebook Graph API Comments not returning

I am trying to get the comments on ratings from the Facebook API.
First I request a list of ratings for a page I own:
https://graph.facebook.com/v3.0/me/ratings?fields=open_graph_story?access_token=[access_token]
Response:
{
"data": [
{
"open_graph_story": {
"message": "The best place in the world(s), and this is to reach that limit in the facebook review.",
"start_time": "2018-05-24T22:56:23+0000",
"type": "pages.rates",
"data": {
"rating": {
"value": 5,
"scale": 5
},
"review_text": "The best place in the world(s), and this is to reach that limit in the facebook review.",
"is_hidden": false,
"language": "en"
},
"id": "1805660589743235"
}
},
{
"open_graph_story": {
"message": "Very good, not excellent though. Does Facebook change the created time if I edit this?",
"start_time": "2018-04-12T20:25:26+0000",
"type": "pages.rates",
"data": {
"rating": {
"value": 3,
"scale": 5
},
"review_text": "Very good, not excellent though. Does Facebook change the created time if I edit this?",
"is_hidden": false,
"language": "en"
},
"id": "106674383523012"
}
}
],
"paging": {
"cursors": {
"before": "MTAwMDA4OTc5MzQ4Mjc3Ojc3MzQwNTI3NjIwMTQyNAZDZD",
"after": "MTAwMDI1NDEzNTE3NzgxOjc3MzQwNTI3NjIwMTQyNAZDZD"
}
}
}
(I removed some superfluous fields)
Then I use the id from the open_graph_story to get the comments for a rating:
https://graph.facebook.com/v3.0/106674383523012/comments?access_token=[access_token]
Response:
{
"data": [
],
"paging": {
"cursors": {
"before": "WTI5dGJXVnVkRjlqZAFhKemIzSTZANVFF5T1RNeU1UUTVPRGszTWpNMU9qRTFNalkwT0RZAeE1qZAz0ZD",
"after": "WTI5dGJXVnVkRjlqZAFhKemIzSTZANVFE0TlRBM09URXlOamN5T1RreU9qRTFNamN5TURJek56ST0ZD"
}
}
}
It returns no data even though I can see comments on the actual rating when I visit the Facebook page. Why are no comments returned?
(Just to make sure that I had the correct permissions, I selected all the permissions possible in the graph api explorer.)

Getting Likes count of each posts on a fan page in Facebook

How do I get the 'like' count of a post on Facebook?
I got a link graph.facebook.com/userid_postid that says says I can do this. But How do I find the user or page ID and the ID of the post?
For example, if take any post on the fan page:
http://www.facebook.com/TipsLearnings of site http://adityabajaj.com
If I make a post on the fan page above, and people like the post, how would I get the number of likes of that post? I want to have that number available to show on a separate website.
You can use FQL
SELECT like_info.like_count, share_info.share_count, comment_info.comment_count FROM stream WHERE post_id = 'your_post_id'
You can get a list of most recent posts a fan page made by using /<PAGE_ID>/posts (which you can find for your page by navigating to http://graph.facebook.com/myown.easytipsandtricks, or just use the username) with a valid access token. From that, you get an object that looks like this:
"data": [
{
"id": "22092443056_115909438544849",
"from": {
"name": "Starbucks",
"category": "Food/beverages",
"id": "22092443056"
},
// ...
"shares": {
"count": 708
},
"likes": {
"data": [
{
"name": "Shanna Gonzales",
"id": "100000244536406"
}
],
"count": 17129
},
"comments": {
"count": 759
}
}
// ... and more posts
Accessing the count subfield of each of those fields should tell you shares, likes and comments, respectively.
You can get the comments/likes count without having to paginate by using the fields parameter in combination with likes.limit(1).summary(true). For example, a search api query for pizza below will give you all public posts and their likes count summarized:
https://graph.facebook.com/search?q=pizza&type=post&fields=id,name,likes.limit(1).summary(true)
results (truncated):
{
"data": [
{
"id": "47883936273_659693910762305",
"name": "Instagram",
"created_time": "2014-02-16T01:15:29+0000",
"likes": {
"data": [
{
"id": "100002243084532",
"name": "Yvette Martin"
}
],
"paging": {
"cursors": {
"after": "MTAwMDAyMjQzMDg0NTMy",
"before": "MTAwMDAyMjQzMDg0NTMy"
},
"next": "https://graph.facebook.com/47883936273_659693910762305/likes?limit=1&summary=1&after=MTAwMDAyMjQzMDg0NTMy"
},
"summary": {
"total_count": 13682
}
}
},
{
"id": "136336876521150_314001148754721",
"name": "Pizza Box Turns into Plates & Storage Unit!",
"created_time": "2014-02-15T21:20:00+0000",
"likes": {
"data": [
{
"id": "100005373008864",
"name": "Liliana Campoli"
}
],
"paging": {
"cursors": {
"after": "MTAwMDA1MzczMDA4ODY0",
"before": "MTAwMDA1MzczMDA4ODY0"
},
"next": "https://graph.facebook.com/136336876521150_314001148754721/likes?limit=1&summary=1&after=MTAwMDA1MzczMDA4ODY0"
},
"summary": {
"total_count": 2792
}
}
}