コード例 #1
0
def spotiterm():
    # While loop to always go back to menu after action performed.
    while (True):
        # Clear terminal.
        clear()
        # Prints menu options (See spotiterm_func.py)
        menu_options()
        user_input = input(info(green("Select a menu option: ")))
        if (user_input) == ("1"):
            clear()
            # Executes track_search(), passing in auth() return (sp object) into
            # it. Then browser_open() executes.
            browser_open(track_search(auth()))
        elif (user_input) == ("2"):
            clear()
            # Executes artist_top_10(), passing in auth() return (sp object).
            artist_top_10(auth())
        elif (user_input) == ("3"):
            clear()
            # Executes user_top_tracks(), user_auth() passed in to get username
            # and token for use. Scope passed in for user_auth().
            user_top_tracks(user_auth("user-top-read"))
        elif (user_input) == ("4"):
            clear()
            # Executes user_top_artist(), user_auth() passed in to get username
            # and token for use. Scope passed in for user_auth().
            user_top_artist(user_auth("user-top-read"))
        elif (user_input) == ("5"):
            clear()
            # Executes playlist_contents(), user_auth() passed in to get username
            # and token for use. Scope passed in for user_auth().
            playlist_contents(user_auth("playlist-read-private"))
        elif (user_input) == ("6"):
            clear()
            # Asks user if a public or private playlist is for tracks to be
            # removed or deleted from.
            public_private = input(info(green("Public or Private Playlist: ")))
            if (public_private) == ("Public"):
                public_scope = "playlist-modify-public"
                # Executes playlist(), user_auth() passed in to get username
                # and token for use. Scope passed in for user_auth().
                playlist(user_auth(public_scope))
            elif (public_private) == ("Private"):
                private_scope = "playlist-modify-private"
                # Executes playlist(), user_auth() passed in to get username
                # and token for use. Scope passed in for user_auth().
                playlist(user_auth(private_scope))
            else:
                print(green("Input a valid menu option."))
                sleep(2)
        elif (user_input) == ("7"):
            clear()
            player_controls(get_devices(user_auth("user-read-playback-state")))
        elif (user_input) == ("8"):
            clear()
            exit()
        else:
            # Catch invalid menu option input.
            print(green("Input a valid menu option."))
            sleep(2)
コード例 #2
0
def youdao_api(words: str):
    print()
    url = ("http://fanyi.youdao.com/openapi.do?keyfrom={}&key={}&"
           "type=data&doctype=json&version=1.1&q={}")
    try:
        resp = requests.get(url.format(CONF.youdao_key_from, CONF.youdao_key,
                                       words),
                            headers=HEADERS).json()
        phonetic = ""
        basic = resp.get("basic", None)
        if basic and resp.get("basic").get("phonetic"):
            phonetic += huepy.purple("  [ " + basic.get("phonetic") + " ]")

        print(" " + words + phonetic + huepy.grey("  ~  fanyi.youdao.com"))
        print()

        translation = resp.get("translation", [])
        if len(translation) > 0:
            print(" - " + huepy.green(translation[0]))

        if basic and basic.get("explains", None):
            for item in basic.get("explains"):
                print(huepy.grey(" - ") + huepy.green(item))
        print()

        web = resp.get("web", None)
        if web and len(web):
            for i, item in enumerate(web):
                print(
                    huepy.grey(" " + str(i + 1) + ". " +
                               highlight(item.get("key"), words)))
                print("    " + huepy.cyan(", ".join(item.get("value"))))

    except Exception:
        print(" " + huepy.red(ERR_MSG))
