def getSongWithUser(user, passw):
    token = None
    if token is None or token_exp < datetime.now():
        data = st.start_session(user, passw)
        token = data[0]
        token_exp = data[1]

    spotheaders = {'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {token}',
    }

    artist = ""
    song = ""

    # TODO: Handle more errors (such as 204)
    response = requests.get('https://api.spotify.com/v1/me/player/currently-playing', headers=spotheaders)
    if response.status_code != 200:
        print(response.status_code)
        print("Bad Response from Spotify API")

    else:
        json_data = json.loads(response.text)
        artist = json_data["item"]["artists"][0]["name"]
        if song != json_data["item"]["name"]:
            song = json_data["item"]["name"]

    return scrape(song, artist)
示例#2
0
def get_token(sp_dc, sp_key, force=False):
    #  Check for file with token and time
    try:
        if force:
            raise NoValidToken
        with open('sp_token', 'r') as file:
            data_file = json.load(file)
            sp_access_token = data_file['access_token']
            sp_expires = data_file['expires']
            if sp_expires - time.time(
            ) < 0:  # If token expires go to generating of a new token
                raise NoValidToken
    # If token is out-of-date or no file found
    except (NoValidToken, FileNotFoundError):
        if force:
            logging.info("[TOKEN] Generating new token forced")
        else:
            logging.info(
                "[TOKEN] Valid token not found. Generating new token.")
        data = st.start_session(sp_dc, sp_key)  # Get new token from Cookies
        sp_access_token = data[0]
        sp_expires = data[1]
        with open('sp_token',
                  'w') as file:  # Write new token and expiration time in file
            json.dump({
                "access_token": sp_access_token,
                "expires": sp_expires
            }, file)
    logging.info(
        f"[TOKEN] New Spotify token valid till: {time.ctime(sp_expires)}")
    return sp_access_token, sp_expires
示例#3
0
 def get_spotify_token(sp_dc, sp_key):
     import spotify_token as st
     data = st.start_session(sp_dc, sp_key)
     access_token = data[0]
     # token_expires = data[1]
     expires = data[1] - int(time.time())
     return access_token, expires
示例#4
0
 def get_spotify_token(username, password):
     import spotify_token as st
     import time
     data = st.start_session(username, password)
     access_token = data[0]
     expires = data[1] - int(time.time())
     return access_token, expires
 def get_spotify_token(self):
     try:
         self._access_token, self._token_expires = st.start_session(
             self.sp_dc, self.sp_key)
         expires = self._token_expires - int(time.time())
         return self._access_token, expires
     except:  # noqa: E722
         raise HomeAssistantError("Could not get spotify token")
示例#6
0
def get_token():
    """ Get an OAuth token for Spotify """
    global TOKEN
    try:
        data = st.start_session(USER,PW)
        TOKEN = data[0]
        EXPIRATION_DATE = data[1]
    except:
        quit('Unable to get OAuth Token :-( -- Check you have set your Spotify username and password correctly.')
def GenerateSpotifyToken():
	print( "Generating Spotify Token" )
	data = st.start_session( OurPersonalDB.self[ "spotify" ][ "username" ] , OurPersonalDB.self[ "spotify" ][ "password" ] )
	access_token = data[ 0 ]
	seconds_left = data[ 1 ] - int( time.time() )
	OurSpotifyTokenDB.self[ "access_token" ] = access_token
	OurSpotifyTokenDB.self[ "expire_time" ] = data[ 1 ]
	OurSpotifyTokenDB.self[ "seconds_left" ] = seconds_left
	OurSpotifyTokenDB.save()
示例#8
0
def login():
    if request.method == 'POST':
        username =  request.form['username']
        password = request.form['password']
        data = st.start_session(username, password)
        session['token'] = data[0]
        session['token_exp'] = data[1]
        return redirect(url_for('lyrics'))

    return render_template('login.html')
