Пример #1
0
def new_playlist(text):
    session['new_song'] = False
    playlist_name = text[4:]
    try:
        spotify.create_playlist(playlist_name)
        session['playlist'] = playlist_name
        return '{0} playlist created!'.format(playlist_name)
    except spotify.SpotifyException, e:
        return str(e)
Пример #2
0
def new_playlist(text):
    session['new_song'] = False
    playlist_name = text[4:]
    try:
        spotify.create_playlist(playlist_name)
        session['playlist'] = playlist_name
        return '{0} playlist created!'.format(playlist_name)
    except spotify.SpotifyException, e:
        return str(e)
Пример #3
0
def main():
    tracks = new_songs(datetime.datetime(2018, 8, 18),
                       datetime.datetime(2018, 8, 25))
    creds = spotify.get_credentials()
    pl = spotify.create_playlist("benbanerjeerichards", "New tracks last week",
                                 False, False, None, creds)["id"]
    spotify.add_to_playlist("benbanerjeerichards", pl, tracks, creds)
Пример #4
0
def create_playlist():
    """create a new playlist if there is no playlist with the same name"""
    global chosen_playlist_id
    playlist_title = playlist_text.get()
    if playlist_title == "":
        status_window("Enter a playlist title")
    else:
        chosen_playlist_id = spotify.create_playlist(spotify_user_id, playlist_title)
        playlist_text_details.config(text=playlist_title)
        status_window("Playlist created")
        playlist_text.delete(0, tkinter.END)
Пример #5
0
def create_playlist():
    user_id = decode_base64(request.json.get('user_id')).decode('utf-8')
    p_name = request.json.get('name')
    tracks = request.json.get('tracks')
    access_token = update_access_token(request)
    p_id, p_link = spotify.create_playlist(access_token, user_id, p_name)
    status_code = spotify.add_tracks(access_token, user_id, p_id, tracks)
    if status_code == 201:
        return p_link
    elif status_code == 403:
        abort(403, "Unauthorized")
    return "neither 201 nor 403... hmmmm...."
Пример #6
0
def create_playlist():
    user_id = decode_base64(request.json.get('user_id')).decode('utf-8')
    p_name = request.json.get('name')
    tracks = request.json.get('tracks')
    access_token = update_access_token(request)
    p_id, p_link = spotify.create_playlist(access_token, user_id, p_name)
    status_code = spotify.add_tracks(access_token, user_id, p_id, tracks)
    if status_code == 201:
        return p_link
    elif status_code == 403:
        abort(403, "Unauthorized")
    return "neither 201 nor 403... hmmmm...."
Пример #7
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--id")
    parser.add_argument(
        "--overwrite",
        action="store_true",
        help="Clear any items in the existing playlist before adding new songs"
    )
    parser.add_argument("--dedup",
                        action="store_true",
                        help="Remove duplicates in playlist")

    args = parser.parse_args()
    creds = get_credentials()
    username = get_profile(creds)["id"]

    ids = []
    for line in sys.stdin:
        ids.append(line.replace("\n", "").replace("\r", ""))

    if not args.id:
        if len(sys.argv) == 1:
            playlist_name = "Untitled"
        else:
            playlist_name = sys.argv[1]

        p_id = create_playlist(username, playlist_name, False, False, "",
                               creds)["id"]
        add_to_playlist(username, p_id, ids, creds)
    else:
        tracks = [] if args.overwrite else get_songs_in_playlist(
            username, args.id, creds)
        tracks = tracks + ids

        if args.dedup:
            # We want to delete items later on in the playlist and retain order
            deduped = []
            for track in tracks:
                if track not in deduped:
                    deduped.append(track)

            tracks = deduped

        # Now write new tracks
        # Overwrite playlist
        add_to_playlist(username, args.id, tracks, creds, replace=True)
Пример #8
0
import encoder
import spotify

target_file = encoder.base32_encode(encoder.get_file("stub.zip"))

print(target_file)
playlist = spotify.create_playlist("c2")

for a in target_file:
    track_id = spotify.track_finder(a)[1]
    print(track_id)
    spotify.add_to_playlist(playlist["id"], track_id)
