Create custom audience using Facebook API SDK - python

I have an access token for Facebook Audiences but I am not able to get create a custom audience using Python-SDK
First I get information about USER id using the following link:
https://developers.facebook.com/tools/debug/accesstoken
Than I use the following URL to list Ad ID's from my account:
https://graph.facebook.com/v3.2/MY_USER_ID/adaccounts
It returns a json with a list of act's like this:
{
"data": [
{
"account_id": "xxxx",
"id": "act_xxxx"
}
] }
With this ID I try to create a new audience:
from facebook_business.adobjects.adaccount import AdAccount
from facebook_business.adobjects.customaudience import CustomAudience
from facebook_business.api import FacebookAdsApi
id = 'act_xxxx'
FacebookAdsApi.init(access_token='MY TOKEN')
fields = [
]
params = {
'name': 'My new Custom Audience',
'subtype': 'CUSTOM',
'description': 'People who purchased on my website',
'customer_file_source': 'USER_PROVIDED_ONLY',
}
print(AdAccount(id).create_custom_audience(
fields=fields,
params=params,
))
Then the code produces the following error:
Unsupported post request. Object with ID 'act_xxxx' does not exist,
cannot be loaded due to missing permissions, or does not support this
operation.
I know that this ID exists because it was returned by the previous call. Debugging the access token I can see it has the following access:
read_insights, read_audience_network_insights, publish_video,
manage_pages, pages_manage_cta, pages_manage_instant_articles,
pages_show_list, publish_pages, read_page_mailboxes, ads_management,
ads_read, business_management, pages_messaging,
pages_messaging_phone_number, pages_messaging_subscriptions,
instagram_basic, instagram_manage_comments, instagram_manage_insights,
leads_retrieval
Can anyone help me to discover the reason of this error?
Thanks!

Related

Google API Cloud identity groups().create(): what is the field customer_id?

I would like to create a group using the API Cloud Identity and the command groups().create().
To do so, I'v used the example provided by Google:
def create_google_group(service, customer_id, group_id, group_display_name, group_description):
group_key = {"id": group_id}
group = {
"parent": "customers/" + customer_id,
"description": group_description,
"displayName": group_display_name,
"groupKey": group_key,
# Set the label to specify creation of a Google Group.
"labels": {
"cloudidentity.googleapis.com/groups.discussion_forum": ""
}
}
try:
request = service.groups().create(body=group)
request.uri += "&initialGroupConfig=WITH_INITIAL_OWNER"
response = request.execute()
print(response)
except Exception as e:
print(e)
But I got an issue:
<HttpError 400 when requesting https://cloudidentity.googleapis.com/v1/groups?alt=json&initialGroupConfig=WITH_INITIAL_OWNER returned "Invalid resource.parent". Details: "[{'#type': 'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations': [{'field': 'resource.parent', 'description': 'Invalid resource.parent'}]}]">
For the field customer_id, I tried without any success:
data from https://console.developers.google.com/
ID clients OAuth 2.0, ID_client: "XXXXXXXXXXXXXXXXX.apps.googleusercontent.com"
idem but only: "XXXXXXXXXXXXXXXXX"
project identifier: 'yyyy-yyyy-123456'
'me'
'my_email#example.com'
'my_customer'
Thank you in advance for your support to understand what is expected for the field customer_id!
You can find your customer ID through the Admin console.
https://support.google.com/a/answer/10070793?hl=en
There are several other ways to find it as well.
User Resource from AdminSDK (customerId field - docs)
Organization API for GCP customers (directoryCustomerId field - docs)

Google calendar api acl