示例#9
0
def access_token(username, password):
    #try:
    data = st.start_session(username, password)
    #except Exception as e:
    #    print(e)
    #    print("did not connect to spotify try to log in again")
    #    return
    token = data[0]
    expiration_date = data[1]
    return token
示例#10
0
 def gettoken(self):
     # uses the spotify_token module to submit credentials to the spotify API and return a token and token experation date
     logger.info('getting token')
     if self.token is None or self.token_exp < datetime.now():
         logger.info('no token found, starting new session')
         data = st.start_session(self.user, self.passw)
         self.token = data[0]
         self.token_exp = data[1]
         logger.info('token acquired')
     else:
         logger.info(f'using cached token')
示例#11
0
def get_json():
    data = st.start_session("*****@*****.**", "is035620")
    token = data[0]
    headers = {
        "Accept": "application/json",
        "Content-Type": "application/json",
        "Authorization": "Bearer " + token,
    }
    response = requests.get(
        'https://api.spotify.com/v1/me/player/currently-playing',
        headers=headers)
    return json.loads(response.text)
示例#12
0
async def gen(e):
      if environ.get("isSuspended") == "True":
        return
      if GENIUS_API is None:
        await e.edit("**We don't support magic! No Genius API!**")
        return
      else:
            genius = lyricsgenius.Genius(GENIUS_API)
      args = get_args_split_by(e.pattern_match.group(), ",")
      if len(args) == 2:
            name = args[0]
            artist = args[1]
            await e.edit("**Searching for song **" + name + "** by **" + artist)
            song = genius.search_song(name, artist)
      else:
            await e.edit("**Trying to get Spotify lyrics...**")
            if SPOTIFY_KEY is None:
                  await e.edit("**Spotify cache KEY is missing**")
                  return
            if SPOTIFY_DC is None:
                  await e.edit("**Spotify cache DC is missing**")
                  return
            #getting spotify token
            sptoken = st.start_session(SPOTIFY_DC, SPOTIFY_KEY) 
            access_token = sptoken[0]
            environ["spftoken"] = access_token
            spftoken = environ.get("spftoken", None)
            hed = {'Authorization': 'Bearer ' + spftoken}
            url = 'https://api.spotify.com/v1/me/player/currently-playing'
            response = get(url, headers=hed)
            data = loads(response.content)
            isLocal = data['item']['is_local']
            if isLocal:
                  artist = data['item']['artists'][0]['name']
            else:
                  artist = data['item']['album']['artists'][0]['name']
            name = data['item']['name']
            print(artist + " - " + name)
            await e.edit("**Searching for song **" + name + "** by **" + artist)
            song = genius.search_song(name, artist)
      if song is None:
        await e.edit("**Can't find song **" + name + "** by **" + artist)
        return
      elif len(song.lyrics) > 4096:
        lyrics_1 = song.lyrics[0:4096]
        lyrics_2 = song.lyrics[4096:len(song.lyrics)]
        await e.edit("**Lyrics for: **" + artist + " - " + name + ": \n")
        await e.client.send_message(e.chat_id, lyrics_1)
        await e.client.send_message(e.chat_id, lyrics_2)

        
      elif (len(song.lyrics + artist + name) + 20) <= 4096:
        await e.edit("**Lyrics for: **" + artist + " - " + name + " \n" + song.lyrics)
示例#13
0
	def GetSpotifyToken(self):
		try:
			if self.SpotifyUsername != "" and self.Spotifypassword != "" and self.SpotifyExpiryTime - time.time() < 60:
				data 					= spotify_token.start_session(self.SpotifyUsername, self.Spotifypassword)
				self.SpotifyAccessToken = data[0]
				self.SpotifyExpiryTime 	= data[1]
				self.SpotifyClient 		= spotipy.Spotify(auth=self.SpotifyAccessToken)
				self.SpotifyUserId 		= self.SpotifyClient.current_user()["id"]
		except requests.exceptions.ConnectionError:
			pass
		except Exception as e:
			senderror(e)
