Example #1
0
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'SubtoneSelector.settings')

import django
django.setup()

SPOTIPY_REDIRECT_URI = 'http://localhost:8000/logged/'
SPOTIPY_CLIENT_ID = 'c6b73836172b40b2ac90879f9b54271b'
SPOTIPY_CLIENT_SECRET = 'bced1ccc150b4ee5b65f295b98e33b95'
CACHE_PATH = ''
token = ''
username = ''

sp_oauth = spotipy.SpotifyOAuth(SPOTIPY_CLIENT_ID,
                                SPOTIPY_CLIENT_SECRET,
                                SPOTIPY_REDIRECT_URI,
                                scope='playlist-modify-public',
                                cache_path=CACHE_PATH,
                                show_dialog=False)

from Recommendation.models import BigArtist, SmallArtist


def getArtistPopularity(artist):
    artist = sp.artist(artist)
    artist_name = artist['name']
    artist_popularity = artist['popularity']
    print(artist_name, artist_popularity)


def getArtists(genre):
    big_artist = []
    def __init__(self, device_name, title, artist, duration_ms, progress_ms, art, is_playing):
        self.device_name = device_name
        self.title = title
        self.artist = artist
        self.duration_ms = duration_ms
        self.progress_ms = progress_ms
        self.art = art
        self.is_playing = is_playing

# get the username from terminal
username = sys.argv[1]

# authorize
spotifyObject = spotipy.Spotify(auth_manager=spotipy.SpotifyOAuth(
    "f34308de95354355a1cd0c3565659dd8",
    "f883197f63654ba0906f2de7ac31be8d",
    "https://google.co.nz/",
    scope="user-read-playback-state"
    ))


def main_loop():
    MAX_TITLE_LENGTH = 36
    TIME_TO_SLEEP = 0.3
    TIME_UNTIL_TIMEOUT = 300
    current_time = 0
    t0 = time.time()
    while current_time < TIME_UNTIL_TIMEOUT:
        current_time += TIME_TO_SLEEP
        try:
            # get track info
            track = spotifyObject.current_user_playing_track()
