Created
May 20, 2023 20:06
-
-
Save adiberr/63317a0cd3f0da4f1449dc879df3eaab to your computer and use it in GitHub Desktop.
Search for a song using Spotify's API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import requests | |
| import webbrowser | |
| import sys | |
| import json | |
| CLIENT_ID= | |
| CLIENT_SECRET= | |
| REDIRECT_URI= | |
| def get_authorization_url(): | |
| endpoint = "https://accounts.spotify.com/authorize" | |
| params = { | |
| "client_id": CLIENT_ID, | |
| "response_type": "code", | |
| "redirect_uri": REDIRECT_URI, | |
| "scope": "user-read-private user-read-email" # Add required scopes | |
| } | |
| url = requests.Request("GET", endpoint, params=params).prepare().url | |
| return url | |
| def get_access_token(authorization_code): | |
| url = "https://accounts.spotify.com/api/token" | |
| headers = { | |
| "Content-Type": "application/x-www-form-urlencoded" | |
| } | |
| data = { | |
| "grant_type": "authorization_code", | |
| "code": authorization_code, | |
| "redirect_uri": REDIRECT_URI, | |
| "client_id": CLIENT_ID, | |
| "client_secret": CLIENT_SECRET | |
| } | |
| response = requests.post(url, headers=headers, data=data) | |
| data = response.json() | |
| if response.status_code == 200: | |
| access_token = data["access_token"] | |
| return access_token | |
| else: | |
| return None | |
| def check_access_token(): | |
| try: | |
| with open('token.txt', "r") as file: | |
| access_token = file.read().strip() | |
| if access_token: | |
| # Check if the access token is valid (e.g., by making an API request) | |
| url = "https://api.spotify.com/v1/me" | |
| headers = { | |
| "Authorization": f"Bearer {access_token}" | |
| } | |
| response = requests.get(url, headers=headers) | |
| if response.status_code == 200: | |
| return access_token | |
| except IOError: | |
| pass | |
| return None | |
| class Song: | |
| def __init__(self, name, artist, album, url, cover): | |
| self.artist = artist | |
| self.name = name | |
| self.album = album | |
| self.url = url | |
| self.cover = cover | |
| def create_song(data): | |
| name = data["name"] | |
| artist = data["artists"][0]["name"] | |
| album = data["album"]["name"] | |
| url = data["external_urls"]['spotify'] | |
| cover = data["album"]["images"][0]['url'] | |
| return Song(name, artist, album, url, cover) | |
| def search_song(query, access_token): | |
| url = "https://api.spotify.com/v1/search" | |
| headers = { | |
| "Authorization": f"Bearer {access_token}" | |
| } | |
| params = { | |
| "q": query, | |
| "type": "track", | |
| "limit": 1 | |
| } | |
| return requests.get(url, headers=headers, params=params) | |
| def main(query): | |
| print("Search:", query) | |
| # Check if access token exists and is valid | |
| access_token = check_access_token() | |
| if access_token: | |
| print("Existing Access Token:", access_token) | |
| else: | |
| authorization_url = get_authorization_url() | |
| print("Please visit the following URL to authorize the application:") | |
| print(authorization_url) | |
| # Open the login page in the default web browser | |
| webbrowser.open(authorization_url, new=2) | |
| # Prompt the user to enter the authorization code after logging in | |
| authorization_code = input("Enter the authorization code: ") | |
| access_token = get_access_token(authorization_code) | |
| if access_token: | |
| # print("Access Token:", access_token) | |
| # Store the access token in a file | |
| with open('token.txt', "w") as file: | |
| file.write(access_token) | |
| else: | |
| print("Failed to obtain access token.") | |
| exit(1) | |
| # Continue with the rest of the script, e.g., calling the search_song function | |
| response = search_song(query, access_token) | |
| data = response.json() | |
| if response.status_code == 200: | |
| if data["tracks"]["items"]: | |
| result = data["tracks"]["items"][0] | |
| # print(json.dumps(result, indent=2)) | |
| song = create_song(result) | |
| print('Name:', f"{song.artist} - {song.name}") | |
| print("Album:", song.album) | |
| print("Listen:", song.url) | |
| print("Cover:", song.cover) | |
| # Open the login page in the default web browser | |
| webbrowser.open(result["external_urls"]['spotify'], new=2) | |
| else: | |
| return "No results found." | |
| else: | |
| return "Error: " + str(response.status_code) | |
| if __name__ == '__main__': | |
| if len(sys.argv) < 2: | |
| raise BaseException("Error: query required") | |
| main(sys.argv[1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment