I am getting an error when using the facebook api - python

File "SAMPLE_CODE.py", line 21, in <module>
from facebookads.adobjects.adaccount import AdAccount
File "/usr/local/lib/python3.7/site-packages/facebookads/adobjects/adaccount.py", line 1582
def get_insights(self, fields=None, params=None, async=False, batch=None, pending=False):
^
SyntaxError: invalid syntax
I am trying to use the Facebook API and I am getting this error. Not sure what to do about it. This is my first time setting up and trying to use this API. Any help would be appreciated
Here is the file I am trying to run
"""python
# Copyright 2014 Facebook, Inc.
# You are hereby granted a non-exclusive, worldwide, royalty-free license to
# use, copy, modify, and distribute this software in source code or binary
# form for use in connection with the web services and APIs provided by
# Facebook.
# As with any software that integrates with the Facebook platform, your use
# of this software is subject to the Facebook Developer Principles and
# Policies [http://developers.facebook.com/policy/]. This copyright notice
# shall be included in all copies or substantial portions of the software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
from facebookads.adobjects.adaccount import AdAccount
from facebookads.adobjects.adsinsights import AdsInsights
from facebookads.api import FacebookAdsApi
access_token = 'token'
ad_account_id = 'id'
app_secret = 'secret'
app_id = 'id'
FacebookAdsApi.init(access_token=access_token)
fields = [
'reach',
'delivery',
'cost_per_result',
'cpp',
'cpm',
'cost_per_action_type:page_engagement',
'purchase_roas:omni_purchase',
'website_purchase_roas:offsite_conversion_fb_pixel_purchase',
'mobile_app_purchase_roas:app_custom_event_fb_mobile_purchase',
'campaign_group_name',
]
params = {
'level': 'ad',
'filtering': [{'field':'delivery_info','operator':'IN','value':['active']}],
'breakdowns': ['days_1'],
'time_range': {'since':'2019-11-14','until':'2019-11-21'},
}
print(AdAccount(ad_account_id).get_insights(
fields=fields,
params=params,
))
"""
Here is another stack overflow question where async= False is the error too
Problem with connect facebookads library for extract data from Facebook with Marketing API using Python
Could someone explain what is going on here ?
Thanks
I downloaded version 3.6 of Python using pyenv and Homebrew and tried to run the file again but I got a new error code.
"""
Kiefer's Macbook Pro:facebook-python-business-sdk kiefergallant$ python3.6 SAMPLE_CODE.py
/Users/kiefergallant/.pyenv/versions/3.6.0/lib/python3.6/site-packages/facebookads/utils/api_utils.py:30: UserWarning: value of breakdowns might not be compatible. Expect list<breakdowns_enum>; got <class 'list'>
warnings.warn(message)
/Users/kiefergallant/.pyenv/versions/3.6.0/lib/python3.6/site-packages/facebookads/utils/api_utils.py:30: UserWarning: insights does not allow field delivery
warnings.warn(message)
/Users/kiefergallant/.pyenv/versions/3.6.0/lib/python3.6/site-packages/facebookads/utils/api_utils.py:30: UserWarning: insights does not allow field cost_per_result
warnings.warn(message)
/Users/kiefergallant/.pyenv/versions/3.6.0/lib/python3.6/site-packages/facebookads/utils/api_utils.py:30: UserWarning: insights does not allow field cost_per_action_type:page_engagement
warnings.warn(message)
/Users/kiefergallant/.pyenv/versions/3.6.0/lib/python3.6/site-packages/facebookads/utils/api_utils.py:30: UserWarning: insights does not allow field purchase_roas:omni_purchase
warnings.warn(message)
/Users/kiefergallant/.pyenv/versions/3.6.0/lib/python3.6/site-packages/facebookads/utils/api_utils.py:30: UserWarning: insights does not allow field website_purchase_roas:offsite_conversion_fb_pixel_purchase
warnings.warn(message)
/Users/kiefergallant/.pyenv/versions/3.6.0/lib/python3.6/site-packages/facebookads/utils/api_utils.py:30: UserWarning: insights does not allow field mobile_app_purchase_roas:app_custom_event_fb_mobile_purchase
warnings.warn(message)
/Users/kiefergallant/.pyenv/versions/3.6.0/lib/python3.6/site-packages/facebookads/utils/api_utils.py:30: UserWarning: insights does not allow field campaign_group_name
warnings.warn(message)
Traceback (most recent call last):
File "SAMPLE_CODE.py", line 51, in <module>
params=params
File "/Users/kiefergallant/.pyenv/versions/3.6.0/lib/python3.6/site-packages/facebookads/adobjects/adaccount.py", line 1639, in get_insights
return request.execute()
File "/Users/kiefergallant/.pyenv/versions/3.6.0/lib/python3.6/site-packages/facebookads/api.py", line 664, in execute
cursor.load_next_page()
File "/Users/kiefergallant/.pyenv/versions/3.6.0/lib/python3.6/site-packages/facebookads/api.py", line 851, in load_next_page
params=self.params,
File "/Users/kiefergallant/.pyenv/versions/3.6.0/lib/python3.6/site-packages/facebookads/api.py", line 332, in call
raise fb_response.error()
facebookads.exceptions.FacebookRequestError:
Message: Call was not successful
Method: GET
Path: https://graph.facebook.com/v2.11/act_423073558387349/insights
Params: {'level': 'ad', 'filtering': '[{"field":"delivery_info","operator":"IN","value":["active"]}]', 'breakdowns': '["days_1"]', 'time_range': '{"since":"2019-11-14","until":"2019-11-21"}', 'fields': 'reach,delivery,cost_per_result,cpp,cpm,cost_per_action_type:page_engagement,purchase_roas:omni_purchase,website_purchase_roas:offsite_conversion_fb_pixel_purchase,mobile_app_purchase_roas:app_custom_event_fb_mobile_purchase,campaign_group_name'}
Status: 400
Response:
{
"error": {
"message": "(#2635) You are calling a deprecated version of the Ads API. Please update to the latest version: v5.0.",
"type": "OAuthException",
"code": 2635,
"fbtrace_id": "AASs5AEHjZ0VOZrOfeNziJy"
}
}
"""

