コード例 #1
0
def main(argv=None):
    parser = argparse.ArgumentParser(
        description='Sync feed with spotify playlist')
    parser.add_argument(
        'username', help='spotify username/account to sync the playlist to')
    parser.add_argument(
        'feed',
        help=
        'playlog URL, e.g. http://www.jouluradio.fi/biisilista/jouluradiolast20.json'
    )
    parser.add_argument(
        '--id',
        required=False,
        default=None,
        help=
        'spotify playlist ID to sync to. overrides the playlist name below.')
    parser.add_argument(
        '--name',
        required=False,
        default=None,
        help=
        'spotify playlist name to sync to. the playlist is created if there is no such playlist for the user. the feed title is used if omitted.'
    )
    parser.add_argument('-v',
                        '--verbose',
                        help='output debug logging',
                        action='store_true',
                        default=False)
    parser.add_argument(
        '-a',
        '--add',
        help=
        'only add songs to the playlist, dont remove them if missing from the feed',
        action='store_true',
        default=False)
    parser.add_argument(
        '-l',
        '--limit',
        help=
        'limit the total number of tracks in the playist (useful with --add, default=0=no limit)',
        default=0)
    args = parser.parse_args()

    logformat = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'

    if args.verbose:
        logging.basicConfig(level=logging.DEBUG, format=logformat)
    else:
        logging.basicConfig(level=logging.INFO, format=logformat)
        logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(
            logging.WARNING)

    logging.debug("got args: %s" % args)

    token = spotipy.util.prompt_for_user_token(args.username,
                                               'playlist-modify-public')
    logging.debug("go auth token")
    spotify = spotipy.Spotify(auth=token)
    logging.debug("logged in to spotify")

    songs = spotify_search_songs(get_jouluradio_songlog(url=args.feed))

    if args.id:
        targetplaylist = args.id
    else:
        if not args.name:
            args.name = os.path.basename(args.feed)
        targetplaylist = get_or_create_playlistid_by_name(
            args.name, args.username, spotify)

    sync_tracks(songs,
                targetplaylist,
                args.username,
                spotify,
                addonly=args.add,
                limit=args.limit)
コード例 #2
0
ファイル: main.py プロジェクト: Aniruddh-482/Python-Bootcamp
import requests
from bs4 import BeautifulSoup
import spotipy
from spotipy.oauth2 import SpotifyOAuth

Client_ID = "Client_ID"
Client_Secret = "Client_Secret"
Redirect_URI = "http://example.com"
URL = "https://www.billboard.com/charts/hot-100/"

sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
    scope="playlist-modify-private",
    redirect_uri=Redirect_URI,
    client_id=Client_ID,
    client_secret=Client_Secret,
    show_dialog=True,
    cache_path="token.txt",
))

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

date = input(
    "Which year do you want to travel to? Type the date in this format YYYY-MM-DD: "
)

response = requests.get(f"{URL}{date}")
website_html = response.text

soup = BeautifulSoup(website_html, "html.parser")
song_names_spans = soup.find_all("span",
                                 class_="chart-element__information__song")
コード例 #3
0
# Deletes user saved album

import spotipy
from spotipy.oauth2 import SpotifyOAuth

scope = 'user-library-modify'
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))

uris = input("input a list of album URIs, URLs or IDs: ")
uris = list(map(str, uris.split()))
deleted = sp.current_user_saved_albums_delete(uris)
print("Deletion successful.")
コード例 #4
0
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'


import spotipy
from spotipy.oauth2 import SpotifyOAuth
import os

scope = "playlist-modify-public"
sp = spotipy.Spotify(
    auth_manager=SpotifyOAuth(scope=scope, cache_path="spotipy_cache"))

user_id = os.environ['SPOTIFY_USER_ID']


def create_playlist(name):
    global sp, user_id
    sp.user_playlist_create(user_id, name)


def get_playlist_id(playlist_name):
    global sp, user_id

    playlists = sp.user_playlists(user_id, limit=3)

    for playlist in playlists['items']:
コード例 #5
0
# Get the username from terminal
username = sys.argv[1]

# Set spotify permission scopes
scope = 'user-library-modify'

# Erase cache and prompt for user permission
try:
    token = util.prompt_for_user_token(username, scope)
except:
    os.remove(f".cache-{username}")
    token = util.prompt_for_user_token(username)

# Create our spotifyObject
spotifyObject = spotipy.Spotify(auth=token)

#
#
#
#
#
#
#
#
#
# //////////////// SET UP //////////////

