Spotify API - authentication via command line - python

In order to access my playlists, I am using the following example code, which I got from spotipy documentation page:
import pprint
import sys
import os
import subprocess
import spotipy
import spotipy.util as util
client_id = 'my_id'
client_secret = 'my_secret'
redirect_uri = 'http://localhost:8000/callback/'
scope = 'user-library-read'
if len(sys.argv) > 1:
username = sys.argv[1]
else:
print "Usage: %s username" % (sys.argv[0],)
sys.exit()
token = util.prompt_for_user_token(username, scope, client_id, client_secret, redirect_uri)
if token:
sp = spotipy.Spotify(auth=token)
results = sp.current_user_saved_tracks()
for item in results['items']:
track = item['track']
print track['name'] + ' - ' + track['artists'][0]['name']
else:
print "Can't get token for", username
when I run the script with python myscript.py myusername, I get this:
User authentication requires interaction with your
web browser. Once you enter your credentials and
give authorization, you will be redirected to
a url. Paste that url you were directed to to
complete the authorization.
Opening https://accounts.spotify.com/authorize?scope=user-library-read&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcallback&response_type=code&client_id=d3b2f7a12362468daa393cf457185973 in your browser
Enter the URL you were redirected to:
then, if I enter http://localhost:8000/callback/, I get the following error:
token = util.prompt_for_user_token(username, scope, client_id, client_secret, redirect_uri)
File "/Library/Python/2.7/site-packages/spotipy/util.py", line 86, in prompt_for_user_token
token_info = sp_oauth.get_access_token(code)
File "/Library/Python/2.7/site-packages/spotipy/oauth2.py", line 210, in get_access_token
raise SpotifyOauthError(response.reason)
spotipy.oauth2.SpotifyOauthError: Bad Request
how do I fix this?

I ran the same example code and ran into the same issues. But got it working by running a server on localhost first python -m SimpleHTTPServer and then made my app's website http://localhost:8000 and my redirect http://localhost:8000 too. After that I opened a new terminal window and ran python myscript.py my_user_name the url then opened in my browser if it didn't open for you, you could just copy and paste the url link it gave you from this line in your terminal
Opening https://accounts.spotify.com/authorize?scope=user-library-read&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcallback&response_type=code&client_id=d3b2f7a12362468daa393cf457185973 in your browser
directly into your browser and you'll be greeted with a page that requests you give the app access to your account. After doing this the new url that you should copy and paste in the terminal will appear directly in the browser. You wont see anything happen afterwards because you need to print the token :
token = util.prompt_for_user_token(
username, scope, client_id, client_secret, redirect_uri)
if token:
print "token: ", token
sp = spotipy.Spotify(auth=token)
# code
else:
print "Can't get token for", username

Related

Play songs in Spotify from code in terminal Python

Hi everyone I'm seeing tutorials of Spotify API but I have one doubt, it's possible to send directly from code comands like play, next or play an specific song?
And if you are playing spotify in your phone it will change the song?
Update 1: This is the code that I have at the moment but I have this error message when I run it: (HELP WITH THIS)
SpotifyException: http status: 403, code:-1 - https://api.spotify.com/v1/me/player/play:
Player command failed: Premium required, reason: PREMIUM_REQUIRED
And this is my code:
from spotipy.oauth2 import SpotifyClientCredentials
import spotipy
client_id = ""
client_secret = ""
autor = 'Radiohead'
sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials(client_id, client_secret))
result = sp.search(autor)
print(result)
#
sp.start_playback(uris=['spotify:artist:4Z8W4fKeB5YxbusRsdQVPb'])
Here is working code:
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from pprint import pprint
client_id = ""
client_secret = ""
redirect_uri = ""
scope = "user-read-playback-state,user-modify-playback-state"
sp = spotipy.Spotify(
auth_manager=spotipy.SpotifyOAuth(
client_id=client_id,
client_secret=client_secret,
redirect_uri=redirect_uri,
scope=scope, open_browser=False))
# Shows playing devices
res = sp.devices()
pprint(res)
# Change track
sp.start_playback(uris=['spotify:track:6gdLoMygLsgktydTQ71b15'])
You have to put a dummy redirect URL inside the code and in the dashboard of your app.
The script will ask “Go to the following URL:”, and after logging in, you'll need copy the resulting URL after “Enter the URL you was redirected to:”.

Python onedrivesdk - invalid_request error

