예제 #1
0
def exportPlaylist(request):
    list_id = request.POST["playlilstid"]
    playlisttoexport = Playlist.objects.get(id=list_id)
    tracks = playlisttoexport.tracks.all()
    uris = []
    for t in tracks:
        uri = "spotify:track:" + t.spotify_id
        uris.append(uri)
    app_token = tk.request_client_token(client_id, client_secret)
    spotify = tk.Spotify(app_token)
    user_token = tk.prompt_for_user_token(client_id,
                                          client_secret,
                                          redirect_uri,
                                          scope=tk.scope.every)
    spotify.token = user_token
    user = spotify.current_user()
    playlist = spotify.playlist_create(
        user.id,
        playlisttoexport.name,
        public=False,
        description='Generated By Ewan\'s Spotify Playlist Assist')
    spotify.playlist_add(playlist.id, uris=uris)

    #THIS IS WHERE ONE AVIODS COPYING PASTING INTO COSNOLE, COULDN'T QUITE WORK IT, FOR THE PURPOSES OF THIS PROJECT I DECIDED TO NOT WASTE MORE TIME ON IT

    #code = request.GET.get('', '')
    #token = cred.request_user_token(code)
    #with spotify.token_as(token):
    #    info = spotify.current_user()
    #    session['user'] = info.id
    #    users[info.id] = token

    return HttpResponseRedirect(reverse("playlistlist"))
예제 #2
0
    def __init__(self, *args, **kwargs):
        """
        The constructor for the Track class.

        Parameters:
            args (*tuple): Positional args for the Player class.
            kwargs (**dict): Keyword args for the Player class.
        """

        super().__init__(*args, **kwargs)

        self.context: commands.Context = kwargs.get('context', None)
        if self.context:
            self.dj: discord.Member = self.context.author

        self.queue = asyncio.Queue()
        self.controller = None

        conf = (getenv('SPOTIFY_ID'), getenv('SPOTIFY_SECRET'))
        token = tk.request_client_token(*conf[:2])
        self.spotify = tk.Spotify(token, asynchronous=True)

        self.waiting = False
        self.updating = False

        self.pause_votes = set()
        self.resume_votes = set()
        self.skip_votes = set()
        self.shuffle_votes = set()
        self.stop_votes = set()
        self.repeat_votes = set()
예제 #3
0
 def __init__(self, client_id=Config.client_id, client_secret=Config.client_secret,
              redirect_uri=Config.redirect_uri):
     # Credentials to access the Spotify Music Data
     self.client_id = client_id
     self.client_secret = client_secret
     self.redirect_uri = redirect_uri
     self.app_token = tk.request_client_token(self.client_id, self.client_secret)
     self.spt = tk.Spotify(self.app_token)
예제 #4
0
 def __init__(self):
     with open(os.getcwd() + "\\token.json") as f:
         data = json.load(f)
     client_id = data['client_id']
     client_secret = data['client_secret']
     token = tk.request_client_token(client_id=client_id,
                                     client_secret=client_secret)
     self.tk_spotify = tk.Spotify(token)
예제 #5
0
 def __init__(self):
     self.client_id = '04b4767cc75549d7a19f70985c837dcb'
     self.client_secret = 'cfbd881c349a409ab4794b2547889ce1'
     self.redirect_uri = 'http://localhost/teste/spotifyTeste.php'
     self.cred = tk.Credentials(self.client_id, self.client_secret,
                                self.redirect_uri)
     self.app_token = tk.request_client_token(self.client_id,
                                              self.client_secret)
     self.spotify = tk.Spotify(self.app_token)
     self.inicialize = False
예제 #6
0
def get_spotify_tekore_client(asynchronous=False):
    """get a spotify client via tekore library

    Returns:
        an instance of a Spotify client
    """
    client_id = current_app.config['SPOTIFY_CLIENT_ID']
    client_secret = current_app.config['SPOTIFY_CLIENT_SECRET']

    app_token = tk.request_client_token(client_id=client_id,
                                        client_secret=client_secret)
    spotify_tekore_client = tk.Spotify(app_token, asynchronous=asynchronous)
    return spotify_tekore_client
예제 #7
0
def add_songs_for_playlist(db, playlist_id: int, playlist_link: str):
    client_id, client_secret, redirect_uri = tk.config_from_environment()
    token = tk.request_client_token(client_id, client_secret)
    spotify = tk.Spotify(token)

    playlist = spotify.playlist(
        playlist_id=playlist_link.split("/").pop(-1).split("?").pop(0))  # ask spotify for tracks
    for item in playlist.tracks.items:
        if item.track:
            name = item.track.name + " - " + item.track.artists.pop().name
            link = item.track.href
            duration = item.track.duration_ms
            crud.song.create_with_playlist(db, obj_in=SongCreate(name=name, link=link, duration=duration),
                                           playlist_id=playlist_id)