# # open data.json and convert it to dict
# with open('data.json') as f:
#     data = json.load(f)
コード例 #6
0
ファイル: main.py プロジェクト: Zayn-Rekhi/SpotifyAdMuter
from spotipy.oauth2 import SpotifyOAuth
import spotipy
import time
import os

volumeLevel = input("Volume Level: ")

sp = spotipy.Spotify(
    auth_manager=SpotifyOAuth(client_id="CLIENT_ID",
                              client_secret="CLIENT_SECRET",
                              redirect_uri="http://localhost:8888/callback",
                              scope="user-read-currently-playing"))


def increaseVolume(level):
    os.popen(f"amixer sset 'Master' {level}%")


#
def setVolumeToOff():
    os.popen("amixer sset 'Master' 0%")


while True:
    results = sp.currently_playing()["currently_playing_type"]
    if results == "ad": setVolumeToOff()
    else: increaseVolume(volumeLevel)
    time.sleep(3)
コード例 #7
0
ファイル: main.py プロジェクト: Anafreisa/billboard_top_100
billboard_html = response.text

soup = BeautifulSoup(billboard_html, "html.parser")
hot_songs = soup.find_all(name="span", class_="chart-element__information__song")
hot_artists = soup.find_all(name="span", class_="chart-element__information__artist")

music_titles = [music.getText() for music in hot_songs]
song_name = music_titles
artists_names = [artist.getText() for artist in hot_artists]
artist_name = artists_names

sp = spotipy.Spotify(
    auth_manager=SpotifyOAuth(
        scope="playlist-modify-private",
        redirect_uri="https://example.com",
        client_id=CLIENT_ID,
        client_secret=CLIENT_SECRET,
        show_dialog=True,
        cache_path="token.txt"
    )
)

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

song_uris = []
year = date.split("-")[0]
for song in song_name:
    result = sp.search(q=f"track:{song} year:{year}", type="track")
    print(result)
    try:
        uri = result["tracks"]["items"][0]["uri"]
        song_uris.append(uri)
コード例 #8
0
    def __init__(self, path_credentials: str):
        self.path_credentials = path_credentials
        self.__set_credentials()

        clm = SpotifyClientCredentials()
        self.sp = spotipy.Spotify(client_credentials_manager=clm)
コード例 #9
0
def create_no_hiphop_hitlist():
    username = '******'
    scope = 'playlist-modify-public'
    token = util.prompt_for_user_token(username, scope)

    client_credentials_manager = SpotifyClientCredentials()
    sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager,
                         auth=token)

    hitlist_id = '7vFQNWXoblEJXpbnTuyz76'
    banned_songs_id = '5QWNXDGREE9hAxddXe2W3m'
    no_hiphop_hitlist = '1ahh5eiX08eeiKxxXqZlPp'

    playlists = sp.playlist_tracks(hitlist_id)
    banned_playlist = sp.playlist_tracks(banned_songs_id)
    banned_songs = [item['track']['id'] for item in banned_playlist['items']]

    def clean_playlist(playlist_id):
        current_playlist = sp.playlist_tracks(playlist_id)
        current_songs = [
            item['track']['id'] for item in current_playlist['items']
        ]
        sp.user_playlist_remove_all_occurrences_of_tracks(
            username, playlist_id, current_songs)

    # If returns True the artist is okay, if false remove, if -1 unknown
    def check_genre(artist_genres):
        banned_genres = ['hip hop', 'rap', 'trap']
        count = 0  #Counts how many matches there has been

        if artist_genres == []:
            return -1

        for genre in banned_genres:
            filtered = fnmatch.filter(artist_genres, '* ' + genre + '*')
            count += len(filtered)

        if len(artist_genres) != count & count <= 1:
            return True
        else:
            return False

    def get_artist_genres(artist_id):
        artist = sp.artist(artist_id)
        return artist['genres']

    with open('hitlist.csv', 'w') as csvfile:
        spamwriter = csv.writer(csvfile,
                                delimiter=',',
                                quotechar='|',
                                quoting=csv.QUOTE_MINIMAL)
        spamwriter.writerow(['Track', 'Artist', 'Genre', 'Genre Status'])

        clean_playlist(no_hiphop_hitlist)
        ok_list = []

        for item in playlists['items']:
            track_name = item['track']['name']
            track_id = item['track']['id']
            artist_name = item['track']['artists'][0]['name']
            artist_id = item['track']['artists'][0]['id']
            artist_genres = get_artist_genres(artist_id)

            genre_status = check_genre(artist_genres)

            if not genre_status or track_id in banned_songs:
                print(
                    "REMOVED____Track: {} -- Artist: {} -- Genre: {} -- Genre Status: {}"
                    .format(track_name, artist_name, artist_genres,
                            genre_status))
                spamwriter.writerow(
                    [track_name, artist_name, artist_genres, genre_status])
                continue

            ok_list.append(track_id)

    if token:
        sp = spotipy.Spotify(auth=token)
        sp.trace = False
        results = sp.user_playlist_add_tracks(username, no_hiphop_hitlist,
                                              ok_list)
        print(results)
        return results
    else:
        print("Can't get token for", username)