示例#14
0
 def get_spotify_token(self) -> tuple[str, int]:
     try:
         self._access_token, self._token_expires = st.start_session(
             self.sp_dc, self.sp_key)
         expires = self._token_expires - int(time.time())
         return self._access_token, expires
     except TooManyRedirects:
         _LOGGER.error(
             "Could not get spotify token. sp_dc and sp_key could be expired. Please update in config."
         )
         raise HomeAssistantError("Expired sp_dc, sp_key")
     except:  # noqa: E722
         raise HomeAssistantError("Could not get spotify token.")
def _getSpotifyChromecastController():
    try:
        spotifyUserUsername = os.environ['SPOTIFY_USER_USERNAME']
        spotifyUserPassword = os.environ['SPOTIFY_USER_PASSWORD']
    except KeyError:
        raise SpotifyPlaybackError(
            'Missing Spotify user credentials in env vars '
            '`SPOTIFY_USER_USERNAME` and/or `SPOTIFY_USER_PASSWORD`')
    (spotifyControllerAccessToken,
     spotifyControllerExpiresAt) = spotify_token.start_session(
         spotifyUserUsername, spotifyUserPassword)
    spotifyControllerExpiresIn = spotifyControllerExpiresAt - int(time())

    return SpotifyController(spotifyControllerAccessToken,
                             spotifyControllerExpiresIn)
示例#16
0
def GenerateSpotifyToken(options):
    try:
        print("Generating Spotify Token")
        print(options)
        data = st.start_session(options["username"], options["password"])
        access_token = data[0]
        seconds_left = data[1] - int(time.time())
        result = {
            "access_token": access_token,
            "expire_time": data[1],
            "seconds_left": seconds_left
        }
        return result
    except Exception as e:
        print("Couldn't Generate Spotify Token")
        print(e)
        return False
示例#17
0
def play_music(song_uri):
    devices = pychromecast.get_chromecasts()
    speaker = next(cc for cc in devices
                   if cc.device.friendly_name == CAST_NAME)
    speaker.wait()
    data = st.start_session("little_wang", "Jumbobean123")
    access_token = data[0]
    expires = data[1] - int(time.time())

    client = spotipy.Spotify(auth=access_token)
    sp = SpotifyController(access_token, expires)
    speaker.register_handler(sp)
    sp.launch_app()
    devices_available = client.devices()
    for device in devices_available['devices']:
        if device['name'] == CAST_NAME:
            device_id = device['id']
            break
    speaker.set_volume(0.5)
    client.start_playback(device_id=device_id, uris=[song_uri])
示例#18
0
    def initialize(self):
        self.sp_key = sp_key
        self.sp_dc = sp_dc
        token, expires = spotify_token.start_session(sp_dc, sp_key)
        self.spotify_controller = SpotifyController(token, expires)

        username = self.settings.get('username')
        password = self.settings.get('password')
        self.log.info("Settings:" + str(self.settings))
        self.log.info("Username:"******"Password:"******"Init device")
        self.log.info("Init spotify cast skill")
        thread = threading.Thread(target=self.update_chromecasts)
        thread.start()
示例#19
0
def get_music(
    query, username, password
):  #coloque seu email ou username e sua senha do spotify para pegar o token
    data = st.start_session(username, password)
    access_token = data[0]

    header = {"Authorization": f"Bearer {access_token}"}

    url = f'https://spclient.wg.spotify.com/searchview/android/v4/search/{query}?&locale=pt-br&username=danisosigan&country=BR&catalogue=premium&limit=1'

    resp = requests.get(url, headers=header)
    # print(resp.text)
    if 'target' in resp.text:
        data = json.loads(resp.text)
        id = data['body'][0]['children'][0]['target']['uri']
        id = id.split(':')[-1]
        url = f'https://open.spotify.com/track/{id}'
        print(url)
        print('Abrindo música...')
        sleep(2)
        open(url)
    else:
        print('Música não encontrada!')