I was trying to use API to make some changes on my google calendar.
I have created a project on google cloud console, enable calendar API, and got the credential ready. The OAuth scope I set is:
scopes = ['https://www.googleapis.com/auth/calendar']
flow = InstalledAppFlow.from_client_secrets_file("client_secret.json", scopes=scopes)
And I got both credentials for my account.
credentials = flow.run_console()
I wanted to use ACL to gain access to the calendar, so I tried "get" and "insert" these two functions. Codes are as follows:
rule = service.acl().get(calendarId='primary', ruleId='ruleId').execute()
print('%s: %s' % (rule['id'], rule['role']))
rule = {
'scope': {
'type': 'group',
'value': 'default',
},
'role': 'owner'
}
created_rule = service.acl().insert(calendarId='primary', body=rule).execute()
print(created_rule)
However, the results show that I have some problems with the access part.
<HttpError 400 when requesting https://www.googleapis.com/calendar/v3/calendars/primary/acl/ruleId?alt=json
returned "Invalid resource id value.">
and
<HttpError 400 when requesting https://www.googleapis.com/calendar/v3/calendars/primary/acl?alt=json
returned "Invalid scope value.">
what step have I miss or do wrong?
The first error shows up in Acl.get whenever you specify an invalid ruleId. So make sure you are providing a valid ruleId in here:
rule = service.acl().get(calendarId='primary', ruleId='valid-rule-id').execute()
If you don't know the ruleId, you can look for it by calling Acl.list.
About the second error, the problem is that you are providing a wrong request body for Acl.insert. If you want to share this calendar with a group, you should provide a valid email address of the group in scope.value. default is not a valid value. Your request body should be something like this:
rule = {
'scope': {
'type': 'group',
'value': 'group-email-address',
},
'role': 'owner'
}
You will find the group email address if you click About in the corresponding group.
I hope this is of any help.

Adding an Audience list to a campaign using google ads API