コード例 #10
0
def create_sp():
    sp = spotipy.Spotify(client_credentials_manager=SpotifyOAuth(
        scope=SCOPE, username='******'))
    return sp
コード例 #11
0
def setup_data(public_id, secret_id):
    """Creates the spotipy object in order to use the sopotify developer's API """
    client_credentials_manager = SpotifyClientCredentials(
        client_id=public_id, client_secret=secret_id)
    return spotipy.Spotify(
        client_credentials_manager=client_credentials_manager)
コード例 #12
0
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
from spotipy.oauth2 import SpotifyOAuth

# https://towardsdatascience.com/using-python-to-create-spotify-playlists-of-the-samples-on-an-album-e3f20187ee5e

# function description (inputs, return uzw)
# https://developer.spotify.com/documentation/web-api/reference/artists/get-artists-albums/

# https://medium.com/better-programming/how-to-extract-any-artists-data-using-spotify-s-api-python-and-spotipy-4c079401bc37

scope = "user-library-read"
token = SpotifyOAuth(scope=scope)
print(token.redirect_uri)
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))

token = SpotifyOAuth(scope=scope)
sp = spotipy.Spotify(auth_manager=token)
print(sp.current_user())
print(1 / 0)
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
    redirect_uri="https://example.com/callback/", scope=scope))

results = sp.current_user_saved_tracks()
print(results)
auth_manager = SpotifyClientCredentials()
auth_manager = SpotifyOAuth()
sp = spotipy.Spotify(auth_manager=auth_manager)
print(sp.current_user())
playlists = sp.user_playlists()
while playlists:
コード例 #13
0
        # post to GCS.
        client = storage.Client("atomic-lens-188216")
        bucket = client.get_bucket('spotify-analysis')
        blob = bucket.blob('audio-features_{}.csv'.format(search_word))
        blob.upload_from_filename(
            filename='df-audio-features/audio_features_{}.csv'.format(
                search_word))

    except:
        print("Could not find the artist.")


def get_new_access_token(oauth):
    refresh_token = REFLESH_TOKEN
    new_token = oauth.refresh_access_token(refresh_token)
    access_token = new_token['access_token']
    return access_token


if __name__ == '__main__':
    user = SpotifyToken()
    oauth = SpotifyOAuth(client_id=user.client_id,
                         client_secret=user.client_secret,
                         redirect_uri=None)
    access_token = get_new_access_token(oauth)
    sp = spotipy.Spotify(auth=access_token)
    sp.trace = False
    search_word = input('artist name: ')
    get_audio_features(sp, search_word)
コード例 #14
0
	def __init__(self):
		self.spotify = spotipy.Spotify()
コード例 #15
0
ファイル: moodmusic.py プロジェクト: saumitrasapre/ChatBots
def authenticate_spotify(token):
    print('...connecting to Spotify')
    sp = spotipy.Spotify(auth=token)
    return sp
コード例 #16
0
import sys
import shutil
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import youtube_dl
from youtube_api import YoutubeDataApi
import config

# Set Configurations
spotify_client_id = config.SPOTIFY_CLIENT_ID
spotify_client_secret = config.SPOTIFY_API_SECRET
youtube_data_api_key = config.YOUTUBE_API_SECRET
youtube_dl_options = config.YOUTUBE_DL_OPTIONS

# Authenticate APIs
sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials(
    spotify_client_id, spotify_client_secret))
yt = YoutubeDataApi(youtube_data_api_key)


def main():
    playlist_uris = sys.argv[1:]
    for pl_uri in playlist_uris:
        if pl_uri is None:
            print('No valid playlists uris were provided.')
            return
        download_tracks(
            get_tracks(
                sp.playlist_tracks(
                    pl_uri,
                    fields='items.track.album.artists, items.track.name')))
import mechanicalsoup
import os
import spotipy
from datetime import datetime
from dotenv import load_dotenv
from spotipy.oauth2 import SpotifyOAuth

