I want to make Spotify Now Playing! I think there are quite a few people who say that (such as me), but since there are surprisingly few articles, this time I will write a program that automatically tweets Spotify's Now Playing to Twitter in Python.
** There is a completed form at the very end, so if you want to see the completed form, please go there ~ **
Have a free or paid Spotify account It can be said that "Python comprehension"
You can hit the Spotify API directly, but when I was looking at the official website, Library of various languages was posted, so this time I will try using Spotipy, which is written here. Spotipy has an overwhelming number of Stars, and since it was jointly developed, I thought it was stable, so I decided to use ** Spotipy ** this time. Look at the Readme etc. and use the one that suits you.
If you look at the creator of the library, the library written on the official website, both ** are made by the same person ^ ^ ** Spotipy is co-developed, Tekore seems to be personal development.
To use the Spotify API, you need to register your application from Dashboard. Please register from here. https://developer.spotify.com/dashboard/applications/
Click ** CREATE AN APP ** to create it.
Enter the name and description of the application, accept the terms of use, and create the application.
When you create an application, ** Your application'application name' has been successfully created. ** will be displayed and the page will open.
Make a note of the ** Client ID ** and ** Client Secret **.
You can install it with PIP, so install it with `` `pip install spotipy```.
This time, I will try to get Guiano's icon URL by name search. Please listen to Guiano's song.
import spotipy
import sys
client_id = 'Client ID'
client_secret = 'Client secret ID'
client_credentials_manager = spotipy.oauth2.SpotifyClientCredentials(client_id, client_secret)
spotify = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
if len(sys.argv) > 1:
name = ' '.join(sys.argv[1:])
else:
name = 'Guiano'
results = spotify.search(q='artist:' + name, type='artist')
items = results['artists']['items']
if len(items) > 0:
artist = items[0]
print(artist['name'], artist['images'][0]['url'])
You can also get the icon by specifying the ID. To get the artist's ID, go to the artist's profile page ... → Share → Copy Spotify URL.
To get the information of the music currently playing (getting information as an individual user), you need your user name and 〇〇, so we will get it.
Go to Account Information (https://www.spotify.com/jp/account/overview/?utm_source=spotify&utm_medium=menu&utm_campaign=your_account) and make a note of your ** username **. Please note that it seems to be different from the name of a normal account.
import spotipy
client_id = 'Client ID'
client_secret = 'Client secret ID'
client_credentials_manager = spotipy.oauth2.SpotifyClientCredentials(client_id, client_secret)
spotify = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
token = spotipy.util.prompt_for_user_token(
username = "username",
scope = "user-read-currently-playing",
client_id = client_id,
client_secret = client_secret,
redirect_uri = "https://example.com/callback/"
)
spotify = spotipy.Spotify(auth=token)
current_playing = spotify.current_user_playing_track()
print(current_playing)
If you leave it as it is, you will get angry with ** INVALID_CLIENT: Invalid redirect URI ** when you execute the code, so set the redirect URL from Spotify Dashboard. This time, the redirect URL (strictly URI) in the code is set to ** example.com/callback/, so set example.com/callback/ to Spotify Dashboard as well. Open Spotify Dashboard, click the application, SETTING, enter ** https://example.com/callback/ in ** Redirect URIs ** and save. If you keep example.com, it may be bad for security, so you may want to use your own domain.
If you run it again with this, it will fly to accounts.spotify.com/ and authenticate the application.
Then try again. Then on the console
Couldn't read cache at: .cache-xxxxxxxxxx
Enter the URL you were redirected to:
Is displayed and a web page is opened. Copy the URL as it is and paste it into the console. Then Enter !!!!!!
Then, what! The song being played or last played on the console! ?? Since it is returned in the form of json, it is taken out like ['item'] ['name']. The code is here.
import spotipy
client_id = 'Client ID'
client_secret = 'Client secret ID'
client_credentials_manager = spotipy.oauth2.SpotifyClientCredentials(client_id, client_secret)
spotify = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
token = spotipy.util.prompt_for_user_token(
username = "username",
scope = "user-read-currently-playing",
client_id = client_id,
client_secret = client_secret,
redirect_uri = "https://example.com/callback/"
)
spotify = spotipy.Spotify(auth=token)
current_playing = spotify.current_user_playing_track()
print(current_playing['item']['name'])
If you run it with this! You should see the title of the song you are playing.
C:\Users\nixo\anaconda3\python.exe C:/Users/nixo/Desktop/NowPlaying/main.py
Untitled
Like this.
This time, we will tweet using the standard Tweepy. Click here for how to use Tweepy Various types of Tweepy. Ma ♡ and ♡ me ♡
import spotipy
import tweepy
#API authentication to Spotify and Twitter
client_id = 'Client ID'
client_secret = 'Client secret ID'
client_credentials_manager = spotipy.oauth2.SpotifyClientCredentials(client_id, client_secret)
spotify = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
CK = "Consumer Key here"
CS = "Here is the Consumer Secret"
AT = "Access Token here"
ATS = "Access Token Secret here"
auth = tweepy.OAuthHandler(CK, CS)
auth.set_access_token(AT, ATS)
api = tweepy.API(auth)
#End of certification
token = spotipy.util.prompt_for_user_token(
username = "username",
scope = "user-read-currently-playing",
client_id = client_id,
client_secret = client_secret,
redirect_uri = "https://example.com/callback/"
)
spotify = spotipy.Spotify(auth=token)
current_playing = spotify.current_user_playing_track()
print(current_playing['item']['name'])
api.update_status(current_playing['item']['name'] + " #NowPlaying")
By doing this, you can tweet Now Playing. But this alone is not tasty,
For those who are not familiar with Python, we will use ** cloudinary **, a service that is taken care of by OGP automatic generation. It is the one that will generate the image when you enter characters in the URL. Although it is an overseas service, it is rarely available in Japanese! !! !!
I bought a pen tab recently, so I wrote it with CLIP STUDIO! !! !! !! !! !! !! This time, I will put the characters on the base of this image.
Yes. Make it, log in and go to the dashboard.
Then go to ** Media Library ** and drag and drop the base image
Then it will be displayed like this
When you move the cursor to the image, a Copy URL will appear, so click it to copy it.
This image is this URL
https://res.cloudinary.com/nixo/image/upload/v1609762642/%E3%81%AA%E3%81%86%E3%81%B7%E3%82%8C%E3%83%BC_vjxior.png
To enter characters https://res.cloudinary.com/nixo/image/upload/ Here/v1609762642 /% E3% 81% AA% E3% 81% 86% E3% 81% B7% E3% 82 Write variously in% 8C% E3% 83% BC_vjxior.png
.
I think Catnose's miscellaneous blog is easy to understand. Please refer to it. https://catnose99.com/cloudinary-dynamic-ogp-image/
Enter `` `l_text: Sawarabi% 20Gothic_50_bold: {music_title}, co_rgb: 333, w_1300, c_fit``` between ** upload ** and ** v naughty. This is the full URL
https://res.cloudinary.com/nixo/image/upload/l_text:Sawarabi%20Gothic_50_bold:{music_title},co_rgb:333,w_1300,c_fit/v1609762642/%E3%81%AA%E3%81%86%E3%81%B7%E3%82%8C%E3%83%BC_vjxior.png
Save the file and try to tweet. (URL cannot be specified directly) By the way, if there is a space in the URL, the URL cannot be accessed, so I try to remove the space. Also, I struggled for several hours to include Japanese in the URL, so please be careful.
import spotipy
import tweepy
import urllib.request
import urllib
#API authentication to Spotify and Twitter
client_id = 'Client ID'
client_secret = 'Client secret ID'
client_credentials_manager = spotipy.oauth2.SpotifyClientCredentials(client_id, client_secret)
spotify = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
CK = "Consumer Key here"
CS = "Here is the Consumer Secret"
AT = "Access Token here"
ATS = "Access Token Secret here"
auth = tweepy.OAuthHandler(CK, CS)
auth.set_access_token(AT, ATS)
api = tweepy.API(auth)
#End of certification
token = spotipy.util.prompt_for_user_token(
username = "username",
scope = "user-read-currently-playing",
client_id = client_id,
client_secret = client_secret,
redirect_uri = "https://example.com/callback/"
)
spotify = spotipy.Spotify(auth=token)
current_playing = spotify.current_user_playing_track()
music_title = current_playing['item']['name']
artist_name = current_playing['item']['artists'][0]['name']
music_title = music_title.replace(' ', '') #If there is a space, an error will not occur in image generation. Both full-width and half-width.
music_title = music_title.replace(' ', '')
artist_name = artist_name.replace(' ', '')
artist_name = artist_name.replace(' ', '')
img_url = 'https://res.cloudinary.com/nixo/image/upload/l_text:Sawarabi%20Gothic_120_bold:' + urllib.parse.quote_plus(music_title, encoding='utf-8') + "-" + urllib.parse.quote_plus(artist_name, encoding='utf-8') + ',co_rgb:333,w_1300,c_fit/v1609768419/nowplay_kzuxtk.png'
img_url = img_url.replace(' ', '') #If there is a space, an error will not occur in image generation
img_url = img_url.replace(' ', '')
img_save_name = "music.png "
urllib.request.urlretrieve(str(img_url), img_save_name)
api.update_with_media(filename = "./music.png ", status = f"SongTitle: {music_title}\nArtist: {artist_name}\n \n#NowPlaying")
This time, I will use Pillow to make a tweet with an image. ** I'm sorry I'm writing now. ** **
It's based on the Cloudinary guy. You can use the schedule library, but in this case, time.sleep is intuitively shorter, so we will use time.sleep this time. I searched for the Spotipy documentation, but it seems that there is no event when the song changes, so this time I will specify the average time of the song. How long is the average time for one song to avoid being alone in karaoke? says that JPOP averages 4 to 5 minutes and Vocaloid averages 3 minutes and 46 seconds, so this time ** 4 minutes and 15 seconds. ** Specify the interval. To do this, simply enclose it in while True and time.sleep at the end, but if the song hasn't changed from the previous time, don't tweet.
import spotipy
import tweepy
import urllib.request
import urllib
#API authentication to Spotify and Twitter
client_id = 'Client ID'
client_secret = 'Client secret ID'
client_credentials_manager = spotipy.oauth2.SpotifyClientCredentials(client_id, client_secret)
spotify = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
CK = "Consumer Key here"
CS = "Here is the Consumer Secret"
AT = "Access Token here"
ATS = "Access Token Secret here"
auth = tweepy.OAuthHandler(CK, CS)
auth.set_access_token(AT, ATS)
api = tweepy.API(auth)
#End of certification
music_title = ""
msc = " "
while True:
try:
token = spotipy.util.prompt_for_user_token(
username="username",
scope="user-read-currently-playing",
client_id=client_id,
client_secret=client_secret,
redirect_uri="https://example.com/callback/"
)
spotify = spotipy.Spotify(auth=token)
current_playing = spotify.current_user_playing_track()
music_title = current_playing['item']['name']
artist_name = current_playing['item']['artists'][0]['name']
music_title = music_title.replace(' ', '') #If there is a space, an error will not occur in image generation. Both full-width and half-width.
music_title = music_title.replace(' ', '')
artist_name = artist_name.replace(' ', '')
artist_name = artist_name.replace(' ', '')
if music_title == msc:
print("The song is the same!")
time.sleep(15)
else:
msc = music_title
img_url = 'https://res.cloudinary.com/nixo/image/upload/l_text:Sawarabi%20Gothic_120_bold:' + urllib.parse.quote_plus(music_title, encoding='utf-8') + "-" + urllib.parse.quote_plus(artist_name, encoding='utf-8') + ',co_rgb:333,w_1300,c_fit/v1609768419/nowplay_kzuxtk.png'
img_url = img_url.replace(' ', '') #If there is a space, an error will not occur in image generation
img_url = img_url.replace(' ', '')
img_save_name = "music.png "
urllib.request.urlretrieve(str(img_url), img_save_name)
api.update_with_media(filename = "./music.png ", status = f"SongTitle: {music_title}\nArtist: {artist_name}\n \n#NowPlaying")
time.sleep(255)#4 minutes 15 seconds
except Exception as e:
print("An error has occurred")
print(e)
time.sleep(15)
time.sleep(60)
At the beginning of the loop, it should not be the same, so I prepared the one with spaces assigned to msc first.
This time I will end with this. What you don't understand or something is wrong here? If there is such a place, I would appreciate it if you could feel free to let me know by DM or comment on Twitter.
Recommended Posts