Taken from this Question:
The version of your API and Python are not compatible.
The error is caused by the parameter called async from get_insights(), which since Python 3.7 isn't allowed anymore since async is now a reserved keyword of python.
Solution: Use an older Python version (<3.7) or use a version of the API that is
compatible with Python 3.7.

Try facebook_business instead of facebookads. See this.

Related

Unable to improve transcription accuracy with speech adaptation boost

I'm using SpeechRecognition Python library to perform Speech to Text operations. I'm using the recognize_google_cloud function to use Google Cloud Speech-to-Text API.
Here is my code:
import speech_recognition as sr;
import json;
j = '';
with open('key.json', 'r') as f:
j = f.read().replace('\n', '');
js = json.loads(j);
r = sr.Recognizer();
mic = sr.Microphone();
with candide as source:
audio = r.record(source);
print(r.recognize_google_cloud(audio, language='fr-FR', preferred_phrases=['pistoles', 'disait'], credentials_json=j));
The function recognize_google_cloud send the data captured by the microphone to Google API and selects the most probable transcription of the given speech among a set of alternatives.
The parameter preferered_phrases, as explained in this page of the documentation, is used to select an other alternative that contains the listed words.
It is possible to improve these results using speech adaptation boost. As the version of the SpeechRecognition library doesn't let us to specify a boost value, I updated the speech_recognition/__init__.py file with an hard-coded boost value:
if preferred_phrases is not None:
speech_config["speechContexts"] = {"phrases": preferred_phrases, "boost": 19}
Unfortunately, when I execute my code, I get the following error:
Traceback (most recent call last):
File "/home/pierre/.local/lib/python3.8/site-packages/speech_recognition/__init__.py", line 931, in recognize_google_cloud
response = request.execute()
File "/home/pierre/.local/lib/python3.8/site-packages/googleapiclient/_helpers.py", line 134, in positional_wrapper
return wrapped(*args, **kwargs)
File "/home/pierre/.local/lib/python3.8/site-packages/googleapiclient/http.py", line 915, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://speech.googleapis.com/v1/speech:recognize?alt=json returned "Invalid JSON payload received. Unknown name "boost" at 'config.speech_contexts': Cannot find field.". Details: "[{'#type': 'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations': [{'field': 'config.speech_contexts', 'description': 'Invalid JSON payload received. Unknown name "boost" at \'config.speech_contexts\': Cannot find field.'}]}]">
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "spech_reco.py", line 23, in <module>
print(r.recognize_google_cloud(audio, language='fr-FR', preferred_phrases=['pistoles', 'disait'], credentials_json=j));
File "/home/pierre/.local/lib/python3.8/site-packages/speech_recognition/__init__.py", line 933, in recognize_google_cloud
raise RequestError(e)
speech_recognition.RequestError: <HttpError 400 when requesting https://speech.googleapis.com/v1/speech:recognize?alt=json returned "Invalid JSON payload received. Unknown name "boost" at 'config.speech_contexts': Cannot find field.". Details: "[{'#type': 'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations': [{'field': 'config.speech_contexts', 'description': 'Invalid JSON payload received. Unknown name "boost" at \'config.speech_contexts\': Cannot find field.'}]}]">
Is there an error in my request?
I understand that you are modifying the speech_recognition/__init__.py file of the SpeechRecognition library in order to include the "boost" parameter in your request.
When reviewing this file I noticed that it is using the 'v1' version of the API; however, the "boost" parameter is only supported in the ‘v1p1beta1’ version
Therefore, another of the adaptations that you could make in the code is the following:
`speech_service = build ("speech","v1p1beta1", credentials = api_credentials, cache_discovery = False)`
With this modification you should no longer see the BadRequest error.
At the same time, please consider that this library is a third-party library that uses the Google Speech-to-text API internally. Therefore, if this library does not cover all your current needs, another alternative could create your own implementation directly using the Speech-to-text API Python Client library.