load_dotenv()
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
    client_id=os.getenv("SPOTIFY_CLIENT_ID"),
    client_secret=os.getenv("SPOTIFY_CLIENT_SECRET"),
    redirect_uri="http://127.0.0.1:9090",
    scope="playlist-read-private playlist-modify-private"))
ORICON_WEEKLY_ROCK_SINGLES_URL = 'https://www.oricon.co.jp/rank/rs/w/'
PLAYLIST_ID = os.getenv("SPOTIFY_PLAYLIST_ID")
SILENT_TRACK_ID = '5XSKC4d0y0DfcGbvDOiL93'


def get_oricon_url():
    # The default url should redirect to something like "https://www.oricon.co.jp/rank/rs/w/2021-02-15/"
    # Use the redirected url in rest of the code
    browser = mechanicalsoup.StatefulBrowser()
    browser.open(ORICON_WEEKLY_ROCK_SINGLES_URL)
    return browser.url


def get_songs(oricon_url):
    print('getting songs from oricon website...')
    browser = mechanicalsoup.StatefulBrowser()
    songs = []
コード例 #18
0
from spotipy.oauth2 import SpotifyOAuth
import pprint
from spotify_secrets import client_id
from spotify_secrets import client_secret

genre='classical'
artist='The Beatles'
song='Here Comes The Sun'
album='Sleep Through The Static'
playlist='OA'
term='long_term'

scope = "user-top-read,app-remote-control,streaming,user-read-playback-state,user-modify-playback-state,user-read-currently-playing"
redirect_uri='https://www.google.com/'

sp = spotipy.Spotify(client_credentials_manager=SpotifyOAuth(client_id=client_id,client_secret=client_secret,redirect_uri=redirect_uri,scope=scope))

def play_artist(artist):
	'''
	streams an artist's top songs
	'''

	results=sp.search(q='artist:' + artist, type='artist')
	# artist uri
	uri=results['artists']['items'][0]['uri']
	# artist's top tracks
	response=sp.artist_top_tracks(uri)
	# collect track uris
	uris=[track['uri'] for track in response['tracks']]
	# Play songs
	sp.start_playback(uris=uris)
コード例 #19
0
from spotipy.oauth2 import SpotifyClientCredentials

#Need to enter the following in terminal prior to running. Proper syntax to run is 'python playlistPull.py <yourspotifyusername>'
# export SPOTIPY_CLIENT_ID='7b00e2e252244c9789e862e391de1306'
# export SPOTIPY_CLIENT_SECRET='dcbbe3b243c549578dbca789858bd222'
# export SPOTIPY_REDIRECT_URI='http://google.com/'

# get username
username = sys.argv[1]
scope = 'user-library-read'

# request user login
token = util.prompt_for_user_token(username, scope)

# create spotify object
spotifyObject = spotipy.Spotify(auth=token)

# need credentials manager to access other users' playlists
client_credentials_manager = SpotifyClientCredentials()
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

playlists = sp.user_playlists('spotify')
while playlists:
    for i, playlist in enumerate(playlists['items']):
        print("%4d %s %s" %
              (i + 1 + playlists['offset'], playlist['uri'], playlist['name']))
    if playlists['next']:
        playlists = sp.next(playlists)
    else:
        playlists = None
コード例 #20
0
    for i in range(3, 203):
        pool.apply_async(SongDataSocket, args=(i,), callback=log_results)  # apply_async because they're indexed
        # by position, so what order they're
        # callback essentially feeds the output of                         # physically stored doesn't matter, can
        # SongDataSocket directly into log_results()                       # efficiently pull the correct data out regardless

    pool.close()
    pool.join()
    pool.close()


def print_results():
    print(c.songAttributeDict)


sp = spotipy.Spotify(auth_manager=SpotifyOAuth(username=username, scope="user-library-read", client_id=CLIENT_ID,
                                               client_secret=CLIENT_SECRET, redirect_uri="https://spotify.com"))
if __name__ == '__main__':
    sp.me()  # to trigger a spotify authentication, without opening 200 chrome tabs
    outFileName = "SpotifyDataDict.txt"
    try:
        with open(outFileName, 'r') as g:
            DataUsable = json.loads(
                g.read())  # checks to see if file exists, if it does, will just use existing data. If not, throws filenotfound, and will create a new file
    except FileNotFoundError:
        allowed_processes = checkCPUcount()
        pbar = tqdm(total=200)  # generates a progress bar
        main(allowed_processes)
        pbar.close()  # ends the progress bar so it isn't displayed twice
        with open(outFileName, 'w') as f:  # outputs the data to the file specified above
            f.write(json.dumps(c.songAttributeDict))
            DataUsable = json.dumps(c.songAttributeDict)