I'm trying to attach an audience list - which I have already created on Google ads using the python api - to an existing campaign on the same Google ads account. I have both the ID of the campaign and the ID of the audience list, but I did not find any clear example in the documentation on how to attach an audience list to campaign.
Can anyone provide example on how the json object to be sent to google ads is structured to request adding an audience list to a campaign?
I tried to follow the reference guidelines in the documentation to compose the request json format object needed to be sent to add an audience list to a certain campaign .
And also searched for similar problems, found this solution in Java,but I did not succeed into coming up with a similar one in python.
from googleads import adwords
import yaml
data = {} # should contain credentials for authentication
auth_data = yaml.dump(data)
client = adwords.AdWordsClient.LoadFromString(auth_data)
campaign_criterion_list_service = client.GetService(
'CampaignCriterionService', version='v201809')
operations = [
{
'operand': {
'campaignId': 1982314222, # some campaign in my account
'criterion': {
'type': 'USER_LIST',
'id': 823895895,# an existing audience list on my google ads account
},
'campaignCriterionStatus': 'ACTIVE'
},
'operator': 'ADD',
}
]
campaign_criterion_list_service.mutate(operations)
But it fails providing the error
GoogleAdsServerFault: [CampaignCriterionError.CONCRETE_TYPE_REQUIRED # operations[0].operand.criterion]
I expected the audience list to be added to the campaign and return a success code.
I think I figured it out . Just needed to adjust the naming of the expected fields
campaign_criterion_list_service = client.GetService(
'CampaignCriterionService', version='v201809')
operations = [
{
'operand': {
'campaignId': 1764074348,
'criterion': {
'xsi_type': 'CriterionUserList',
'type': 'USER_LIST',
'userListId': 823895895,
'userListEligibleForDisplay': True,
'userListEligibleForSearch': True
},
'campaignCriterionStatus': 'ACTIVE'
},
'operator': 'ADD',
}
]

while creating the runbook as draft using azure REST api in python i am facing the error...!

I need to create Azure Automation account, and I want to create run book under automation account for auto-scheduling the VM's
Steps I followed for creating Azure automation account.
creating cloud service using API
https://management.core.windows.net/sdjgsdgj-abcd-2323-98cd-3bd6bcf93702/cloudServices/cloudsername
Next step, is I am creating Azure automation account under the created cloud service using above api.
https://management.core.windows.net/sdjgsdgj-abcd-2323-98cd-3bd6bcf93702/cloudServices/cloudsername/resources/automation/AutomationAccount/testacc2?resourceType=AutomationAccount&detailLevel=Full&resourceProviderNamespace=automation'
After that, i want to create runbook under that create automation account for this I am using the below API in Python
import adal
import requests
import json
token_response = adal.acquire_token_with_username_password(
'https://login.windows.net/rapiddirectory.onmicrosoft.com',
'test#xyz.onmicrosoft.com',
'abcd'
)
access_token = token_response.get('accessToken')
create_run_draft = 'https://management.core.windows.net/sdjgsdgj-abcd-2323-98cd-3bd6bcf93702/cloudServices/cloudsername/resources/automation/~/automationAccounts/testacc2/runbooks/write-helloworld/draft?api-version=2014-12-08'
param3 = {
"tags":{
"Testing":"show value",
"Source":"TechNet Script Center"
},
"properties":{
"description":"Hello world",
"runbookType":"Script",
"logProgress":"false",
"logVerbose":"false",
"draft":{
"draftContentLink":{
"uri":"https://gallery.technet.microsoft.com/scriptcenter/The-Hello-World-of-Windows-81b69574/file/111354/1/Write-HelloWorld.ps1",
"contentVersion":"1.0.0.0",
"contentHash":{
"algorithm":"sha256",
"value":"EqdfsYoVzERQZ3l69N55y1RcYDwkib2+2X+aGUSdr4Q="
}
}
}
}
}
headers2 = {'x-ms-version' : '2013-06-01','Content-Type' : 'application/json',"Authorization": 'Bearer ' + access_token}
output = requests.put(create_run_draft,headers=headers2,data=param3).text
print output
I am using Python programming language to achieve this for Azure REST API
I am getting the below error
<Error xmlns="http://schemas.microsoft.com/windowsazure" xmlns:i="http://www.w3.
org/2001/XMLSchema-instance"><Code>InternalError</Code><Message>The server encou
ntered an internal error. Please retry the request.</Message></Error>
Please help me out of this problem I am struggling with error
Could be because you are passing the values of logProgress and logVerbose as strings ("false") instead of as booleans (false).
This worked for me:
Create runbook:
PUT https://management.core.windows.net/90751b51-7cb6-4480-8dbd-e199395b296f/cloudservices/OaaSCS/resources/automation/~/automationAccounts/JoeAutomationAccount/runbooks/testabc?api-version=2014-12-08
Request body:
{
"properties": {
"logVerbose": false,
"logProgress": false,
"runbookType": "Script",
"draft": {
"inEdit": false,
"creationTime": "0001-01-01T00:00:00+00:00",
"lastModifiedTime": "0001-01-01T00:00:00+00:00"
}
},
"name": "testabc"
}
Upload draft content:
PUT https://management.core.windows.net/90751b51-7cb6-4480-8dbd-e199395b296f/cloudservices/OaaSCS/resources/automation/~/automationAccounts/JoeAutomationAccount/runbooks/testabc/draft/content?api-version=2014-12-08
Request body:
workflow testabc {
"hello"
}

Getting my wall posts or friends from Facebook - lists are empty

I performed following:
installed 2 kinds of the Facebook APIs: pip install facebook and pip install fb
Went to https://developers.facebook.com/tools/access_token/, registered my app and got User Token (some long string, used currently as hardcoded in the code, I'll change it later)
Created the following code (please see comments what and how works or doesn't:
import re
import urllib2
import requests
import facebook
import fb
token="User Token"
graph = facebook.GraphAPI(token)
profile = graph.get_object("me") #POSITIVE: I can get profile info
friends = graph.get_connections('me', "friends") #POSITIVE: I can get real friends count, NEGATIVE - the list itself is empty
posts = graph.get_connections('me', "posts") #NEGATIVE - the list itself is empty, no count is returned, as in "friends" case
feed= graph.get_connections('me', "feed") #NEGATIVE - the list itself is empty, no count is returned, as in "friends" case
fb1=fb.graph.api(token)
profile = fb1.get_object(cat='single', id="me") #NEGATIVE - error in given parameters
To be sure I used also https://developers.facebook.com/tools/explorer with the same token and got the same results:
GET me\friends:
{
"data": [
],
"summary": {
"total_count": 575
},
}
GET me\feed:
{
"data": [
],
}
Why the returned lists are empty?
Thanks!
Update: I found that I have no permissions, only those. How to get more? and why with permission "friends" I can't see info about them, but only total number of them?
{
"data": [
{
"permission": "user_friends",
"status": "granted"
},
{
"permission": "public_profile",
"status": "granted"
}
],
}
Resolved: I found where the problem! I didn't get app token with all permissions. Perform the following:
Go to the https://developers.facebook.com/tools/explorer
Choose your APP name (my is lj_for_me in attached image)
Press "Get User Token" and check all boxes (or what you really need).
Now you APP will have permission to get post and photos and etc from YOUR FB account. For getting the same from other users accounts you need to get such permission from FB (as far as I understood, but I did not enter too deep into this subject)
Since v2.0 of the Graph API, you can only get friends who authorized your App with the user_friends permission too, for privacy reasons. You only get the total_count if none of your friends authorized the App.
Access to wall posts is possible with the user_posts permission, btw.

Categories