示例#20
0
def play_spotify(user,
                 password,
                 uri=["spotify:track:3Zwu2K0Qa5sT6teCCHPShP"],
                 show_debug=False,
                 cast="Sadie's TV"):
    if show_debug:
        logging.basicConfig(level=logging.DEBUG)
        # Uncomment to enable http.client debug log
        #http_client.HTTPConnection.debuglevel = 1

    # Store the ip in a txt file
    # Open File
    cast_ip = None

    with open('cast.txt', 'r+') as f:
        print("This is the file pointer", f)
        if len(f.read(1)) == 0:
            cast = discover_casts(cast)
        else:
            f.seek(0)
            cast_ip = [line for line in f][0]
            cast = get_cast(cast_ip, cast)

        if (cast.host != cast_ip):
            f.write(cast.host)

    # Wait for connection to the chromecast
    cast.wait()

    spotify_device_id = None

    # Create a spotify token
    data = st.start_session(user, password)
    access_token = data[0]
    expires = data[1] - int(time.time())

    # Create a spotify client
    client = spotipy.Spotify(auth=access_token)
    if show_debug:
        spotipy.trace = True
        spotipy.trace_out = True

    # Launch the spotify app on the cast we want to cast to
    sp = SpotifyController(access_token, expires)
    cast.register_handler(sp)
    sp.launch_app()

    if not sp.is_launched and not sp.credential_error:
        print('Failed to launch spotify controller due to timeout')
        sys.exit(1)
    if not sp.is_launched and sp.credential_error:
        print('Failed to launch spotify controller due to credential error')
        sys.exit(1)

    # Query spotify for active devices
    devices_available = client.devices()

    # Match active spotify devices with the spotify controller's device id
    for device in devices_available['devices']:
        if device['id'] == sp.device:
            spotify_device_id = device['id']
            break

    if not spotify_device_id:
        print('No device with id "{}" known by Spotify'.format(sp.device))
        print('Known devices: {}'.format(devices_available['devices']))
        sys.exit(1)

    # Start playback
    if uri[0].find('track') > 0:
        client.start_playback(device_id=spotify_device_id, uris=uri)
    else:
        client.start_playback(device_id=spotify_device_id, context_uri=uri[0])
示例#21
0
def runner(db, songs) :

    config = open("config.txt", "r")
    config_lines = config.readlines()

    username = config_lines[0].strip()
    password = config_lines[1].strip()
    consumer_key = config_lines[2].strip()
    consumer_secret = config_lines[3].strip()
    access_token = config_lines[4].strip()
    access_secret = config_lines[5].strip()
    name = config_lines[6].strip()
    

    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_secret)

    api = tweepy.API(auth)

    data = st.start_session(username, password)
    token = data[0]
    expiration_date = data[1]

    #print("Token : " + token, end="\n\n")
    #print("Expiration Date : {}".format(expiration_date), end="\n\n")
    
    counter = 0
    previous_response = -1
    song_name = ""
    artist_name = ""


    while counter < 100 :
        headers = {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + token,
        }

        params = (
            ('market', 'ES'),
        )

        response = requests.get('https://api.spotify.com/v1/me/player/currently-playing', headers=headers, params=params)
        
        if response.status_code == 200 :
            x = response.json()

            # Check if there is still the same song playing
            if (artist_name == x["item"]["artists"][0]["name"] and song_name == x["item"]["name"]) :
                continue

            song_name = x["item"]["name"]
            song_url = x["item"]["external_urls"]["spotify"]
            artist_name = x["item"]["artists"][0]["name"]
            string = artist_name + " - " + song_name

            print(string)
            
            if songs[string] < 1 :
                try :
                    songs[string] += 1
                    api.update_status(name + ' is currently listening to "' + string + '"' + " " + song_url)
                    db.write(string + '\n')
                except :
                    print("You have tweeted it before.")
                    sleep(60)
                    continue

        elif response.status_code == 204 and previous_response != 204:
            print("Not playing at the moment")
            sleep(60)
        elif response.status_code == 401 :        
            data = st.start_session(username, password)
            token = data[0]
            expiration_date = data[1]
            sleep(60)
            

        counter += 1
        previous_response = response.status_code
        sleep(60)