コード例 #21
0
 def setup_read(self):
     auth = oauth2.SpotifyClientCredentials(
         client_id=self.client_id, client_secret=self.client_secret)
     token = auth.get_access_token()
     spotify = spotipy.Spotify(auth=token)
     return spotify
コード例 #22
0
import config
import sys
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials(config.client_id, config.client_secret))

# getting track IDs from playlist IDs
def playlist_track_ids(playlist_id):
    results = sp.playlist_tracks(playlist_id)['items']
    return [results[i]['track']['id'] for i in range(len(results))]

# getting playlist names and track IDs from user ID
def playlist_pipeline(user):
    playlists = sp.user_playlists(user)['items']
    playlist_ids = [p['id'] for p in playlists]

    return {sp.playlist(p)['name']: playlist_track_ids(p) for p in playlist_ids}
コード例 #23
0
if response.status_code != 200:
    print("ERROR: Status = %d" % response.status_code)
    sys.exit(1)

top_tracks = json.loads(response.content.decode('utf-8'))['toptracks']['track']

if len(top_tracks) == 0:
    print("ERROR: No tracks available")
    sys.exit(1)

###############################################################################

# get download playlist tracks
token = util.prompt_for_user_token(user_id, 'playlist-read-private')
sp = spotipy.Spotify(auth=token)
playlist = pull_playlist_tracks(user_id, playlist_id)

