2
\$\begingroup\$

Just a simple script that puts a user's currently playing track(on Spotify) to his account's status on vk.com. And printing info about the track in the console.

import requests
import os
import json


URL_TRACK = 'https://api.spotify.com/v1/me/player/currently-playing'
URL_STATUS = "https://api.vk.com/method/status.set"
VK_TOKEN = os.environ.get('VK_TOKEN')
SP_TOKEN = os.environ.get('SP_TOKEN')


def set_status():
    params = {
              'user_id': 8573490,
              'v': 5.92,
              'access_token': VK_TOKEN,
              'text': current_track()
    }

    status = requests.get(url=URL_STATUS, params=params)


def track_data():
    headers = {
               'Accept': 'application/json',
               'Content-Type': 'application/json',
               'Authorization': f'Bearer {SP_TOKEN}',
    }

    return requests.get(url=URL_TRACK, headers=headers)


def track_is_playing():
    return track_data().status_code == 200


def current_track():
    data = track_data().json()
    artist_path = data["item"]['artists'][0]['name']
    track_path = data["item"]['name']

    return(f'{artist_path} - {track_path}')


def run_script():
    if track_is_playing():
        set_status()
        print(current_track())
    else:
        print('Not playing')


if __name__ == "__main__":
    run_script()
\$\endgroup\$
  • \$\begingroup\$ I'm also wondering what are the options to make this thing used by many users so they don't have to deal with command-line, manual input of tokens etc. Now I could think only of web-app, written in Django for example. \$\endgroup\$ – edvard_munch Dec 11 '18 at 13:05
3
\$\begingroup\$

Rather than os.environ.get you can do getenv.

In track_data, don't pass Content-Type, because you aren't passing any body with your request.

Otherwise, it's quite reasonable. You may want to expand error checking and reporting, particularly for track_data, since you aren't currently checking the status. raise_for_status is often a good thing to do.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.