How do I get ondapyV20 to complete authorization? - python

Here is my code:
from oandapyV20 import API
import oandapyV20.endpoints.trades as trades
api = API(access_token="xxx")
accountID = "xxx-xxx-xxxxxxx-xxx"
r = trades.TradesList(accountID)
print("REQUEST:{}".format(r))
rv = api.request(r)
print("RESPONSE:\n{}".format(json.dumps(rv, indent=2)))
I get the following error:
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\oanda tester.py", line 10, in
rv = api.request(r)
File "C:\Python37\lib\site-packages\oandapyV20\oandapyV20.py", line 306, in request
request_args, headers=headers)
File "C:\Python37\lib\site-packages\oandapyV20\oandapyV20.py", line 243, in __request
response.content.decode('utf-8'))
oandapyV20.exceptions.V20Error: {"errorMessage":"Insufficient authorization to perform request."}
My token and account info is correct.
This code was copied straight from documentation.
Am I missing something here?

Try this instead:
from oandapyV20 import API
import oandapyV20.endpoints.trades as trades
import json
access_token="xxx"
accountID = "xxxx"
client= API(access_token=access_token,environment="live" or "practice")
r = trades.TradesList(accountID)
print("REQUEST:{}".format(r))
rv = client.request(r)
print("RESPONSE:\n{}".format(json.dumps(rv, indent=2)))

When you define the client object, you should specify if your account is of type live or practice:
client= API(access_token = access_token, environment = "live")
Regularly, when you work with practice accounts you define the client object like this:
client= API(access_token = access_token)

Related

Status parameter not working when using python blogger api

I'm trying to use google-api-python-client 1.12.5 with Service account auth under Python 3.8. It seems to me that the when specifying the status parameter, Google responds with a 404 HTTP code. I can't figure out why. I also looked in the docs but I can't relate anything to this error.
I have pasted my code. The error is happening in the third call.
This is the code:
from google.oauth2 import service_account
from googleapiclient.discovery import build
SCOPES = ['https://www.googleapis.com/auth/blogger']
SERVICE_ACCOUNT_FILE = 'new_service_account.json'
BLOG_ID = '<your_blog_id>'
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = build('blogger', 'v3', credentials=credentials)
p = service.posts()
# FIRST
promise = p.list(blogId=BLOG_ID)
result = promise.execute()
# SECOND
promise = p.list(blogId=BLOG_ID, orderBy='UPDATED')
result = promise.execute()
#THIRD
promise = p.list(blogId=BLOG_ID, orderBy='UPDATED', status='DRAFT')
result = promise.execute() # <===== ERROR HAPPENS HERE!!!!
service.close()
And this is the traceback:
Traceback (most recent call last):
File "/home/madtyn/.local/share/JetBrains/Toolbox/apps/PyCharm-P/ch-0/202.7660.27/plugins/python/helpers/pydev/pydevd.py", line 1448, in _exec
pydev_imports.execfile(file, globals, locals) # execute the script
File "/home/madtyn/.local/share/JetBrains/Toolbox/apps/PyCharm-P/ch-0/202.7660.27/plugins/python/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "/home/madtyn/PycharmProjects/blogger/main.py", line 24, in <module>
result = promise.execute()
File "/home/madtyn/venvs/blogger/lib/python3.8/site-packages/googleapiclient/_helpers.py", line 134, in positional_wrapper
return wrapped(*args, **kwargs)
File "/home/madtyn/venvs/blogger/lib/python3.8/site-packages/googleapiclient/http.py", line 915, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 404 when requesting https://blogger.googleapis.com/v3/blogs/<blog_id>/posts?orderBy=UPDATED&status=DRAFT&alt=json returned "Not Found">
python-BaseException
I can reproduce this issue... Adding status=DRAFT will return 404 but any other filter is working...
Tried with service account and your code: 404
Tried with API Key like this result = requests.get('https://blogger.googleapis.com/v3/blogs/<blog_id>/posts?status=DRAFT&orderBy=UPDATED&alt=json&key=<api_key>'): 404
Extracted "access_token" from service account (credentials.token after a call): result = requests.get('https://blogger.googleapis.com/v3/blogs/<blog_id>/posts?status=DRAFT&orderBy=UPDATED&alt=json&access_token=<extracted_service_account_token>'): 404
But very strangely if I use access_token given by "Try this API" here : https://developers.google.com/blogger/docs/3.0/reference/posts/list?apix_params={"blogId"%3A"blog_id"%2C"orderBy"%3A"UPDATED"%2C"status"%3A["DRAFT"]%2C"alt"%3A"json"} it's works !
Used that token with requests give me my blog post in draft status...
Just copy/paste raw Authorization header inside that script:
import requests
blog_id = '<blog_id>'
headers = {
'Authorization' : 'Bearer <replace_here>'
}
# Using only Authorization header
result = requests.get(
'https://blogger.googleapis.com/v3/blogs/%s/posts?status=DRAFT&orderBy=UPDATED&alt=json' % (blog_id),
headers=headers
)
print(result)
# This should print DRAFT if you have at least one draft post
print(result.json()['items'][0]['status'])
# Using "access_token" param constructed with Authorization header splited to have only token
result = requests.get('https://blogger.googleapis.com/v3/blogs/%s/posts?status=DRAFT&orderBy=UPDATED&alt=json&access_token=%s' % (blog_id, headers['Authorization'][len('Bearer '):]))
print(result)
# This should print DRAFT if you have at least one draft post
print(result.json()['items'][0]['status'])
Results I have currently:
The bug doesn't seem to come from the library but rather from the token rights...However I also used the console normally to generate accesses like you.
To conclude I think it's either a bug or it's voluntary from Google... I don't know how long the "Try this API" token is valid but it is currently the only way I found to get the draft articles... Maybe you can try to open a bug ticket but I don't know specifically where it is possible to do that.