Facebook marketing api 'Unsupported get request. Object with ID '[number_of_ad_account_id]' does not exist

I'm new on Facebook marketing API.
1) they let me open only a sandbox account and I want to create a real one and get a real report.
2) after generating the example code and working with Python SDK and getting this error -
Unsupported get request. Object with ID '[number_of_ad_account_id]' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api
please help me solve this issues.
thanks.
EDIT: CODE (take from Facebook sample code)
from facebookads.adobjects.adaccount import AdAccount
from facebookads.adobjects.adsinsights import AdsInsights
from facebookads.api import FacebookAdsApi
access_token = '{secret}'
ad_account_id = '{secret}'
app_secret = '{secret}'
FacebookAdsApi.init(access_token=access_token)
fields = [
'account_id',
'adgroup_id',
'campaign_group_id',
'campaign_id',
]
params = {
'time_range': {'since':'2017-07-10','until':'2017-07-10'},
'filtering': [],
'level': 'account',
'breakdowns': [],
}
print AdAccount(ad_account_id).get_insights(
fields=fields,
params=params,
)
I had the same problem. The SAMPLE_CODE.py auto-generated from Marketing API's quickstart doesn't prefix ad_account_id with act_ by default; it puts the Sandbox Account ID directly, while the Ad Insights API expects:
act_<AD_ACCOUNT_ID>/insights
Just prefix you ad_account_id with act_ and it will work.

Duo Security API with python client

