def send(link, chat_id): DETAIL = Detail(link) song_name_folder = valuetotxt.read(3) trackname = valuetotxt.read(3) song_name = valuetotxt.read(2) try: bot.sendAudio(chat_id, open(f'song//{song_name_folder}.mp3', 'rb'), title=trackname) except: youtube.search(song_name, valuetotxt.read(5), valuetotxt.read(6), valuetotxt.read(10), valuetotxt.read(11)) bot.sendAudio(chat_id, open(f'song//{song_name_folder}.mp3', 'rb'), title=trackname)
def listening_now(max_tunes, by_id=True): """ Gets a list of tunes other people using last.fm are listening to, and turns them in to a youtube list of tracks. :param max_tunes: int the amount of tracks we want. :param by_id: bool if set to True, only tunes that have a youtube id will be added(recommended) :return: list[ dict{'type=youtube', 'video_id', 'int(video_time)', 'video_title'} ] or None on error. """ url = LISTENING_NOW_URL.format(max_tunes) lastfm = util.web.http_get(url=url, json=True) log.debug('lastfm response %s' % lastfm) if lastfm['json'] is not None: if len(lastfm['json']['Users']) is not 0: # make this list unique yt_tracks = [] for user in lastfm['json']['Users']: if 'playlink' in user: if 'data-youtube-id' in user['playlink']: youtube_id = user['playlink']['data-youtube-id'] yt = youtube.video_details(youtube_id) log.debug(yt) if yt is not None: yt_tracks.append(yt) else: if 'Track' in user: search_str = '%s - %s' % (user['Track']['Artist'], user['Track']['Name']) if not by_id: yt = youtube.search(search_str) log.debug('search by search string: %s result: %s' % (search_str, yt)) if yt is not None: yt_tracks.append(yt) return yt_tracks return None
def chart(chart_items=5): """ Finds the currently most played tunes on last.fm and turns them in to a youtube list of tracks. :param chart_items: int the amount of tracks we want. :return: list[ dict{'type=youtube', 'video_id', 'int(video_time)', 'video_title'} ] or None on error. """ url = CHART_URL.format(chart_items) lastfm = util.web.http_get(url=url, json=True) log.debug('lastfm response %s' % lastfm) if lastfm['json'] is not None: if 'results' in lastfm['json']: if 'track' in lastfm['json']['results']: if len(lastfm['json']['results']['track']) is not 0: # make this list unique yt_tracks = [] for track in lastfm['json']['results']['track']: search_str = '%s - %s' % (track['artist'], track['name']) yt = youtube.search(search_str) log.info(yt) if yt is not None: yt_tracks.append(yt) return yt_tracks return None
def do_GET(s): s.send_response(200) s.send_header("Content-type", "text/html") s.end_headers() url = youtube.search("hotel california") if url == False: url = "foobar" s.wfile.write("%s\n" % url)
def getYoutube(self, query): if query == "": rand = random.randint(0, len(PeonBot.youtubeRandomVideos) - 1) query = PeonBot.youtubeRandomVideos[rand] result = youtube.search(query) name = result['snippet']['title'] url = "https://youtu.be/" + result['id']['videoId'] return name, url
def tag_search(search_str, by_id=True, max_tunes=40): """ Search last.fm for tunes matching the search term and turns them in to a youtube list of tracks. :param search_str: str the search term to search for. :param by_id: bool if set to True, only tunes that have a youtube id will be added(recommended) :param max_tunes: int the max amount of tunes to return. :return: list[ dict{'type=youtube', 'video_id', 'int(video_time)', 'video_title'} ] or None on error. """ url = TAG_SEARCH_URL.format(max_tunes, util.web.quote(search_str)) lastfm = util.web.http_get(url=url, json=True) log.debug('lastfm response %s' % lastfm) if lastfm['json'] is not None: if 'track' in lastfm['json']['results']: if len(lastfm['json']['results']['track']) is not 0: # make this list unique yt_tracks = [] for track in lastfm['json']['results']['track']: search_str = '%s - %s' % (track['artist'], track['name']) if 'playlink' in track: if 'data-youtube-id' in track['playlink']: youtube_id = track['playlink']['data-youtube-id'] yt = youtube.video_details(youtube_id) log.debug(yt) if yt is not None: yt_tracks.append(yt) else: if not by_id: yt = youtube.search(search_str) log.debug( 'search by search string: %s result: %s' % (search_str, yt)) if yt is not None: yt_tracks.append(yt) else: if not by_id: yt = youtube.search(search_str) log.debug( 'search by search string: %s result: %s' % (search_str, yt)) if yt is not None: yt_tracks.append(yt) return yt_tracks return None
def tag_search(search_str, by_id=True, max_tunes=40): """ Search last.fm for tunes matching the search term and turns them in to a youtube list of tracks. :param search_str: str the search term to search for. :param by_id: bool if set to True, only tunes that have a youtube id will be added(recommended) :param max_tunes: int the max amount of tunes to return. :return: list[ dict{'type=youtube', 'video_id', 'int(video_time)', 'video_title'} ] or None on error. """ url = TAG_SEARCH_URL.format(max_tunes, util.web.quote(search_str)) lastfm = util.web.http_get(url=url, json=True) log.debug('lastfm response %s' % lastfm) if lastfm['json'] is not None: if 'track' in lastfm['json']['results']: if len(lastfm['json']['results']['track']) is not 0: # make this list unique yt_tracks = [] for track in lastfm['json']['results']['track']: search_str = '%s - %s' % (track['artist'], track['name']) if 'playlink' in track: if 'data-youtube-id' in track['playlink']: youtube_id = track['playlink']['data-youtube-id'] yt = youtube.video_details(youtube_id) log.debug(yt) if yt is not None: yt_tracks.append(yt) else: if not by_id: yt = youtube.search(search_str) log.debug('search by search string: %s result: %s' % (search_str, yt)) if yt is not None: yt_tracks.append(yt) else: if not by_id: yt = youtube.search(search_str) log.debug('search by search string: %s result: %s' % (search_str, yt)) if yt is not None: yt_tracks.append(yt) return yt_tracks return None
def callback(ch, method, properties, body): print(body) if str(body).startswith("b'[youtube]"): query = str(body)[13:-1] print(query) result = youtube.summary(youtube.search(query)[0], sentences=3, auto_suggest=False) print(result) ########## PUBLICA EL RESULTADO COMO EVENTO EN RABBITMQ ########## channel.basic_publish(exchange='nestor', routing_key="publicar_slack", body=query + ":" + result)
def spotify_search_api_request(): """Return API responses for search query.""" access_token = session['spotify_token'] query = request.args.get("userquery") spotify_data = spotify.search(query, access_token) youtube_data = youtube.search(query) mixcloud_data = mixcloud.search(query) return jsonify({ 'spotify': spotify_data, 'youtube': youtube_data, 'mixcloud': mixcloud_data })
def send_video(intent, session): youtube_result = youtube.search(intent["slots"]["video"]["value"]) try: publish_command_to_sns("play_video", {"videoId": youtube_result["id"]}) except SNSPublishError as error: speech = build_speechlet_response( title="ChromeCast - Command Failed", output=str(error) ) return build_response({}, speech) else: speech = build_speechlet_response( title="ChromeCast - Video Added", output="Adding {} from YouTube".format(youtube_result["title"]) ) return build_response({}, speech)
def post(self): # renders results page, calls on youtube module to do search and get video attributes user = users.get_current_user() login_url = '' logout_url = '' email = '' redirect_url = users.create_login_url('/') if user: user_key = ndb.Key('User', user.email()) check_user = models.User.query(models.User.key == user_key).fetch() if check_user == []: new_user = models.User(name=user.nickname(), id=user.email()) new_user.put() user_key = ndb.Key('User', user.email()) logout_url = users.create_logout_url('/') else: login_url = users.create_login_url(self.request.uri) hours = self.request.get("HOURS") if hours=="": hours = 0 else: hours = int(hours) minutes = self.request.get("MINUTES") if minutes=="": minutes = 0 else: minutes = int(minutes) seconds = self.request.get("SECONDS") if seconds=="": seconds = 0 else: seconds = int(seconds) time = (hours*3600) + (minutes*60) + (seconds) videos = youtube.search(time, self.request.get_all("genre")) template_values = { 'videos': videos, 'login_url':login_url, 'logout_url':logout_url, 'redirect_url':redirect_url } template = env.get_template('results.html') self.response.write(template.render(template_values))
def get(self, artist, song): try: if artist.find('%20') != -1 or song.find('%20') != -1: # url contains space, redirect to correct url with + instead of space self.redirect( '/_/%s/%s' % (artist.replace('%20', '+'), song.replace('%20', '+'))) artist = unicode(unquote(artist), 'utf-8').replace('+', ' ') song = unicode(unquote(song), 'utf-8').replace('+', ' ') similar_tracks = lastfm.get_similar_tracks(artist, song) template_values = { 'song': song, 'artist': artist, 'lyric': lyricswiki.get_lyric(artist, song), 'related_songs': similar_tracks[:5] if similar_tracks else None, 'video': youtube.search('%s %s' % (song, artist)) } self.render_template('song', template_values) except Exception, ex: self.internal_error()
def search(): params = request.query lat = params.get('lat') lng = params.get('lng') radius = params.get('radius') # quick validation if not all([lat, lng, radius]): response.status = 400 return {'error': 'Check geo params.'} location = "%s,%s" % (lat, lng) locationRadius = "%skm" % radius results = youtube.search( part=params.get('part', 'id'), type=params.get('type', 'video'), q=params.get('q'), location=location, locationRadius=locationRadius, order=params.get('order', 'date'), channelId=params.get('channelId'), maxResults=params.get('limit', 50), pageToken=params.get('next') ) # extract video ids video_ids = youtube.extract_video_ids(results) # retrieve video results videos = youtube.videos( part='snippet,recordingDetails', id=','.join(video_ids) ) return { 'videos': videos.get('items', []), 'next': results.get('nextPageToken') }
def listening_now(max_tunes, by_id=True): """ Gets a list of tunes other people using last.fm are listening to, and turns them in to a youtube list of tracks. :param max_tunes: int the amount of tracks we want. :param by_id: bool if set to True, only tunes that have a youtube id will be added(recommended) :return: list[ dict{'type=youtube', 'video_id', 'int(video_time)', 'video_title'} ] or None on error. """ url = LISTENING_NOW_URL.format(max_tunes) lastfm = util.web.http_get(url=url, json=True) log.debug('lastfm response %s' % lastfm) if lastfm['json'] is not None: if len(lastfm['json']['Users']) is not 0: # make this list unique yt_tracks = [] for user in lastfm['json']['Users']: if 'playlink' in user: if 'data-youtube-id' in user['playlink']: youtube_id = user['playlink']['data-youtube-id'] yt = youtube.video_details(youtube_id) log.debug(yt) if yt is not None: yt_tracks.append(yt) else: if 'Track' in user: search_str = '%s - %s' % (user['Track']['Artist'], user['Track']['Name']) if not by_id: yt = youtube.search(search_str) log.debug( 'search by search string: %s result: %s' % (search_str, yt)) if yt is not None: yt_tracks.append(yt) return yt_tracks return None
data = [item.lower() for item in data] #make all lower case data = [item.strip() for item in data] sample = random.sample(data, 10) DEVELOPER_KEY = 'AIzaSyBYl6LkkHOIfBCSzRpMcptBiEArCDKwq7g' YOUTUBE_API_SERVICE_NAME = 'youtube' YOUTUBE_API_VERSION = 'v3' youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY) out = [] for i in range(len(sample)): search_response = youtube.search().list(q=sample[i], part='id', maxResults=2).execute() search_response search_response["search_key"] = sample[i] out.append(search_response) print out[0].keys() out[0].keys() out[0]['items'][0] out[9]['items'][0]['id']['videoId'] ids = [] keywords = [] for i in range(len(out)): for j in range(len(out[i]['items'])): id = out[i]['items'][j]['id']['videoId'].encode("utf-8")
async def play(self, ctx, *, music): if str(ctx.channel) != 'music': return channel = ctx.message.author.voice.channel voice = get(self.bot.voice_clients, guild=ctx.guild) self.ctx = ctx global video_choice if voice is None: await channel.connect() elif voice and voice.is_connected(): await voice.move_to(channel) voice = get(self.bot.voice_clients, guild=ctx.guild) option = None try: if music[-1].isdigit() and music[-2] == '=' and music[-3] == ' ': option = int(music[-1]) music = music[:-3] except Exception as e: print(e) if music.isdigit(): if int(music) > len(video_choice): await ctx.send("Wrong option") return else: music = video_choice[int(music) - 1] song_play = True song_there = os.path.isfile("song.mp3") try: if song_there: os.remove("song.mp3") await ctx.send("Preparing song") song_play = False except PermissionError: await ctx.send("Song is playing now. Your song will be in queue") try: if int(music_duration(music)) < 800: if song_play: title = music_title(music) song_queue.append([title, music]) await ctx.send("{} was placed in queue".format(title)) else: title = download(music) await ctx.send("{} is playing now".format(title)) voice.play(discord.FFmpegPCMAudio("song.mp3")) else: await ctx.send("Song too long") except Exception as e: print(e) if option is None: video_choice = {} videos = search(music) embed = discord.Embed(title="Select song", color=0x0ff0ff) for i in range(len(videos)): embed.add_field(name="** **", value="**{}**. {} | {}".format( i + 1, videos[i][3], videos[i][5]), inline=False) video_choice[i] = videos[i][2] await ctx.send(embed=embed) else: videos = search(music) for i in range(len(videos)): video_choice[i] = videos[i][2] if option > len(video_choice): await ctx.send("Wrong option") return else: music = video_choice[option - 1] if int(music_duration(music)) < 800: if song_play: title = music_title(music) song_queue.append([title, music]) await ctx.send("{} was placed in queue".format(title)) else: title = download(music) await ctx.send("{} is playing now".format(title)) voice.play(discord.FFmpegPCMAudio("song.mp3")) else: await ctx.send("Song too long") return
def callback(ch, method, props, body): """ DMZ consumer callback. """ try: data = json.loads(body) except Exception as e: return # Malformed JSON # No data? No idea. if not data: return car_md_args = lambda d: ( d.get('make'), d.get('model'), d.get('year'), d.get('mileage') ) action = data.get('action') result = { 'success': True } # Received youtube search request if action == 'youtube_search': try: result['results'] = youtube.search(data.get('query')) raise 'www' except Exception as e: result['success'] = False ez_log('LOG', 'YOUTUBE_SEARCH', str(e)) # Received car maintence request elif action == 'get_maintenance': try: result['results'] = carmd.get_maintenance(*car_md_args(data)) if result['results']['message'].get('code') == 1003: ez_log('LOG', 'CARMD_API_OUT_OF_CREDITS', 'Maintenance') except Exception as e: result['success'] = False ez_log('LOG', 'GET_MAINTENANCE', str(e)) # Received car recalls request elif action == 'get_recalls': try: result['results'] = carmd.get_recalls(*car_md_args(data)) if result['results']['message'].get('code') == 1003: ez_log('LOG', 'CARMD_API_OUT_OF_CREDITS', 'Recalls') except Exception as e: result['success'] = False ez_log('LOG', 'GET_RECALLS', str(e)) # Received oauth link request elif action == 'get_oauth_link': try: result['results'] = google_calendar.get_oauth_link() except Exception as e: result['success'] = False ez_log('LOG', 'GET_OAUTH_LINK', str(e)) # Received oauth link request elif action == 'add_events': oauth_code = data.get('oauth_code') events = data.get('events') try: result['results'] = google_calendar.add_events(oauth_code, events) except Exception as e: result['success'] = False ez_log('LOG', 'ADD_EVENTS', str(e)) # Unknown action else: result['success'] = False return json.dumps(result, default=default)
def youtube_search(): query = request.args.get('q', '') return render_template('youtube_search.html',videos=youtube.search(query),q=query)
#!/usr/bin/env python # -*- coding: utf-8 -*- # file: ytsearch.py # author: Frank Chang <*****@*****.**> import youtube import sys from youtube import YouTube youtube.search(sys.argv[1])
def enqueue(self, track: Track) -> None: url = youtube.search(title=track.title, artists=track.artists) audio = pafy.new(url).getbestaudio() media = self.instance.media_new(audio.url) self.player.set_media(media)
def elaborate(text, auth_state, key, mixer, voice): #Set variables running = True #Every possible command #Stop the program if text in shutdown: #If the user has enough authorization if auth_state >= auth_levels['Admin']: voice.say("Spegnimento in corso") voice.runAndWait() running = False else: #Try to login with higher authorization level voice.say( "Livello di autorizzazione insufficiente. Esegui l'accesso.") voice.runAndWait() auth_state = login(auth_state, key, voice) if auth_state >= auth_levels['Admin']: voice.say("Spegnimento in corso") voice.runAndWait() running = False else: voice.say( "Impossibile spegnere il sistema. Livello di autorizzazione insufficiente." ) voice.runAndWait() #Play a song elif any(word in text for word in play_music): for word in play_music: if word in text: text = text.replace(word, ' ') text.lstrip() link = youtube.search(text) path = youtube.download_mp4(link) path = youtube.convert_mp4_to_mp3(path) mixer = [musicPlayer.play(path), path] #Pause the song elif text in pause_music: musicPlayer.pause(mixer[0]) #Resume the song elif text in resume_music: musicPlayer.resume(mixer[0]) #Stop the song elif text in stop_music: musicPlayer.stop(mixer[0], mixer[1]) #Turn on all lights in a room elif any(word in text for word in turn_on_light_room): for word in turn_on_light_room: if word in text: text = text.replace(word, ' ') try: Lights.turn_on_room(text) except RoomNotFound: voice.say("Impossibile trovare la stanza.") voice.runAndWait() else: voice.say("Fatto") voice.runAndWait() #Turn off all lights in a room elif any(word in text for word in turn_off_light_room): for word in turn_off_light_room: if word in text: text = text.replace(word, ' ') try: Lights.turn_off_room(text) except RoomNotFound: voice.say("Impossibile trovare la stanza.") voice.runAndWait() else: voice.say("Fatto") voice.runAndWait() #Turn on lights in the default room elif text == turn_on: room = setting.get_setting("lights_room") try: Lights.turn_on_room(room) except RoomNotFound: voice.say("Impossibile trovare la stanza.") voice.runAndWait() else: voice.say("Fatto") voice.runAndWait() #Turn off lights in the default room elif text == turn_off: room = setting.get_setting("lights_room") try: Lights.turn_off_room(room) except RoomNotFound: voice.say("Impossibile trovare la stanza.") voice.runAndWait() else: voice.say("Fatto") voice.runAndWait() #Change a setting elif text in set_setting: #Check authorization level if auth_state >= auth_levels['Utente generico']: settings.change_setting(voice) else: # Try to login with higher authorization level voice.say( "Livello di autorizzazione insufficiente. Esegui l'accesso.") voice.runAndWait() auth_state = login(auth_state, key, voice) if auth_state >= auth_levels['Utente generico']: settings.change_setting(voice) else: voice.say( "Impossibile modificare le impostazioni. Livello di autorizzazione insufficiente." ) voice.runAndWait() #Reset settings elif text in reset_settings: # Check authorization level if auth_state >= auth_levels['Admin']: settings.reset_to_default(voice) else: # Try to login with higher authorization level voice.say( "Livello di autorizzazione insufficiente. Esegui l'accesso.") voice.runAndWait() auth_state = login(auth_state, key, voice) if auth_state >= auth_levels['Admin']: settings.reset_to_default(voice) else: voice.say( "Impossibile resettare le impostazioni. Livello di autorizzazione insufficiente." ) voice.runAndWait() #Do nothing elif text in cancel: voice.say("Come non detto") voice.runAndWait() return running, auth_state, mixer