def __init__(self, bot: Life) -> None: self.bot = bot self.bot.lavalink = client.Client(bot=self.bot, session=self.bot.session) self.bot.spotify = spotify.Client(client_id=self.bot.config.spotify_app_id, client_secret=self.bot.config.spotify_secret) self.bot.spotify_http = spotify.HTTPClient(client_id=self.bot.config.spotify_app_id, client_secret=self.bot.config.spotify_secret) self.bot.ksoft = ksoftapi.Client(self.bot.config.ksoft_token)
def __init__(self, *args, **kwargs) -> None: """Initialize the subclass.""" super().__init__(*args, **kwargs) # -- Prefix -- self.default_prefix = config.COMMAND_PREFIX self.prefix_dict = {} # -- Bot info -- self.cluster = kwargs.get("cluster_id") self.cluster_count = kwargs.get("cluster_count") self.version = kwargs.get("version") # -- Start time config -- self.start_time = datetime.utcnow() # -- Sessions config -- self.session = None self.database = None # -- Startup config -- self.initial_call = True # -- Spotify config -- self.spotify = spotify.Client( client_id=config.spotify_client_id, client_secret=config.spotify_client_secret, ) self.spotify_http = spotify.HTTPClient( client_id=config.spotify_client_id, client_secret=config.spotify_client_secret, )
async def search_music_from_playlist(self, playlist): async with spotify.Client(self.client_id, self.client_secret) as client: matched_tracks = [] for artist, songs in playlist.items(): artist_name = artist for song in songs: track_name = song query_result = await client.search(q='{} {}'.format( artist_name, track_name), types=['track']) if query_result.tracks: match = next( (x for x in query_result.tracks if matcher.WRatio(x.name, track_name) >= 90), None) if match: logger.info('There is a match for: {} - {}'.format( artist_name, track_name)) matched_tracks.append(match) else: logger.warning('No match for: {} - {}'.format( artist_name, track_name)) else: logger.warning('Nothing found for: {} - {}'.format( artist_name, track_name)) return matched_tracks
def __init__(self, *args, prefix=None, **kwargs): super().__init__(*args, **kwargs) self.spclient = spotify.Client(config["client_id"], config["client_secret"]) self.color = 0x1ed760 self.stats = Counter() self.img = "https://cdn.discordapp.com/emojis/382423939680305153.png" self.last = None
async def client_fix(): if not bot.is_ready(): return await bot.spclient.close() bot.spclient = None bot.spclient = spotify.Client('a3c571001085446eb8c28e7cf77a76cf', '58bcd0a71e354abe989a776ae0564fc0') await asyncio.sleep(1000)
def main(args): auth_json = {} with open(args[0]) as f: auth_json = json.load(f) client = spotify.Client( auth_json['client-id'], auth_json['client-secret']) user_id = args[1] out_dir = args[2] client.loop.run_until_complete(async_main(client, user_id, out_dir))
async def generate_playlist(self, authorization_code, name, tracks): async with spotify.Client(self.client_id, self.client_secret) as client: user = await spotify.User.from_code( client, authorization_code, redirect_uri='http://localhost/callback') playlist = await user.create_playlist(name, public=True) await playlist.extend(tracks) logger.info('Playlist {} successfully created!'.format(name)) await user.http.close()
async def main(): async with spotify.Client(client_id, client_secret) as client: user = await client.get_user(username) print("User found: ", user) playlists = await user.get_all_playlists() for p in playlists: if p.url == playlist_url: break else: print("Playlist not found") return should_stop_at = datetime.datetime.now().replace(hour=9, minute=1, second=0, microsecond=0) length = 0 all_tracks = await p.get_all_tracks() playlist = [] for t in all_tracks[::-1]: length += t.duration sta = should_stop_at - datetime.timedelta(milliseconds=length) playlist.append(t) if sta <= datetime.datetime.now(): break while True: time.sleep(1) clearscreen() should_stop_at = datetime.datetime.now().replace(hour=9, minute=1, second=0, microsecond=0) length = 0 print(should_stop_at.strftime("%H:%M:%S"), "End of playlist", p.name) for t in playlist: length += t.duration sta = should_stop_at - datetime.timedelta(milliseconds=length) playlist.append({ "track": t.name, "sta": sta, }) if sta > datetime.datetime.now(): print(sta.strftime("%H:%M:%S"), t.name) else: print( sta.strftime("%H:%M:%S"), t.name, "(currently at", datetime.datetime.now() - sta, ")", ) break
def __init__(self, bot: Life) -> None: self.bot = bot self.slate = slate.Client(bot=self.bot) self.spotify = spotify.Client( client_id=self.bot.config.spotify_client_id, client_secret=self.bot.config.spotify_client_secret) self.spotify_http = spotify.HTTPClient( client_id=self.bot.config.spotify_client_id, client_secret=self.bot.config.spotify_client_secret) self.ksoft = ksoftapi.Client(self.bot.config.ksoft_token)
def __init__(self, bot: Life) -> None: self.bot = bot self.bot.lavalink = client.Client(bot=self.bot, session=self.bot.session) self.bot.spotify = spotify.Client( client_id=self.bot.config.spotify_app_id, client_secret=self.bot.config.spotify_secret) self.bot.spotify_http = spotify.HTTPClient( client_id=self.bot.config.spotify_app_id, client_secret=self.bot.config.spotify_secret) self.load_task = asyncio.create_task(self.load())
async def main(): playlist_uri = input("playlist_uri: ") client_id = input("client_id: ") secret = getpass.getpass("application secret: ") token = getpass.getpass("user token: ") async with spotify.Client(client_id, secret) as client: user = await spotify.User.from_token(client, token) async for playlist in user: if playlist.uri == playlist_uri: return await playlist.sort(reverse=True, key=(lambda track: track.popularity)) print('No playlists were found!', file=sys.stderr)
async def spot_search(search): client = spotify.Client('7c53c48485d5470badc45ef1fefb92aa', 'c74a53cbe9d44073a6febdf4cf069cdd') results = await client.search(search) playlists = results['playlists'] pl_tracks = {} for playlist in playlists[:20]: pl_tracks[playlist.name] = [] tracks = await playlist.get_all_tracks() for track in tracks[:50]: pl_tracks[playlist.name].append({"artist": track.artist.name, "song": track.name}) return pl_tracks
async def callback(request): async with spotify.Client(CLIENT_ID, CLIENT_SECRET) as client: user = await spotify.User.from_code( client=client, code=request.query_params['code'], redirect_uri=get_redirect_uri(request), ) user = await user display_name = user.display_name or user.id public_library = "%s's Public library" % display_name for playlist in await user.get_all_playlists(): if playlist.name == public_library: break else: playlist = await user.create_playlist(public_library) tracks = await user.library.get_all_tracks() await playlist.replace_tracks(*tracks) return RedirectResponse(playlist.url)
import asyncio import spotify client = spotify.Client("some id", "some secret") async def main(): episode_id = "27SyhdfgURYPhw4JSSEPVs" episode = await client.get_episode(episode_id) print(episode.name, episode.description) if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(main())
async def auth(request): async with spotify.Client(CLIENT_ID, CLIENT_SECRET) as client: url = client.oauth2_url( redirect_uri=get_redirect_uri(request), scopes=['user-library-read', 'playlist-modify-public']) return RedirectResponse(url)
async def inner(): async with spotify.Client(*client_args, **client_kwargs) as client: kwargs["client"] = client await corofunc(*args, **kwargs)
raw = await client.http.request(route, headers=headers, params=payload) token = raw["access_token"] refresh_token = raw["refresh_token"] return cls.from_token(client, token, refresh_token) # Create the FastAPI App app = FastAPI() # Get the nessecary variables from the secure .env file load_dotenv() CLI_ID = os.getenv("CLIENT_ID") CLI_SEC = os.getenv("CLIENT_SECRET") SPOTIFY_CLIENT = spotify.Client(CLI_ID, CLI_SEC) REDIRECT_URI: str = 'https://musicdiary.tech:5000/spotify/callback' # OAuth2 Settup OAUTH2_SCOPES: Tuple[str] = ('user-top-read',) scope = 'user-top-read' OAUTH2: spotify.OAuth2 = spotify.OAuth2(SPOTIFY_CLIENT.id, REDIRECT_URI, scopes=OAUTH2_SCOPES) SPOTIFY_USERS: Dict[str, spotify.User] = {} # setting up routing for linking between different html files templates = fastapi.templating.Jinja2Templates(directory="templates") app.mount("/static",fastapi.staticfiles.StaticFiles(directory="static"),name="static")
async def main(): client = spotify.Client(SPOTIFY_CLIENT_ID, SPOTIFY_SECRET) song: DirEntry entry: spotify.SearchResults tasks = [] for song in music_files: tasks.append( asyncio.create_task( client.search(cleanup_name(song.name), types=["track"]))) done = await asyncio.gather(*tasks) track: spotify.Track songs = dict(zip(music_files, done)) async def cover_download(url): async with aiohttp.ClientSession() as s: async with s.get(url) as r: data = await r.read() f, path = tempfile.mkstemp(suffix=".jpg") f = open(path, "wb") f.write(data) return path for song, tracks in songs.items(): tracks: spotify.SearchResults try: track = tracks.tracks[0] except Exception: print(f"Results not found for song {song.name}") continue cover_art = MP3(song.path, ID3=ID3) try: cover_art.add_tags() except error: pass p = await cover_download(track.album.images[0].url) with open(p, "rb") as f: raw_image = f.read() cover_art.tags.add( APIC(mime="image/jpeg", desc=u"Cover", data=raw_image)) cover_art.save() os.remove(p) for song, tracks in songs.items(): tracks: spotify.SearchResults try: track = tracks.tracks[0] except Exception: print(f"Results not found for song {song.name}") continue try: mutagen = EasyID3(song.path) except ID3NoHeaderError: continue mutagen['title'] = track.name mutagen['album'] = track.album.name mutagen['artist'] = track.artist.name mutagen['genre'] = "" try: cover_art.add_tags() except error: pass mutagen.save() await client.close() cleanup_file_names()
import sys import asyncio import random import spotify import time import warnings from subprocess import call client = spotify.Client('e05eaa83adef40d880e370a1c0685e53', 'f5e057bbed864fdeb793bf725d23a3f3') async def research_album(album): results = await client.search(album, types=["artist", "album"]) album = await client.get_album(str(results.albums[0])) all_tracks = await album.get_all_tracks() call(["spotify", "--uri=" + str(all_tracks[0]) + "#0:0.01"]) async def f(): asyncio.get_running_loop().set_exception_handler( lambda loop, context: None) def help_menu(): print( " ____ ____ ____ ___ ____ _ ____ __ __ ___ ___ \n| \ / | \| \ / | | | \| | | | |\n| D | o | _ | \| o | | | o | | | _ _ |\n| /| | | | D | | |___| | | | \_/ |\n| \| _ | | | | _ | | O | : | | |\n| . | | | | | | | | | | | | |\n|__|\_|__|__|__|__|_____|__|__|_____|_____|\__,_|___|___|" ) print("\nUsage: python3 randalbum.py [OPTION...]") print("\n OPTIONS:") print(
async def main(): print(f"Preparing to work on {len(music_files)} songs...") client = spotify.Client(SPOTIFY_CLIENT_ID, SPOTIFY_SECRET) song: DirEntry entry: spotify.SearchResults tracks: Dict[DirEntry, spotify.SearchResults] done = [] print("Searching songs on spotify's api...") for song in tqdm(music_files, "Searching... ", unit="songs"): done.append(await client.search( cleanup_name(song.name) if cleanup_name(song.name) != "" or None else "Song not available", # Fixes bad request issue types=["track"])) track: spotify.Track songs = dict(zip(music_files, done)) async def cover_download(url: str, song: DirEntry) -> None: async with aiohttp.ClientSession() as s: async with s.get(url) as r: raw_data = await r.read() tracks: spotify.SearchResults try: cover_art = MP3(song.path, ID3=ID3) except HeaderNotFoundError: pass try: cover_art.add_tags() except error: pass cover_art.tags.add( APIC(mime="image/jpeg", desc=u"Cover", data=raw_data)) cover_art.save() print("Adding cover art to songs...") for song, tracks in tqdm(songs.items(), "Searching... ", unit="songs"): try: mutagen = EasyID3(song.path) except ID3NoHeaderError: continue if tracks[0] is not None and mutagen["title"] != "": await cover_download(tracks[0].albums[0].url, song=song) songs_not_found = 0 print("Adding metadata to songs...") for song, tracks in tqdm(songs.items(), "Searching... ", unit="songs"): tracks: spotify.SearchResults try: track = tracks.tracks[0] except Exception: songs_not_found += 1 continue try: mutagen = EasyID3(song.path) except ID3NoHeaderError: continue print(mutagen["title"]) mutagen["title"] = track.name mutagen["album"] = track.album.name mutagen["artist"] = track.artist.name mutagen["genre"] = "" mutagen.save() song_results[song.name] = track.name if songs_not_found != 0: print(f"{songs_not_found} songs not found in spotify's api") await client.close() cleanup_file_names()
import asyncio import spotify client = spotify.Client('someid', 'somesecret') async def main(): user = await client.user_from_token('sometoken') ### Add from a spotify track id track_id = '0HVv5bEOiI9a0QfgcASXpX' await user.library.add_track(track_id) ### Add from a spotify.Track object track_obj = await client.get_track(track_id) await user.library.add_track(track_obj) if __name__ == '__main__': asyncio.loop.run_until_complete(main())
import random from dotenv import load_dotenv from discord.ext import commands from gtts import gTTS import spotify import audio_streaming import file_manager import user load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') bot = commands.Bot(command_prefix='#', help_command=None) client = spotify.Client() users = {} redirect_uri = 'http://127.0.0.1:5000/callback' @bot.event async def on_ready(): print(f"{bot.user.name} has connected to Discord!") @bot.command(name='connect') async def connect(ctx): try: channel = ctx.author.voice.channel await channel.connect()