Authenticate to linkedin - python

I am trying to write a code that get some user's linkedin profile and just print it
this is my code
from linkedin import linkedin
CONSUMER_KEY = "XXXXX"
CONSUMER_SECRET = "XXXXX"
RETURN_URL = r"http://localhost:8000"
authentication = linkedin.LinkedInAuthentication(CONSUMER_KEY, CONSUMER_SECRET,
RETURN_URL, linkedin.PERMISSIONS.enums.values())
application = linkedin.LinkedInApplication(authentication)
a = application.get_profile(member_url=my_url)
print(a)
I get the following error
Traceback (most recent call last):
File "C:/Users/Linkedin/main.py", line 28, in <module>
a = application.get_profile(member_url=my_url)
File "C:\Python34\lib\site-packages\python_linkedin-4.2-py3.4.egg\linkedin\linkedin.py", line 189, in get_profile
response = self.make_request('GET', url, params=params, headers=headers)
File "C:\Python34\lib\site-packages\python_linkedin-4.2-py3.4.egg\linkedin\linkedin.py", line 169, in make_request
params.update({'oauth2_access_token': self.authentication.token.access_token})
AttributeError: 'NoneType' object has no attribute 'access_token'
What do I do wrong?

Not tested. Try this
As per the documentation. Access token must be generated to grand access to the application.
authentication = linkedin.LinkedInAuthentication(API_KEY, API_SECRET, RETURN_URL, linkedin.PERMISSIONS.enums.values())
application = linkedin.LinkedInApplication(token=authentication.get_access_token())
print authentication.authorization_url
When you grant access to the application, you will be redirected to the return url with the following query strings appended to your RETURN_URL:
"http://localhost:8000/?code=AQTXrv3Pe1iWS0EQvLg0NJA8ju_XuiadXACqHennhWih7iRyDSzAm5jaf3R7I8&state=ea34a04b91c72863c82878d2b8f1836c"
Copy the code manually and set like
authentication.authorization_code = 'AQTXrv3Pe1iWS0EQvLg0NJA8ju_XuiadXACqHennhWih7iRyDSzAm5jaf3R7I8'
authentication.get_access_token() #AQTFtPILQkJzXHrHtyQ0rjLe3W0I
application = linkedin.LinkedInApplication(token='AQTFtPILQkJzXHrHtyQ0rjLe3W0I')

Related

401 error when trying to stream tweets with Tweepy