for track in top_tracks:
    # check if track already in playlist
    # if not, tell IFTTT to add track to download playlist
    if not is_track_in_playlist(track['name'], track['artist']['name'],
                                playlist):
        print('   ADDING: "%s" by %s' %
              (clean_utf8(track['name']), clean_utf8(track['artist']['name'])))
        requests.post(
            'https://maker.ifttt.com/trigger/specify_top_song/with/key/%s' %
            apikeys['ifttt-key'],
            data={
                'value1': track['name'],
                'value2': track['artist']['name']
コード例 #24
0
ファイル: scrape.py プロジェクト: jpnaterer/sonicboards
import spotipy
import textdistance
from spotipy.oauth2 import SpotifyClientCredentials

# Create a spotipy object to query spotify. Requires exporting
# SPOTIPY_CLIENT_ID and SPOTIPY_CLIENT_SECRET as environment variables.
# https://spotipy.readthedocs.io/en/2.11.2/
sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())


# The parent class that provides spotify utils to scrape album information.
class AlbumScraper:

    def __init__(self, album_list):
        self.album_list = album_list

    def run(self):
        self.get_spotify_albums()
        self.get_spotify_artist()
        return self.album_list

    # Given a list of album dicts, search popularity of the artist.
    def get_spotify_artist(this):
        for album in this.album_list:
            sp_result = sp.artist(album['sp_artist_id'])
            album['sp_popularity'] = sp_result['popularity']

    # Given a list of album dicts, search details about the album on spotify.
    # Remove elements from the list that cannot be found on spotify.
    def get_spotify_albums(this):
        album_list_new = list()
コード例 #25
0
# Testing if CLIENT_ID and CLIENT_SECRET exist
assert CLIENT_ID != None; assert CLIENT_SECRET != None
print(f'This is your client_id: {CLIENT_ID}.\nThis is your client_secret: {CLIENT_SECRET}.')

# Importing libraries for scraping
import pandas as pd
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

# Import Data Dict Pack
import data_dict
music_info = data_dict.music_data

# Spotify API Login
CLIENT_CREDENTIALS = SpotifyClientCredentials(client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
sp = spotipy.Spotify(client_credentials_manager=CLIENT_CREDENTIALS)

# Artist Input (ITZY For Sample) (sample.txt)
artist_name = []
with open('./sample_artist_list/sample_input.txt') as sample:
    for name in sample:
        artist_name.append(str(name.strip()))

# Feature Names
feature_list = ['danceability', 'energy', 'key', 'loudness', 'mode', 'speechiness', 'acousticness', 'instrumentalness', 'liveness', 'valence', 'tempo', 'duration_ms', 'time_signature', 'isWestern']
temp_loop_feature = feature_list[:-1]

# Append the artists that were entered by the user in the ``artist_name`` list.
for i in artist_name:
    music_info['call_data']['kpop_western'].append(i)
コード例 #26
0
ファイル: RecursifyClient.py プロジェクト: adeaver/recursify
 def initialize_spotify_client(self, token):
     self.SP_CLIENT = spotipy.Spotify(auth=token)
コード例 #27
0
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

auth_manager = SpotifyClientCredentials()
sp = spotipy.Spotify(auth_manager=auth_manager)

results = spotify.search(q='artist:' + 'Billie Eillish', type='artist')
コード例 #28
0
ファイル: Spotify.py プロジェクト: kazoeru/Acinonyx-v3
    async def music(self, ctx, *, music=None):
        with open("Settings.json") as settingsJson:
            data = json.load(settingsJson)
            Freemium = data["Servers"]["440765395172065280"]["Members"]
            user = "******".format(ctx.author.id)
            isOwner = self.settings.isOwner(ctx.author)
            #if isOwner == None:
            #    return
            #elif isOwner == False:
            #    msgText = "Command ini sedang dalam tahap pengembangan"
            #    em = discord.Embed(color = 0XFF8C00, description = msgText)
            #    await ctx.channel.send(embed = em)
            #    return

            if user not in Freemium:
                msg = "Ini adalah fitur ***PREMIUM***\n"
                msg += "Dengan bergabung server kami, kamu dapat menggunakan fitur ini\n\n"
                msg += "**[Klik Disini](https://discord.gg/vMcMe8f)** untuk bergabung dengan kami"
                em = discord.Embed(color=0XFF8C00, description=msg)
                em.set_author(name="PREMION ONLY")
                em.set_footer(text="{}".format(ctx.author),
                              icon_url="{}".format(ctx.author.avatar_url))
                return await ctx.send(embed=em)

            if music == None:
                em = discord.Embed(
                    title=
                    "<a:exclamation:750557709107068939>**COMMAND FAILURE**<a:exclamation:750557709107068939>",
                    color=0XFF8C00,
                    description=help_spotdl)
                em.set_thumbnail(
                    url=
                    "https://cdn.discordapp.com/attachments/518118753226063887/725569194304733435/photo.jpg"
                )
                em.set_footer(text=f"Request by : {ctx.author.name}",
                              icon_url=f"{ctx.author.avatar_url}")
                return await ctx.send(embed=em)

            sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(
                client_id="690da446e39b44a7baf8deaff12be418",
                client_secret="782ddebbf58846f1a1d70a074d62ce1a"))

            results = sp.search(q=f'{music}', limit=1)
            for idx, track in enumerate(results['tracks']['items']):
                artist_name = track['artists'][0]['name']
                album_info = track['album']
                album_images = album_info['images'][0]
                album_images_url = album_images['url']
                album_artist = album_info['artists'][0]
                album_artist_name = album_artist['name']
                external_urls = track['external_urls']
                #external_urls_json = json.loads(external_urls)
                track_name = track['name']
                spotify_urls = external_urls['spotify']
                #embed dan hasil output
                em = discord.Embed(
                    title=None,
                    color=0XFF8C00,
                    description=
                    f"> [{album_artist_name} - {track_name}]({spotify_urls})\n> \n> • [DISCLAIMER](https://github.com/acinonyx-esports/Acinonyx-Bot/wiki/SPOTIFY-DOWNLOADER-DISCLAIMER)\n> • [HOW THIS BOT IS WORK?](https://github.com/acinonyx-esports/Acinonyx-Bot/wiki/HOW-SPOTIFY-DOWNLOADER-IS-WORK%3F)\n> \n> <a:acx_mp3:744868331382767617> **.MP3 Format**"
                )
                em.set_author(
                    name="Spotify downloader",
                    url=
                    "https://github.com/acinonyx-esports/Acinonyx-Bot/wiki/SPOTIFY-DOWNLOADER-DISCLAIMER",
                    icon_url=
                    "https://cdn.discordapp.com/attachments/726031951101689897/739778620658155602/spotify-logo-png-7061.png"
                )
                em.set_thumbnail(url=album_images_url)
                em.set_footer(text="Request by : {}".format(
                    ctx.message.author.name),
                              icon_url=ctx.message.author.avatar_url)
                msg = await ctx.send(embed=em, delete_after=15)
                await msg.add_reaction('<a:acx_mp3:744868331382767617>')
                while True:
                    reaction, user = await self.bot.wait_for(
                        event='reaction_add', )
                    if user == ctx.author:
                        emoji = str(reaction.emoji)
                        if emoji == '<a:acx_mp3:744868331382767617>':
                            await msg.delete()
                            s = Savify(api_credentials=(
                                "690da446e39b44a7baf8deaff12be418",
                                "782ddebbf58846f1a1d70a074d62ce1a"),
                                       quality=Quality.BEST,
                                       download_format=Format.MP3,
                                       group='{}'.format(ctx.author.id),
                                       output_path=Path(
                                           '/home/nvstar/Corp-ina.py/Temp'))
                            em = discord.Embed(
                                title=None,
                                color=0XFF8C00,
                                description=
                                f"[{album_artist_name} - {track_name}]({spotify_urls})\n"
                                + processing_file)
                            em.set_author(
                                name="Spotify downloader",
                                url=
                                "https://github.com/acinonyx-esports/Acinonyx-Bot/wiki/SPOTIFY-DOWNLOADER-DISCLAIMER",
                                icon_url=
                                "https://cdn.discordapp.com/attachments/726031951101689897/739778620658155602/spotify-logo-png-7061.png"
                            )
                            em.set_thumbnail(url=album_images_url)
                            em.set_footer(
                                text=f"{ctx.author}",
                                icon_url=ctx.message.author.avatar_url)
                            dld = await ctx.send(embed=em)

                            musicDownload = s.download(
                                "{}".format(spotify_urls))

                            checkServer = ctx.guild.premium_tier
                            if checkServer > 1:
                                em = discord.Embed(
                                    title=None,
                                    color=0XFF8C00,
                                    description=
                                    f"[{album_artist_name} - {track_name}]({spotify_urls})\n"
                                    + uploading_file)
                                em.set_author(
                                    name="Spotify downloader",
                                    url=
                                    "https://github.com/acinonyx-esports/Acinonyx-Bot/wiki/SPOTIFY-DOWNLOADER-DISCLAIMER",
                                    icon_url=
                                    "https://cdn.discordapp.com/attachments/726031951101689897/739778620658155602/spotify-logo-png-7061.png"
                                )
                                em.set_thumbnail(url=album_images_url)
                                em.set_footer(
                                    text=f"{ctx.author}",
                                    icon_url=ctx.message.author.avatar_url)
                                await dld.edit(embed=em)
                                await ctx.send(file=discord.File(
                                    f"/Temp/{ctx.author.id}/{artist_name} - {track_name}.mp3"
                                ))

                                botKernel_DeleteFile = subprocess.Popen(
                                    [
                                        "rm", "-rf",
                                        f"/Temp/{ctx.author.id}/{artist_name} - {track_name}.mp3"
                                    ],
                                    stdout=subprocess.PIPE).communicate()[0]

                                await dld.delete()
                                await ctx.send(
                                    f"{ctx.author.mention} :arrow_up:")

                            checkFile = os.path.getsize(
                                f"/Temp/{ctx.author.id}/{artist_name} - {track_name}.mp3"
                            )
                            if checkFile > 8000000:
                                await dld.delete()
                                em = discord.Embed(
                                    title=
                                    "<a:exclamation:750557709107068939>**EXCEED THE LIMIT**<a:exclamation:750557709107068939>",
                                    color=0XFF8C00,
                                    description=
                                    f"[{album_artist_name} - {track_name}]({spotify_urls})\n\n"
                                    + upload_dropbox)
                                em.set_thumbnail(url=album_images_url)
                                em.set_footer(
                                    text=f"{ctx.author}",
                                    icon_url=f"{ctx.author.avatar_url}")
                                msg2 = await ctx.send(embed=em)

                                # MEMULAI UPLOAD DROPBOX
                                dropbox_access_token = "INmLpmjvCLQAAAAAAAAAAa--h2Jb571-pTJ_UHPdqp3XoMC0KJuSekPufnCI-a2y"
                                computer_path = '/Temp/{}/{} - {}.mp3'.format(
                                    ctx.author.id, artist_name, track_name)
                                dropbox_path = f"/Apps/Acinonyc music file/{album_artist_name} - {track_name}.mp3"
                                client = dropbox.Dropbox(dropbox_access_token)
                                print("[SUCCESS] dropbox account linked")
                                client.files_upload(
                                    open(computer_path, "rb").read(),
                                    dropbox_path,
                                    mode=dropbox.files.WriteMode("overwrite"))
                                print("[UPLOADED] {}".format(computer_path))
                                d = dropbox.Dropbox(dropbox_access_token)
                                target = dropbox_path
                                link_dropbox = d.sharing_create_shared_link(
                                    target)
                                dl_link = re.sub(r"\?dl\=0", "?dl=1",
                                                 str(link_dropbox.url))
                                botKernel_DeleteFile = subprocess.Popen(
                                    [
                                        "rm", "-rf",
                                        '/Temp/{}/{} - {}.mp3'.format(
                                            ctx.author.id, artist_name,
                                            track_name)
                                    ],
                                    stdout=subprocess.PIPE).communicate()[0]

                                #EMBED FILE SELESAI UPLOAD
                                em = discord.Embed(
                                    title=None,
                                    color=0XFF8C00,
                                    description=
                                    f"{upload_complete}\n**[DOWNLOAD HERE]({dl_link})**"
                                )
                                em.set_author(
                                    name="Spotify downloader",
                                    url=
                                    "https://github.com/acinonyx-esports/Acinonyx-Bot/wiki/SPOTIFY-DOWNLOADER-DISCLAIMER",
                                    icon_url=
                                    "https://cdn.discordapp.com/attachments/726031951101689897/739778620658155602/spotify-logo-png-7061.png"
                                )
                                em.set_thumbnail(url=album_images_url)
                                em.set_footer(
                                    text=f"{ctx.author.name}",
                                    icon_url=f"{ctx.author.avatar_url}")
                                await msg2.delete()
                                msg3 = await ctx.send(embed=em)

                                #DELETE FILES
                                await asyncio.sleep(420)
                                dropbox_delete = d.files_delete(dropbox_path)
                                await msg3.delete()

                            em2 = discord.Embed(
                                title=None,
                                color=0XFF8C00,
                                description=
                                f"[{album_artist_name} - {track_name}]({spotify_urls})\n"
                                + uploading_file)
                            em2.set_author(
                                name="Spotify downloader",
                                url=
                                "https://github.com/acinonyx-esports/Acinonyx-Bot/wiki/SPOTIFY-DOWNLOADER-DISCLAIMER",
                                icon_url=
                                "https://cdn.discordapp.com/attachments/726031951101689897/739778620658155602/spotify-logo-png-7061.png"
                            )
                            em2.set_thumbnail(url=album_images_url)
                            em2.set_footer(
                                text=f"{ctx.author}",
                                icon_url=ctx.message.author.avatar_url)
                            await dld.edit(embed=em2)
                            await ctx.send(file=discord.File(
                                '/Temp/{}/{} - {}.mp3'.format(
                                    ctx.author.id, artist_name, track_name)))

                            botKernel_DeleteFile = subprocess.Popen(
                                [
                                    "rm", "-rf", '/Temp/{}/{} - {}.mp3'.format(
                                        ctx.author.id, artist_name, track_name)
                                ],
                                stdout=subprocess.PIPE).communicate()[0]

                            await dld.delete()
                            await ctx.send(f"{ctx.author.mention} :arrow_up:")
コード例 #29
0
import spotipy
import pprint
import sys
import spotipy.util as util
import os
from spotipy.oauth2 import SpotifyClientCredentials
import json
#from google.appengine.ext import ndb
#from spotify_data_model import spotifyUserInfo

client_credentials_manager = SpotifyClientCredentials()
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

#my_user=spotifyUserInfo(postUserName=amelialutz9)
print client_credentials_manager


def getGenres():
    user = raw_input("Username: ")
    playlists = sp.user_playlists(user)
    playlist = playlists['items'][0]
    length = playlist['tracks']['total']
    #print playlist
    print length
    playlist_name = playlists['items'][0]['name']
    print playlist_name
    playlist_tracks = sp.user_playlist_tracks(user,
                                              playlist['uri'],
                                              limit=100,
                                              offset=0)
    artists = []
コード例 #30
0
ファイル: app.py プロジェクト: evanphilipsmith/red-rover
    'user-top-read',
    'user-read-playback-position',
    'user-read-playback-state',
    'user-modify-playback-state',
    'user-read-currently-playing',
    'streaming',
    'playlist-read-private',
    'playlist-read-collaborative',
    'user-follow-read',
    'user-library-read',
    'user-read-email',
    'user-read-private',
]

spotify_cache_handler = SessionCacheHandler()
sp = spotipy.Spotify(auth_manager=SpotifyPKCE(
    scope=SCOPES, cache_handler=spotify_cache_handler))


@app.before_request
def make_session_permanent():
    session.permanent = True


@app.route('/')
def index():
    """Look for valid site access token"""
    if not site_access_token_is_valid():
        return redirect(url_for('coming_soon'))
    if not spotify_access_token_is_valid():
        return sign_in_with_spotify()
    access_token = spotify_cache_handler.get_cached_token()['access_token']