예제 #8
0
def query_spotify_by_id(id_list):
    import tekore as tk

    app_token = tk.request_client_token(SPOTIFY_API_CLIENT_ID,
                                        SPOTIFY_API_CLIENT_SECRET)

    spotify = tk.Spotify(app_token)

    # shows, = spotify.show(cur_id) # shows don't work right now, instead tracks

    response_list = []
    for cur_id in id_list:
        response_list.append(spotify.track(cur_id))

        ids = []
        names = []
        artists = []
        covers = []
        durations = []
        previews = []

    for result in response_list:
        ids.append(result.id)
        names.append(result.name)
        artists.append(result.artists[0].name)
        covers.append(result.album.images[0].url)
        durations.append(result.duration_ms)
        previews.append(result.preview_url)

    # durations = durations / 1000 / 60 # ms -> minutes # numpy needed

    return_dict = {
        "id": ids,
        "name": names,
        "artist": artists,
        "cover": covers,
        "duration": durations,
        "preview": previews
    }

    return return_dict
예제 #9
0
def query_spotify(query):
    import tekore as tk

    app_token = tk.request_client_token(SPOTIFY_API_CLIENT_ID,
                                        SPOTIFY_API_CLIENT_SECRET)

    spotify = tk.Spotify(app_token)

    # shows, = spotify.search('meditation', types=('shows',)) # shows don't work right now, instead tracks
    tracks, = spotify.search(query, types=('track', ))

    ids = []
    names = []
    artists = []
    covers = []
    durations = []
    previews = []

    for result in tracks.items:
        ids.append(result.id)
        names.append(result.name)
        artists.append(result.artists[0].name)
        covers.append(result.album.images[0].url)
        durations.append(result.duration_ms)
        previews.append(result.preview_url)

    # durations = durations / 1000 / 60 # ms -> minutes # numpy needed

    return_dict = {
        "id": ids,
        "name": names,
        "artist": artists,
        "cover": covers,
        "duration": durations,
        "preview": previews
    }

    return return_dict
예제 #10
0
 def test_expiring_client_token_refreshed(self, app_env):
     token = request_client_token(app_env[0], app_env[1])
     old_token = str(token)
     token._token._expires_at -= token._token.expires_in - 30
     assert old_token != str(token)
예제 #11
0
 def test_request_client_token_returns_refreshing_token(self, app_env):
     token = request_client_token(app_env[0], app_env[1])
     assert isinstance(token, RefreshingToken)
예제 #12
0
    emojiList = {
        "YoutubeLogo": emojiList["YouTubeLogo"],
        "SpotifyLogo": emojiList["SpotifyLogo"],
        "SoundcloudLogo": emojiList["SoundCloudLogo"],
        "DeezerLogo": emojiList["DeezerLogo"],
        "True": emojiList["True"],
        "False": emojiList["False"],
        "Alert": emojiList["Alert"]
    }

intents = discord.Intents.default()
bot = commands.Bot(prefix, intents=intents)

# Spotify
if (spotifyClientId != ""):
    spotifyAppToken = tekore.request_client_token(spotifyClientId,
                                                  spotifyClientSecret)
    bot.spotify = tekore.Spotify(spotifyAppToken, asynchronous=True)

# Lavalink
bot.lavalink = createLavalink()

# Top.gg
bot.dblToken = dblToken

# Emojis
bot.emojiList = createEmojiList(emojiList)

# Help
bot.remove_command("help")  # To create a personal help command

# Database
예제 #13
0
    def __init__(self):

        client_id, client_secret, _ = tk.config_from_file(
            "/bot/server/conf.ini", section='SPOTIFY')
        app_token = tk.request_client_token(client_id, client_secret)
        self.spotify = tk.Spotify(app_token)
예제 #14
0
import tekore as tk
from tekore.model import FullArtist

from api_keys import SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET

if __name__ == '__main__':
    app_token = tk.request_client_token(SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET)
    spotify = tk.Spotify(app_token)

    res = spotify.search('Silverstein', ('artist',))
    for result in res:
        for a in result.items:
            a: FullArtist = a
            if a.name == 'Silverstein':
                art = spotify.artist(a.id)
                art_albums = spotify.artist_albums(a.id)
                album = spotify.album_tracks('6HtcHNGQ9CNGisIS7DlMLW')
                track = spotify.track('2DADATOYLLFrNlp6jN6J4t')
                print('debug')