Facebook Business API request campaigns via python

We are busy upgrading from the Marketing API to the Business API (not graph API and not marketing API) for Facebook. The documentation states that one should be able to create a test.py with the following code:
import sys
sys.path.append('/opt/homebrew/lib/python2.7/site-packages')
sys.path.append('/opt/homebrew/lib/python2.7/site-packages/facebook_business-3.0.0-py2.7.egg-info')
from facebook_business.api import FacebookAdsApi
from facebook_business.adobjects.adaccount import AdAccount
my_app_id = 'your-app-id'
my_app_secret = 'your-appsecret'
my_access_token = 'your-access-token'
FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)
my_account = AdAccount('your-adaccount-id')
campaigns = my_account.get_campaigns()
print(campaigns)
This requires an app secret proof which I am obtaining with the following hash:
facebook_app_id = 'xxxxx'
facebook_app_secret = 'xxxxx'
facebook_app_token = 'xxxxx|xxxxx'.format(facebook_app_id,facebook_app_secret)
import hmac,hashlib
app_secret_proof = hmac.new(facebook_app_secret.encode('utf-8'),
msg=facebook_app_token.encode('utf-8'),
digestmod=hashlib.sha256).hexdigest()
print(app_secret_proof)
The is the error I get:
Traceback (most recent call last):
File "test.py", line 12, in <module>
FacebookAdsApi.init(my_app_id,my_app_secret,my_access_token,my_appsecret_proof)
File "/Users/facebook_business/api.py", line 202, in init
cls.set_default_account_id(account_id)
File "/Users/facebook_business/api.py", line 225, in set_default_account_id
"Account ID provided in FacebookAdsApi.set_default_account_id "
ValueError: Account ID provided in FacebookAdsApi.set_default_account_id expects a string that begins with 'act_'
None of the ID's start with act_, I am currently using the App ID that is at the top left of the app dashboard which one should I be using?
Marketing API
The Ad account number in business manager is obtained on the front log in screen.
From Business Manager

Google Cloud Pub Sub With Service Account