0M7IiBVBquus5YkeV4xEyt YouTube channel with minimal dub, industrial techno, minimal techno. Add your own on www.mirror.fm #mirrorfm
7xbwKyY3vYNFGunL35KtYo YouTube channel with industrial techno. Add your own on www.mirror.fm #mirrorfm
6LFZ6taEfZ0i7VWnZl8u4Z YouTube channel. Add your own on www.mirror.fm #mirrorfm
"""

import boto3
from collections import OrderedDict
from operator import itemgetter
import spotipy

client = boto3.client("dynamodb", region_name='eu-west-1')
dynamodb = boto3.resource("dynamodb", region_name='eu-west-1')
mirrorfm_yt_playlists = dynamodb.Table('mirrorfm_yt_playlists')

sp = spotipy.Spotify(auth_manager=spotipy.SpotifyOAuth(
    scope='playlist-modify-public playlist-modify-private',
    username="******"))

# Get all
playlists = mirrorfm_yt_playlists.scan()
print(len(playlists['Items']))

for p in playlists['Items']:
    # Get top 3 genres
    genres = p.get('genres')
    sorted_genres = OrderedDict(
        sorted(genres.items(), key=itemgetter(1), reverse=True))
    top3_genres = list(sorted_genres)[:3]

    # Description
    genres_str = ''
Example #4
0
tag_list = soup.findAll(
    class_='chart-element__information__song text--truncate color--primary')
print('Song List Created')

for tag in tag_list:
    song_list.append(tag.text)

# Search Songs and Extract URIs

uri_list = []

scope = "user-library-read"
sp = spotipy.Spotify(
    auth_manager=spotipy.SpotifyOAuth(client_id=keys.spotify_client_id,
                                      client_secret=keys.spotify_client_secret,
                                      scope=scope,
                                      redirect_uri=keys.spotify_redirect_uri))

user_id = sp.current_user()['id']

for i in range(10):
    search_string = song_list[i]

    test = sp.search(q=search_string, type='track')
    name = test['tracks']['items'][0]['name']
    uri = test['tracks']['items'][0]['uri']
    uri_list.append(uri)
    print(f'Song \'{name}\' added')

print('All Songs added')
import json

import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

from colour_puller.album import SpotifyAlbum
from colour_puller.database import AlbumDatabase


auth = spotipy.SpotifyOAuth(
    redirect_uri='http://localhost:8888/callback', username='******'
)

sp = spotipy.Spotify(auth_manager=auth)

recently_played = sp.current_user_recently_played()

recent_albums = []

for item in recently_played['items'][::-1]:
    album = SpotifyAlbum(item['track']['album'])
    if album.art_link and not any(prev == album for prev in recent_albums):
        recent_albums.append(album)

ad = AlbumDatabase()

ad.add_albums(recent_albums)

# Get counts
queue = ad.count_records(status='queued')
completed = ad.count_records(status='completed')
Example #6
0
        return None


def sleeping(duration, result, index):
    time.sleep(duration)
    result[index] = True
    sys.exit()


# Scope required for currently playing
scope = "user-read-currently-playing"

# Create our spotifyOAuth object
spotifyOAuth = spotipy.SpotifyOAuth(
    client_id=os.environ['SPOTIPY_CLIENT_ID'],
    client_secret=os.environ['SPOTIPY_CLIENT_SECRET'],
    redirect_uri=os.environ['SPOTIPY_REDIRECT_URI'],
    scope=scope)

token = spotifyOAuth.get_access_token()
# print(json.dumps(token, sort_keys=True, indent=4))

# Create our spotifyObject
spotifyObject = spotipy.Spotify(auth=token['access_token'])

# Create out geniusObject
access_token = os.environ['GENIUS_ACCESS_TOKEN']
genius = lg.Genius(access_token)

counter = 1
result = [False]
Example #7
0
def prompt_for_user_token_mod(username,
                              scope=None,
                              client_id=None,
                              client_secret=None,
                              redirect_uri=None,
                              cache_path=None,
                              oauth_manager=None,
                              show_dialog=False):
    if not oauth_manager:
        if not client_id:
            client_id = os.getenv("SPOTIPY_CLIENT_ID")

        if not client_secret:
            client_secret = os.getenv("SPOTIPY_CLIENT_SECRET")

        if not redirect_uri:
            redirect_uri = os.getenv("SPOTIPY_REDIRECT_URI")

        if not client_id:
            print("""
                You need to set your Spotify API credentials.
                You can do this by setting environment variables like so:
                export SPOTIPY_CLIENT_ID='your-spotify-client-id'
                export SPOTIPY_CLIENT_SECRET='your-spotify-client-secret'
                export SPOTIPY_REDIRECT_URI='your-app-redirect-url'
                Get your credentials at
                    https://developer.spotify.com/my-applications
            """)
            raise spotipy.SpotifyException(550, -1, "no credentials set")

        cache_path = cache_path or ".cache-" + username

    sp_oauth = oauth_manager or spotipy.SpotifyOAuth(client_id,
                                                     client_secret,
                                                     redirect_uri,
                                                     scope=scope,
                                                     cache_path=cache_path,
                                                     show_dialog=show_dialog)

    # try to get a valid token for this user, from the cache,
    # if not in the cache, the create a new (this will send
    # the user to a web page where they can authorize this app)

    token_info = sp_oauth.get_cached_token()

    if not token_info:

        server_address = ('', 8420)
        httpd = OAuthHTTPServer(server_address)

        import webbrowser

        webbrowser.open(sp_oauth.get_authorize_url())
        httpd.server.handle_request()

        if httpd.server.url:
            url = httpd.server.url

            code = sp_oauth.parse_response_code(url)
            token = sp_oauth.get_access_token(code, as_dict=False)
    else:
        return token_info["access_token"]

    # Auth'ed API request
    if token:
        return token
    else:
        return None
Example #8
0
username = ''
#Scope to view the playing song
scope = 'user-read-currently-playing'
#Add your client ID from Spotify Dev
client_id = ''
#Add your client secret from Spotify Dev
client_secret = ''
redirect_uri = 'http://localhost:8080/callback'

#script has a bunch of time.sleep, if it seems to take too long try changing these values

#spotify authenticator / manages tokens as well
sp = spotipy.Spotify(
    auth_manager=spotipy.SpotifyOAuth(username=username,
                                      client_id=client_id,
                                      client_secret=client_secret,
                                      redirect_uri=redirect_uri,
                                      scope=scope))


def relaunchSpotify():

    keyboard = Controller()

    #Finds all PIDs with the name Spotify
    for proc in psutil.process_iter():
        if any(procstr in proc.name() for procstr in ['Spotify']):
            try:
                #Kills all processes of spotify
                proc.kill()
            #sometimes the process will already be gone
Example #9
0
 def get_spotipy_instance(self):
     return spotipy.Spotify(auth_manager=spotipy.SpotifyOAuth(scope=SCOPE, client_id=self.client_id,
                                                              client_secret=self.client_secret,
                                                              redirect_uri=REDIRECT_URI))
Example #10
0
def main():
    spotify = spotipy.Spotify(auth_manager=spotipy.SpotifyOAuth())
    me = spotify.me()
    pprint(me)
Example #11
0
import json
import uuid

from django.conf import settings
from django.http import JsonResponse, HttpResponseBadRequest, HttpResponseRedirect, HttpResponseNotAllowed, HttpResponseNotFound

import spotipy

from . import db, mail, patterns, apikeys

SPOTIFY_OAUTH = spotipy.SpotifyOAuth(
    settings.SPOTIFY_CLIENT_ID,
    settings.SPOTIFY_CLIENT_SECRET,
    settings.SPOTIFY_REDIRECT_URI,
    scope=settings.SPOTIFY_SCOPE,
    username=settings.SPOTIFY_USERNAME,
)

SPOTIFY_MARKET = 'US'
SPOTIFY_CONTENT_TYPES = ['track', 'artist', 'album', 'playlist']


def _enforce_method(request, method):
    if not request.method == method:
        return HttpResponseNotAllowed([method])


def _get_user(request):
    if 'user' not in request.session:
        return None
    else:
0M7IiBVBquus5YkeV4xEyt YouTube channel with minimal dub, industrial techno, minimal techno. Add your own on www.mirror.fm #mirrorfm
7xbwKyY3vYNFGunL35KtYo YouTube channel with industrial techno. Add your own on www.mirror.fm #mirrorfm
6LFZ6taEfZ0i7VWnZl8u4Z YouTube channel. Add your own on www.mirror.fm #mirrorfm
"""

