class YoutubeAPI(AliceSkill): """ Author: Psychokiller1888 Description: Access and manage your youtube account """ def __init__(self): super().__init__() try: self._youtube: Optional[YouTubeDataAPI] = None except ValueError: raise SkillStartingFailed('Youtube api key not valid') def onStart(self): super().onStart() self._youtube = YouTubeDataAPI(self.getConfig('youtubeApiKey')) if not self._youtube.verify_key(): raise SkillStartingFailed('Youtube api key not valid') @IntentHandler('GetYoutubeChannelStats') def getChannelStats(self, session: DialogSession, **_kwargs): metadata = self._youtube.get_channel_metadata('') if not metadata: self.endDialog(sessionId=session.sessionId, text=self.randomTalk(text='error')) return print(metadata) self.endDialog(sessionId=session.sessionId, text=self.randomTalk(text='myText', replace=[sub]))
def search(self, query): yt = YouTubeDataAPI(self.API_KEY) results = yt.search(q=query, max_results=10) if results: return [self._transform_video(v) for v in results] else: return None
def get_channels_videos(channel_id, max_results, order_by, api_key): yt = YouTubeDataAPI(api_key) videos = yt.search(channel_id=channel_id, max_results=max_results, order_by=order_by, api_key=api_key) return [video["video_id"] for video in videos]
async def ffindyoutube(string): yt = YouTubeDataAPI(next(MusicBot.YOUTUBE_API)) searches = yt.search(q=string, max_results=1) video_id = [] for id_ in searches: video_id.append(id_["video_id"]) return video_id
def look_new_video(): driver = webdriver.Firefox(executable_path='Webdriver location') api_key = 'Get your API key from google' channel_id = 'Youtuber channel id' base_video_url = 'https://www.youtube.com/watch?v=' yt = YouTubeDataAPI(api_key) youtuber = yt.search(channel_id=channel_id, max_results=30, order_by=('date')) videos_title, videos_id = [], [] for i in youtuber: videos_title.append(i['video_title']) videos_id.append(i['video_id']) videos_id_check = videos_id[0] video_details = pd.DataFrame({ 'video_title': videos_title, 'video_id': videos_id }) video_details.to_csv('video.csv') with open('video.csv', 'r') as r_file: data = csv.reader(r_file) for i in data: if i[-1] == videos_id_check: driver.get(base_video_url + videos_id_check)
def fetch(self, keywords, published_after=None, published_before=None, max_results=5, order_by='date'): yt = YouTubeDataAPI(self.credentials.api_key) if published_after: _published_after = published_after.date() else: _published_after = datetime.datetime.timestamp( datetime.datetime(2000, 1, 1)) if published_before: _published_before = published_before.date() else: _published_before = datetime.datetime.timestamp( datetime.datetime(3000, 1, 1)) response = yt.search( keywords, max_results=max_results, order_by=order_by, published_after=_published_after, published_before=_published_before, ) print(response) return response
def get_data(): api_key = 'XXXXXXX' yt = YouTubeDataAPI(api_key) data_json = yt.search('django') for every_val in data_json: if YoutubeVideo.objects.filter( video_id=every_val['video_id']).exists(): print("Video Already exists in db") continue else: datetime_time = datetime.datetime.fromtimestamp( every_val['video_publish_date']) video_entry = YoutubeVideo( video_id=every_val['video_id'], video_title=every_val['video_title'], video_description=every_val['video_description'], channel_title=every_val['channel_title'], video_thumbnail=every_val['video_thumbnail'], video_publish_date=datetime_time) video_entry.save() print("Video Added to db") return data_json
def callback(ch, method, properties, body): api_key = 'AKAIXXXXXXXX' yt = YouTubeDataAPI(api_key) search = yt.search(body) print("[X] Received") print("Los resultados de busqueda para " + str(body) + " en Youtube son:") print(search)
def test_init(self): '''#Verified by Megan Brown on 11/30/2018''' with self.assertRaisesRegex(ValueError, 'No API key used to initate the class.'): yt = YouTubeDataAPI('') with self.assertRaisesRegex(ValueError, 'The API Key is invalid'): yt = YouTubeDataAPI(self.wrong_key)
def get_recent_song_ids(INT_TIME_ARRAY): yt = YouTubeDataAPI(API_KEY) all_song_info = yt.get_videos_from_playlist_id( 'PL63ZO-jXFTasqvj7WdEFQ6QtG6UBrl9CR', published_after=datetime(INT_TIME_ARRAY[0], INT_TIME_ARRAY[1], INT_TIME_ARRAY[2])) return select_ids(all_song_info)
def get_video(self, video_id): #conn = sqlite3.connect("{}/youtube.db".format(self.path)) yt = YouTubeDataAPI(self.API_KEY) results = yt.search(q=video_id, max_results=1) if results: return self._transform_video(results[0]) else: return None
async def ffindyoutube(title): id_ = [] yt = YouTubeDataAPI(next(MusicBot.YOUTUBE_API)) video_id = yt.search(q=title, max_results=1, parser=None) for i in video_id: id_.append(i["id"]["videoId"]) return id_
def getURL(searchQuery: str, searchResults: int = 1) -> str: api_key = json.load(open("../data/api.json"))["apiKey"] yt = YouTubeDataAPI(api_key) searches = yt.search(q=searchQuery, max_results=searchResults, video_duration="short") rNum = random.randint(0, searchResults - 1) # returns [url to video, video title, url to thumbnail] return [ "https://www.youtube.com/watch?v=" + searches[rNum]["video_id"], searches[rNum]["video_title"], searches[rNum]["video_thumbnail"] ]
async def findyoutube(title): id_ = [] titel_ = [] yt = YouTubeDataAPI(next(MusicBot.YOUTUBE_API)) video_id = yt.search(q=title, max_results=10, parser=None) for i in video_id: id_.append(await _id(i)) for i in video_id: titel_.append(await titel_func(i)) return titel_, id_
async def youtube(self, ctx, *, arg): """ Searches Youtube for the given search, and returns the first video given. """ await jsondb.load_servers(self) if jsondb.permission(self, ctx) is False: return await ctx.send(jsondb.NOPERMISSION, delete_after=10) yt = YouTubeDataAPI(google_key) lmao = yt.search(arg) print(lmao[0]) pog = lmao[0] link = 'https://www.youtube.com/watch?v=' + pog['video_id'] await ctx.send(link)
def setUpClass(cls): cls.key = config.key cls.yt = YouTubeDataAPI(config.key) cls.defunct_playlist_id = 'UUvsye7V9psc-APX6wV1twLg' #alex jones cls.playlist_id = 'UU3XTzVzaHQEd30rQbuvCtTQ' #lastweektonight cls.future_date = datetime.datetime(2200, 1, 1) cls.cutoff_date = datetime.datetime(2018, 1, 1) cls.default_parser_output_keys = [ 'channel_id', 'collection_date', 'publish_date', 'video_id' ] cls.raw_json_output_keys = [ 'snippet.thumbnails.medium.width', 'snippet.thumbnails.maxres.height', 'snippet.channelId', 'snippet.thumbnails.standard.height', 'snippet.thumbnails.high.url', 'collection_date', 'snippet.playlistId', 'snippet.publishedAt', 'snippet.thumbnails.default.height', 'kind', 'channel_id', 'snippet.thumbnails.maxres.url', 'etag', 'snippet.description', 'snippet.resourceId.kind', 'snippet.thumbnails.high.width', 'snippet.title', 'snippet.thumbnails.medium.height', 'publish_date', 'snippet.thumbnails.standard.width', 'snippet.channelTitle', 'snippet.position', 'video_id', 'snippet.thumbnails.default.width', 'snippet.thumbnails.medium.url', 'snippet.thumbnails.standard.url', 'id', 'snippet.thumbnails.high.height', 'snippet.thumbnails.default.url', 'snippet.thumbnails.maxres.width', 'snippet.resourceId.videoId' ]
def add_urls_fom_recommended_videos(url, max_results=10, return_df=False, source='reco', destination_func=add_urls_list): yt = YouTubeDataAPI(os.environ.get('YOUTUBE_API_KEY')) res = yt.get_recommended_videos(url, max_results=max_results) df = pd.DataFrame(res) urls_to_add = list(df.video_id) added = destination_func(urls_to_add, verbose=True, source=source, max_comments=200) if return_df: return df, added, urls_to_add return added, urls_to_add
class youtube: def __init__(self): self.yt_key = botCommon.yt_api_key self.yt = YouTubeDataAPI(self.yt_key) async def search_yt(self, search_term): return self.yt.search(q=search_term, max_results=1)
class Starter: """ Used to return a list of videos based on search query and video category """ api_key = config.api_key yt = YouTubeDataAPI(api_key) def __init__(self, query, category, max_results=5): self.query = query self.category = category self.max_results = max_results def find_video(self): """ Takes in query and returns a dictionary of result(s) """ response = self.yt.search(q=self.query, max_results=self.max_results, topic_id=self.category) return response def get_arb(self): """ Returns arbitrary video id Used for debugging @return: a video id from start """ return self.start[0]
def setUpClass(cls): cls.key = os.environ.get('YT_KEY') cls.yt = YouTubeDataAPI(cls.key) cls.video_id = 'QE5KOfjKLy0' cls.channel_id = 'UC_x5XG1OV2P6uZZ5FSM9Ttw' #cls.vid_publish = datetime.datetime(2018, 11, 28, 10, 0, 3) cls.search_term = 'John Oliver' cls.list_of_videos = ['ximgPmJ9A5s', 'gl1aHhXnN1k']
def youtube_data_collector(url): api_key = ' ' yt = YouTubeDataAPI(api_key) searches = yt.search(q=url, max_results=2) data = searches[0] print("video_id: ", data['video_id']) video_id = data['video_id'] print("channel title: ", data['channel_title']) channel_title = data['channel_title'] print("channel id : ", data['channel_id']) channel_id = data['channel_id'] print("Publish Date : ", data['video_publish_date']) publish_date = data['video_publish_date'] print("Video Title : ", data['video_title']) video_title = data['video_title'] print("Video Description : ", data['video_description']) video_description = data['video_description'] print("Video Category : ", data['video_category']) video_category = data['video_category'] print("Video Thumbnail : ", data['video_thumbnail']) print("Date Collected : ", data['collection_date']) collection_date = data['collection_date'] video = pafy.new('https://www.youtube.com/watch?v={}'.format(video_id)) print('video url : https://www.youtube.com/watch?v={}'.format(video_id)) video_url = 'video url : https://www.youtube.com/watch?v={}'.format(video_id) print("video rating : ", video.rating) video_rating = video.rating print("video length : ", video.length) video_length = video.length print("video likes : ", video.likes) video_likes = video.likes print("video dislikes : ", video.dislikes) video_dislikes = video.dislikes print("video views : ", video.viewcount) view_count = video.viewcount database(channel_title, channel_id, publish_date, video_title, video_description, collection_date, video_url, video_rating, video_length, video_likes, video_dislikes)
def __init__(self, admin_user, telegram_token, handlers): self.admin_user = admin_user self.telegram_token = telegram_token self.admin_filter = Filters.chat(username=self.admin_user) self.updater = Updater(token=telegram_token, use_context=True) self.dispatcher = self.updater.dispatcher self.messages_sent = 0 self.handlers = handlers self.nyofla_channel = os.getenv('NYOFLA_YT_CHANNEL') self.channel_rostollador_i_jo = os.getenv('ROSTOLLADOR_I_JO_CHANNEL') self.channel_rostolladors_hab = os.getenv('ROSTOLLADORS_CHANNEL') self.youtube_api_key = os.getenv('YOUTUBE_API_KEY') self.yt = YouTubeDataAPI(self.youtube_api_key) self.last_checked = datetime.fromtimestamp(0)
def setUpClass(cls): cls.key = os.environ.get('YT_KEY') cls.yt = YouTubeDataAPI(cls.key) cls.search_term = 'John Oliver' cls.channel_id = 'UC3XTzVzaHQEd30rQbuvCtTQ' cls.max_results = 10 cls.published_after = datetime.datetime.timestamp(datetime.datetime(2018,11,30)) cls.published_before = datetime.datetime.timestamp(datetime.datetime(2018,12,1)) cls.topic_search = 'ted talks' cls.topic_id = 22
class Rostollador: def __init__(self, admin_user, telegram_token, handlers): self.admin_user = admin_user self.telegram_token = telegram_token self.admin_filter = Filters.chat(username=self.admin_user) self.updater = Updater(token=telegram_token, use_context=True) self.dispatcher = self.updater.dispatcher self.messages_sent = 0 self.handlers = handlers self.nyofla_channel = os.getenv('NYOFLA_YT_CHANNEL') self.channel_rostollador_i_jo = os.getenv('ROSTOLLADOR_I_JO_CHANNEL') self.channel_rostolladors_hab = os.getenv('ROSTOLLADORS_CHANNEL') self.youtube_api_key = os.getenv('YOUTUBE_API_KEY') self.yt = YouTubeDataAPI(self.youtube_api_key) self.last_checked = datetime.fromtimestamp(0) def latest_nyofla_youtube(self, unused): global messages_sent # global last_checked kvaas_client = Kvaas() last_checked = datetime(1970, 1, 1, 0, 0, 0) # init in the past fmt = '%c' try: stored_date = kvaas_client.getValue('lc') except: stored_date = last_checked logging.warning("Couldn''t retrieve stored date") try: last_checked = last_checked.strptime(stored_date, fmt) except Exception: logging.warning(Exception) ylist = self.yt.search(channel_id=self.nyofla_channel, search_type="video", max_results=1, order_by="date") if len(ylist) > 0: ylatest = ylist[0] if ylatest['video_publish_date'] > last_checked: kvaas_client.setValue('lc', ylatest['video_publish_date'].strftime(fmt)) self.updater.bot.send_message(chat_id=self.channel_rostolladors_hab, text='Nou video de {}\n https://www.youtube.com/watch?v={}'.format( ylatest['channel_title'], ylatest['video_id']), parse_mode=ParseMode.HTML) def start(self): for handler in self.handlers: self.dispatcher.add_handler(handler.get_handler()) self.dispatcher.job_queue.run_repeating(self.latest_nyofla_youtube, 2700, 0, 'NyoflaYT') self.updater.start_polling()
class YTSearch: def __init__(self): self.api_key = 'api_key' self.yt = YouTubeDataAPI(self.api_key) def get_videos( self, key_words ): # key_word = co wyszukiwac czy spokojne czy jakies do rozruszenia videos_ids = [] for k in key_words: if self.yt.verify_key(): results = self.yt.search(parser=None, q=k, max_results=round(200 / len(key_words)), type="videos", videoEmbeddable="true") for result in results: videos_ids.append(result['id']['videoId']) np.unique(videos_ids) random.shuffle(videos_ids) #print("Zaleziono: "+str(len(videos_ids))) # print("Id") # print(videos_ids) return videos_ids def update(self, key_word): result = [] low = ["calm music", "sad music"] high = ["hard rock music", 'dance music 90s'] #print("Searching for: "+key_word) if key_word == "high": # puls za wysoki, dla uspokojenia videos_ids = self.get_videos( low) # wypluwa id playlist i linki do nich result = videos_ids elif key_word == "low": # puls za niski, dla rozruszania videos_ids = self.get_videos( high) # wypluwa id playlist i linki do nich result = videos_ids return result
def run(self): # Please input your youtube-data-v3 api key! api_key = '' yt = YouTubeDataAPI(api_key) dir = yt.get_channel_metadata(self.user) # Channel name, subscribers, views, description channel = [dir['title'], dir['subscription_count'], dir['view_count'], re.sub('\n', ' ', dir['description'])] for col in range(2, 6): # Thousands seperator if channel[col-2].isdigit(): channel[col-2] = format(int(channel[col-2]), ',') self.sheet.cell(row=self.index+2, column=col).value = channel[col-2] if col == 3: self.sheet.cell(row=self.index+2, column=col).font = Font(color='FF0000') # Hidden value for x in range(len(channel)): if channel[x] == '0': self.sheet.cell(row=self.index+2, column=x+2).value = 'HIDDEN' self.sheet.cell(row=self.index+2, column=x+2).font = Font(color='808080')
def setUpClass(cls): cls.key = os.environ.get('YT_KEY') cls.yt = YouTubeDataAPI(cls.key) cls.channel_id = 'UC3XTzVzaHQEd30rQbuvCtTQ' cls.upload_id = 'UU3XTzVzaHQEd30rQbuvCtTQ' cls.liked_id = 'LL3XTzVzaHQEd30rQbuvCtTQ' cls.date = '2018-03-14T20:53:14.000Z' cls.datetime_date = datetime.datetime.timestamp(datetime.datetime(2018, 3, 14, 20, 53, 14)) cls.user_url = 'https://www.youtube.com/user/LastWeekTonight' cls.channel_url = 'https://www.youtube.com/channel/UC3XTzVzaHQEd30rQbuvCtTQ' cls.video_id = '481YX6T9Xzs' cls.video_url = 'https://youtube.com/watch?v=481YX6T9Xzs'
def add_urls_from_yt_search( query_string, # q (list or str) – regex pattern to search using | for or, && for and, and - for not. IE boat|fishing is boat or fishing max_results=100, destination_func=add_urls_list, return_df=False, **kwargs): yt = YouTubeDataAPI(os.environ.get('YOUTUBE_API_KEY')) res = yt.search(query_string, max_results=max_results, **kwargs) df = pd.DataFrame(res) search_results = list(df.video_id) if not kwargs or isinstance(kwargs['source_string'], type(None)): source_string = 'yt_search:' + query_string + '_' + name_from_config( kwargs) else: source_string = kwargs['source_string'] added = destination_func(search_results, verbose=True, source=source_string) if return_df: return df, added, search_results return added, search_results
def main(): from youtube_api import YouTubeDataAPI api_key = "AIzaSyAB5Dg1HeqzlV6y2d37-tektKrts2bNOSc" yt = YouTubeDataAPI(api_key) zout = yt.get_video_metadata(video_id='k7DGeWlKu0Q') Num_likes = zout['video_like_count'] Num_dislikes = zout['video_dislike_count'] Num_comments = zout['video_comment_count'] zcomment = yt.get_video_comments(video_id='k7DGeWlKu0Q') Commentlist = [] for item in zcomment: Commentlist.append(item['text']) zcaption = yt.get_captions(video_id='k7DGeWlKu0Q') Transcript = zcaption['caption'] Result1 = { 'Num_likes': Num_likes, 'Num_dislikes': Num_dislikes, 'Num_comments': Num_comments, 'Transcript': Transcript, 'Commentlist': Commentlist } Result2 = yt.search(q='vaccine', published_after=datetime.datetime(2018, 1, 1), published_before=datetime.datetime(2019, 1, 1)) return Result1, Result2
def __init__(self,vid_id, api_key, gen_WC = False, loop = None): self.cancelled = False self.loop = loop self.t_pool = concurrent.futures.ThreadPoolExecutor(max_workers=5) self.api_points_used = 1.0 self.api = YouTubeDataAPI(api_key) #uses 1p to check key self.videoid = vid_id self.channel_id = "" self.metadata = {} self.videoinfo = {} self.stats = [] self.dict_list = [] self.gen_wc = gen_WC self.clean_currency = {"¥": "JPY", "NT$": "TWD", "$": "USD", "CA$": "CAD", "MX$": "MXN", "HK$": "HKD", "A$": "AUD", "£": "GBP", "€": "EUR", "R$": "BRL", "₹": "INR", "\u20b1": "PHP"} self.metadata = self.get_video_info(self.videoid) self.api_points_used += 1.0 self.channel_id = self.metadata["channelId"] self.running = True if self.metadata is not None: self.videoinfo = self.metadata self.channel_id = self.metadata["channelId"] else: exit(-1) pathlib.Path('./' + self.channel_id + '/sc_logs').mkdir(parents=True, exist_ok=True) pathlib.Path('./' + self.channel_id + '/vid_stats').mkdir(parents=True, exist_ok=True)