I'm trying to work with Duo's python client (https://github.com/duosecurity/duo_client_python) and I believe I'm simply missing something with my novice python eyes. I somehow need to authenticate my requests to the API using an HMAC signature -- which I've not worked with before but seems trivial to generate (they even provide a python function). Doc here https://duo.com/docs/adminapi#authentication
I'm at a loss as to HOW to craft this signature for authentication, prior to passing my request to the API. From https://duo.com/docs/adminapi#authentication:
The API uses HTTP Basic Authentication to authenticate requests. Use your >Duo application’s integration key as the HTTP Username.
Generate the HTTP Password as an HMAC signature of the request. This will >be different for each request and must be re-generated each time.
It then goes into which parameters are added and necessary for the HMAC signature to be generated properly. I understand this part. My issue is how and when to pass the HMAC signature that I generate. As the Duo doc doesn't specifically go into that, I'm thinking that this is something I should already know [were I not such a python novice].
For example, simple auth calls work fine (as they need no authentication):
root#box:~# python -m duo_client.client --ikey XXXXXXXX --skey XXXXXXXX --host XXXXXXXX.duosecurity.com --method GET --path /auth/v2/check 200 OK
{
"response":
{ "time": 1496437236 }
,
"stat": "OK"
}
However, calls using admin require authentication, and thus fail with:
root#box:~# python -m duo_client.client --ikey XXXXXXXX --skey XXXXXXXX --host XXXXXXXX.duosecurity.com --method GET --path /admin/v1/users signature=XXXXXXXX
401 Unauthorized
{
"code": 40103,
"message": "Invalid signature in request credentials",
"stat": "FAIL"
}
Thanks in advance for any insight!
==EDIT==
So I thought I'd post the function that Duo provide for creating the signature, which appears similar to what is happening in the StackOverflow question I found that I thought might help (Python, HTTPS GET with basic authentication). From https://duo.com/docs/adminapi#authentication:
def sign(method, host, path, params, skey, ikey):
"""
Return HTTP Basic Authentication ("Authorization" and "Date") headers.
method, host, path: strings from request
params: dict of request parameters
skey: secret key
ikey: integration key
"""
# create canonical string
now = email.Utils.formatdate()
canon = [now, method.upper(), host.lower(), path]
args = []
for key in sorted(params.keys()):
val = params[key]
if isinstance(val, unicode):
val = val.encode("utf-8")
args.append(
'%s=%s' % (urllib.quote(key, '~'), urllib.quote(val, '~')))
canon.append('&'.join(args))
canon = '\n'.join(canon)
# sign canonical string
sig = hmac.new(skey, canon, hashlib.sha1)
auth = '%s:%s' % (ikey, sig.hexdigest())
# return headers
return {'Date': now, 'Authorization': 'Basic %s' % base64.b64encode(auth)}
I've used the above function in a simple script to print out (just so I can visualize) what should be getting passed within the script I'll create to server our needs -- I added the function to a script and used print by adding the following:
# Printing Signature Headers ### TESTING ###
print sign('GET', 'XXXhostXXX', '/admin/v1/users', 'XXXparamXXX', 'XXXskeyXXX', 'XXXXikeyXXXX')
However, I'm getting this error:
root#box:~# ./duo.py
Traceback (most recent call last):
File "./duo.py", line 39, in
print sign('GET', 'XXXhostXXX', '/admin/v1/users', 'XXXparamXXX', 'XXXskeyXXX', 'XXXikeyXXX')
File "./duo.py", line 18, in sign
for key in sorted(params.keys()):
AttributeError: 'str' object has no attribute 'keys'
Am I just missing something here? I've been looking for what could cause that error but I thought I'd ask here as well.
This was an "issue" on Duo's side...wrong skey was being used and my user did not have the proper access.

PyBingSearch Module: Bing API error

I am trying to use the PyBingSearch module from https://github.com/tristantao/py-bing-search to use the Bing API to return search results. In the github page they have an example of how to use it that goes.
from py_bing_search import PyBingWebSearch
search_term = "Python Software Foundation"
bing_web = PyBingWebSearch('Your-Api-Key-Here', search_term, web_only=False) # web_only is optional, but should be true to use your web only quota instead of your all purpose quota
first_fifty_result= bing_web.search(limit=50, format='json') #1-50
When I try and run the line that declares first_fifity_result I get an error stating Request returned with code 401, error msg: The authorization type you provided is not supported. Only Basic and OAuth are supported
Why do I get this error? In my code I made sure to change Your-Api-Key-Here to my API key.
Did you swap your API key? Where is says "Your-API-Key-Here"
bing_web = PyBingWebSearch('Your-Api-Key-Here', search_term, web_only=False) # web_only is optional, but should be true to use your web only quota instead of your all purpose quota

ValidationError while running Google adwords client library examples

I get the following error when I try to run sample example of Google adwords
[root#some v200909]# python get_related_keywords.py Traceback (most recent call last): File "get_related_keywords.py", line 53, in
page = targeting_idea_service.Get(selector)[0] File "../../aw_api/TargetingIdeaService.py", line 105, in Get
'TargetingIdea', self.__loc, request) File "../../aw_api/WebService.py", line 350, in CallMethod
raise ValidationError(error['data']) aw_api.Errors.ValidationError: Invalid headers for 'https://adwords-sandbox.google.com', see http://code.google.com/apis/adwords/docs/developer/adwords_api_sandbox.html#requestheaders. [root#some v200909]#
This sounds like an issue with the headers you're providing. The headers must be especially formatted for the sandbox, so make sure that:
a) You're formatting the headers as specified in http://code.google.com/apis/adwords/docs/developer/adwords_api_sandbox.html#requestheaders , as Goose Bumper mentioned. This applies to both v2009 and v13, as you still need to format the developer token and client email according to the instructions (the application token is now obsolete).
b) You're choosing the right endpoint, namely adwords-sandbox.google.com for v2009 and sandbox.google.com for v13
If this still doesn't work for you, the SOAP logs for your request might be useful.

Categories