import boto3
from collections import OrderedDict
from operator import itemgetter
import spotipy

client = boto3.client("dynamodb", region_name='eu-west-1')
dynamodb = boto3.resource("dynamodb", region_name='eu-west-1')
mirrorfm_yt_playlists = dynamodb.Table('mirrorfm_yt_playlists')

sp = spotipy.Spotify(auth_manager=spotipy.SpotifyOAuth(
    scope='playlist-modify-public playlist-modify-private'))

# Get all
playlists = mirrorfm_yt_playlists.scan()
print(len(playlists['Items']))

for p in playlists['Items']:
    # Get top 3 genres
    genres = p.get('genres')
    sorted_genres = OrderedDict(
        sorted(genres.items(), key=itemgetter(1), reverse=True))
    top3_genres = list(sorted_genres)[:3]

    # Description
    genres_str = ''
    if len(top3_genres) > 0:
Example #13
0
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import os

scope = "user-read-playback-state,user-modify-playback-state"
spotify = spotipy.Spotify(
    client_credentials_manager=SpotifyClientCredentials(),
    auth_manager=spotipy.SpotifyOAuth(scope=scope))


def get_device_id():
    devices = spotify.devices()
    print(devices)
    for device in devices["devices"]:
        if device["name"] == os.getenv("SPOTIPY_DEVICE_NAME"):
            return device["id"]


def play_song(query, source="track"):
    device_id = get_device_id()
    try:
        results = spotify.search(q=query, type=source, limit=1)

        if "playlists" in results and len(results["playlists"]["items"]) > 0:
            playlist = results["playlists"]["items"][0]["uri"]
            spotify.start_playback(device_id=device_id, context_uri=playlist)
            return True, "Playing the " + source + results["playlists"][
                "items"][0]["name"]

        if "tracks" in results and len(results["tracks"]["items"]) > 0:
            track = results["tracks"]["items"][0]["uri"]
Example #14
0
GRAPH_DIR.mkdir(exist_ok=True)

parser = argparse.ArgumentParser()
parser.add_argument('-config', help='yaml config file')
config_path = parser.parse_args().config