I want to upload files and create folders on OneDrive with Python. So i copied the code from the OnDrive GitHub GitHub, registered my App at Azure, copied the ID and created an secret. So far so good.
But now, if i run my code. The Browser opens asking for the permission to login automatically, agreed and then i get this error:
Exception: invalid_request
I think it has something to do with the redirect_uri because if i copy this into my browser i cant access it.
Here is my code:
import onedrivesdk
from onedrivesdk.helpers import GetAuthCodeServer
redirect_uri = 'http://localhost:8080/'
client_secret = 'The secret i created on Azure'
scopes=['wl.signin', 'wl.offline_access', 'onedrive.readwrite']
client = onedrivesdk.get_default_client(
client_id='The ID Azure created for me', scopes=scopes)
auth_url = client.auth_provider.get_auth_url(redirect_uri)
#this will block until we have the code
code = GetAuthCodeServer.get_auth_code(auth_url, redirect_uri)
client.auth_provider.authenticate(code, redirect_uri, client_secret)
I also tried it with an Proxy:
import onedrivesdk
from onedrivesdk.helpers import GetAuthCodeServer
from onedrivesdk.helpers import http_provider_with_proxy
redirect_uri = 'http://localhost:8080'
client_secret = 'Secret created with Azure'
client_id = 'ID id got from Azure'
scopes=['wl.signin', 'wl.offline_access', 'onedrive.readwrite']
client = onedrivesdk.get_default_client(client_id, scopes=scopes)
auth_url = client.auth_provider.get_auth_url(redirect_uri)
code = GetAuthCodeServer.get_auth_code(auth_url, redirect_uri)
proxy = {
'http': 'http://localhost:8888',
'https': 'https://localhost:8888'
}
http = http_provider_with_proxy.HttpProviderWithProxy(proxy, verify_ssl=True)
auth = onedrivesdk.AuthProvider(http, client_id, ['onedrive.readwrite'])
client = onedrivesdk.OneDriveClient(redirect_uri, auth, http)
f = onedrivesdk.Folder()
i = onedrivesdk.Item()
i.name = 'New Folder'
i.folder = f
returned_item = client.item(drive='me', id='root').children.add(i)
That gives me this error message:
RuntimeError: Session must be authenticated
before applying authentication to a request.
Your code works - e.g. it sends the info you want to send. However the credentials you have entered will of course return an invalid request - you're trying to connect to azure with:
client_id: 'The ID Azure created for me'
Which I'm pretty sure doesn't exists. The issue is you need an account & pass your script those (valid) account informations to connect to it.

Submit sitemaps using Python and Google Search Console API

I'm writing a Python script to submit sitemaps in a row to the Search Console.
Python quickstart example is working OK : https://developers.google.com/webmaster-tools/search-console-api-original/v3/quickstart/quickstart-python
I tried with the following code to submit my sitemaps:
CLIENT_ID = 'xxxxx'
CLIENT_SECRET = 'yyyyyy'
OAUTH_SCOPE = 'https://www.googleapis.com/auth/webmasters'
# 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 = 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)
WEBSITE = 'http://www.mywebsite.com'
SITEMAP_PATH = 'http://www.mywebsite.com/sitemaps/'
SITEMAPS_LIST = ['sitemap1.xml','sitemap2.xml','sitemap3.xml']
print ('Adding sitemaps to website ' + WEBSITE)
for sitemap in SITEMAPS_LIST:
print (' '+SITEMAP_PATH + sitemap)
webmasters_service.sitemaps().submit(siteUrl=WEBSITE, feedpath=SITEMAP_PATH + sitemap)
No error. But the sitemaps are not added to my Search Console.
If I try to add a file manually in Search Console or through the API explorer web interface, it's working.
Can you please try adding .execute() to the last of the statement?
like
webmasters_service.sitemaps().submit(siteUrl=WEBSITE, feedpath=SITEMAP_PATH + sitemap).execute()

INVALID_CLIENT when trying to use Spotipy to authorize an api call

I'm attempting to call the Spotify API and have set up an app/got my client ID and Secret. Here's an example of my code (with specifics blocked out):
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)
I've made sure my URL is exactly the same as what's registered in my Spotify app development page, and I've added the client ID, redirect URIs and client Secret keys to my environment variables.
So far a separate tab opens up (https://accounts.spotify.com/authorize?client_id=http%3A%2F%2Flocalhost%3A8888%2Fcallback%2F&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A8888%2Fcallback%2F&scope=playlist-read-private+user-library-read) but I'm only getting 'INVALID_CLIENT: Invalid client' on that page. What can I do/change to make this work?
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/')
Is there a typo in here, since you copied the redirect uri also as the client id and secret?

"Oops! Something went wrong" when trying to get spotipy token

I'm trying to access my library using spotipy and have the following code:
import spotipy
import spotipy.util as util
clientid = 'myid'
clientsecret = 'mysecret'
username = 'myname'
scopes = 'user-library-modify playlist-modify-private'
redirect = 'localhost:8888/callback'
def getToken(SPOTIPY_CLIENT_ID, SPOTIPY_CLIENT_SECRET, username, scope, redirect):
token = util.prompt_for_user_token(username,
scope,
client_id=SPOTIPY_CLIENT_ID,
client_secret=SPOTIPY_CLIENT_SECRET,
redirect_uri=redirect)
if token:
print('Token successfully obtained!')
return token
else:
print('Failed to get token!')
return 0
getToken(clientid, clientsecret, username, scopes, redirect)
This does one of two things: It will open up another browser window and give an option to click "Okay" or "Cancel", neither of which does anything when I click them; or it will give me the following error:
The Enter the URL you were redirected to: prompt that I get seems to throw a Bad Request error whenever I try to put in either my redirect url as defined above or URL I'm directed to, with the Client ID and Client Secret verbatim.
Any help is appreciated.

Categories