예제 #15
0
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session
from starlette.responses import RedirectResponse
from spotify import audio_features, album_songs
from typing import List

model.Base.metadata.create_all(bind=engine)

client_id = os.getenv("CLIENT_ID")
client_secret_id = os.getenv("CLIENT_SECRET_ID")
basilica_key = os.getenv("BASILICA_KEY")
client_credentials_manager = SpotifyClientCredentials(
    client_id=client_id, client_secret=client_secret_id)
BASILICA = basilica.Connection(basilica_key)

app_token = tk.request_client_token(client_id, client_secret_id)
sp = tk.Spotify(app_token)

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
    allow_credentials=True,
)


@app.get("/", status_code=200)
def main():
예제 #16
0
import discord
import lyricsgenius
import pylast
import tekore
from tekore._model import SimpleAlbum, FullAlbum, SimpleArtist, FullArtist, FullTrack

from .classes import *

lastfm_net = pylast.LastFMNetwork(
    api_key=(os.environ["LAST_API_KEY"]),
    api_secret=(os.environ["LAST_API_SECRET"]))

spotify_api = tekore.Spotify(
    tekore.request_client_token(
        os.environ["SPOTIFY_CLIENT_ID"],
        os.environ["SPOTIFY_CLIENT_SECRET"]),
    asynchronous=True)

genius = lyricsgenius.Genius(
    os.environ["GENIUS_CLIENT_SECRET"])


async def get_scrobble(username: str) -> Optional[Track]:
    result = await asyncio.to_thread(lastfm_net.get_user(username).get_now_playing)
    return await asyncio.to_thread(pack_lastfm_track, result)


async def search_lastfm_album(search: str) -> Optional[Album]:
    result = await asyncio.to_thread(lastfm_net.search_for_album(search).get_next_page)
    return await asyncio.to_thread(pack_lastfm_album, result[0])
# Get credentials and create an API client
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
    client_secrets_file, scopes)
credentials = flow.run_console()
youtube = googleapiclient.discovery.build(api_service_name,
                                          api_version,
                                          credentials=credentials)

with open("client_codes_Spotify.json") as f:
    client_codes = json.load(f)

# Initializes Spotify API client codes
client_id = str(client_codes["client_id"])
client_secret = str(client_codes["client_secret"])
app_token = request_client_token(client_id, client_secret)
playlist_id_youtube = input("Enter the YouTube id")
attempts = 0


# Gets the name of the song and the artist from a spotify playlist
def get_song_spotify(app_token):
    global attempts
    spotify = Spotify(app_token)
    playlist_id_spotify = input("Enter the spotify playlist id")
    playlist = spotify.playlist_items(playlist_id_spotify, as_tracks=True)
    print(playlist)
    playlist = playlist["items"]
    print(playlist)
    try:
        i = 0
예제 #18
0
 def auth(self):
     app_token = tk.request_client_token(self._client_id,
                                         self._client_secret)
     return tk.Spotify(app_token)
예제 #19
0
def init():
    conf = get_config()
    app_token = tk.request_client_token(*conf[:2])
    spotify = tk.Spotify(app_token)
    spotify.token = get_user_token()
    return spotify
예제 #20
0
import tekore as tk

app_token = tk.request_client_token("b516728497b34264afab4e995b4e2569",
                                    "0a0fec97699443d6b1a25b875f17325a")
spotify = tk.Spotify(app_token)


def menu():

    print("search for:\n1. Artist\n2. Album\n3. Track ")
    num = input("type your input there : ")
    if num == "1":
        artist_name = input("what's the artist name : ")
        searh_string = "artist:" + artist_name
        artists, = spotify.search(searh_string, types=('track', ), limit=50)
        print_article(artists)
    elif num == "2":
        album_name = input("what's the album name : ")
        searh_string = "album:" + album_name
        album, = spotify.search(searh_string, types=('track', ), limit=50)
        print_article(album)
    elif num == "3":
        track_name = input("what's the track name : ")
        tracks, = spotify.search(track_name, types=('track', ), limit=50)
        print_article(tracks)
    else:
        print("what did you just type? try again!")
    menu()


def print_article(element):
예제 #21
0
파일: spotify.py 프로젝트: urfonline/api
 def __init__(self, api_key):
     self.api_key = api_key
     client_id, client_secret = api_key.split(':')
     self.token = request_client_token(client_id, client_secret)
     self.spotify = Spotify(self.token)
예제 #22
0
def spotify_connection(client_id,client_secret):
    client_id = client_id
    client_secret = client_secret
    app_token = tk.request_client_token(client_id, client_secret)
    return app_token