args = yaml.load(Path(config_path).read_text(), Loader=yaml.SafeLoader)

if 'rcParams' in args.keys():
    for k, v in args['rcParams'].items():
        plt.rcParams[k] = v

if 'style' in args.keys():
    plt.style.use(args['style'])

auth = spotipy.SpotifyOAuth(redirect_uri='http://localhost:8888/callback',
                            username=args['username'])

sp = spotipy.Spotify(auth_manager=auth)

album = tools.get_album(sp, args['album_id'])

all_data = pd.concat(
    tools.Track(t).loudness(sp) for t in album['tracks']['items'])
all_data['Centred Time'] = (
    all_data['Time'] -
    (all_data.groupby('TrackNo')['Time'].transform('max') / 2))

g = sns.FacetGrid(data=all_data,
                  sharex=True,
                  sharey=True,
                  row='Name',
Example #15
0
import json
import spotipy
import spotipy.util as util
import sys
import time

scope = 'user-read-private user-read-currently-playing'

if len(sys.argv) > 1:
    username = sys.argv[1]
else:
    print("Usage: %s username" % (sys.argv[0], ))
    sys.exit()

while True:
    sp_oauth = spotipy.SpotifyOAuth(scope=scope, username=username)

    if sp_oauth:
        sp = spotipy.Spotify(oauth_manager=sp_oauth)
        for i in range(0, 359):
            results = sp.currently_playing()
            playing_file = open("playing.txt", "w+", encoding='utf-8')
            contents = str(playing_file.read())
            if results == None or results['item'] == None or results[
                    'is_playing'] == False:
                if contents != "":
                    contents = ""
                    playing_file.write("")
                    playing_file.close()
                    print("Paused or nothing's playing on Spotify.",
                          flush=True)
Example #16
0
def sleep_timer(
    username: str,
    client_id: str,
    client_secret: str,
    scope: Iterable[str],
    redirect_uri: str,
    music_stop_time: Union[int, float, datetime, timedelta],
    elapced_time_check_interval: Union[int, float] = 1.0,
) -> None:
    """Spotify sleep timer

    Args:
        username (str): spotify username code
        client_id (str): spotify client id code
        client_secret (str): spotify client secret code
        scope (Iterable[str]): spotify authorization scope
        redirect_uri (str): spotify client redirect uri
        music_stop_time (int|float|datetime|timedelta): timer setting
        elapsed_time_check_interval(int|float, optional): time check interval
    Raises:
        ValueError: cannot convert from music_stop_time to timedelta object
    """

    auth_manager: SpotifyOAuth = spotipy.SpotifyOAuth(
        client_id=client_id,
        client_secret=client_secret,
        redirect_uri=redirect_uri,
        scope=" ".join(scope),
        username=username,
    )
    spotify: Spotify = spotipy.Spotify(auth_manager=auth_manager)

    if not is_playing(spotify):
        print("does not play songs.")
        return

    stop_time: Optional[timedelta] = None
    if isinstance(music_stop_time, (int, float)):
        stop_time = timedelta(seconds=music_stop_time)
    elif isinstance(music_stop_time, datetime):
        stop_time = music_stop_time - datetime.now()
    elif isinstance(music_stop_time, timedelta):
        stop_time = music_stop_time
    else:
        raise ValueError("cannot convert stop time.")
    if stop_time < timedelta(days=0):
        raise ValueError("stopping time is before now.")

    print("start sleep timer")

    start_time: Final[datetime] = datetime.now()
    print("start {} -> {} end.".format(
        start_time.strftime("%H:%M:%S"),
        (datetime.now() + stop_time).strftime("%H:%M:%S"),
    ))

    with Progress() as progress:
        pbar = progress.add_task("will stop playing at...",
                                 total=int(stop_time /
                                           timedelta(microseconds=1)))

        while True:
            elapsed_time: timedelta = datetime.now() - start_time
            progress.update(pbar,
                            completed=elapsed_time / timedelta(microseconds=1))

            if elapsed_time > stop_time:
                break

            sleep(elapced_time_check_interval)

    if is_playing(spotify):
        spotify.pause_playback()
        print("stop playing")
Example #17
0
from telethon.tl.functions.photos import UploadProfilePhotoRequest, DeletePhotosRequest
from telethon.tl.functions.account import UpdateProfileRequest
from telethon import TelegramClient
from datetime import datetime
from termcolor import colored
import urllib.request
import configparser
import spotipy

config = configparser.ConfigParser()
config.read("config.ini")
client = TelegramClient('default', int(config["!USER!"]["tg_api_id"]),
                        config["!USER!"]["tg_api_hash"])
sp = spotipy.Spotify(auth_manager=spotipy.SpotifyOAuth(
    scope="user-read-currently-playing",
    client_id=config["!SPOTIFY!"]["client"],
    client_secret=config["!SPOTIFY!"]["secret"],
    redirect_uri=config["!SPOTIFY!"]["redirect"]))  # Connects to Spotify API


async def main():
    """ This function is the main function of the program. """

    first_name = config["!SETTINGS!"]["first_name"]
    last_name = config["!SETTINGS!"]["last_name"]
    profile_photo = config["!SETTINGS!"]["profile_photo"]
    bio_act = config["!SETTINGS!"]["bio"]
    bio_link = config["!SETTINGS!"]["bio_link"]
    market = config["!SPOTIFY!"]["market"]
    image = ["", ""]
Example #18
0
def temp():
    spotify = spotipy.Spotify(auth_manager=spotipy.SpotifyOAuth(username="******"))
    print(spotify.me())
    return render_template('home.html')
Example #19
0
def prompt_for_user_token(username,
                          scope=None,
                          client_id=None,
                          client_secret=None,
                          redirect_uri=None,
                          cache_path=None,
                          oauth_manager=None,
                          show_dialog=False):
    warnings.warn(
        "'prompt_for_user_token' is deprecated."
        "Use the following instead: "
        "    auth_manager=SpotifyOAuth(scope=scope)"
        "    spotipy.Spotify(auth_manager=auth_manager)", DeprecationWarning)
    """ prompts the user to login if necessary and returns
        the user token suitable for use with the spotipy.Spotify
        constructor

        Parameters:

         - username - the Spotify username
         - scope - the desired scope of the request
         - client_id - the client id of your app
         - client_secret - the client secret of your app
         - redirect_uri - the redirect URI of your app
         - cache_path - path to location to save tokens
         - oauth_manager - Oauth manager object.
         - show_dialog - If true, a login prompt always shows

    """
    if not oauth_manager:
        if not client_id:
            client_id = os.getenv("SPOTIPY_CLIENT_ID")

        if not client_secret:
            client_secret = os.getenv("SPOTIPY_CLIENT_SECRET")

        if not redirect_uri:
            redirect_uri = os.getenv("SPOTIPY_REDIRECT_URI")

        if not client_id:
            LOGGER.warning("""
                You need to set your Spotify API credentials.
                You can do this by setting environment variables like so:

                export SPOTIPY_CLIENT_ID='your-spotify-client-id'
                export SPOTIPY_CLIENT_SECRET='your-spotify-client-secret'
                export SPOTIPY_REDIRECT_URI='your-app-redirect-url'

                Get your credentials at
                    https://developer.spotify.com/my-applications
            """)
            raise spotipy.SpotifyException(550, -1, "no credentials set")

        cache_path = cache_path or ".cache-" + username

    sp_oauth = oauth_manager or spotipy.SpotifyOAuth(client_id,
                                                     client_secret,
                                                     redirect_uri,
                                                     scope=scope,
                                                     cache_path=cache_path,
                                                     show_dialog=show_dialog)

    # try to get a valid token for this user, from the cache,
    # if not in the cache, the create a new (this will send
    # the user to a web page where they can authorize this app)

    token_info = sp_oauth.get_cached_token()

    if not token_info:
        code = sp_oauth.get_auth_response()
        token = sp_oauth.get_access_token(code, as_dict=False)
    else:
        return token_info["access_token"]

    # Auth'ed API request
    if token:
        return token
    else:
        return None
Example #20
0
 async def get_new_token(self):
     sp = spotipy.Spotify(auth_manager=spotipy.SpotifyOAuth(
         username=config.SPOTIFY_USERNAME, scope=config.SPOTIFY_SCOPE))
     token = sp.auth_manager.get_access_token(as_dict=False)
     self.headers = {'Authorization': f'Bearer {token}'}
     self.sp = sp