示例#22
0
async def update_token():
    sptoken = st.start_session(USERNAME, PASSWORD)
    access_token = sptoken[0]
    environ["spftoken"] = access_token
    environ["errorcheck"] = "1"
    await update_spotify_info()
示例#23
0
def run_spotify():
    """
	Example on how to use the Spotify Controller.
	NOTE: You need to install the spotipy and spotify-token dependencies.
	
	This can be done by running the following:
	pip install spotify-token
	pip install git+https://github.com/plamere/spotipy.git
	"""
    import argparse
    import logging
    import time
    import sys

    import pychromecast
    from pychromecast.controllers.spotify import SpotifyController
    import spotify_token as st
    import spotipy

    CAST_NAME = "My Chromecast"

    parser = argparse.ArgumentParser(
        description="Example on how to use the Spotify Controller.")
    parser.add_argument("--show-debug",
                        help="Enable debug log",
                        action="store_true")
    parser.add_argument("--cast",
                        help='Name of cast device (default: "%(default)s")',
                        default=CAST_NAME)
    parser.add_argument("--user", help="Spotify username", required=True)
    parser.add_argument("--password", help="Spotify password", required=True)
    parser.add_argument(
        "--uri",
        help='Spotify uri(s) (default: "%(default)s")',
        default=["spotify:track:3Zwu2K0Qa5sT6teCCHPShP"],
        nargs="+",
    )
    args = parser.parse_args()

    if args.show_debug:
        logging.basicConfig(level=logging.DEBUG)
        # Uncomment to enable http.client debug log
        # http_client.HTTPConnection.debuglevel = 1

    chromecasts = pychromecast.get_listed_chromecasts(
        friendly_names=[args.cast])
    cast = None
    for _cast in chromecasts:
        if _cast.name == args.cast:
            cast = _cast
            break

    if not cast:
        print('No chromecast with name "{}" discovered'.format(args.cast))
        print("Discovered casts: {}".format(chromecasts))
        sys.exit(1)

    print("cast {}".format(cast))

    class ConnListener:
        def __init__(self, mz):
            self._mz = mz

        def new_connection_status(self, connection_status):
            """Handle reception of a new ConnectionStatus."""
            if connection_status.status == "CONNECTED":
                self._mz.update_members()

    class MzListener:
        def __init__(self):
            self.got_members = False

        def multizone_member_added(self, uuid):
            pass

        def multizone_member_removed(self, uuid):
            pass

        def multizone_status_received(self):
            self.got_members = True

    # Wait for connection to the chromecast
    cast.wait()

    spotify_device_id = None

    # Create a spotify token
    data = st.start_session(args.user, args.password)
    access_token = data[0]
    expires = data[1] - int(time.time())

    # Create a spotify client
    client = spotipy.Spotify(auth=access_token)
    if args.show_debug:
        spotipy.trace = True
        spotipy.trace_out = True

    # Launch the spotify app on the cast we want to cast to
    sp = SpotifyController(access_token, expires)
    cast.register_handler(sp)
    sp.launch_app()

    if not sp.is_launched and not sp.credential_error:
        print("Failed to launch spotify controller due to timeout")
        sys.exit(1)
    if not sp.is_launched and sp.credential_error:
        print("Failed to launch spotify controller due to credential error")
        sys.exit(1)

    # Query spotify for active devices
    devices_available = client.devices()

    # Match active spotify devices with the spotify controller's device id
    for device in devices_available["devices"]:
        if device["id"] == sp.device:
            spotify_device_id = device["id"]
            break

    if not spotify_device_id:
        print('No device with id "{}" known by Spotify'.format(sp.device))
        print("Known devices: {}".format(devices_available["devices"]))
        sys.exit(1)

    # Start playback
    if args.uri[0].find("track") > 0:
        client.start_playback(device_id=spotify_device_id, uris=args.uri)
    else:
        client.start_playback(device_id=spotify_device_id,
                              context_uri=args.uri[0])
