def process_submission(submission): # Ignore non-YouTube submissions (for now) youtube_match_pattern = 'https://www.youtube.com/*' youtu_match_pattern = 'https://youtu.be/*' if (urlmatch(youtube_match_pattern, submission.url) == False and urlmatch(youtu_match_pattern, submission.url) == False): return parser = argparse.ArgumentParser() parser.add_argument('--q', help='Search term', default=re.sub(r'([\[]).*?([\]])', '', submission.title)) parser.add_argument('--max-results', help='Max results', default=5) args = parser.parse_args() if (youtube.youtube_search(args)): url_title = quote_plus(youtube.youtube_search(args)) reply_text = REPLY_TEMPLATE.format(url_title) if (url_title in submission.url): return print('Replying to: {}'.format(submission.permalink)) try: submission.reply(reply_text) except Exception as exc: print(exc)
def main(): args = _args() parse_url = lp3_parser.URL.format(notowanie=args.notowanie, rok=args.rok) yt = youtube.get_youtube(args) f = urllib.request.urlopen(parse_url) parser = lp3_parser.LP3HTMLParser() parser.feed(f.read().decode(f.headers.get_content_charset())) video_ids = [] for chl in parser.chart_list: if not chl: continue video = youtube.youtube_search(yt, q=' '.join(chl).strip().replace( '\n', '')) items = video.get('items', None) if items is not None: print('{}: {}'.format(' '.join(chl).strip().replace('\n', ''), items[0]['snippet']['title'])) videoId = items[0]['id']['videoId'] video_ids.append((videoId, items[0]['snippet']['title'])) print(('Found {} videos'.format(len(video_ids)))) playlist = youtube.create_playlist( yt, 'LP3 - {} ({})'.format(args.notowanie, args.rok), 'Notowanie {notowanie} ({rok}) listy przebojów Trójki {url}'.format( notowanie=args.notowanie, rok=args.rok, url=parse_url)) if playlist: print(('Playlist id: {}'.format(playlist['id']))) for video_id, title in video_ids: print(('Added {} - {}'.format(video_id, title))) youtube.add_video_to_playlist(yt, video_id, playlist['id'])
def handler(): app = ClarifaiApp(api_key=env_vars.clarifai_api_key) model = app.models.get('food-items-v1.0') img = ClImage(file_obj=open('pics/fridge2.jpeg', 'rb')) pred = model.predict([img]) items = "" for con in pred['outputs'][0]['data']['concepts']: items += json.dumps(con['name'])[1:-1] + ", " items = items[:-2] params = {"ingredients": items} response = unirest.get( "https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/findByIngredients", params=params, headers={ "X-Mashape-Key": "IwLJqO6bAtmshh9PXpr3EhpVvpJWp1smLbBjsnwCNvi8KTvV4u", "X-Mashape-Host": "spoonacular-recipe-food-nutrition-v1.p.mashape.com" }) title_video_id = {} for res in response.body: title = json.dumps(res['title'])[1:-1] video_id = youtube.youtube_search(title) if video_id: title_video_id[title] = str(video_id) return title_video_id
def lastfm_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 = 'http://lastfm-ajax-vip1.phx1.cbsig.net/kerve/listeningnow?limit=%s&format=json' % max_tunes lastfm = web_request.get_request(url, json=True) log.debug(lastfm) if lastfm is not None: if len(lastfm['content']['Users']) is not 0: yt_tracks = [] for user in lastfm['content']['Users']: if 'playlink' in user: if 'data-youtube-id' in user['playlink']: youtube_id = user['playlink']['data-youtube-id'] yt = youtube.youtube_time(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.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 lastfm_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 = 'http://lastfm-ajax-vip1.phx1.cbsig.net/kerve/listeningnow?limit=%s&format=json' % max_tunes lastfm = web_request.get_request(url, json=True) log.debug(lastfm) if lastfm is not None: if len(lastfm['content']['Users']) is not 0: yt_tracks = [] for user in lastfm['content']['Users']: if 'playlink' in user: if 'data-youtube-id' in user['playlink']: youtube_id = user['playlink']['data-youtube-id'] yt = youtube.youtube_time(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.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 api_search(): if 'name' in request.args: id = youtube_search(request.args['name']) ydl_opts = {'format': 'best'} with youtube_dl.YoutubeDL(ydl_opts) as ydl: result = ydl.extract_info(id, download=False) return jsonify(url=result['url'], duration=result['duration'])
def get_similar_music(): ip = request.remote_addr artist = request.args.get('artist') if not artist: return jsonify({}) similar_ones = get_similar_artists(quote(artist), ip) if 'error' in similar_ones: return jsonify(similar_ones['error']) # Youtube APi f*****g sucks, let use scrapper instead similar_ones = similar_ones[:20] videos = [] songs_not_found = 0 for song in similar_ones: query = song['artist']['name'] + " - " + song['name'] yt_result = youtube_search(query, ip) if 'error' in yt_result: if yt_result['error'] == 'song not found' and songs_not_found < 5: # some songs cannot be found, just skip this one (max 5 skips) songs_not_found += 1 continue return jsonify(yt_result['error']) # Dont use actual youtube title, is full of noise (e.g "[ Official video ]") yt_result['title'] = song['name'] yt_result['artist'] = song['artist']['name'] videos.append(yt_result) return jsonify(videos)
def lookSong(name): id = youtube_search(name) ydl_opts = {'format': '140'} with youtube_dl.YoutubeDL(ydl_opts) as ydl: result = ydl.extract_info('https://www.youtube.com/watch?v=X2oPI688EQM', download=False) x = result['url'],result['duration'] print x[0], x[1]
def drink_when(name=None): random_candidate = helper.getRandomCandidate() candidate_phrases = helper.getCandidatePhrases(random_candidate) party = helper.getCandidateParty(random_candidate) random_video = youtube.youtube_search(random_candidate, 15) vid_title = random_video[0] vid_id = random_video[1] drunk_phrase = helper.getRandomDrunkPhrase() return render_template('drinkwhen.html', video_title=vid_title, video_id=vid_id, candidate=random_candidate, phrases=candidate_phrases, party=party, drunk_phrase= drunk_phrase)
def search_lastfm_by_tag(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 = 'http://lastfm-ajax-vip1.phx1.cbsig.net/kerve/charts?nr=%s&type=track&f=tag:%s&format=json' % \ (max_tunes, search_str) lastfm = web_request.get_request(url, json=True) log.debug(lastfm) if lastfm is not None: if 'track' in lastfm['content']['results']: if len(lastfm['content']['results']['track']) is not 0: yt_tracks = [] for track in lastfm['content']['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.youtube_time(youtube_id) log.debug(yt) if yt is not None: yt_tracks.append(yt) else: if not by_id: yt = youtube.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.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 get_and_play(mbid, queue): play_barrier = threading.Barrier(2) pause_music = threading.Event() stop_song = threading.Event() album = lastfm.get_album_info(mbid) image = None for i in range(20): image = get_image_from_url(album['image']) if image: break if not image: print('No Image Found') return image.thumbnail((THUMBSIZE, THUMBSIZE), Image.ANTIALIAS) image = convert_image.convert_image(image) data = convert_image.get_escape_codes(image) diff = image_diff(data) for track in album['tracks']: videos = youtube_search(album['title'], album['artist'], track) for video in videos: try: opts = { 'quiet': True, 'no_warnings': True, 'outtmpl': '{}/%(id)s.tmp'.format(BASE), 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'wav' }] } with YoutubeDL(opts) as ydl: ydl.download([video[1]]) except Exception as e: print('Failed', e) continue else: queue.put((album, image, diff, play_barrier, pause_music, stop_song)) play_barrier.wait() play.play_wave('{}/{}.wav'.format(BASE, video[1]), pause_music, stop_song) return finally: try: for f in glob.glob(video[1] + '.{wav,tmp,part}'): os.remove(os.path.join(BASE, f)) except OSError as e: print('Error:', e)
def search_lastfm_by_tag(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 = 'http://lastfm-ajax-vip1.phx1.cbsig.net/kerve/charts?nr=%s&type=track&f=tag:%s&format=json' % \ (max_tunes, search_str) lastfm = web_request.get_request(url, json=True) log.debug(lastfm) if lastfm is not None: if 'track' in lastfm['content']['results']: if len(lastfm['content']['results']['track']) is not 0: yt_tracks = [] for track in lastfm['content']['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.youtube_time(youtube_id) log.debug(yt) if yt is not None: yt_tracks.append(yt) else: if not by_id: yt = youtube.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.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 youtubeSearchResults(getrequest, results=10): if results <= 0: return None options = dict({ "q": getrequest.get("query", None), "maxResults": getrequest.get("maxResults", results), "pageToken": getrequest.get("pageToken", "") }) searchResults = youtube.youtube_search(options) videos = Video.objects.filter( vid__in=searchResults.get("vids", None)).prefetch_related( 'songs__composers', 'groups') results = [searchResults, videos] return results
def youtubeSearchResults(getrequest, results = 10): if results <= 0: return None options = dict({ "q" : getrequest.get("query", None), "maxResults" : getrequest.get("maxResults", results), "pageToken" : getrequest.get("pageToken", "") }) searchResults = youtube.youtube_search(options) videos = Video.objects.filter( vid__in=searchResults.get("vids", None) ).prefetch_related( 'songs__composers', 'groups' ) results = [searchResults, videos] return results
def graph_song_selected(Song): """ Song page with youtube video and graphs """ A = db.session.query(models.graphs).filter(models.graphs.SongID == Song).all() Title = db.session.query(models.songs).filter(models.songs.SongID == Song).first() Artist = Title.Artist Title = Title.Title D = [] for song in A: D.append(tls.get_embed(song.URL)) return render_template( 'song_graph.html', B=D, Title=Title, Artist=Artist, URL=youtube_search(Title + Artist), )
def get_lastfm_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 = 'http://lastfm-ajax-vip1.phx1.cbsig.net/kerve/charts?nr=%s&type=track&format=json' % chart_items lastfm = web_request.get_request(url, json=True) log.debug(lastfm) if lastfm is not None: if 'results' in lastfm['content']: if 'track' in lastfm['content']['results']: if len(lastfm['content']['results']['track']) is not 0: yt_tracks = [] for track in lastfm['content']['results']['track']: search_str = '%s - %s' % (track['artist'], track['name']) yt = youtube.youtube_search(search_str) log.info(yt) if yt is not None: yt_tracks.append(yt) return yt_tracks return None
def main(): #create bot sc = SlackClient(BOT_TOKEN) # Connect to slack using RTM websocket if sc.rtm_connect(): print "Successfully connected" sc.rtm_send_message(CHANNEL_NAME, "Slacktubebot connecting!") while True: for slack_message in sc.rtm_read(): message = slack_message.get("text") user = slack_message.get("user") if not message or not user: continue message_list = message.split() if 'define' in message_list: argument = message_list[1] print argument elif 'video' and 'of' in message_list: argument = message_list[2] video = youtube_search(argument) post_data = requests.post(webhook, json={'text': "https://www.youtube.com/watch?v=%s" % (video)}) print sc.rtm_read() time.sleep(0.5)
if tweet.retweet_count > 0: # if tweet has retweets, ensure that it is appended only once if parsed_tweet not in tweets: tweets.append(parsed_tweet) else: tweets.append(parsed_tweet) # return parsed tweets return tweets except tweepy.TweepError as e: # print error (if any) print("Error : " + str(e)) def youtube() test = youtube_search("Deadpool 2: The Final Trailer") df = pd.DataFrame(data=test) df.head() df1 = df[['title','viewCount','channelTitle','commentCount','likeCount','dislikeCount','tags','favoriteCount','videoId','channelId','categoryId']] df1.columns = ['Title','viewCount','channelTitle','commentCount','likeCount','dislikeCount','tags','favoriteCount','videoId','channelId','categoryId'] #assigning column names df1.head() #import numpy as np numeric_dtype = ['viewCount','likeCount','dislikeCount'] for i in numeric_dtype: df1[i] = df[i].astype(int) movie = df1[df1['Title']=='Deadpool 2: The Final Trailer'] movie.head()
def search(query): logging.info("got search request for %s", query) return json.dumps(youtube.youtube_search(query, 10))
import string playlist_id = sys.argv[1] # move mp3s to music folder def move_mp3_to_music(): Path('music').mkdir(parents=True, exist_ok=True) files = glob.glob('*mp3') for mp3 in files: if not Path('music/' + mp3).is_file(): shutil.move(mp3, 'music') else: new = mp3[:len(mp3)-4] + random_string() + ".mp3" os.rename(mp3, new) shutil.move(new, 'music') def random_string(size=6, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for x in range(size)) tracks = spotify.get_all_tracks_in_playlist(playlist_id) youtube_ids = [] for track in tracks: youtube_ids.append(youtube.youtube_search(track)) youtube.youtube_to_mp3(youtube_ids) move_mp3_to_music() print('Passed:',youtube.passed)
def get_answer(user_input, user_date): ans = "" ##################################################################################################################### ##################################################################################################################### name_of_service = "No" # чтобы определить именно запрос для википедиия я создал эту переменную ##################################################################################################################### ##################################################################################################################### # write predefined set of questions and answers here if user_input == u"Привет": ans = u"Привет. Как я могу помочь?" elif ('привет' in user_input) or ('как дела' in user_input): ans = "Привет! Как ваши дела?" elif ('хорошо' in user_input) or ('сама' in user_input): ans = "Рада это слышать. У меня тоже все хорошо" elif user_input == "/text": ans = "Задайте мне любую из команд в моем списке. Я постараюсь выполнить или можем просто поговорить.\n- Какая сегодня погода в Алмате?\n- Расскажи о Казахстане\n- Переведи слово кофе на английский\n- 2 доллара в тенге\n- Давай поболтаем, AIbota\n* Чтобы воспользоваться голосовым помощником, отправьте аудиозапрос.\n" elif ('умеешь' in user_input) or ('умеешь делать' in user_input): ans = 'Вот что я умею:\n- Показать прогноз погоды\n("Какая сегодня погода в Алмате?") ' + u'⛅' + '\n- Рассказать интересные факты\n("Расскажи о Казахстане") ' + u'🔍' + '\n- Переводить слова\n("кофе на английском") ' + u'🔄' + '\n- Узнавать курсы валют\n("доллары в тенге") ' + u'💲' + '\n- Составить компанию\n("Давай поболтаем, AIbota") ' + u'💬' + "\n* Чтобы воспользоваться голосовым помощником, отправьте аудиозапрос " + u'📣' + ".\n" elif (user_input == '/info') or ('подробнее о функциях' in user_input or 'о своих функциях' in user_input or 'о своих функциях' in user_input): ans = "С помощью этого бота вы можете\n [ " + u'📣' + " ] - Воспользоваться персональной голосовой помощницей, отправляя аудио запросы\n [ " + u'⛅' + " Прогноз погоды] - Узнавать погоду на сегодня(ближайщий час), завтра, послезавтра в любом городе\n [ " + u'🔍' + " Энциклопедия] - Получать информацию из энциклопедии\n [ " + u'🔄' + " Переводчик] - Переводить слова\n [ " + u'💲' + " Конвертер валют] - Узнавать курсы валют\n [ " + u'💬' + " Болталка] - Или просто поболтать\n" else: serv = ner(user_input) print(serv[0]) if serv[0] == "weather": settings.context["service"] = "weather" [service, city, date] = ner(user_input) # [service, city, date] = ner(user_input) #ans="connct to the api: " + service + " " + " " + city + " " + date ans = weatherapp(city, date, user_date)[1] print(city) if ans == "error": ans = "К сожалению места с таким именем не найдено, проверьте имя места и попробуйте снова" name_of_service = "weather" # если это погода возвращаю имя сервиса return ans, name_of_service if (settings.context["service"] == "weather" and ("завтра" in user_input)): settings.context["service"] = "weather" [service, city, date] = [ settings.context["service"], settings.context["city"], "завтра" ] # [service, city, date] = ner(user_input) ans = "connct to the api: " + service + " " + " " + city + " " + date ans = weatherapp(city, date, user_date)[1] print(city) if ans == "error": ans = "К сожалению места с таким именем не найдено, проверьте имя места и попробуйте снова" name_of_service = "weather" # если это погода возвращаю имя сервиса return ans, name_of_service if serv[0] == "translate": settings.context["service"] = "translate" [service, textToTranslate, finalLangToTranslate] = ner(user_input) ans = translate("", finalLangToTranslate, textToTranslate) name_of_service = "translate" # если это переводчик возвращаю имя сервиса return ans, name_of_service if serv[0] == "currency": settings.context["service"] = "currency" [service, finalFirstCurr, finalSecondCurr, curr] = ner(user_input) ans = currencyapp(finalFirstCurr, finalSecondCurr, curr) name_of_service = "currency" # если это конвертор валют возвращаю имя сервиса return ans, name_of_service if serv[0] == "wiki": settings.context["service"] = "wiki" [service, query] = ner(user_input) print(query) ans = wikiapp(query) name_of_service = query + "serviceapiwikipedia" # если это википедия возвращаю имя сервиса return ans, name_of_service if serv[0] == "youtube": settings.context["service"] = "youtube" [service, result] = ner(user_input) print(result) ans = youtube_search(result) name_of_service = "youtube" # если это википедия возвращаю имя сервиса return ans, name_of_service if serv == "chitchat" and ans == "": settings.context["service"] = "chitchat" ans = chat(user_input) name_of_service = "chitchat" # если это болталка возвращаю имя сервиса return ans, name_of_service return ans, name_of_service
def test(): data = youtube_search() return render_template("testing.html", data=data)
def get_answer_for_voice(user_input, user_date): ans = [] name_of_service = "No" user_input = user_input.lower() if ('$' in user_input): user_input = user_input.replace("$", " доллар ") if (' р ' in user_input): user_input = user_input.replace(" р ", " рубль ") # print("changed" + user_input) # write predefined set of questions and answers here if user_input == u"привет": ans = [u"Привет. Как я могу помочь?", u"Привет. Как я могу помочь?"] elif user_input == "/start": ans = [ "Задайте мне любую из команд в моем списке. Я постараюсь выполнить или можем просто поговорить.\n- Какая сегодня погода в Алмате?\n- Расскажи о Казахстане\n- Переведи слово кофе на английский\n- 2 доллара в тенге\n- Давай поболтаем, AIbota\n* Чтобы воспользоваться голосовым помощником, отправьте аудиозапрос.\n", "Задайте мне любую из команд в моем списке. Я постараюсь выполнить или можем просто поговорить.\n- Какая сегодня погода в Алмате?\n- Расскажи о Казахстане\n- Переведи слово кофе на английский\n- 2 доллара в тенге\n- Давай поболтаем, AIbota\n* Чтобы воспользоваться голосовым помощником, отправьте аудиозапрос.\n"] elif ('умеешь' in user_input) or ('умеешь делать' in user_input): ans = [ 'Вот что я умею:\n- Показать прогноз погоды\n("Какая сегодня погода в Алмате?") ' + u'⛅' + '\n- Рассказать интересные факты\n("Расскажи о Казахстане") ' + u'🔍' + '\n- Переводить слова\n("кофе на английском") ' + u'🔄' + '\n- Узнавать курсы валют\n("доллары в тенге") ' + u'💲' + '\n- Показывать муз. клипы\n("поставь клип despacito") ' + u'🎬' + '\n- Составить компанию\n("Давай поболтаем, AIbota") ' + u'💬' + "\n* Чтобы воспользоваться голосовым помощником, отправьте аудиозапрос " + u'📣' + ".\n", 'Вот что я умею:\n- Показать прогноз погоды\n("Какая сегодня погода в Алмате?") ' + u'⛅' + '\n- Рассказать интересные факты\n("Расскажи о Казахстане") ' + u'🔍' + '\n- Переводить слова\n("кофе на английском") ' + u'🔄' + '\n- Узнавать курсы валют\n("доллары в тенге") ' + u'💲' + '\n- Показывать муз. клипы\n("поставь клип despacito") ' + u'🎬' + '\n- Составить компанию\n("Давай поболтаем, AIbota") ' + u'💬' + "\n* Чтобы воспользоваться голосовым помощником, отправьте аудиозапрос " + u'📣' + ".\n"] elif (user_input == '/info') or ('подробнее о функциях' in user_input or 'подробней о функциях' in user_input or 'функциях' in user_input or 'о своих функциях' in user_input or 'о своих функциях' in user_input): ans = ["С помощью этого бота вы можете\n [ " + u'📣' + " ] - Воспользоваться персональной голосовой помощницей, отправляя аудио запросы\n [ " + u'⛅' + " Прогноз погоды] - Узнавать погоду на сегодня(ближайщий час), завтра, послезавтра в любом городе\n [ " + u'🔍' + " Энциклопедия] - Получать информацию из энциклопедии\n [ " + u'🔄' + " Переводчик] - Переводить слова\n [ " + u'💲' + " Конвертер валют] - Узнавать курсы валют\n [ "+ u'🎬' + " Клипы] - Посмотреть клипы\n [ " + u'💬' + " Болталка] - Или просто поболтать\n", "С помощью этого бота вы можете\n [ " + u'📣' + " ] - Воспользоваться персональной голосовой помощницей, отправляя аудио запросы\n [ " + u'⛅' + " Прогноз погоды] - Узнавать погоду на сегодня(ближайщий час), завтра, послезавтра в любом городе\n [ " + u'🔍' + " Энциклопедия] - Получать информацию из энциклопедии\n [ " + u'🔄' + " Переводчик] - Переводить слова\n [ " + u'💲' + " Конвертер валют] - Узнавать курсы валют\n [ " + u'🎬' + " Клипы] - Посмотреть клипы\n [ " + u'💬' + " Болталка] - Или просто поболтать\n"] else: serv = ner(user_input) print(serv[0]) if serv[0] == "weather": settings.context["service"] = "weather" [service, city, date] = ner(user_input) # [service, city, date] = ner(user_input) # ans="connct to the api: " + service + " " + " " + city + " " + date ans = weatherapp(city, date, user_date) print(city) if ans[0] == "error": ans = ["К сожалению места с таким именем не найдено, проверьте имя места и попробуйте снова", "К сожалению места с таким именем не найдено, проверьте имя места и попробуйте снова"] name_of_service = "weather" return ans, name_of_service if (settings.context["service"] == "weather" and (" завтра" in user_input)): settings.context["service"] = "weather" [service, city, date] = [settings.context["service"], settings.context["city"], "завтра"] # [service, city, date] = ner(user_input) # ans="connct to the api: " + service + " " + " " + city + " " + date ans = weatherapp(city, date, user_date) print(city) if ans[0] == "error": ans = ["К сожалению места с таким именем не найдено, проверьте имя места и попробуйте снова", "К сожалению места с таким именем не найдено, проверьте имя места и попробуйте снова"] name_of_service = "weather" return ans, name_of_service if (settings.context["service"] == "weather" and ("послезавтра" in user_input)): settings.context["service"] = "weather" [service, city, date] = [settings.context["service"], settings.context["city"], "послезавтра"] # [service, city, date] = ner(user_input) ans = "connct to the api: " + service + " " + " " + city + " " + date ans = weatherapp(city, date, user_date) print(city) if ans[0] == "error": ans = "К сожалению места с таким именем не найдено, проверьте имя места и попробуйте снова" name_of_service = "weather" # если это погода возвращаю имя сервиса return ans, name_of_service if serv[0] == "translate": [service, textToTranslate, finalLangToTranslate] = ner(user_input) ans = translate("", finalLangToTranslate, textToTranslate) name_of_service = "translate" return [ans, ans], name_of_service if serv[0] == "currency": settings.context["service"] = "currency" [service, finalFirstCurr, finalSecondCurr, curr] = ner(user_input) ans = currencyapp(finalFirstCurr, finalSecondCurr, curr) name_of_service = "currency" return [ans, ans], name_of_service if serv[0] == "wiki": settings.context["service"] = "wiki" [service, query] = ner(user_input) print(query) ans = wikiapp(query) name_of_service = query + " sw94" return [ans, ans], name_of_service if serv[0] == "youtube": settings.context["service"] = "youtube" [service, result] = ner(user_input) print(result) ans = youtube_search(result) name_of_service = "youtube" # если это википедия возвращаю имя сервиса return [ans, ans], name_of_service if serv[0] == "time": settings.context["service"] = "time" [service, city] = ner(user_input) ans = find_time(city) name_of_service = "time" # если это переводчик возвращаю имя сервиса return ans, name_of_service if serv == "chitchat" or ans == "": settings.context["service"] = "chitchat" ans = chat(user_input) name_of_service = "chitchat" return [ans, ans], name_of_service return ans, name_of_service
def youtube_search(artist, track): r = youtube.youtube_search(artist, track)
def handle_command(command, details, channel, respond = True): """ Receives commands directed at the bot and determines if they are valid commands. If so, then acts on the commands. If not, returns back what it needs for clarification. """ response = False if command == "learn": learner = Learner() response = learner.learn(details[0], " ".join(details[1:])) elif command == "unlearn": learner = Learner() content = None if len(details) > 1: content = " ".join(details[1:]) response = learner.unlearn(details[0], content) elif command == "commands": learner = Learner() response = learner.list_commands() elif command == "list": learner = Learner() response = learner.list(details[0]) elif command == "cowsay": out = subprocess.check_output(['cowsay', " ".join(details)]) response = "```" + out + "```" elif command == "meme": memer = Memer() if not details or len(details) == 0: response = memer.list_templates() else: template = details.pop(0).strip() parts = [x.strip() for x in " ".join(details).split(",")] top = parts[0] if len(parts) > 0 else None bottom = parts[1] if len(parts) > 1 else None response = memer.get_meme(template, top, bottom) elif command == "hostname": response = "slurms coming to you live from: `%s (%s)`" % (subprocess.check_output("hostname -A", shell=True).strip(), subprocess.check_output("hostname -i", shell=True).strip()) elif command == "write": writer = Writer() response = writer.get_writing(" ".join(details)) elif command == "imglearn": learner = Learner() imgur = Imgur() image_url = imgur.save_from_url(" ".join(details[1:])) response = learner.learn(details[0], image_url) elif command == "++" or command == "endorse": plusser = Plusser() reason = "" if len(details) > 1: reason = " ".join(details[1:]) response = plusser.plus(details[0], reason) elif command == "plusses": plusser = Plusser() response = plusser.get(details[0]) elif command == "leaders" or command == "leader_board": plusser = Plusser() response = plusser.leader_board() elif command == "monthly_leaders" or command == "monthly_leader_board": plusser = Plusser() months_ago = 0 if details and len(details) > 0: months_ago = details[0] response = plusser.monthly_leader_board(months_ago) elif command == "youtube": query = " ".join(details) videos = youtube.youtube_search(query) if len(videos) > 0: response = videos[-1] else: response = "sorry, couldnt find any videos for %s" % query elif command == "echo": response = " ".join(details) elif command == "pipe": pipe(command, details, channel) elif command == "doom": doom = Doom() response = doom.doom(details) else: """ see if a randomly entered command is something that was previously learned """ learner = Learner() response = learner.get(command) if response and respond: slack_client.api_call("chat.postMessage", channel=channel, text=response, as_user=True) elif not respond: return response
def main(russian_question): for item in translate(russian_question): yield from youtube_search(search_query=item)