Spotipy same data for two users - python

I'm trying to get two users' top tracks. Why does this program produce the same results for both users? (user_2 is getting user_1's results). I've allowed access for both of the Spotify accounts in question.
import spotipy
from spotipy import util
from spotipy.oauth2 import SpotifyOAuth
import pandas as pd
CLIENT_ID = CLIENT_ID
CLIENT_SECRET = CLIENT_SECRET
REDIRECT_URI = REDIRECT_URI
# list of Spotify usernames to get top tracks for
usernames = ["user_1", "user_2"]
# Spotify API scope
scope = 'user-top-read'
tokens = []
for username in usernames:
token = util.prompt_for_user_token(username, scope, client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri)
if token:
tokens.append(token)
else:
print(f"Can't get token for {username}")
sp = spotipy.Spotify(auth=tokens[0]) # initialize the Spotify object using the first token
user_ids = []
for token, username in zip(tokens, usernames):
sp = spotipy.Spotify(auth=token)
user_id = sp.current_user()['id'] # get the user ID
user_ids.append(user_id) # add the user ID to the list
# now make API requests for each user's top tracks
for user_id, username in zip(user_ids, usernames):
print(f"Top tracks for {username}:")
top_tracks = sp.current_user_top_tracks(limit=10, time_range='short_term') # make API request
for i, track in enumerate(top_tracks['items']):
print(f"{i+1}. {track['name']} by {track['artists'][0]['name']}")
print()

Related

How to use 3-legged OAuth in Tweepy with Twitter API v2 to read protected Tweets?

I am trying to access protected Tweets from Twitter handles using Tweepy and Twitter API v2. To do this I know I have to use 3-legged OAuth. I have done it and successfully generated an access token and access token secret. But with those access keys I am not able to see the protected Tweets of my own protected account when I am authorizing with the same account.
Does anyone know what I am doing wrong here?
This is a login.py file with the authorization function
#!/usr/bin/env python
import tweepy
def authrize():
CONSUMER_KEY = "XXXXXXXXXXXxx"
CONSUMER_SECRET = "XXXXXXXXXXXXXXXXx"
BEARER_TOKEN = "XXXXXXXXXXXXXXXX"
auth = tweepy.OAuth1UserHandler(CONSUMER_KEY, CONSUMER_SECRET,callback="oob")
print(auth.get_authorization_url())
verifier = input("Input PIN: ")
ACCESS_TOKEN, ACCESS_TOKEN_SECRET = auth.get_access_token(verifier)
print(ACCESS_TOKEN,"******",ACCESS_TOKEN_SECRET)
return (CONSUMER_KEY,CONSUMER_SECRET,BEARER_TOKEN,ACCESS_TOKEN,ACCESS_TOKEN_SECRET)
and my tweepy code app.py is as follows
import tweepy
import login
def get_client(CONSUMER_KEY,CONSUMER_SECRET,BEARER_TOKEN,ACCESS_TOKEN,ACCESS_TOKEN_SECRET):
client = tweepy.Client(bearer_token=BEARER_TOKEN,
consumer_key=CONSUMER_KEY,
consumer_secret=CONSUMER_SECRET,
access_token=ACCESS_TOKEN,
access_token_secret=ACCESS_TOKEN_SECRET, wait_on_rate_limit=True)
return client
def get_user_id(username):
user = client.get_user(username=username)
return user.data.id
def pagination(user_id):
responses = tweepy.Paginator(client.get_users_tweets, user_id,
exclude='replies,retweets',
max_results=100,
expansions='referenced_tweets.id',
tweet_fields=['created_at', 'public_metrics', 'entities'])
return responses
def get_original_tweets(user_id):
tweet_list = []
responses = pagination(user_id)
for response in responses:
if response.data ==None:
continue
else:
for tweets in response.data:
tweet_list.append([tweets.text,
tweets['public_metrics']['like_count'],
tweets['public_metrics']['retweet_count'],
tweets['created_at'].date()])
return tweet_list
def user_details(username):
user = {}
user_response = client.get_user(username=username, user_fields=['public_metrics', 'description', 'url'])
user_metrics = user_response.data['public_metrics']
user['description'] = user_response.data['description']
user['followers'] = user_metrics['followers_count']
user['following'] = user_metrics['following_count']
return user
keys = login.authrize()
client = get_client(*keys)
username = input("Username:")
userid = get_user_id(username)
print(user_details(username))
print(get_original_tweets(userid))
By default, Client.get_users_tweets uses your bearer token rather than OAuth 1.0a User Context to authenticate. You need to set the user_auth parameter to True.

Error when trying to authenticate Spotify: Bad Request Error

I was trying to run the following code on my jupyter notebook:
import spotipy
sp = spotipy.Spotify()
from spotipy.oauth2 import SpotifyClientCredentials
import spotipy.util as util
# setting up authorization
cid ="my client id"
secret = "my client secret"
# saving the info you're going to need
username = 'your_account_number'
scope = 'user-library-read' #check the documentation
authorization_url = 'https://accounts.spotify.com/authorize'
token_url = 'https://accounts.spotify.com/api/token'
redirect_uri ='https://localhost.com/callback/'
token = util.prompt_for_user_token(username,scope,client_id='client_id_number',client_secret='client_secret',redirect_uri='https://localhost.com/callback/')
client_credentials_manager = SpotifyClientCredentials(client_id=cid, client_secret=secret)
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
Which would redirect me to a site. However the site just contains a text saying "INVALID_CLIENT: Invalid client" and nothing else. When I paste this URL in the prompt, I keep getting a Bad Request error. I would be grateful for any help or guidance you can provide. Thanks!
this was the code that worked for me:
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import spotipy.util as util
import os
from Spotify_isplaying import isplay
os.environ["SPOTIPY_CLIENT_ID"] = '' # client id
os.environ["SPOTIPY_CLIENT_SECRET"] = '' # Secret ID
os.environ["SPOTIPY_REDIRECT_URI"] = '' # Redirect URI
username = "" # username
client_credentials_manager = SpotifyClientCredentials(client_id="SPOTIPY_CLIENT_ID",client_secret="SPOTIPY_CLIENT_SECRET")
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
scope = '' # scope needed for your programme
token = util.prompt_for_user_token(username, scope)
if token:
sp = spotipy.Spotify(auth=token)
else:
print("Can't get token for", username)
# where you put your code

Serialize and de-serialize oauth2client.client.OAuth2Credentials

So I have an object, which is credentials from an OAuth2 authorization for a web service. I want to save the users credentials so I can continue to use them in the future. I'm using Django.
The object is: <oauth2client.client.OAuth2Credentials object at 0x104b47310>
I'm not sure how I can stringify the credentials and then build the credentials object back from a string.
Sample code as requested:
#!/usr/bin/python
import httplib2
from apiclient import errors
from apiclient.discovery import build
from oauth2client.client import OAuth2WebServerFlow
# Copy your credentials from the console
CLIENT_ID = 'YOUR_CLIENT_ID'
CLIENT_SECRET = 'YOUR_CLIENT_SECRET'
# Check https://developers.google.com/webmaster-tools/search-console-api-original/v3/ for all available scopes
OAUTH_SCOPE = 'https://www.googleapis.com/auth/webmasters.readonly'
# Redirect URI for installed apps
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
# Run through the OAuth flow and retrieve credentials
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()
print 'Go to the following link in your browser: ' + authorize_url
code = raw_input('Enter verification code: ').strip()
credentials = flow.step2_exchange(code)
# Create an httplib2.Http object and authorize it with our credentials
http = httplib2.Http()
http = credentials.authorize(http)
webmasters_service = build('webmasters', 'v3', http=http)
# Retrieve list of properties in account
site_list = webmasters_service.sites().list().execute()
# Filter for verified websites
verified_sites_urls = [s['siteUrl'] for s in site_list['siteEntry']
if s['permissionLevel'] != 'siteUnverifiedUser'
and s['siteUrl'][:4] == 'http']
# Printing the URLs of all websites you are verified for.
for site_url in verified_sites_urls:
print site_url
# Retrieve list of sitemaps submitted
sitemaps = webmasters_service.sitemaps().list(siteUrl=site_url).execute()
if 'sitemap' in sitemaps:
sitemap_urls = [s['path'] for s in sitemaps['sitemap']]
print " " + "\n ".join(sitemap_urls)
You can use pickle module to serialize and de-serialize python objects. Here is untested code:
import pickle
# Store OAuth2Credentials to a file
with open(FILENAME, 'wb') as credentials_file:
pickle.dump(credentials, credentials_file)
# Read OAuth2Credentials from file
with open(FILENAME, 'rb') as credentials_file:
credentials = pickle.load(credentials_file)

Can anyone tell me why I'm still getting an INVALID_CLIENT message? Spotipy on mac

I am trying to build a Spotify player with python and spotipy. I keep getting a message that says INVALID_CLIENT. The client id is entered properly along with the secret and the username
import spotipy
import spotipy.util as util
from spotipy.oauth2 import SpotifyClientCredentials
cid ="xx"
secret = "xx"
username = "xx"
client_credentials_manager = SpotifyClientCredentials(client_id=cid, client_secret=secret)
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
scope = 'user-library-read playlist-read-private'
token = util.prompt_for_user_token(username,scope,client_id='http://localhost:8888/callback/',client_secret='http://localhost:8888/callback/',redirect_uri='http://localhost:8888/callback/')
if token:
sp = spotipy.Spotify(auth=token)
else:
print("Can't get token for", username)
cache_token = token.get_access_token()
sp = spotipy.Spotify(cache_token)
currentfaves = sp.current_user_top_tracks(limit=20, offset=0, time_range='medium_term')
print(currentfaves)
You're using both the Client Credentials and Authorization Code Flow. To get user's top tracks, you need to use Authorization Code Flow.
You should remove the client credentials lines, then make sure the util.prompt_for_user_token call is configured properly. In your code, you have all parameters set to your redirect URI, which is giving you the Invalid Client error. Seems like you're following the Spotipy documentation, which is incorrect for this call. I'll try to make a PR.
Your code should look like this:
import spotipy
import spotipy.util as util
cid ="xx"
secret = "xx"
username = "xx"
scope = 'user-library-read playlist-read-private'
token = util.prompt_for_user_token(username,scope,client_id=cid,client_secret=secret,redirect_uri='http://localhost:8888/callback/')
if token:
sp = spotipy.Spotify(auth=token)
else:
print("Can't get token for", username)
cache_token = token.get_access_token()
sp = spotipy.Spotify(cache_token)
currentfaves = sp.current_user_top_tracks(limit=20, offset=0, time_range='medium_term')
print(currentfaves)

Python - oauth2 - linkedin API

I am trying to follow some companies registered on LinkedIn through python code and as per LinkedIn API documentation I need to use oauth2 - POST method to follow a company.
My queries are below:
How to specify a particular company name via python code to follow a company?
Can someone advise the python code for this?
My code is below:
oauth_token = oauth.Token(key=access_token_key, secret=access_token_secret)
oauth_consumer = oauth.Consumer(key=api_key, secret=api_secret)
signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1()
http_method = "POST"
http_handler = urllib.HTTPHandler(debuglevel=_debug)
https_handler = urllib.HTTPSHandler(debuglevel=_debug)
def linkedinreq(url, method, parameters):
req = oauth.Request.from_consumer_and_token(oauth_consumer,
token=oauth_token,
http_method=http_method,
http_url=url,
parameters=parameters)
req.sign_request(signature_method_hmac_sha1, oauth_consumer, oauth_token)
req.to_postdata()
def fetchsamples():
url = "https://api.linkedin.com/v1/people/~/following/companies"
parameters = []
response = linkedinreq(url, "POST", parameters)
fetchsamples()
The python modules python-linkedin and python-linkedin-v2 are outdated. Thus, I suggest you to use the requests_oauthlib module instead.
from requests_oauthlib import OAuth2Session
from requests_oauthlib.compliance_fixes import linkedin_compliance_fix
# In case the `redirect_url` does not implement https
import os
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
# Credentials you get from registering a new application
client_id = '<the client id you get from linkedin>'
client_secret = '<the client secret you get from linkedin>'
redirect_url = '<authorized redirect URL from LinkedIn config>'
# OAuth endpoints given in the LinkedIn API documentation (check for updates)
authorization_base_url = 'https://www.linkedin.com/oauth/v2/authorization'
token_url = 'https://www.linkedin.com/oauth/v2/accessToken'
# Authorized Redirect URL (from LinkedIn config)
linkedin = OAuth2Session(client_id, redirect_uri=redirect_url)
linkedin = linkedin_compliance_fix(linkedin)
# Redirect user to LinkedIn for authorization
authorization_url, state = linkedin.authorization_url(authorization_base_url)
print('Please go here and authorize,', authorization_url)
# Get the authorization verifier code from the callback url
redirect_response = input('Paste the full redirect URL here:')
# Fetch the access token
linkedin.fetch_token(token_url, client_secret=client_secret,
authorization_response=redirect_response)
# Fetch a protected resource, i.e. user profile
r = linkedin.get('https://api.linkedin.com/v1/people/~')
print(r.content)
Instead of reinventing the wheel, use python-linkedin wrapper.
Example code to search for the companies:
from linkedin import linkedin
CONSUMER_KEY = 'your key'
CONSUMER_SECRET = 'your secret'
USER_TOKEN = 'your token'
USER_SECRET = 'your user secret'
RETURN_URL = ''
# Instantiate the developer authentication class
authentication = linkedin.LinkedInDeveloperAuthentication(CONSUMER_KEY, CONSUMER_SECRET,
USER_TOKEN, USER_SECRET,
RETURN_URL, linkedin.PERMISSIONS.enums.values())
# Pass it in to the app...
application = linkedin.LinkedInApplication(authentication)
print application.search_company(selectors=[{'companies': ['name', 'universal-name', 'website-url']}],
params={'keywords': 'apple microsoft'})
To follow the company, use follow_company() method, see more information and examples here:
COMPANY_ID = 1035 # this you would get from the `search_company()`
application.follow_company(COMPANY_ID)

Categories

Resources