示例#24
0
import spotipy
import spotify_token as st

#Get the Access Token (just needed for authentification purposes in order to use the Spotify API)
username = ""
password = ""
data = st.start_session(username, password)
access_token = data[0]

spotify = spotipy.Spotify()

token = data[0]
spotify = spotipy.Spotify(auth=token)

#Get Artist's URI from Spotify
artist_uri = 'spotify:artist:06HL4z0CvFAxyc27GXpf02'

artist = spotify.artist_top_tracks(artist_uri)

for track in artist['tracks'][:10]:
    print('Song Name: ' + track['name'])
    print('Song Preview: ' + track['preview_url'])
    print('Song Cover Art: ' + track['album']['images'][0]['url'] + "\n")
示例#25
0
async def update_token():
    sptoken = st.start_session(sp_dc, sp_key)
    access_token = sptoken[0]
    environ["spftoken"] = access_token
    environ["errorcheck"] = "1"
    await update_spotify_info()
示例#26
0
async def get_spotify_token():
    sptoken = st.start_session(sp_dc, sp_key)
    access_token = sptoken[0]
    environ["spftoken"] = access_token
示例#27
0
 def get_spotify_token(self):
     import spotify_token as st
     self._access_token, self._token_expires = st.start_session(
         self.sp_dc, self.sp_key)
     expires = self._token_expires - int(time.time())
     return self._access_token, expires
示例#28
0
        pass

    def multizone_member_removed(self, uuid):
        pass

    def multizone_status_received(self):
        self.got_members = True


# Wait for connection to the chromecast
cast.wait()

spotify_device_id = None

# Create a spotify token
data = st.start_session(args.user, args.password)
access_token = data[0]
expires = data[1] - int(time.time())

# Create a spotify client
client = spotipy.Spotify(auth=access_token)
if args.show_debug:
    spotipy.trace = True
    spotipy.trace_out = True

# Launch the spotify app on the cast we want to cast to
sp = SpotifyController(access_token, expires)
cast.register_handler(sp)
sp.launch_app()

if not sp.is_launched and not sp.credential_error:
示例#29
0
debug = '--show-debug' in sys.argv
if debug:
    logging.basicConfig(level=logging.DEBUG)

chromecasts = pychromecast.get_chromecasts()
cast = None
for _cast in chromecasts:
    if _cast.name == CAST_NAME:
        cast = _cast
        break

if cast:
    cast.wait()
    device_id = None

    data = st.start_session("SPOTIFY_USERNAME", "SPOTIFY_PASSWORD")
    access_token = data[0]

    client = spotipy.Spotify(auth=access_token)

    sp = SpotifyController(access_token)
    cast.register_handler(sp)
    sp.launch_app()

    devices_available = client.devices()

    for device in devices_available['devices']:
        if device['name'] == CAST_NAME:
            device_id = device['id']
            break
示例#30
0
async def get_spotify_token():
    sptoken = st.start_session(USERNAME, PASSWORD)
    access_token = sptoken[0]
    environ["spftoken"] = access_token
示例#31
0
    def multizone_member_added(self, uuid):
        pass

    def multizone_member_removed(self, uuid):
        pass

    def multizone_status_received(self):
        self.got_members=True

# Wait for connection to the chromecast
cast.wait()

spotify_device_id = None

# Create a spotify token
data = st.start_session(args.user, args.password)
access_token = data[0]
expires = data[1] - int(time.time())

# Create a spotify client
client = spotipy.Spotify(auth=access_token)
if args.show_debug:
    spotipy.trace = True
    spotipy.trace_out = True

# Launch the spotify app on the cast we want to cast to
sp = SpotifyController(access_token, expires)
cast.register_handler(sp)
sp.launch_app()

if not sp.is_launched and not sp.credential_error: