Tweet Now Playing to Twitter using the Spotify API. [Python]

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 ~ **

Premise

Have a free or paid Spotify account It can be said that "Python comprehension"

Library to use

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.

Register the application

To use the Spotify API, you need to register your application from Dashboard. Please register from here. https://developer.spotify.com/dashboard/applications/ スクリーンショット.png

Click ** CREATE AN APP ** to create it. スクリーンショット.png

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 **.

Install Spotipy

You can install it with PIP, so install it with `` `pip install spotipy```.

Try to get the composer's thumbnail image using 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. ArtistID.jpg

Get the currently playing song

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. スクリーンショット.png

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.

Tweet with the NowPlaing hashtag

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,

Let's generate an image! (For "Python comprehension")

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! !! !!

First, create a base image

I bought a pen tab recently, so I wrote it with CLIP STUDIO! !! !! !! !! !! !! なうぷれー.png This time, I will put the characters on the base of this image.

Oh, you can use this image freely (1920x1080)

Cloudinary account

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 image.png 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

Incorporate into Python code

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")

Let's generate an image! (For genius programmers)

This time, I will use Pillow to make a tweet with an image. ** I'm sorry I'm writing now. ** **

Tweet regularly (using time.sleep)

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.

end

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

Tweet Now Playing to Twitter using the Spotify API. [Python]
Tweet using the Twitter API in Python
Try using the Twitter API
Post to Twitter using Python
Try using the Twitter API
Post to your account using the API on Twitter
Access the Twitter API in Python
How to get followers and followers from python using the Mastodon API
Regularly upload files to Google Drive using the Google Drive API in Python
Try using the Wunderlist API in Python
Try using the Kraken API in Python
Create an application using the Spotify API
Sample code to get the Twitter API oauth_token and oauth_token_secret in Python 2.7
Tweet regularly with the Go language Twitter API
Procedure to use TeamGant's WEB API (using python)
Try using the BitFlyer Ligntning API in Python
Try using the DropBox Core API in Python
Convert the cURL API to a Python script (using IBM Cloud object storage)
To automatically send an email with an attachment using the Gmail API in Python
Continue to retrieve tweets containing specific keywords using the Streaming API in Python
Search Twitter using Python
Push notifications from Python to Android using Google's API
Crawl the URL contained in the twitter tweet with python
Send and receive Gmail via the Gmail API using Python
Try to delete tweets in bulk using Twitter API
[Introduction to Python] How to stop the loop using break?
Using the National Diet Library Search API in Python
A little bit from Python using the Jenkins API
A story about a Python beginner trying to get Google search results using the API
Try hitting the Twitter API quickly and easily with Python
The first API to make with python Djnago REST framework
Create a real-time auto-reply bot using the Twitter Streaming API
Start to Selenium using python
[Python] I tried to visualize the follow relationship of Twitter
Connect to the Bitcoin network using pycoin (Python Cryptocoin Utili)
Try using the PeeringDB 2.0 API
[Python] I tried collecting data using the API of wikipedia
Call the API with python3.
Output product information to csv using Rakuten product search API [Python]
An easy way to hit the Amazon Product API in Python
[Introduction to Python] What is the most powerful programming language now?
[September 2020 version] Explains the procedure to use Gmail API with Python
I created a Python library to call the LINE WORKS API
[Python] LINE notification of the latest information using Twitter automatic search
Hit the New Relic API in Python to get the server status
I tried to analyze my favorite singer (SHISHAMO) using Spotify API
[Python] Conversation using OpenJTalk and Talk API (up to voice output)
[Python] I tried to get various information using YouTube Data API!
How to send a request to the DMM (FANZA) API with python
Python beginners hit the unofficial API of Google Play Music to play music
How to install python using anaconda
Leave the troublesome processing to Python
Getting the arXiv API in Python
Data acquisition using python googlemap api
Hit the Sesami API in Python
Specifying the date with the Twitter API
[Python] Hit the Google Translation API
[Python3] Google translate google translate without using api
[Lambda] [Python] Post to Twitter from Lambda!
Try using Pleasant's API (python / FastAPI)
In the python command python points to python3.8