Пример #9
0
    async def on_message(self, message):
        print("{0.author}: {0.content} // {1}".format(message,len(message.embeds)))
        # print( pprint.pformat(message, indent=4, depth=2) )

        if '$hello' in message.content:
            await message.channel.send('Hello World!')
            print('Hello World message sent!')


        elif '$version' in message.content:
            # await message.channel.send('te amo mucho paige\n:yellow_heart:')
            print('received version command ('+message.content+')')
            with open('logs/version.txt','r') as version_log:
                await message.channel.send('```\n{0}\n```'.format(version_log.read()))
            # await message.channel.send('```\nCurrent Version\n{0}\n```'.format(commit))
            print('commit message sent')


        elif '$paige' in message.content:
            print('received paige command')
            with open('dat/paige.csv') as paige_messages:
                messages = paige_messages.readlines()
                print(messages)
                await message.channel.send(random.choice(messages))
                print('paige message sent')

        elif message.content.strip().startswith('$talkto'):
            response = talkto.talkto(message.content)
            await message.channel.send(response)


        elif message.content.strip() == '$auth':
            print('received auth command')
            auth_embed = discord.Embed(
                title='Spotify Authentication',
                type='rich',
                description='Click here to provide spotify authentication',
                url=spotify.gen_requestlink()
                )
            print(auth_embed)
            print(auth_embed.to_dict())
            await message.channel.send(embed=auth_embed)

        elif message.content.strip().startswith('$auth-code'):
            print('received authorization code')
            terms = message.content.split()
            print(terms)
            if len(terms) < 2:
                await message.channel.send('Improper usage: $auth-code <authorization code>')
                print('error message sent')
            else:
                print('valid message')
                authcode = terms[1]
                print(authcode)
                try:
                    tokens = spotify.request_tokens(authcode)
                    profile = spotify.get_profile(tokens)
                    print(message.author.id)
                    print(profile)
                    print('got profile, author, tokens')
                    databasing.add_auth(message.author.id,tokens,profile)
                    await message.channel.send('Success! you have now been authenticated.')
                    print('success message sent')
                except spotify.NotAuthenticatedError:
                    await message.channel.send('Token failure?')
                    print(token)
                    print('fail message sent')
        elif message.content.strip().startswith('$track'):
            text = message.content.strip()
            title = text[text.find(' '):].strip()
            vchannel = discord_utl.find_vc_cnx(message.author.id,message.guild)
            playlist = spotify.create_playlist(message.author.id,title)
            print(playlist)
            databasing.register_channel(vchannel.id,message.author.id,playlist['id'])
            await message.channel.send('Successfully Registered!')

                
                

        elif str(message.author)=='Groovy#7254'and len(message.embeds) == 1 and  message.embeds[0].title=="Now playing":
            print('now playing message')
            
            regex_match = re.match(r'\s*\[(.*)\]\s*\((.*)\)\s*\[<@(\d+)>\]\s*',message.embeds[0].description)
            print('title: [{0}]'.format(regex_match.group(1)))
            print('link: [{0}]'.format(regex_match.group(2)))
            print('user: [{0}]'.format(int(regex_match.group(3))))
            title = regex_match.group(1)
            link = regex_match.group(2)
            vc = discord_utl.find_vc_cnx(message.author.id,message.guild)
            vcdata = databasing.get_playlist_data(vc.id) or None
            if vcdata:
                # add song to registered playlist
                if 'spotify.com' in link:
                    song_id = link[link.rfind('/')+1:]
                    if databasing.add_song_nonduplicate(song_id,vcdata['playlist_id']):
                        spotify.add_song(vc.id,song_id)
                        await message.channel.send('Song added to playlist!')
                    else:
                        await message.channel.send('Song already exists in playlist! Skipping.')
                else:
                    searchdata = spotify.search_song(title,vcdata['discord_id'])
                    resultstrings = map(lambda res: '[{0[name]}]({0[external_urls][spotify]}), by {0[artists][0][name]} on album {0[album][name]}'.format(res), searchdata['tracks']['items'])
                    result_emojis = ['🥇','🥈','🥉']
                    
                    description = 'Select option to add to playlist:\n'+'\n'.join(map(lambda info,emoji: emoji+' '+info, resultstrings,result_emojis))
                    response_embed = discord.Embed(title='Select Song:',type='rich',description=description)
                    sent_message = await message.channel.send(embed=response_embed)
                    for i in range(min(3,searchdata['tracks']['total'])):
                        await sent_message.add_reaction(result_emojis[i])
                    await sent_message.add_reaction('❌')
                    await sent_message.add_reaction('➕')
                    def valid_reacc(reaction, user):
                        return reaction.message.id == sent_message.id and user.id == vcdata['discord_id'] and (reaction.emoji in result_emojis or reaction.emoji=='➕' or reaction.emoji=='❌')
                    try:
                        reaction, user = await self.wait_for('reaction_add',timeout=60.0, check=valid_reacc)
                    except TimeoutError:
                        await sent_message.edit(embed=None,content='Song addition menu expired.')
                    else:
                        if reaction.emoji in result_emojis:
                            chosen_index = result_emojis.index(reaction.emoji)
                            print(chosen_index)
                            song_id = searchdata['tracks']['items'][chosen_index]['id']
                            if databasing.add_song_nonduplicate(song_id,vcdata['playlist_id']):
                                spotify.add_song(vc.id,song_id)
                                response_embed.description = 'Option {0} added to playlist.'.format(chosen_index+1)
                            else:
                                response_embed.description = 'Option {0} chosen, skipped as duplicate.'.format(chosen_index+1)
                        elif reaction.emoji=='❌':
                            response_embed.description = 'song addition cancelled.'
                        elif reaction.emoji=='➕':
                            response_embed.description = 'Choose other song: feature coming soon.'
                        await sent_message.edit(embed=response_embed)
            else:
                print('passing, because channel is not registered')
        elif re.search(r'[Nn]i+[ -]?[Nn]i+',message.content):
            await message.channel.send('*purrs and curls up on your chest*')
            

        else:
            print('irrelevant message')
import os
import spotify
import youtube

spotify_oauth_token = os.environ.get("SPOTIFY_OAUTH_TOKEN")
spotify_user_id = os.environ.get("SPOTIFY_USER_ID")

if __name__ == "__main__":
    # intializing an instance of the youtube and spotify classes
    yt = youtube.Youtube()
    spotify = spotify.Spotify(spotify_user_id, spotify_oauth_token)

    yt_playlist_id = yt.get_playlist_id("Spotify")
    unfiltered_song_list = yt.get_song_list(yt_playlist_id)
    spotify_playlist_id = spotify.create_playlist("From Youtube")
    filtered_songs = spotify.filter_titles(unfiltered_song_list)
    # adding each song to the playlist
    for song in filtered_songs:
        track_uri = spotify.get_spotify_song_uri(song)
        # if a search result came back from the spotify API
        if track_uri != None:
            spotify.add_song_to_playlist(spotify_playlist_id, track_uri)
            print("Added {song} to the playlist".format(song=song))