import tweepy
import time
# Credentials (INSERT YOUR KEYS AND TOKENS IN THE STRINGS BELOW)
api_key = "XXX"
api_secret = "XXX"
bearer_token = r"XXX"
access_token = "XXXX"
access_token_secret = "XXXX"
# Gainaing access and connecting to Twitter API using Credentials
client = tweepy.Client(bearer_token, api_key, api_secret, access_token, access_token_secret)
auth = tweepy.OAuth1UserHandler(api_key, api_secret, access_token, access_token_secret)
#api = tweepy.API(auth)
search_terms = ["mahomes", "NFL"]
# Bot searches for tweets containing certain keywords
class MyStream(tweepy.StreamingClient):
# This function gets called when the stream is working
def on_connect(self):
print("Connected")
# This function gets called when a tweet passes the stream
def on_tweet(self, tweet):
# Displaying tweet in console
if tweet.referenced_tweets == None:
print(tweet.text)
client.like(tweet.id)
# Delay between tweets
#time.sleep(30)
# Creating Stream object
stream = MyStream(bearer_token=bearer_token)
# Adding terms to search rules
# It's important to know that these rules don't get deleted when you stop the
# program, so you'd need to use stream.get_rules() and stream.delete_rules()
# to change them, or you can use the optional parameter to stream.add_rules()
# called dry_run (set it to True, and the rules will get deleted after the bot
# stopped running).
for term in search_terms:
stream.add_rules(tweepy.StreamRule(term))
# Starting stream
stream.filter(tweet_fields=["referenced_tweets"])
Prints out the first tweet then gives the error:
Stream encountered an exception
Traceback (most recent call last):
File "C:\Users\Eric\anaconda3\lib\site-packages\tweepy\streaming.py", line 94, in _connect
self.on_data(line)
File "C:\Users\Eric\anaconda3\lib\site-packages\tweepy\streaming.py", line 936, in on_data
self.on_tweet(tweet)
File "<ipython-input-13-9febcb625821>", line 34, in on_tweet
client.like(tweet.id)
File "C:\Users\Eric\anaconda3\lib\site-packages\tweepy\client.py", line 691, in like
return self._make_request(
File "C:\Users\Eric\anaconda3\lib\site-packages\tweepy\client.py", line 129, in _make_request
response = self.request(method, route, params=request_params,
File "C:\Users\Eric\anaconda3\lib\site-packages\tweepy\client.py", line 98, in request
raise Unauthorized(response)
tweepy.errors.Unauthorized: 401 Unauthorized
Unauthorized
Giants postpone Carlos Correa’s intro news conference over unresolved medical results: Reports
#Jersey #MLB #NFL #NBA #NHL #NCAA #baseball #Americanfootball #baseballjersey #Americanfootballjersey #basketball #basketballJersey

Getting error making calls with twilio python api

Getting this error when I try to make a call with the twilio python api:
Jacob-Mac-mini:downloads kovyjacob$ python3 twilio_call.py
Traceback (most recent call last):
File "/Users/kovyjacob/Downloads/twilio_call.py", line 11, in <module>
call = client.calls.create(
File "/Users/kovyjacob/Library/Python/3.9/lib/python/site-packages/twilio/rest/api/v2010/account/call/__init__.py", line 141, in create
payload = self._version.create(method='POST', uri=self._uri, data=data, )
File "/Users/kovyjacob/Library/Python/3.9/lib/python/site-packages/twilio/base/version.py", line 205, in create
raise self.exception(method, uri, response, 'Unable to create record')
twilio.base.exceptions.TwilioRestException:
HTTP Error Your request was:
POST /Accounts/['AC766eaf7ef8d79de658756223cee446df']/Calls.json
Twilio returned the following information:
Unable to create record: The requested resource /2010-04-01/Accounts/['AC766eaf7ef8d79de658756223cee446df']/Calls.json was not found
More information may be available here:
https://www.twilio.com/docs/errors/20404
I checked the link, but a) I'm not sure what the problem is exactly, and b) it doesn't say how to fix it.
This is the code:
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = ['AC766eaf7ef8d79de658756223cee446df']
auth_token = ['74ef4743a7a9a748cxxxxxxxxxxxxxxx']
client = Client(account_sid, auth_token)
call = client.calls.create(
twiml='<Response><Say>Ahoy, World!</Say></Response>',
to='+14372341004',
from_='+14243560675'
)
print(call.sid)
account_sid and auth_token should be passed as strings, not array with string inside.
Twillio Rest Client Source Code
Edit your code to:
account_sid = 'AC766eaf7ef8d79de658756223cee446df'
auth_token = '74ef4743a7a9a748cxxxxxxxxxxxxxxx'

Authenticate Tableau REST API using Python 2.7

I'm having a similar issue to this recently answered question: Authenticate & Embed Tableau Rest API using python 2.7
I'm using the same code, but getting a different error. Confirmed that I am calling the correct API version for my Tableau server version.
from urllib2 import urlopen, Request
import xml.etree.ElementTree as ET # for parsing XML responses
server_name = "http://dashboard.myorg.org"
user_name = "abc"
password = "abc"
site_url_id = ""
signin_url = "{server}/api/2.4/auth/signin".format(server=server_name)
request_xml = ET.Element('tsRequest')
credentials = ET.SubElement(request_xml, 'credentials',
name=user_name, password=password)
site_element = ET.SubElement(credentials, 'site',
contentUrl=site_url_id)
request_data = ET.tostring(request_xml)
req = Request(signin_url, data=request_data)
req = urlopen(req)
server_response = req.read
response_xml = ET.fromstring(server_response)
token = response_xml.find('.//t:credentials',
namespaces={'t': "http://tableau.com/api"}).attrib['token']
site_id = response_xml.find('.//t:site',
namespaces={'t': "http://tableau.com/api"}).attrib['id']
print('Sign in successful!')
print('/tToken: {token}'.format(token=token))
print('/tSite ID: {site_id}'.format(site_id=site_id))
headers = {'X-tableau-auth': token}
signout_url = "{server}/api/2.4/auth/signout".format(server=server_name)
req = Request(signout_url, headers=headers, data=b'')
req = urlopen(req)
print('Sign out successful!')
My error is:
Traceback (most recent call last):
File "api_call.py", line 20, in <module>
response_xml = ET.fromstring(server_response)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 1311, in XML
parser.feed(text)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 1311, in feed
self._parser.Parse(data, 0)
TypeError: Parse() argument 1 must be string or read-only buffer, not instancemethod
As mentioned by #mzjn, issue is resolved by updating
server_response = req.read
to
server_response = req.read()

HttpError 400 Bad Request - Google Admin Directory API (Python)

I'm having difficulty creating a Google Project as a Service Account. I am using the Admin SDK in Python, specifically the Directory API. I believe I am authenticating correctly but when it comes to calling users.list I get the following error:
Traceback (most recent call last):
File "googleproject.py", line 17, in <module>
userlist = service.users().list().execute(http = http_auth)
File "/usr/local/lib/python2.7/dist-packages/oauth2client/util.py", line 135, in positional_wrapper
return wrapped(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/googleapiclient/http.py", line 723, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/admin/directory/v1/users?alt=json returned "Bad Request">
My code is as follows:
from oauth2client.client import SignedJwtAssertionCredentials
from httplib2 import Http
from apiclient.discovery import build
#----AUTHORISATION----#
client_email = '*****#developer.gserviceaccount.com'
with open('*****.p12') as f:
private_key = f.read()
credentials = SignedJwtAssertionCredentials(client_email, private_key, 'https://www.googleapis.com/auth/admin.directory.user')
http_auth = credentials.authorize(Http())
#--------------------#
service = build('admin', 'directory_v1', http = http_auth)
userlist = service.users().list().execute(http = http_auth)
I have tried it with and without passing http = http_auth as an argument to execute(). I've basically followed the example given here: https://code.google.com/p/google-api-python-client/source/browse/samples/service_account/tasks.py
I have enabled Admin SDK in the Developers console, as well as added the client id and scope in the Google Apps control panel.
I managed to fix it! The problem was I wasn't setting the domain in the list argument. So the new code is as follows:
from oauth2client.client import SignedJwtAssertionCredentials
from httplib2 import Http
from apiclient.discovery import build
#----AUTHORISATION----#
client_email = '*****#developer.gserviceaccount.com'
with open('*****') as f:
private_key = f.read()
credentials = SignedJwtAssertionCredentials(client_email, private_key, 'https://www.googleapis.com/auth/admin.directory.user', sub = 'super-admin#domain.com')
http_auth = credentials.authorize(Http())
#--------------------#
service = build('admin', 'directory_v1', http = http_auth)
user = service.users().list(showDeleted = False, domain = 'domain.com').execute()

Python Dropbox API error: 'The provided token does not allow this operation' [duplicate]

I'm following the tutorial here
So far so good but the upload example give me errors. The code:
from dropbox import client, rest, session
f = open('txt2.txt') # upload a file
response = client.put_file('/magnum-opus.txt', f)
print "uploaded:", response
The error:
Traceback (most recent call last):
File "dropbox_ul.py", line 4, in <module>
response = client.put_file('/magnum-opus.txt', f)
AttributeError: 'module' object has no attribute 'put_file'
Where did I go wrong?
EDIT: The new code I'm trying. This is actually from the dropbox developer website. As I stated earlier, I did go through the authentication and setup:
# Include the Dropbox SDK libraries
from dropbox import client, rest, session
# Get your app key and secret from the Dropbox developer website
APP_KEY = 'iqxjea6s7ctxv9j'
APP_SECRET = 'npac0nca3p3ct9f'
# ACCESS_TYPE should be 'dropbox' or 'app_folder' as configured for your app
ACCESS_TYPE = 'dropbox'
sess = session.DropboxSession(APP_KEY,APP_SECRET, ACCESS_TYPE )
request_token = sess.obtain_request_token()
# Make the user sign in and authorize this token
url = sess.build_authorize_url(request_token)
print "url:", url
print "Please authorize in the browser. After you're done, press enter."
raw_input()
# This will fail if the user didn't visit the above URL and hit 'Allow'
access_token = sess.obtain_access_token(request_token)
client = client.DropboxClient(sess)
print "linked account:", client.account_info()
f = open('txt2.txt')
response = client.put_file('/magnum-opus.txt', f)
print "uploaded:", response
folder_metadata = client.metadata('/')
print "metadata:", folder_metadata
f, metadata = client.get_file_and_metadata('/magnum-opus.txt',rev='362e2029684fe')
out = open('magnum-opus.txt', 'w')
out.write(f)
print(metadata)
and the error:
url: https://www.dropbox.com/1/oauth/authorize?oauth_token=jqbasca63c0a84m
Please authorize in the browser. After you're done, press enter.
linked account: {'referral_link': 'https://www.dropbox.com/referrals/NTMxMzM4NjY5', 'display_name': 'Greg Lorincz', 'uid': 3133866, 'country': 'GB', 'quota_info': {'shared': 78211, 'quota': 28185722880, 'normal': 468671581}, 'email': 'alkopop79#gmail.com'}
Traceback (most recent call last):
File "dropb.py", line 28, in <module>
response = client.put_file('/magnum-opus.txt', f)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/dropbox-1.4-py2.7.egg/dropbox/client.py", line 149, in put_file
return RESTClient.PUT(url, file_obj, headers)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/dropbox-1.4-py2.7.egg/dropbox/rest.py", line 146, in PUT
return cls.request("PUT", url, body=body, headers=headers, raw_response=raw_response)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/dropbox-1.4-py2.7.egg/dropbox/rest.py", line 113, in request
raise ErrorResponse(r)
dropbox.rest.ErrorResponse: [403] 'The provided token does not allow this operation'
You haven't initialized the client object. Refer to the tutorial again and you'll see this:
client = client.DropboxClient(sess)
The sess object must also be initialized before calling the client module's DropboxClient method:
sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE)
You should have all the required parameters (i.e., APP_KEY, APP_SECRET, ACCESS_TYPE) assigned to you when you register your application.
I followed the edited code of yours and things worked out perfectly.
from dropbox import client, rest, session
# Get your app key and secret from the Dropbox developer website
app_key = 'enter-your-app_key'
app_secret = 'enter-your-app_secret'
ACCESS_TYPE = 'dropbox'
sess = session.DropboxSession(app_key, app_secret, ACCESS_TYPE )
request_token = sess.obtain_request_token()
# Make the user sign in and authorize this token
url = sess.build_authorize_url(request_token)
print "url:", url
print "Please authorize in the browser. After you're done, press enter."
raw_input()
# This will fail if the user didn't visit the above URL and hit 'Allow'
access_token = sess.obtain_access_token(request_token)
client = client.DropboxClient(sess)
print "linked account:", client.account_info()
f = open('/home/anurag/Documents/sayan.odt')
response = client.put_file('/sayan.odt', f)
print "uploaded:", response
Notice the response and file location on your system, in your code that doesn't matches.
Thanks.

Categories

Resources