Код: Выделить всё
import datetime
import json
import os
import time
import requests
import spotipy
from spotipy.oauth2 import SpotifyOAuth
LAST_REFRESH = None
def refresh_access_token():
sp = spotipy.Spotify(
auth_manager=SpotifyOAuth(
client_id="",
client_secret="",
redirect_uri="http://localhost:8888",
scope="user-read-currently-playing",
)
)
current_user = sp.current_user()
assert current_user is not None
with open(".cache", "r") as f:
data = json.load(f)
access_token = data["access_token"]
os.remove(".cache")
global LAST_REFRESH
LAST_REFRESH = datetime.datetime.now()
print("Access token refreshed")
return access_token
def get_current_track(access_token):
try:
response = requests.get(
'https://api.spotify.com/v1/me/player/currently-playing',
headers={
"Authorization": f"Bearer {access_token}"
}
)
json_resp = response.json()
track_id = json_resp['item']['id']
track_name = json_resp['item']['name']
artists = [artist for artist in json_resp['item']['artists']]
link = json_resp['item']['external_urls']['spotify']
artist_names = ', '.join([artist['name'] for artist in artists])
current_track_info = {
"id": track_id,
"track_name": track_name,
"artists": artist_names,
"link": link
}
return current_track_info
except:
print('Error: Unable to get current track')
time.sleep(10)
def send_to_server(spotifyID):
print(spotifyID)
#...
def main():
current_track_id = None
access_token = refresh_access_token()
while True:
try:
if (datetime.datetime.now() - LAST_REFRESH).seconds > 3500:
access_token = refresh_access_token()
current_track_info = get_current_track(access_token)
if current_track_info['id'] != current_track_id:
current_track_id = current_track_info['id']
send_to_server(current_track_id)
time.sleep(1)
except:
print('Error: Unable to get current track')
time.sleep(10)
if __name__ == '__main__':
main()
Код: Выделить всё
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["python", "main.py"]
Код: Выделить всё
version: '3.1'
services:
test:
image: test
build:
context: .
dockerfile: Dockerfile
container_name: test
Подробнее здесь: https://stackoverflow.com/questions/785 ... sing-flask