Hi everyone I am having an issue with pub sub that is driving me nuts. Basically I have a service account with admin priivs for pubsub but I can't get any thing to work and am getting the following error:
ERROR:root:AuthMetadataPluginCallback "" raised exception!
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/grpc/_plugin_wrapping.py", line 77, in call
callback_state, callback))
File "/usr/local/lib/python2.7/dist-packages/google/auth/transport/grpc.py", line 77, in call
callback(self._get_authorization_headers(context), None)
File "/usr/local/lib/python2.7/dist-packages/google/auth/transport/grpc.py", line 61, in _get_authorization_headers
self._credentials.before_request(
AttributeError: 'str' object has no attribute 'before_request'
Code is super simple
from google.cloud import pubsub
credentials = '/home/airflow/Desktop/test/config/test.json'
publisher = pubsub.PublisherClient(credentials=credentials)
topic_path = publisher.topic_path("test-proj", "test")
for n in range(1, 2):
data = u'Message number {}'.format(n)
# Data must be a bytestring
data = data.encode('utf-8')
test = publisher.publish(topic_path, data=data).result()
print(test, "s")
Amy help would be really appreciated as the error message doesn't make much sense to me. Thanks
The credentials argument for PublisherClient is not a string. It is a google.auth.credentials.Credentials object. The google-auth-guide indicates how to create it:
from google.oauth2 import service_account
credentials = service_account.Credentials.from_service_account_file(
'/home/airflow/Desktop/test/config/test.json')

Foursquare authentication - 'No handlers could be found for logger "foursquare"'

I'm starting with the Foursquare API, in Python, and I'm not sure why I can't authenticate.
Following the tutorial, so far I have this piece of code:
import foursquare
client = foursquare.Foursquare(client_id=myid, client_secret=mysecret,
redirect_uri='http://fondu.com/oauth/authorize')
auth_uri = client.oauth.auth_url()
access_token = client.oauth.get_token('XX_CODE_RETURNED_IN_REDIRECT_XX')
client.set_access_token(access_token)
client.venues.explore(params={'near': 'New York, NY', 'time' : date})
I've created an app here:
https://foursquare.com/developers/apps
and I'm using both:
Client id
Client secret
shown in the page.
However, when running this code, I get:
No handlers could be found for logger "foursquare"
Traceback (most recent call last):
File "noiseInference.py", line 270, in <module>
getFoursquareCheckIns(date)
File "noiseInference.py", line 156, in getFoursquareCheckIns
access_token = client.oauth.get_token('XX_CODE_RETURNED_IN_REDIRECT_XX')
File "/Library/Python/2.7/site-packages/foursquare/__init__.py", line 134, in get_token
response = _request_with_retry(url)
File "/Library/Python/2.7/site-packages/foursquare/__init__.py", line 707, in _request_with_retry
return _process_request_with_httplib2(url, headers, data)
File "/Library/Python/2.7/site-packages/foursquare/__init__.py", line 730, in _process_request_with_httplib2
return _check_response(data)
File "/Library/Python/2.7/site-packages/foursquare/__init__.py", line 763, in _check_response
raise FoursquareException(errmsg)
foursquare.FoursquareException: Response format invalid, missing meta property. data: {u'error': u'invalid_client'}
Not sure what's the problem.
The handler message is just complaining you didn't set up a logger under for the foursquare namespace.
Your real error is the message at the end of the stack trace:
foursquare.FoursquareException:
Response format invalid, missing meta property. data: {u'error': u'invalid_client'}
The message indicates that your client's credentials are incorrect. The credentials aren't fully checked until you attempt to use the client for a privileged action like client.set_access_token, so the most likely culprit here is to look at what you pass for client_secret when constructing the Foursquare client object.
client_id is probably not the problem because you'd have to go through the URL-OAuth flow in order to get the access_token you use.

Twitter API returned a 401 (Unauthorized) when trying to get users's friends on twitter

I'm using the following code which for a while worked like charm, but recently in 9 of the 10 attempts I'm getting error from twitter api
from twython import Twython, TwythonError
from pymongo import Connection
import pika, time
connection = Connection("host")
connection.admin.authenticate('admin', 'passwords')
db = connection['tweets']
consumer_key="key"
consumer_secret="secret"
access_token="token"
access_token_secret="secret_token"
t = Twython(app_key=consumer_key,
app_secret=consumer_secret,
oauth_token=access_token,
oauth_token_secret=access_token_secret
)
Q ='download_friends'
r_connection = pika.BlockingConnection(pika.ConnectionParameters(
'host'))
channel = r_connection.channel()
channel.queue_declare(queue= Q,
arguments={'x-message-ttl':600000})
while 1:
method_frame, header_frame, id = channel.basic_get(Q)
if db.friends.find_one({"_id": id}) != None:
print "Panic, user already exists"
continue
try:
r = t.get_friends_list(user_id = id)
except Exception as ex:
print ex, id
else:
print id
r['_id'] = id
r['time'] = time.time()
db.friends.save(r)
time.sleep(121)
Twitter API returned a 401 (Unauthorized), An error occurred
processing your request.
Here is a stacktrace
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/twython/endpoints.py", line 290, in get_friends_list
return self.get('friends/list', params=params)
File "/usr/local/lib/python2.7/dist-packages/twython/api.py", line 230, in get
return self.request(endpoint, params=params, version=version)
File "/usr/local/lib/python2.7/dist-packages/twython/api.py", line 224, in request
content = self._request(url, method=method, params=params, api_call=url)
File "/usr/local/lib/python2.7/dist-packages/twython/api.py", line 194, in _request
retry_after=response.headers.get('retry-after'))
twython.exceptions.TwythonAuthError: Twitter API returned a 401 (Unauthorized), An error occurred processing your request.
I the remaining 1 attempt I'm actually getting a user's friends.
I've googled a bit and corrected time on the machine (as they say one of the most common causes of this error), yet error still persists.
Also there is minimal not working example:
twitter = Twython('API key', 'API secret', oauth_version=2)
ACCESS_TOKEN = twitter.obtain_access_token()
print ACCESS_TOKEN
t = Twython('API key', access_token=ACCESS_TOKEN)
r = t.get_friends_list(user_id = 'id')
It is able to get ACCESS_TOKEN but nothing more.
Could it be, because user_id has private profile and you just can't access it's friends?
I also thought, it's problem in rate limit, but according to twitter api it returns 429 error, if limit reached
UPDATE:
I haven't tested, but found similar situation: https://dev.twitter.com/discussions/4389

Categories

Resources