コード例 #3
0
def user_auth(scope):
    try:
        username = input(info(green("Spotify Username: "******".cache-{username}")
        return username, token
    except spotipy.oauth2.SpotifyOauthError as err:
        print(green(f"User Authentication Failed: {err}"))
        sleep(2)
コード例 #4
0
ファイル: option7.py プロジェクト: chrishudetz/SpotiTerm
def get_devices(username_token):
    try:
        # Unpack returns from user_auth(): authentication.py
        username, token = username_token
        if token:
            # clear() to remove authentication text.
            clear()
            sp = spotipy.Spotify(auth=token)
            resp = sp.devices()
            # List objects.
            device_id_list = []
            device_name_list = []
            # For device names and ids in resp, append each to corresponding
            # list.
            for item, devices in enumerate(resp["devices"], 1):
                device_name_list.append(devices["name"])
                device_id_list.append(devices["id"])
                device_name = devices["name"]
                device_id = devices["id"]
                print(
                    green(
                        f" Device: {item} -- Name: {device_name} -- Device ID: {device_id}"
                    ))
            user_input = input(info(green("Select Device Number: ")))
            # Start from 0 due to python indexing starting at 0.
            # Support currently for only 4 devices. This is due to my own lack of knowledge.
            # Which ever device selected: Select data from corresponding lists.
            if (user_input) == ("1"):
                id_choice = device_id_list[0]
                name_choice = device_name_list[0]
            elif (user_input) == ("2"):
                id_choice = device_id_list[1]
                name_choice = device_name_list[1]
            elif (user_input) == ("3"):
                id_choice = device_id_list[2]
                name_choice = device_name_list[2]
            elif (user_input) == ("4"):
                id_choice = device_id_list[3]
                name_choice = device_name_list[3]
            return name_choice, id_choice
        else:
            print(green(f"Can't get token for {username}"))
            sleep(2)
    except spotipy.client.SpotifyException as err:
        print(green(f"Failed to get devices: {err}"))
        sleep(2)
    except UnboundLocalError as err:
        print(green(f"Please select a valid device: {err}"))
        sleep(2)
コード例 #5
0
ファイル: main.py プロジェクト: vindu939/Playlist-Length
def calculate_length(BASE_PATH, no_subdir, media_type):
    if not os.path.isdir(BASE_PATH):
        return bold(red('Error: This doesn\'t seem to be a valid directory.'))

    all_files = get_all_files(BASE_PATH, no_subdir)

    with ProcessPoolExecutor() as executor:
        sys.stdout.write('\n')
        result = list(
            tqdm(
                executor.map(duration, all_files),
                total=len(all_files),
                desc='Processing files',
            )
        )

    length = round(sum(result))

    if length == 0:
        return bold(red('Seems like there are no {} files. ¯\_(ツ)_/¯'.format(media_type)))
    elif length < 60:
        minutes_string = pluralize(length, base='minute', suffix='s')
        result = 'Length of all {} is {}.'.format(media_type, minutes_string)
    else:
        hours, minutes = divmod(length, 60)
        hours_string = pluralize(hours, base='hour', suffix='s')
        minutes_string = pluralize(minutes, base='minute', suffix='s')
        result = 'Length of all {} is {} and {}.'.format(
            media_type, hours_string, minutes_string
        )
    return bold(green(result))
コード例 #6
0
def calculate_length(BASE_PATH, no_subdir, media_type, queue, cache_ob):
    if not os.path.isdir(BASE_PATH):
        return bold(red('Error: This doesn\'t seem to be a valid directory.'))

    all_files = get_all_files(BASE_PATH, no_subdir)
    max_workers = multiprocessing.cpu_count() + 1
    with ProcessPoolExecutor(max_workers=max_workers) as executor:
        sys.stdout.write('\n')
        cache = cache_ob.cache
        args = ((file, queue, cache) for file in all_files)
        result = list(
            tqdm(
                executor.map(duration, args),
                total=len(all_files),
                desc='Processing files',
            ))

    length = round(sum(result))

    queue.put(None)  # poison pill

    if length == 0:
        return bold(
            red('Seems like there are no {} files. ¯\_(ツ)_/¯'.format(
                media_type)))
    elif length < 60:
        minutes_string = pluralize(length, base='minute', suffix='s')
        result = 'Length of all {} is {}.'.format(media_type, minutes_string)
    else:
        hours, minutes = divmod(length, 60)
        hours_string = pluralize(hours, base='hour', suffix='s')
        minutes_string = pluralize(minutes, base='minute', suffix='s')
        result = 'Length of all {} is {} and {}.'.format(
            media_type, hours_string, minutes_string)
    return bold(green(result))
コード例 #7
0
ファイル: option2.py プロジェクト: chrishudetz/SpotiTerm
def artist_top_10(sp):
    try:
        artist_name = input(info(green("What is the artist name: ")))
        # resp for searching artist name. Get top artist tracks.
        resp = sp.search(q=artist_name, limit=10)
        # int: 1 is passed to start from 1 instead of 0.
        for item, track in enumerate(resp["tracks"]["items"], 1):
            print(green(f" {item} {track['name']}"))
        # Sleep to observe above print.
        sleep(8)
    except spotipy.client.SpotifyException as err:
        print(green(f"Top 10 track lookup failed: {err}"))
        sleep(2)
    except spotipy.oauth2.SpotifyOauthError as err:
        print(green(f"Bad request. Check Client ID and Client S: {err}"))
        sleep(2)
コード例 #8
0
def add_del_track():
    try:
        print(
            info(
                green(
                    "Input one or more track(s): seperated by , if multiple")))
        # Input tracks, seperated by "," if multiple.
        track_ids = input(info(green("Tracks: "))).split(",")
        return track_ids
    # Exception here is unlikely however, basic handle has been done.
    except:
        print(
            green("""
                    add_del_track function failed.
                    Ensure you added , when adding more than one track."""))
        sleep(2)
コード例 #9
0
    def get_weather_data_from_city_page_source(self, url, page_source):
        print(hue.blue(f'Scrapying Climatempo page source at {url}'))
        page = BeautifulSoup(page_source, 'html.parser')
        table_attrs = {
            'class': 'left top20 small-12 border-none',
        }
        table = page.find('table', attrs=table_attrs)

        metric_trs = table.find_all('tr')
        last_month_measured_weather_tr = metric_trs[-1]
        last_mesured_month_metric_tds = last_month_measured_weather_tr\
            .find_all('td')

        city_name_p = page.find('p', attrs={'data-reveal-id': 'geolocation'})
        city_name_span = city_name_p.find_all('span')[1]
        city_name, city_state = city_name_span.text.split('-')

        clean_temp = lambda temp: re.sub(r'\W+', '', temp)

        data = {
            'city': city_name.strip(),
            'state': city_state.strip(),
            'month': last_mesured_month_metric_tds[0].text,
            'min_temp': clean_temp(last_mesured_month_metric_tds[1].text),
            'max_temp': clean_temp(last_mesured_month_metric_tds[2].text),
            'rain': last_mesured_month_metric_tds[3].text,
        }
        print(
            hue.green(
                f'Scraped Climatempo page source at {url} - Data: {data}'))
        return data
コード例 #10
0
ファイル: follow_bot.py プロジェクト: m-henderson/instacron
    def follow_and_like(self):
        self.update_to_follow()
        if self.bot.reached_limit("likes"):
            print(green(bold(f"\nOut of likes, pausing for 10 minutes.")))
            self.print_sleep(600)
            return
        user_id = self.to_follow.random()
        busy = True
        while busy:
            if self.get_user_info(
                    user_id)["is_private"] or not self.bot.check_user(user_id):
                user_id = self.to_follow.random()
                self.to_follow.remove(user_id)
            else:
                busy = False

        username = self.get_user_info(user_id)["username"]
        medias = self.bot.get_user_medias(user_id)
        self.to_follow.remove(user_id)
        if medias and self.lastest_post(medias) < 21:  # days
            n = min(random.randint(4, 10), len(medias))
            print(f"Liking {n} medias from `{username}`.")
            self.bot.like_medias(random.sample(medias, n))
            self.follow(user_id, tmp_follow=True)
        else:
            # Abandon user and call self recusively.
            self.follow_and_like()
コード例 #11
0
ファイル: utils.py プロジェクト: fauzanakbar/py_instagram_bot
 def remove(self, x):
     x = str(x)
     items = self.list
     if x in items:
         items.remove(x)
         msg = "Removing '{}' from `{}`.".format(x, self.fname)
         print(bold(green(msg)))
         self.save_list(items)
コード例 #12
0
ファイル: option1.py プロジェクト: chrishudetz/SpotiTerm
def browser_open(url):
    try:
        if url:
            user_input = input(
                green("Open track in your browser?: Yes or No "))
            if (user_input) == ("Yes"):
                # Opens URL in default system browser.
                webbrowser.open(url)
            else:
                # If any other input ie No. Exit to main menu (spotiterm)
                pass
        else:
            print(green("url was not recieved as parameter."))
            sleep(2)
    except webbrowser.Error as err:
        print(green(f"Failed to open url in your browser: {err}"))
        sleep(2)
コード例 #13
0
 def remove(self, x):
     x = str(x)
     items = self.list
     if x in items:
         items.remove(x)
         msg = "Removing '{}' from `{}`.".format(x, self.fname)
         print(bold(green(msg)))
         self.save_list(items)
コード例 #14
0
def clear():
    try:
        # execute "cls" if os is windows else execute "clear".
        subprocess.call(["cls" if platform.system() == "Windows" else "clear"],
                        shell=True)
    except subprocess.CalledProcessError:
        print(green("Terminal clear failed."))
        sleep(2)
コード例 #15
0
def user_top_tracks(username_token):
    try:
        # Unpack returns from user_auth(): authentication.py
        username, token = username_token
        if token:
            # clear() to remove authentication text.
            clear()
            sp = spotipy.Spotify(auth=token)
            print(green("Short Term Tracks"))
            resp = sp.current_user_top_tracks(time_range="short_term",
                                              limit=10)
            for i, item in enumerate(resp["items"], 1):
                # Prints item number. Track name, artist name.
                print(
                    green(
                        f" {i} {item['name']} -- {item['artists'][0]['name']}")
                )
            print(green("Long Term Tracks"))
            resp = sp.current_user_top_tracks(time_range="long_term", limit=10)
            for i, item in enumerate(resp["items"], 1):
                print(
                    green(
                        f" {i} {item['name']} -- {item['artists'][0]['name']}")
                )
            # Sleep for user to observe output.
            sleep(15)
        else:
            print(green(f"Can't get token for {username}"))
            sleep(2)
    except spotipy.client.SpotifyException as err:
        print(green(f"User Top Track Lookup Failed: {err}"))
        sleep(2)
    except TypeError as err:
        print(green(f"Failed to get redirect URL from browser: {err}"))
        sleep(2)
コード例 #16
0
ファイル: option7.py プロジェクト: chrishudetz/SpotiTerm
def next_previous(username_token, name_choice, id_choice):
    try:
        # Unpack returns from user_auth(): authentication.py
        username, token = username_token
        if token:
            # clear() to remove authentication text.
            clear()
            sp = spotipy.Spotify(auth=token)
            user_input = input(info(green("Next or Previous?: ")))
            if (user_input) == ("Next"):
                # Skip track.
                sp.next_track(device_id=id_choice)
                print(green(f" Track skipped on {name_choice}"))
                sleep(2)
            elif (user_input) == ("Previous"):
                try:
                    # Previous track.
                    sp.previous_track(device_id=id_choice)
                    print(green(f" Previous track on {name_choice}"))
                except spotipy.client.SpotifyException:
                    print(green("No previous track available."))
                    sleep(2)
            else:
                print(green("Input a valid menu option."))
                sleep(2)
        else:
            print(green(f"Can't get token for {username}"))
    except spotipy.client.SpotifyException as err:
        print(green(f"Failed to skip -- go to previous track: {err}"))
コード例 #17
0
ファイル: option7.py プロジェクト: chrishudetz/SpotiTerm
def shuffle(username_token, state, id_choice):
    try:
        # Unpack returns from user_auth(): authentication.py
        username, token = username_token
        if token:
            # clear() to remove authentication text.
            clear()
            sp = spotipy.Spotify(auth=token)
            # State passed in from player_controls() Can be True or False.
            sp.shuffle(state, device_id=id_choice)
            print(green(" Complete."))
            sleep(2)
        else:
            print(green(f"Can't get token for {username}"))
            sleep(2)
    except spotipy.client.SpotifyException as err:
        print(green(f"Failed to shuffle: {err}"))
        sleep(2)
コード例 #18
0
ファイル: misc.py プロジェクト: chenlq123/MAE
def lucky_bunny(i):
    print('')
    print('| ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄|')
    print('|    TRAINING    |')
    print('|     epoch      |')
    print('|       ' + hue.bold(hue.green(str(i))) + '        |')
    print('|    (*^▽^*)     |')
    print('|    (≧∇≦)ノ)     |')
    print('| ________|')
コード例 #19
0
    def process(self, data):
        print(hue.bold(hue.green("\n------ {} ------".format(datetime.now()))))
        print(
            hue.yellow("Full packet data: ") +
            hue.italic(binascii.hexlify(data)))

        # Checks if the 802.15.4 packet is valid
        if makeFCS(data[:-2]) != data[-2:]:
            print(hue.bad("Invalid packet"))
            return

        # Parses 802.15.4 packet
        packet = Dot15d4FCS(data)
        packet.show()

        if packet.fcf_frametype == 2:  # ACK
            return

        # Tries to match received packet with a known link
        # configuration
        matched = False
        for link in self.link_configs:
            if packet.dest_panid != link.dest_panid:
                continue
            if packet.fcf_srcaddrmode == 3:  # Long addressing mode
                if packet.src_addr != link.source.get_long_address():
                    continue
                if packet.dest_addr != link.destination.get_long_address():
                    continue
            else:
                if packet.src_addr != link.source.get_short_address():
                    continue
                if packet.dest_addr != link.destination.get_short_address():
                    continue
                source = link.source
                destination = link.destination
                key = link.key
                matched = True

        if not matched:
            if packet.fcf_srcaddrmode == 3:
                source = Rf4ceNode(packet.src_addr, None)
                destination = Rf4ceNode(packet.dest_addr, None)
            else:
                source = Rf4ceNode(None, packet.src_addr)
                destination = Rf4ceNode(None, packet.dest_addr)
            key = None

        # Process RF4CE payload
        frame = Rf4ceFrame()
        try:
            rf4ce_payload = bytes(packet[3].fields["load"])
            frame.parse_from_string(rf4ce_payload, source, destination, key)
        except Rf4ceException, e:
            print(hue.bad("Cannot parse RF4CE frame: {}".format(e)))
            return
コード例 #20
0
def logo():
    print(
        green("""
       ___           _   _ _____
      / __|_ __  ___| |_(_)_   _|__ _ _ _ __
      \__ \ '_ \/ _ \  _| | | |/ -_) '_| '  |
      |___/ .__/\___/\__|_| |_|\___|_| |_|_|_|
          |_|
    Created By: Daniel Brennand a.k.a: Dextroz
         """))
コード例 #21
0
ファイル: misc.py プロジェクト: zhangxinyu-xyz/HOIM-PyTorch
def lucky_bunny(i):
    print('')
    print('| ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄|')
    print('|    TRAINING    |')
    print('|     epoch      |')
    print('|       ' + hue.bold(hue.green(str(i))) + '        |')
    print('| ________|')
    print(' (\__/) ||')
    print(' (•ㅅ•) || ')
    print(' /   づ')
    print('')
コード例 #22
0
ファイル: utils.py プロジェクト: fauzanakbar/py_instagram_bot
    def append(self, item, allow_duplicates=False):
        if self.verbose:
            msg = "Adding '{}' to `{}`.".format(item, self.fname)
            print(bold(green(msg)))

        if not allow_duplicates and str(item) in self.list:
            msg = "'{}' already in `{}`.".format(item, self.fname)
            print(bold(orange(msg)))
            return

        with open(self.fname, 'a') as f:
            f.write('{item}\n'.format(item=item))
コード例 #23
0
def auth():
    try:
        # authorisation. Gets token for functions. CLIENT_ID and CLIENT_SECRET passed in.
        client_credentials = SpotifyClientCredentials(
            client_id=CLIENT_ID, client_secret=CLIENT_S)
        # sp currently for global use.
        sp = spotipy.Spotify(client_credentials_manager=client_credentials)
        # Return sp object. For use in non user required calls to API.
        return sp
    except spotipy.oauth2.SpotifyOauthError:
        print(green("Authentication Failed! Check connection or CLIENT_ID or CLIENT_SECRET keys."))
        sleep(2)
コード例 #24
0
    def append(self, item, allow_duplicates=False):
        if self.verbose:
            msg = "Adding '{}' to `{}`.".format(item, self.fname)
            print(bold(green(msg)))

        if not allow_duplicates and str(item) in self.list:
            msg = "'{}' already in `{}`.".format(item, self.fname)
            print(bold(orange(msg)))
            return

        with open(self.fname, "a", encoding="utf8") as f:
            f.write("{item}\n".format(item=item))
コード例 #25
0
 def output_stats(self):
     print("\t| {} {}".format(green("Player:"), self.name))
     print("\t|\t {} {}, {} {}".format(yellow("Gold:"), self.gold,
                                       orange("Infamy:"), self.infamy))
     for unit in self.units:
         print("\t|\t {}".format(unit))
     print("\t| {} {}".format(red("Opponent:"), self.opponent.name))
     print("\t|\t {} {}, {} {}".format(yellow("Gold:"), self.opponent.gold,
                                       orange("Infamy:"),
                                       self.opponent.infamy))
     for unit in self.opponent.units:
         print("\t|\t {}".format(unit))
コード例 #26
0
ファイル: option7.py プロジェクト: chrishudetz/SpotiTerm
def set_volume(username_token, name_choice, id_choice):
    try:
        # Unpack returns from user_auth(): authentication.py
        username, token = username_token
        if token:
            # clear() to remove authentication text.
            clear()
            sp = spotipy.Spotify(auth=token)
            # Asks for volume input. String due to Hue function usage.
            volume = input(info(green("Volume: ")))
            # String input converted into integer.
            volume_int = int(volume)
            if (volume_int) >= (0) and (volume_int) <= (100):
                sp.volume(volume_int, device_id=id_choice)
                print(green(f" Volume set to {volume_int}% for {name_choice}"))
                sleep(2)
            else:
                print(green("Volume must be between 0 and 100 or equal to."))
                sleep(2)
        else:
            print(green(f"Can't get token for {username}"))
            sleep(2)
    except spotipy.client.SpotifyException as err:
        print(green(f"Failed to set volume: {err}"))
        sleep(2)
    except ValueError as err:
        print(green(f"Input only an integer: {err}"))
        sleep(2)
コード例 #27
0
ファイル: option7.py プロジェクト: chrishudetz/SpotiTerm
def seek_track(username_token, name_choice, id_choice):
    try:
        # Unpack returns from user_auth(): authentication.py
        username, token = username_token
        if token:
            sp = spotipy.Spotify(auth=token)
            # clear() to remove authentication text.
            clear()
            progress_input = input(info(green("Skip to? (ms): ")))
            # Convert input to int.
            progress_int = int(progress_input)
            sp.seek_track(progress_int, device_id=id_choice)
            print(green(f" Track seeked to {progress_int}ms on {name_choice}"))
            sleep(2)
        else:
            print(green(f"Can't get token for {username}"))
    except spotipy.client.SpotifyException as err:
        print(green(f"Failed to seek to point on track: {err}"))
        sleep(2)
    except ValueError as err:
        print(green(f"Input only an integer: {err}"))
        sleep(2)
コード例 #28
0
ファイル: utils.py プロジェクト: geeknam/instabot
    def append(self, item, allow_duplicates=False):
        if self.verbose:
            msg = "Adding '{}' to `{}`.".format(item, self.fname)
            print(bold(green(msg)))

        if not allow_duplicates and str(item) in self.list:
            msg = "'{}' already in `{}`.".format(item, self.fname)
            print(bold(orange(msg)))
            return

        file_content = self.get_file().read()
        new_content = file_content + '{item}\n'.format(item=item)
        self.write_file(new_content)
コード例 #29
0
ファイル: option1.py プロジェクト: chrishudetz/SpotiTerm
def track_search(sp):
    try:
        # User input for trackname
        track_name = input(info(green("What is the track name?")))
        # Resp holding results from search track.
        resp = sp.search(q=f"track:{track_name}",
                         limit=1,
                         type="track",
                         market="GB")
        for item, track in enumerate(resp["tracks"]["items"]):
            # Gets URL for song searched.
            url = track["external_urls"]["spotify"]
            # Prints trackname and its spotify URL.
            print(green(f" Track: {track['name']}, url: {url}"))
            # Returns URL so it can be used in browser_open()
            return url
    except spotipy.client.SpotifyException as err:
        print(green(f"Track lookup failed: {err}"))
        sleep(2)
    except spotipy.oauth2.SpotifyOauthError as err:
        print(green(f"Bad Request. Check Client ID, Client S: {err}"))
        sleep(2)
コード例 #30
0
def menu_options():
    logo()
    # green() is from huepy. Helps stick to colour scheme.
    print(
        green("""
    1. Track Search
    2. Artist Top 10
    3. Get User's Top Tracks
    4. Get User's Top Artists
    5. Show User's Playlists Tracks
    6. Add -- Delete Track(s) From Playlist
    7. Player Controls: Premium Required
    8. Exit SpotiTerm
    """))
コード例 #31
0
ファイル: option7.py プロジェクト: chrishudetz/SpotiTerm
def current_play(username_token):
    try:
        # Unpack returns from user_auth(): authentication.py
        username, token = username_token
        if token:
            # clear() to remove authentication text.
            clear()
            sp = spotipy.Spotify(auth=token)
            resp = sp.currently_playing(market="GB")
            is_playing = resp["is_playing"]
            progress_ms = resp["progress_ms"]
            track_name = resp["item"]["name"]
            album_name = resp["item"]["album"]["name"]
            artist_name = resp["item"]["album"]["artists"][0]["name"]
            print(
                green(
                    f"Track: {track_name} -- Album: {album_name} -- Artist: {artist_name} -- Playing: {is_playing} -- Progress: {progress_ms}"
                ))
            sleep(10)
        else:
            print(green(f"Can't get token for {username}"))
    except spotipy.client.SpotifyException as err:
        print(green(f"Failed to get current playing track: {err}"))
        sleep(2)
コード例 #32
0
 def get_climatempo_city_link(self, url, page_source):
     print(hue.blue(f'Scraping Google page at {url}'))
     page = BeautifulSoup(page_source, 'html.parser')
     css_selector = 'a[href*=/url?q=https://www.climatempo.com.br/climatologia/]'
     climatempo_link_tag = page.select_one(css_selector)
     if climatempo_link_tag is None:
         print(hue.yellow(f'Climatempo link not found on Google at {url}'))
         return ''
     climatempo_link = self.get_climatempo_link_from_tag(
         climatempo_link_tag)
     print(
         hue.green(
             f'Climatempo link {climatempo_link} scraped on google at {url}'
         ))
     return climatempo_link