def get_pafy(item, force=False, callback=None): """ Get pafy object for an item. """ callback_fn = callback or (lambda x: None) cached = g.pafs.get(item.ytid) if not force and cached and cached.expiry > time.time(): dbg("get pafy cache hit for %s", cached.title) cached.fresh = False return cached else: try: p = pafy.new(item.ytid, callback=callback_fn) except IOError as e: if "pafy" in str(e): dbg(c.p + "retrying failed pafy get: " + item.ytid + c.w) p = pafy.new(item.ytid, callback=callback) else: raise g.pafs[item.ytid] = p p.fresh = True thread = "preload: " if not callback else "" dbg("%s%sgot new pafy object: %s%s" % (c.y, thread, p.title[:26], c.w)) dbg("%s%sgot new pafy object: %s%s" % (c.y, thread, p.videoid, c.w)) return p
def update_values(self): try: video = pafy.new( self.URL ) ipc.set_read(0, video.viewcount) ipc.set_read(1, video.likes) ipc.set_read(2, video.dislikes) ipc.set_read(3, int(10 * video.rating) ) video2 = pafy.new( self.URL2 ) ipc.set_read(4, video2.viewcount) ipc.set_read(5, video2.likes) ipc.set_read(6, video2.dislikes) ipc.set_read(7, int(10 * video2.rating) ) except Exception as err: logger.error("failed to fetch data, %s", str(err).splitlines()[0]) ipc.set_no_data(0) ipc.set_no_data(1) ipc.set_no_data(2) ipc.set_no_data(3) ipc.set_no_data(4) ipc.set_no_data(5) ipc.set_no_data(6) ipc.set_no_data(7) ipc.go_parcook()
def download_playlist(tag, video_id, max_downloads=None, audio_dir=AUDIO_DIR): """ Download's the audio of a YT mix playlist based on a seed video id Optional parameter to select max download number. Returns the list of converted audio files that were downloaded. """ print "Downloading playlist for \ [Tag:'{0}', Seed:'{1}]'...\n".format(tag.upper(),video_id) #use seed_video to generate mix playlist id seed_video = pafy.new(video_id) playlist_id = seed_video.mix.plid playlist = pafy.get_playlist(playlist_id)['items'] #decide number of files to download if not max_downloads: max_downloads = len(playlist) download_count = min(len(playlist),max_downloads) wav_files = [] #iterate over list of video urls to download their audio for x in xrange(-1,download_count): if x == -1: video = pafy.new(video_id) #process seed video else: video = playlist[x]['pafy'] #process playlist videos video_id = video.videoid wav_file = get_wav_from_vid(video_id) wav_files.append(wav_file) print "Playlist download completed\n" return wav_files
def update(self, username, db_manager, command_args): if command_args[0] == "!sr" or command_args[0] == "!songrequest": if len(command_args) < 2: return "Usage: !songrequest https://www.youtube.com/watch?v=KMFLnlg883I" else: # TODO: More params should make a youtube query video_id = "" video = None input = command_args[1] if(input.startswith("http")): try: video_id = urlparse.parse_qs(urlparse.urlparse(input).query)['v'][0] except: return "Sorry " + username + ", that URL does not appear to have a YouTube video in it FeelsBadMan :gun:" else: video_id = input try: video = pafy.new("https://www.youtube.com/watch?v=" + video_id) except ValueError: query = "" for i in range(1, len(command_args)): query += command_args[i] query_string = urlparse.urlencode({"search_query" : query}) html_content = urllib.request.urlopen("http://www.youtube.com/results?" + query_string) search_results = re.findall(r'href=\"\/watch\?v=(.{11})', html_content.read().decode()) try: video = pafy.new("https://www.youtube.com/watch?v=" + search_results[0]) except ValueError: return "Something horrible happened when I tried loading your video!" if video is None: return "Whoops! An error occurred upon processing the video!" if video.length > 600: return "Sorry " + username + ", the song must be less than 10 minutes long FeelsBadMan :gun:" if self.is_song_in_queue(video_id): return "Sorry " + username + ", the song is already in the queue NotLikeThis" audio_streams = video.audiostreams desired_stream = None for a in audio_streams: print(a.extension) desired_stream = a if desired_stream == None: return "No compatible format found for the song " + username + " FeelsBadMan :gun:" if not os.path.isfile("tmp/" + video_id + "." + desired_stream.extension): desired_stream.download(filepath="tmp/" + video_id + "." + desired_stream.extension) # TODO: Check if file exists event_overview.song_list.append({ "username": username, "filename": "tmp/" + video_id + "." + desired_stream.extension, "title": video.title, "id": video_id, "length": video.length }) return "Added the song '" + video.title + "' to the queue."
def parseUrl(self): try: # try to declare the url as a playlist self.playlist = pafy.get_playlist(self.url) # assuming the declaration did not fail with ValueError proceed to parse further print(self.playlist["title"]) self.title(self.playlist["title"]) try: # check to see if the url of the playlist ALSO contains a video self.video = pafy.new(self.url) # assuming the declaration did not fail with some error proceed to ask user what course of action should be taken valid = False while not valid: # Make user decide the best course of action print("Download the whole playlist or just this video?") print(" 1.) The whole playlist from the begining.") print(" 2.) Select where to start and where to end.") print(" 3.) Download this video only.") print("=================================================================") opt = input("Enter 1, 2, or 3: ") if opt == "1": # Classify url as a playlist and set the limits to beggining and end self.ytype = "PLIST" self.conf.data["limit"][0] == 1 self.conf.data["limit"][1] == -1 valid = True elif opt == "2": # Classify url as a playlist and make the user choose the limits manually self.conf.set_pl_bound() self.ytype = "PLIST" valid = True elif opt == "3": # Classify the url as a video self.ytype = "VIDEO" valid = True else: # Make the user pick again and explain that they didnt choose from the available options print("I didn't understand that :C") valid = False except Exception as e: self.ytype = "PLIST" except ValueError: try: # Assuming the url is not a playlist, declare the url as a video, and classify it as such self.video = pafy.new(self.url) # print(self.video.title) self.title(self.video.title) self.ytype = "VIDEO" except ValueError: # Assuming the URL is not a video or a playlist, it falls outside of the scope of this program # inform user, and classify the URL as "NONE" print("This is not a youtube or other compatable url.") self.ytype = "NONE" except OSError: # self.parseUrl() was passed something that it could not parse print("I didn't understand that :C") self.ytype = "NONE"
def cmd_music(self, message): if not(self.client.is_voice_connected(self.server)): self.voice_client = yield from self.client.join_voice_channel(self.voice_channel) youtubeURL = message.content.split()[1] if self.player is not None and self.player.is_playing(): video = pafy.new(youtubeURL) self.music_queue.append(youtubeURL) self.music_dict[youtubeURL] = video.title yield from self.client.send_message(message.channel, "Added {} to the queue (Requested by {})".format(video.title, message.author.name)) else: video = pafy.new(youtubeURL) bestaudio = video.getbestaudio() title = bestaudio.download(quiet = True) self.create_player_and_play(title)
def download_last_video(task): print(HEADER + "Download video" + ENDC) if(task == "latest"): # Subprocess get most recent video ID proc = subprocess.Popen(["python", "-c", "import ytsubs; ytsubs.do_it()"], stdout=subprocess.PIPE) # Get out of the subprocess which is the video id out = proc.communicate()[0] else: out = task #print "out = " + out # New pafy object with video ID v = pafy.new(out) print(WARNING + "\tTitle : "+v.title + ENDC) print(WARNING + "\tDuration : "+v.duration + ENDC) # Get the best quality available s = v.getbestvideo(preftype="mp4", ftypestrict=False) sa = v.getbestaudio() # Download the video # print("Video file size is %s" % s.get_filesize()) filename = s.download(filepath="files/inputr.mp4") # starts download filename = sa.download(filepath="files/audio.m4a") # starts download return v.title
def download(url,filename,resol, desc=None): video = pafy.new(url) print (video.title) print (video.rating) streams = video.streams l=len(streams)-1 u = urllib2.urlopen(streams[int(resol)].url) scheme, netloc, path, query, fragment = urlparse.urlsplit(streams[int(resol)].url) #filename = "d:/{}.mp4".format("video") with open(filename, 'wb') as f: meta = u.info() meta_func = meta.getheaders if hasattr(meta, 'getheaders') else meta.get_all meta_length = meta_func("Content-Length") file_size = None if meta_length: file_size = int(meta_length[0]) print("Downloading: {0} Bytes: {1}".format(url, file_size)) file_size_dl = 0 block_sz = 8192 while True: buffer = u.read(block_sz) if not buffer: break file_size_dl += len(buffer) f.write(buffer) status = "{0:16}".format(file_size_dl) if file_size: status += " [{0:6.2f}%]".format(file_size_dl * 100 / file_size) status += chr(13) Label( root, text="Done:{0} size: {1}kb".format(file_size_dl * 100 / file_size, file_size/1024)).grid(row=6,column=0) #root.mainloop() print(status, end="") print()
def loadVideo(self, url): video = pafy.new(url) best = video.getbest() key=hashlib.sha1(url).hexdigest() fn="{base_path}/{key}.{ext}".format(base_path=self.cache_path,key=key,ext=best.extension) res = best.download(fn) return res
def test_pafy_download(self): """ Test downloading. """ callback = lambda a, b, c, d, e: 0 vid = pafy.new("DsAn_n6O5Ns", gdata=True) vstream = vid.audiostreams[-1] name = vstream.download(callback=callback) self.assertEqual(name[0:5], "WASTE")
def runOnce(self): """ Create pafy objects for tests. """ if hasattr(Test, "hasrun"): return Test.quick = os.environ.get("quick") Test.videos = VIDEOS if not Test.quick else [] Test.playlists = PLAYLISTS if not Test.quick else [] for video in Test.videos: time.sleep(0 if Test.quick else self.delay) video['pafy'] = pafy.new(video['identifier']) video['streams'] = video['pafy'].streams video['best'] = video['pafy'].getbest() video['bestaudio'] = video['pafy'].getbestaudio() video['bestvideo'] = video['pafy'].getbestvideo() # get urls for age restricted vids if video['pafy'].videoid == "07FYdnEawAQ": _ = video['pafy'].streams[0].url _ = video['pafy'].streams[1].url_https del _ for playlist in Test.playlists: playlist['fetched'] = pafy.get_playlist(playlist['identifier']) Test.hasrun = True
def test_pafy_download_resume(self): """ Test resuming a partial download. """ tempname = "WASTE 2 SECONDS OF YOUR LIFE-DsAn_n6O5Ns-171.m4a.temp" with open(tempname, "w") as ladeeda: ladeeda.write("abc") vid = pafy.new("DsAn_n6O5Ns", gdata=True, basic=False) vstream = vid.audiostreams[-1].download(meta=True, remux_audio=True) name = "WASTE 2 SECONDS OF YOUR LIFE.m4a" self.assertEqual(63639, os.stat(name).st_size) # test fetching attributes vid._title = None _ = vid.title vid._rating = None _ = vid.rating vid._author = None _ = vid.author vid._rating = None _ = vid.rating vid._length = None _ = vid.length vid._viewcount = None _ = vid.viewcount vid._thumb = None _ = vid.thumb vid._length = None _ = vid.duration
def get_result(self, results=None, index=0): """Returns a terminal representation of a YouTube Video result.""" if results is None: results = self.results try: vid = pafy.new(results[index]) except Exception: return str(index + 1) + ") This video is not available.\n" string = "" string += str(index + 1) + ") " string += str(color.bold(color.underline(vid.title))) + "\n" more_info = "Time: {} | Rating: {:.2f} | Views: {:,}\n" string += more_info.format(vid.duration, vid.rating, vid.viewcount) utils.term.bgcolor = 'white' thumbnail = requests.get(vid.thumb) image = fi.Image(StringIO(thumbnail.content)) width = min(utils.term.width, self.MAX_WIDTH) image.resize(width) string += textwrap.fill(vid.description[:500] + "...", width) + "\n" string += str(image) string += "/"*width + "\n" return string
def poo(): #print("URL : %s\n" %(e.get())) url = e.get() global v v = pafy.new(url) b = v.streams global pos global s global man x=0 print "video Title : ",v.title print "video.duration : ",v.duration print "video length : ",v.length for i in b: #Label(root, text=str(i)).grid(row=pos, column=0) size_KB = i.get_filesize()/(1024) size_MB = size_KB/1024 mand = str(i)+" \t\t Size In KB "+str(size_KB)+" \t\t Size in MB "+str(size_MB) #print mand Radiobutton(root, text=mand, padx = 200, variable=vec, command=downloadfun, value=x).pack(anchor=W) x=x+1 pos=pos+1 size_v = i.get_filesize()/1024
def home(request): c = {} c.update(csrf(request)) if request.GET: url = request.GET.get('url') if url: validate = URLValidator() try: validate(url) video = pafy.new(url) streams = video.streams f = open('getlist.txt','a') f.write(str(url)+'\n') f.close() print "\n \n \n############ The details of the Video are as follows: ########### \n" print "Title : %s\n"%(video.title) print "Author : %s\n"%(video.author) print "Length : %s seconds\n"%(video.length) print "No. of views : %s \n"%(video.viewcount) for s in streams: print " Link to Video : %s"%(s.url) print print print "#################################################################\n \n \n" return render_to_response('result.html') except ValidationError: return render(request, 'index.html', {'error':'Please enter a valid url!'}) else: return render(request, 'index.html', {'error':'Please enter a url!'}) return render_to_response('index.html')
def run(self): v = pafy.new(self.url) l = v.getbest() print("Size is %s" % l.get_filesize()) l.download(filepath="Videos") time.sleep(5) self.taskFinished.emit()
def GetInfo(request, url): try: vidobject = pafy.new(url) return render(request,"airotub/video.html",{"thumbnail":vidobject.thumb,"titulo":vidobject.title, "videodown":"getdown/%s/1"%(url),"audiodown":"getdown/%s/2"%(url),"vale":1}) except: return render(request, "airotub/video.html", {"vale":2})
def download_video (url, videofile=None, tmproot=None): if not videofile: # create a temporary directory tempdir = tempfile.mkdtemp(prefix='y2b',dir=tmproot) tempvideofile, videofile = tempfile.mkstemp(dir=tempdir, prefix='y2bvideo') os.close(tempvideofile) video = pafy.new(url) logging.info( video.title ) logging.info( "Duration: {0}".format(video.duration) ) # now, get the length in seconds, which will be important later on for # decoding times = video.duration times_arr = times.rsplit(':') total_seconds = 0 for t in times_arr: total_seconds = 60*total_seconds + int(t) logging.debug("Duration in seconds: {0}".format(total_seconds)) # best = video.getbest() # display all possible streams logging.debug("Possible video streams:") for s in video.streams: logging.debug(s) best = video.getbest(preftype="flv") logging.info("Downloading the {0} video of {1} to {2}".format(best.resolution, url, videofile)) best.download(quiet=False, filepath=videofile) return videofile, total_seconds
def fetch_youtube(self, processor, request): """Fetches YouTube audio. Request: key: filename in the cache, without extension. id: YouTube id. Response: string path of the downloaded file. """ if self.cache is None: return processor(request, None) cache_path = os.path.join(self.cache, request['key']) cache_files = glob.glob(cache_path + '.*') if not self.fresh and len(cache_files) > 0: cache_full_path = cache_files[0] self.logger.info("Got %s from cache", request['key']) return processor(request, cache_full_path) os.makedirs(os.path.dirname(cache_path), exist_ok=True) try: audio_stream = pafy.new(request['id']).getbestaudio() if audio_stream is None: self.logger.info("%s has no audio", request['key']) return processor(request, None) cache_full_path = '{}.{}'.format(cache_path, audio_stream.extension) audio_stream.download(filepath=cache_full_path) self.logger.info("Got %s", request['key']) return processor(request, cache_full_path) except OSError as e: self.logger.error("Couldn't get %s", request['key']) return processor(request, None) except ValueError as e: self.logger.error("%s invalid", request['key']) return processor(request, None)
def downloadvideo(url, ptype='mp4', audio=False, silent=False): video = pafy.new(url) if audio: best = video.getbestaudio() else: best = video.getbest(preftype=ptype) best.download(quiet=silent, callback=op)
def download(directory, youtube_id, clear=False): """Download the audio of a YouTube video. The audio is downloaded in the highest available quality. Progress is printed to `stdout`. The file is named `youtube_id.m4a`, where `youtube_id` is the 11-character code identifiying the YouTube video (can be determined from the URL). Parameters ---------- directory : str The directory in which to save the downloaded audio file. youtube_id : str 11-character video ID (taken from YouTube URL) clear : bool If `True`, it deletes the downloaded video. Otherwise it downloads it. Defaults to `False`. """ filepath = os.path.join(directory, '{}.m4a'.format(youtube_id)) if clear: os.remove(filepath) return if not PAFY_AVAILABLE: raise ImportError("pafy is required to download YouTube videos") url = 'https://www.youtube.com/watch?v={}'.format(youtube_id) video = pafy.new(url) audio = video.getbestaudio() audio.download(quiet=False, filepath=filepath)
def youtube_download_audio(video_url, file_path, file_name): try: import pafy except ImportError: print("Module \"pafy\" not installed - install with \"pip3 install pafy\"") return False temp_dir_name = "./temp_audio_downloads" if not os.path.exists(temp_dir_name): os.mkdir(temp_dir_name) try: # Download video = pafy.new(video_url) video.getbestaudio(preftype = "m4a").download(filepath = os.path.join(file_path, file_name), quiet = True) # TODO Check if this is even necessary # Convert to MP3 # m4aFile = os.path.join(temp_dir_name, file_name) # mp3File = os.path.join(file_path, "%s.mp3" % file_name[: -4]) # subprocess.call(["ffmpeg", "-i", m4aFile, "-acodec", "libmp3lame", "-ab", "256k", mp3File]) except FileNotFoundError as err: if "ffmpeg" in str(err): # ffmpeg not installed print("Package \"ffmpeg\" not install - install with \"sudo apt-get install ffmpeg\"") return False else: raise err finally: shutil.rmtree(temp_dir_name)
def fileData(self, url): vcode = os.path.basename(url) try: gvcode = vcode.split('v=') gvcode = gvcode[1].split('&') vcode = gvcode[0] except: vcode = vcode url = 'http://www.youtube.com/watch?v=' + vcode video_i = pafy.new(url) title = video_i.title length = video_i.length downurl = self.select_quality(video_i.streams) rq = urllib2.Request(downurl) gtdata = urllib2.urlopen(rq) contentlength = gtdata.info().getheader('Content-Length') data = {"url": url, "title": title, "length": time.strftime('%M:%S', time.gmtime(length)), "type": FILE_TYPE_VIDEO, "fsize": contentlength, "downurl": downurl, "hiquality": False} return data
def resolve_url(url, stream=False): try: video = pafy.new(url) if not stream: uri = 'youtube:video/%s.%s' % ( safe_url(video.title), video.videoid ) else: uri = video.getbestaudio() if not uri: # get video url uri = video.getbest() logger.debug('%s - %s %s %s' % ( video.title, uri.bitrate, uri.mediatype, uri.extension)) uri = uri.url if not uri: return except Exception as e: # Video is private or doesn't exist logger.info(e.message) return track = Track( name=video.title, comment=video.videoid, length=video.length * 1000, album=Album( name='YouTube', images=[video.bigthumb, video.bigthumbhd] ), uri=uri ) return track
def download_video(self,video_link, video_title): """ Download the video using pytube. Initialized self.yt_downloader. Args: video_link (str): video url link video_title (str): video title (may need to convert) try if can use the video title from downloader itself. """ try: video = pafy.new(video_link) if not self.download_as_audio: selected_video_obj = video.getbest('mp4') if selected_video_obj == None: selected_video_obj = video.getbest('flv') if selected_video_obj: download_fullpath = os.path.join(self.video_download_folder, selected_video_obj.filename) if not os.path.isfile(download_fullpath): selected_video_obj.download(download_fullpath, quiet= True) else: bestaudio = video.getbestaudio() download_fullpath = os.path.join(self.video_download_folder, bestaudio.filename) if not os.path.isfile(download_fullpath): bestaudio.download(download_fullpath, quiet= True) except: #print 'Have problem downloading this file', video_title print 'Have problem downloading this file'
def createFromYouTube(track): id = track["id"] #p = Popen("youtube-dl -f 'mp3/m4a/mp4/ogg' --simulate --get-url https://www.youtube.com/watch?v="+id, stdout=PIPE, shell=True, stderr=None) #streamurl, err = p.communicate() #rc = p.returncode model = StreamModel() #model.Stream = streamurl #model.Description = track["description"] #model.Name = track["title"] #model.Format = "-" #model.Image = track["thumbnail"] video = pafy.new(id) audio = video.getbestaudio(preftype="m4a") if not audio: audio = video.getbest() print("video: " + audio.title + " " + audio.mediatype) model.Id = id, model.Description = video.description model.Name = video.title model.Format = video.title image = video.thumb if video.bigthumb: image = video.bigthumb model.Image = image model.Stream = audio.url return model
def downloadVideo(self, url, ptype='mp4', audio=False, silent=False): video = pafy.new(url) if audio: best = video.getbestaudio() else: best = video.getbest(preftype=ptype) best.download(quiet=silent, filepath="../../files")
def downloadYouTube(videourl): # function for downloading the video yt = pafy.new(videourl) # pafy object print("Video Title: ",yt.title," Views: ", yt.viewcount, " Duration: ", yt.duration) # using pafy to get title, views, duration and description of video print(" ") print("Description: ") print(yt.description) print(" ") stream = yt.streams # a list to get all video formats res_itr = 0 # iterator print("Formats...") for reslt in stream: print(res_itr,reslt) # printing all formats of video res_itr += 1 best = yt.getbest() # get best resolution regardless of format print(" ") choice = int(input("Choose any format (resolution): ")) choice_itr = 0 for Vid in stream: if choice == choice_itr: stream[choice].download() # downloading the selected video format else: choice_itr += 1
def downloadSong(videos, searchTerm): global successfullyDownloaded global unsuccessfulDownloads global downloadDirectory global totalDownload try: url = "https://www.youtube.com/watch?v=" + videos[0].split()[-1][1:-1] video = pafy.new(url) song = video.getbestaudio() songname = song.title songname = songname.split('.')[0] songname = string.replace(songname, '/', '_') songname = songname.decode('unicode_escape').encode('ascii','ignore') print "name:",songname if songname in onlyfiles: print "File with the same name already present in folder downloads" else: print "Title:", video.title print "Size :", round(song.get_filesize()/(1024.0*1024), 2), "MB" print "Downloading Audio...\n" totalDownload+=round(song.get_filesize()/(1024.0*1024), 2) filename = song.download(quiet=False, filepath=downloadDirectory) successfullyDownloaded.add(searchTerm) print "\nDownload Successful!\n" except: e = sys.exc_info()[0] unsuccessfulDownloads.add(searchTerm) print "\n*****************Download of ", searchTerm, "is unsuccessful!******************" print "Reason is here!" print e
def ytinfo(self, id, desc): p = pafy.new(id) d = p.description.strip() if len(d) > 300: d = d[0:300] + "..." href = ' <font size="7"><a href="https://github.com/efskap/skype-youtube-info">' + "(github)" + '</a></font>' return '<font size="10" color="#6B523B">'+ name + '</font>' + href + '\n<font size="13"><a href="https://www.youtube.com/watch?v='+ id + '">' + p.title + '</a></font><font color="#5B6F73" size="13"> [' + p.duration + "]</font>" + "\n" +( ( '<font color="#5B6F73">' + d + "</font>") if desc else "")
def bot(): incoming_msg = request.values.get('Body', '') #print(incoming_msg) resp = MessagingResponse() msg = resp.message() responded = False if 'start' in incoming_msg: text = f'🤖 _Halo Saya Adalah Recsec Bot, Ada Yang Bisa Saya Bantu?_\n\n*Admin :*\n\n📞 : 085885105039\n📱 : _fb.me/rezzapriatna12_ \n\n🚀 *Fitur* \n\n✅ _Youtube Downloader_ \n✅ _Facebook Downloader_ \n✅ _Instagram Downloader_ \n✅ _Google Search_ \n✅ _Text To Speech_ \n✅ _Stalking Profil Instagram_ \n✅ _Translate_ \n\n\n _Untuk Menampilkan Command Ketik_ *Menu*' msg.body(text) responded = True if 'info-covid' in incoming_msg or 'Info-covid' in incoming_msg: import requests as r, json req = r.get( 'https://coronavirus-19-api.herokuapp.com/countries/indonesia') reqq = r.get( 'https://coronavirus-19-api.herokuapp.com/countries/world') jss = reqq.json() js = req.json() text = f'*Info Coronavirus Indonesia*\n\n\n*Positif* : {js["cases"]} \n*Sembuh* : {js["recovered"]} \n*Meninggal* : {js["deaths"]} \n\n\n*Global* \n\n\n*Positif* : {jss["cases"]} \n*Sembuh* : {jss["recovered"]} \n*Meninggal* : {jss["deaths"]}' msg.body(text) responded = True import requests as r import re par = incoming_msg[3:] html = r.get(par) video_url = re.search('sd_src:"(.+?)"', html.text).group(1) msg.media(video_url) responded = True if '/IG' in incoming_msg: import requests as r par = incoming_msg[3:] a = r.get(par + '?__a=1') b = a.json() c = b['graphql']['shortcode_media'] d = (c['video_url']) msg.media(d) responded = True if '/GL' in incoming_msg: from googlesearch import search query = incoming_msg[3:] for i in search(query, tld="com", num=10, stop=10, pause=2): text = f'==========Results==========\n\n *Reff* : ' + i msg.body(text) responded = True if '/TR-en-id' in incoming_msg: par = incoming_msg[9:] translator = Translator() result = translator.translate(par, src='en', dest='id') msg.body(result.text) responded = True if '/TR-id-en' in incoming_msg: par = incoming_msg[9:] translator = Translator() result = translator.translate(par, src='id', dest='en') msg.body(result.text) responded = True if '/TR-id-kor' in incoming_msg: par = incoming_msg[10:] translator = Translator() result = translator.translate(par, src='id', dest='ko') msg.body(result.text) responded = True if '/TR-kor-id' in incoming_msg: par = incoming_msg[10:] translator = Translator() result = translator.translate(par, src='ko', dest='id') msg.body(result.text) responded = True if '/FL' in incoming_msg: import requests as r import re par = incoming_msg[3:] html = r.get(par) video_url = re.search('sd_src:"(.+?)"', html.text).group(1) reqq = r.get('http://tinyurl.com/api-create.php?url=' + video_url) msg.body('*VIDEO BERHASIL DI CONVERT*\n\nLINK : ' + reqq.text + '\n\n_Cara Download Lihat Foto Diatas_') msg.media( 'https://user-images.githubusercontent.com/58212770/78709692-47566900-793e-11ea-9b48-69c72f9bec1e.png' ) responded = True if '/TTS' in incoming_msg: par = incoming_msg[5:] msg.media('https://api.farzain.com/tts.php?id=' + par + '&apikey=JsaChFteVJakyjBa0M5syf64z&') responded = True if '/SG' in incoming_msg: import requests import json par = incoming_msg[4:] p = requests.get('http://api.farzain.com/ig_profile.php?id=' + par + '&apikey=JsaChFteVJakyjBa0M5syf64z') js = p.json()['info'] ms = (js['profile_pict']) jp = p.json()['count'] text = f'Nama : *{js["full_name"]}* \nUsername : {js["username"]} \nBio : *{js["bio"]}* \nSitus Web : *{js["url_bio"]}* \nPengikut : *{jp["followers"]}* \nMengikuti : *{jp["following"]}* \nTotal Postingan : *{jp["post"]}* ' msg.body(text) msg.media(ms) responded = True if '/YT' in incoming_msg: import pafy import requests as r par = incoming_msg[4:] audio = pafy.new(par) gen = audio.getbestaudio(preftype='m4a') genn = audio.getbestvideo(preftype='mp4') req = r.get('http://tinyurl.com/api-create.php?url=' + gen.url) popo = r.get('http://tinyurl.com/api-create.php?url=' + genn.url) msg.body( '_=========================_\n\n _Video Berhasil Diconvert_\n\n_=========================_\n\n' '*' + gen.title + '*' '\n\n*Link Download Music* :' + req.text + '\n\n*Link Download Video* :' + popo.text) responded = True if '/SY' in incoming_msg: import requests as r par = incoming_msg[3:] req = r.get('http://api.farzain.com/yt_search.php?id=' + par + '&apikey=JsaChFteVJakyjBa0M5syf64z&') js = req.json()[1] text = f'*Judul* : _{js["title"]}_ \n\n*Url Video* : _{js["url"]}_\n\n*Video ID* : _{js["videoId"]}\n\n_Note : Jika Ingin Download Video Ini Atau Convert Ke Musik, Salin Link Diatas Dan Gunakan Command /YT_' msg.body(text) msg.media((js['videoThumbs'])) responded = True if '/JS' in incoming_msg: import requests as r par = incoming_msg[3:] req = r.get('http://api.farzain.com/shalat.php?id=' + par + '&apikey=JsaChFteVJakyjBa0M5syf64z&') js = req.json()['respon'] text = f'*Waktu Sholat* \n\n*Subuh* : {js["shubuh"]} \n*Dzuhur* : {js["dzuhur"]} \n*Ashar* : {js["ashar"]} \n*Magrib* : {js["maghrib"]} \n*Isya* : {js["isya"]}' msg.body(text) responded = True if 'jadwal-imsak' in incoming_msg: msg.media( 'https://user-images.githubusercontent.com/58212770/80048733-35c6b100-853b-11ea-8043-ec0614a40039.jpeg' ) responded = True if 'help' in incoming_msg: text = f'💻 *Help For Instagram*\n\n/IG <Link Video> Contoh : \n/IG https://www.instagram.com/p/BWhyIhRDBCw/\n\n\n*Note* : Link Harus Seperti Di Contoh Kalo link Akhirannya Ada ?utm_source=ig_web_copy_link hapus bagian itu\n\n 💻 *Help For Facebook*\n\n/FB _link video_ Contoh :\n\n/FB https://www.facebook.com/100010246050928/posts/1143182719366586/?app=fbl \n\n💻 *Help For Google Search* \n\n /GL <Query> Contoh : \n\n/GL rezzaapr \n\n💻 *Help For Instagram Stalking \n\n/SG <username> Contoh : \n\n/SG rzapr \n\n💻 *Help For Translate* \n\nTR-id-en Translate indonesia Ke inggris\n\n/TR-en-id Translate Inggris Ke Indonesia\n\n/TR-id-kor Translate Indonesia Ke Korea \n\n/TR-kor-id Translate Korea Ke Indonesia \n\n💻 *Help For Text To Speech* \n\n/TTS WhatsappBotRezzaapr\n\nJika Ingin Menggunakan Spasi Ganti Dengan %20\n\nContoh : /TTS Whatsapp%20Bot%Rezzaapr' msg.body(text) responded = True if '!' in incoming_msg: import requests as r us = incoming_msg[2:] import requests import json url = 'https://wsapi.simsimi.com/190410/talk/' body = { 'utext': us, 'lang': 'id', 'country': ['ID'], 'atext_bad_prob_max': '0.7' } headers = { 'content-type': 'application/json', 'x-api-key': 'LKgWy5I-HoG8K0CmpWl.SNncus1UOpwBiA1XAZzA' } r = requests.post(url, data=json.dumps(body), headers=headers) js = r.json() msg.body(js['atext']) responded = True if responded == False: msg.body( 'Maaf Saya Hanya Bot Tidak Mengenal Perintah Itu :), Silahkan Kirim start Untuk Menunju Ke Menu' ) return str(resp)
# print viewcount print(video.viewcount) # print author & video length print(video.author, video.length) # print duration, likes, dislikes & description print(video.duration, video.likes, video.dislikes, video.description)''' ############################################################################################################3 '''Download best resolution video regardless of extension''' import pafy url = "https://youtu.be/8rmBYN6HhmM" video = pafy.new(url) streams = video.streams for i in streams: print(i) # get best resolution regardless of format best = video.getbest() print(best.resolution, best.extension) # Download the video best.download() ################################################################################################################# '''Download video of a particular format specified (let say .mp4)'''
import json import time import keyboard import cv2 import numpy as np import dlib from scipy.spatial import distance as dist import pafy from ffpyplayer.player import MediaPlayer # In[ ]: #Use Youtube video diirectly url = "https://www.youtube.com/watch?v=eIhp7VhLa-o" videoPafy = pafy.new(url) best = videoPafy.getbest() # In[2]: def eye_aspect_ratio(eye): """Computes the EAR""" A = dist.euclidean(eye[1], eye[5]) B = dist.euclidean(eye[2], eye[4]) C = dist.euclidean(eye[0], eye[3]) ear = (A + B) / (2 * C) return ear # In[3]:
import pafy #%% # Download the video video = pafy.new('https://www.youtube.com/watch?v=Re5NFApk9dQ') resolution = video.getbestvideo(preftype="mp4") input_movie = resolution.download(quiet=False) # Process it process_video(input_movie) os.remove(input_movie) image_1 = cv2.resize(img, size, interpolation=cv2.INTER_AREA) cv2.imwrite("barcode_%d.png" % size[0], image_1) def generate_pic (colours, size): # Generates the picture height = size[1]
def load_tracks(self, data, loading_notifier=NonceVar()): # loading_notifier is a StringVar, usually, for a loading screen, because loading tracks fresh can take a sec; NonceVar mimics StringVar interface cache = Path(self.app.DIR, 'yt_cache') urls = json.load(open(cache + 'urls.json')) tracks_per_channel = {} for channel in self.channels.values(): if listing := data.get(channel.name): l = len(listing) track_list = [] for i, track in enumerate(listing): YT = track.get('url') cache_fp = None i += 1 if YT: # YOUTUBE DOWNLOADS WORK AHAHAHAHAHA IM SO HAPPY url = track['url'].replace('music.', '') video_id = parse_qs(urlparse(url).query).get( 'v', (url, ) )[0] # this can take youtube music, youtube, youtu.be, http://, and even just the video code that comes after v= url_short = url # Shortened for visual appeal in the loading screen if len(url) > 41: url_short = url[:19] + '...' + url[-19:] loading_notifier.set( f'[{channel.name}] Resolving \n {url_short} \n ({i}/{l})' ) self.app.root.update() print('Resolving', url) vid = None if video_id in urls: # We keep urls stored with their video titles in case we have them; cuts the 2 seconds required for pafy.new() name = urls[video_id] else: # If it's not listed then that's very suspicious, probably not cached, so we resolve it ourselves try: vid = pafy.new(video_id) except: continue urls[video_id] = name = sanitize(vid.title) wave_path = Path(self.app.DIR, 'wave_cache', name + '.wav').path if os.path.exists(wave_path): # Now actually check if we have it cached. # If you clear urls.json but still have the wav hanging around this will save you, # otherwise it's a redundant check track['file'] = wave_path print('Not downloading, found a cached copy.') else: # But if not cached, gotta download! if vid is None: try: vid = pafy.new(video_id) except: continue loading_notifier.set( f'[{channel.name}]\nDownloading "{name}" from YouTube ({i}/{l})' ) self.app.root.update() print('Downloading audio...') print(vid) aud = vid.getbestaudio() # mod this # download it to the yt_cache cache_fp = cache + (sanitize(vid.title) + '.' + aud.extension) aud.download(cache_fp) print('DOWNLOADED:', cache_fp) track['file'] = cache_fp if not track.get('name'): # Give it a name track['name'] = name + ' (YT)' # not a Track() arg, and videos should have been downloaded... if 'url' in track: del track['url'] # Handles general files, as well as the downloaded YouTube audio name = track.get('name', track['file']) loading_notifier.set( f'[{channel.name}]\nLoading {name} ({i}/{l})') self.app.root.update() # Generate track and queue it self.track_dict[name] = t = audio.Track( **track, chunk_override=audio.Track.CHUNK ) # track_dict used for autofollow track_list.append(t) # yt_cache is EVANESCENT if cache_fp: os.remove(cache_fp) # Fix up autofollows and at_times print('Making autofollows...') loading_notifier.set( f'[{channel.name}]\nRendering autofollows...') self.app.root.update() tracks_to_remove = [] for track in track_list: for at_data in track.at_time_mods: # [5.0, "print('hello')"] track.at_time(*at_data) for af_name in track.auto_follow_mods: print('AUTOFOLLOW:', track, '+', af_name) # "track name" if not (af_track := self.track_dict.get(af_name)): print( f'Couldn\'t find track "{af_name}" for autofollow' ) continue #print('AUTOFOLLOW 2:', af_track) track.autofollow(af_track) # inherit timed commands track.at_time_mods += [ (t + af_track.length * 1000, f) for t, f in af_track.at_time_mods ] tracks_to_remove.append(af_track) # Remove auto'd tracks from the queue since they attach to the parent # REMOVE autofollowed etc. for track in tracks_to_remove: track_list.remove(track) # We'll queue in a hot sec tracks_per_channel[channel] = track_list
from pytchat import LiveChat import pafy import pandas as pd pafy.set_api_key('INSERT YOUR API KEY') video_id = 'SX7EnUYfb1I' v = pafy.new(video_id) title = v.title author = v.author published = v.published print(title) print(author) print(published) empty_frame = pd.DataFrame( columns=['제목', '채널 명', '스트리밍 시작 시간', '댓글 작성자', '댓글 내용', '댓글 작성 시간']) empty_frame.to_csv('./youtube.csv')
#importing pafy for youtube download import pafy import math #importing pretty table for table design from prettytable import PrettyTable #taking url as input url = input("enter youtube url:") #line break print('\n') #assigning main module to yt variable yt = pafy.new(url) audio = yt.audiostreams video = yt.streams all = yt.allstreams #printing print(yt) #line break print('\n') #Taking input for selecting media type type = input('audio/video:') #line break print('\n')
def main(_argv): # Definition of the parameters max_cosine_distance = 0.4 nn_budget = None nms_max_overlap = 1.0 # initialize deep sort model_filename = cfg.PATH + '/model_data/mars-small128.pb' encoder = gdet.create_box_encoder(model_filename, batch_size=1) # calculate cosine distance metric metric = nn_matching.NearestNeighborDistanceMetric("cosine", max_cosine_distance, nn_budget) # initialize tracker tracker = Tracker(metric) # load configuration for object detector config = ConfigProto() config.gpu_options.allow_growth = True session = InteractiveSession(config=config) STRIDES, ANCHORS, NUM_CLASS, XYSCALE = utils.load_config(FLAGS) input_size = FLAGS.size if FLAGS.stream is not None: url_pafy = pafy.new(FLAGS.stream) videoplay = url_pafy.getbest(preftype="mp4") video_path = videoplay.url else: video_path = FLAGS.video # load tflite model if flag is set if FLAGS.framework == 'tflite': interpreter = tf.lite.Interpreter(model_path=FLAGS.weights) interpreter.allocate_tensors() input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() # otherwise load standard tensorflow saved model else: saved_model_loaded = tf.saved_model.load(FLAGS.weights, tags=[tag_constants.SERVING]) infer = saved_model_loaded.signatures['serving_default'] # begin video capture try: vid = cv2.VideoCapture(int(video_path)) except: vid = cv2.VideoCapture(video_path) out = None # get video ready to save locally if flag is set if FLAGS.output: # by default VideoCapture returns float instead of int width = int(vid.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT)) fps = int(vid.get(cv2.CAP_PROP_FPS)) codec = cv2.VideoWriter_fourcc(*FLAGS.output_format) out = cv2.VideoWriter(FLAGS.output, codec, fps, (width, height)) frame_num = 0 last_interval_time = time.time() # while video is running while True: return_value, frame = vid.read() if return_value: frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) image = Image.fromarray(frame) else: print(json.dumps({'end': True}, indent=4)) break frame_num += 1 frame_size = frame.shape[:2] image_data = cv2.resize(frame, (input_size, input_size)) image_data = image_data / 255. image_data = image_data[np.newaxis, ...].astype(np.float32) start_time = time.time() # run detections on tflite if flag is set if FLAGS.framework == 'tflite': interpreter.set_tensor(input_details[0]['index'], image_data) interpreter.invoke() pred = [ interpreter.get_tensor(output_details[i]['index']) for i in range(len(output_details)) ] # run detections using yolov3 if flag is set if FLAGS.model == 'yolov3' and FLAGS.tiny == True: boxes, pred_conf = filter_boxes(pred[1], pred[0], score_threshold=0.25, input_shape=tf.constant( [input_size, input_size])) else: boxes, pred_conf = filter_boxes(pred[0], pred[1], score_threshold=0.25, input_shape=tf.constant( [input_size, input_size])) else: batch_data = tf.constant(image_data) pred_bbox = infer(batch_data) for key, value in pred_bbox.items(): boxes = value[:, :, 0:4] pred_conf = value[:, :, 4:] boxes, scores, classes, valid_detections = tf.image.combined_non_max_suppression( boxes=tf.reshape(boxes, (tf.shape(boxes)[0], -1, 1, 4)), scores=tf.reshape( pred_conf, (tf.shape(pred_conf)[0], -1, tf.shape(pred_conf)[-1])), max_output_size_per_class=50, max_total_size=50, iou_threshold=FLAGS.iou, score_threshold=FLAGS.score) # convert data to numpy arrays and slice out unused elements num_objects = valid_detections.numpy()[0] bboxes = boxes.numpy()[0] bboxes = bboxes[0:int(num_objects)] scores = scores.numpy()[0] scores = scores[0:int(num_objects)] classes = classes.numpy()[0] classes = classes[0:int(num_objects)] # format bounding boxes from normalized ymin, xmin, ymax, xmax ---> xmin, ymin, width, height original_h, original_w, _ = frame.shape bboxes = utils.format_boxes(bboxes, original_h, original_w) # store all predictions in one parameter for simplicity when calling functions pred_bbox = [bboxes, scores, classes, num_objects] # read in all class names from config class_names = utils.read_class_names(cfg.YOLO.CLASSES) # by default allow all classes in .names file allowed_classes = list(class_names.values()) # custom allowed classes (uncomment line below to customize tracker for only people) #allowed_classes = ['person'] # loop through objects and use class index to get class name, allow only classes in allowed_classes list names = [] deleted_indx = [] for i in range(num_objects): class_indx = int(classes[i]) class_name = class_names[class_indx] if class_name not in allowed_classes: deleted_indx.append(i) else: names.append(class_name) names = np.array(names) count = len(names) if FLAGS.count: cv2.putText(frame, "Objects being tracked: {}".format(count), (5, 35), cv2.FONT_HERSHEY_COMPLEX_SMALL, 2, (0, 255, 0), 2) #print(frame_num + "Objects being tracked: {}".format(count)) # delete detections that are not in allowed_classes bboxes = np.delete(bboxes, deleted_indx, axis=0) scores = np.delete(scores, deleted_indx, axis=0) # encode yolo detections and feed to tracker features = encoder(frame, bboxes) detections = [ Detection(bbox, score, class_name, feature) for bbox, score, class_name, feature in zip( bboxes, scores, names, features) ] #initialize color map cmap = plt.get_cmap('tab20b') colors = [cmap(i)[:3] for i in np.linspace(0, 1, 20)] # run non-maxima supression boxs = np.array([d.tlwh for d in detections]) scores = np.array([d.confidence for d in detections]) classes = np.array([d.class_name for d in detections]) indices = preprocessing.non_max_suppression(boxs, classes, nms_max_overlap, scores) detections = [detections[i] for i in indices] # Call the tracker tracker.predict() tracker.update(detections) # Store tracks for json... tracks = [] # update tracks for track in tracker.tracks: if not track.is_confirmed() or track.time_since_update > 1: continue bbox = track.to_tlbr() class_name = track.get_class() t = dict() t["class"] = class_name t["bbox"] = bbox.tolist() t["id"] = track.track_id t["confidence"] = track.detection_actual_score tracks.append(t) # draw bbox on screen color = colors[int(track.track_id) % len(colors)] color = [i * 255 for i in color] cv2.rectangle(frame, (int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])), color, 2) cv2.rectangle( frame, (int(bbox[0]), int(bbox[1] - 30)), (int(bbox[0]) + (len(class_name) + len(str(track.track_id)) + len(str(track.detection_actual_score))) * 17, int(bbox[1])), color, -1) cv2.putText( frame, class_name + "-" + str(track.track_id) + "-" + str(track.detection_actual_score), (int(bbox[0]), int(bbox[1] - 10)), 0, 0.75, (255, 255, 255), 2) # if enable info flag then print details about each track # if FLAGS.info: # print("Tracker ID: {}, Detection Confidence: {}, Class: {}, BBox Coords (xmin, ymin, xmax, ymax): {}".format(str(track.track_id), str(track.detection_actual_score), class_name, (int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3])))) # calculate frames per second of running detections fps = 1.0 / (time.time() - start_time) tdelta = start_time - last_interval_time if tdelta > FLAGS.data_min_interval: print( json.dumps( { 'end': False, 'fps': fps, 'frame_num': frame_num, 'tracks': tracks, 'time': time.strftime("%d/%m/%Y, %H:%M:%S", time.gmtime(start_time)) }, indent=4)) last_interval_time = start_time result = np.asarray(frame) result = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) if not FLAGS.dont_show: cv2.imshow("Output Video", result) # if output flag is set, save video file if FLAGS.output: out.write(result) if cv2.waitKey(1) & 0xFF == ord('q'): break cv2.destroyAllWindows()
def get_video_info(youtube_id): url = "https://www.youtube.com/watch?v=" + youtube_id video = pafy.new(url) return video
def load_video(self, context, num=0): self.vid_url = self.video_url(context, num) print("Video url is: %s" % self.vid_url) self.video = new(self.vid_url) return self.video.title, self.video.rating, self.video.length, self.video.description, self.video.getbest( )
def save(): if request.method=="GET": return ''' <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <form method="POST" action="/youtubedl"> <input name=urld type=url> ENTER mp3 URL:</input> <button type=submit class="btn btn-success">DOWNLOAD</button> <script> var pass=prompt("A password is required to access the page"); if(pass=="'''+pword+'''"){ alert("Access granted"); }else{ document.body.innerHTML="<h1>I'm afraid you cannot use this, redirect in 5 seconds</h1>"; function Cat(){ window.location="about:blank"; } } </script> <script src='https://www.google.com/recaptcha/api.js'></script> <select name=filetype class="form-control"> <option value="mp4">mp4</option> <option value="webm">webm</option> <option value="mp3">mp3</option> <option value="m4a">m4a</option> <option value="3gp">3GP</option> <option value="flv">flv</option> <option value="mov">mov</option> <option value="mpg">mpg</option> <option value="avi">avi</option> </select> <div class="g-recaptcha" data-sitekey="6LfPUk8UAAAAAPqjhnvAiiSYw8Ng8rcR7CSYk0EL"></div> </form> <script type="text/javascript"> var infolinks_pid = 3084238; var infolinks_wsid = 0; </script> <script type="text/javascript" src="//resources.infolinks.com/js/infolinks_main.js"></script> ''' else: try: video = pafy.new(request.form["urld"]) if not request.form["filetype"] in ["m4a","mp3"]: best = video.getbest(preftype=request.form["filetype"]) filename = best.download(filepath=(pa+"/static/"+"dlfile")) else: best=video.getbestaudio(preftype=request.form["filetype"]) filename = best.download(filepath=(pa+"/static/"+"dlfile")) #filename = best.download(filepath="/home/Pythonsnake2017/mysite/templates/file1.html",quiet=False) return ''' <h1>FILE DONE</h1> <script src="https://apis.google.com/js/platform.js" async defer></script> <div class="g-savetodrive" data-src="/dlfile" data-filename="youtubedl" data-sitename="Ulimate youtube"> </div> <h1>'''+video.title+'''</h1> </p>'''+video.description+''' <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> ''' except Exception as e: return str(e)+str(type(request.form["urld"]))
def ninjasave(): with open("yt.json","w") as f: f.write(json.dumps(database1)) if request.method=="GET": return ''' <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <style> button{ font-size:45px; } input{ background-color:black; color:white; border-color:white; border-radius:2px; } </style> <link rel="apple-touch-icon" href="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTbtula7phAfFEsEYR7_BTnonXg1H_QfJnAai8p56elb4LZBf90"> <meta name="apple-mobile-web-app-title" content="youtube"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="red"> <form method="POST" action="/youtube.io"> <input name=urld type=url> ENTER mp3 URL:</input> <button type=submit class="btn btn-success">DOWNLOAD</button> <script> if(window.localStorage.getItem("pass")){ }else{ var pass=prompt("A password is required to access the page"); } if(pass=="io"||(window.localStorage.getItem("pass")=="used")){ window.localStorage.setItem("pass","used"); alert("Access granted"); }else{ alert("Access denied: "); document.body.innerHTML="<h1>I'm afraid you cannot use thisredirect in 5 seconds</h1>"; function Cat(){ window.location="https://google.com/DENIED"; } setTimeout(Cat,3000); } </script> </form> '''+gen() else: try: if request.form["urld"].find("youtube")==-1 or False: d(request.form["urld"],"/home/Pythonsnake2017/mysite/static/file1.html") d(request.form["urld"],"/home/Pythonsnake2017/mysite/templates/file1.html") video=1 video.title="" video.description="" return "THAts not a youtube url" else: video = pafy.new(request.form["urld"]) if True: best = video.getbest(preftype="mp4") database1.append([best.url,video.title,video.description,request.form["urld"]]) return ''' <h1> Your video has been submitted to database and will be processed reload to see</h1> \ ''' except Exception as e: return str(e)+str(type(request.form["urld"]))
def home(): name_list = get_name_list() # for item in name_list: # print(item) if request.method == 'GET': print('get') return render_template('video.html') Instance = None if request.method == 'POST': if request.form.get('Encrypt') == 'Play': if Instance == None: Instance = vlc.Instance( '--no-video --verbose=2 --file-logging --logfile=vlc_log.txt --sout-keep' ) player = Instance.media_player_new() while True: videolist = yt_crawler(random.choice(name_list)) for item in videolist[0:1]: try: video = pafy.new(item) best = video.getbest() playurl = best.url except: print('Error link') else: print(video.title, video.duration) options = ':sout=#transcode{vcodec=none,acodec=mp3,ab=128,channels=2,samplerate=44100,scodec=none}:http{mux=mp3,dst=:8080/}' Media = Instance.media_new(best.url, options) Media.get_mrl() player.set_media(Media) player.audio_set_volume(100) player.play() # thread = Thread(target = render_title, args = (video.title, video.duration, )) # thread.daemon = True # thread.start() # thread.join() pt = datetime.datetime.strptime( video.duration, '%H:%M:%S') total_seconds = pt.second + pt.minute * 60 + pt.hour * 3600 if total_seconds < 300: time.sleep(total_seconds - 5) else: time.sleep(300) for i in range(100, 0, -1): player.audio_set_volume(i) time.sleep(0.05) #player.stop() # render_template('main_play.html', title = video.title, duration = video.duration) return render_template('video.html')
#pip install pafy #pip install youtube-dl import pafy #url="https://www.youtube.com/watch?v=SA4m_rcSwqs&list=RDSA4m_rcSwqs" url = input("Enter URL of Youtube video : ") audio = pafy.new(url).videostreams print(audio) #best quality at last audio[-1] filename = audio[-1].download(quiet=False)
start_total=start_minutes*60+start_seconds #get end time in seconds end_time=time[index+1:] end_minutes=int(end_time[0]) end_seconds=int(end_time[-2:]) end_total=end_minutes*60+end_seconds #update lists start_times.append(start_total) end_times.append(end_total) #labels labels.append(str(label[i])) files=list() for i in range(len(links)): try: video=pafy.new(links[i]) bestaudio=video.getbestaudio() filename=bestaudio.download() start=start_times[i] end=end_times[i] extension=bestaudio.extension #get file extension and convert to .wav for processing later os.rename(filename,'%s_start_%s_end_%s%s'%(str(i),start,end,extension)) filename='%s_start_%s_end_%s%s'%(str(i),start,end,extension) if extension not in ['.wav']: xindex=filename.find(extension) filename=filename[0:xindex] ff=ffmpy.FFmpeg( inputs={filename+extension:None}, outputs={filename+'.wav':None} )
def download(): video = pafy.new(url) bestResolutionVideo = video.getbest() bestResolutionVideo.download()
import pafy import requests asd="metallica unforgiven" pafy.new(requests.get(r'http://www.google.com/search?q=' + asd + ' www.youtube.com/watch?v=&btnI').url).getbestaudio().download()
# import libraries import cv2 import pafy url = 'https://www.youtube.com/watch?v=rnN7CpPPVVw' #CHANGE URL vPafy = pafy.new(url) play = vPafy.getbest() def do_video_face_recognition(): #start the video # Get a reference to webcam # Initialize variables face_locations = [] cap = cv2.VideoCapture(play.url) while True: # Grab a single frame of video ret, frame = cap.read() #ret, frame = video_capture.read() # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses) rgb_frame = frame[:, :, ::-1]
if path == ".": #if path = "." means that user didnt type a path path = path + "/" + video.title + "." + stream.extension #just add name of the file and extension filename = stream.download(path) else: #user typed a path path = path[:-1] + "/" + video.title + "." + stream.extension #a little bit tricky: remove last char from string path (the . placed at row 37) -> add name of the file filename = stream.download(path) print("File downloaded at: " + path + "\n") def dl_both(video, path=None): dl_audio(video, path) dl_video(video, path) url = input("Insert youtube video url: ") v = pafy.new(url) #creates an instance of Pafy value = input( "Do you want the video or the audio? 1: Video, 2: Audio, 3: Both >>") path = input("Insert the path >> ") #Print informations about the video print("General Informations: \n \n ") print("Title: ") print(v.title + "\n") print("Duration: ") print(v.duration + "\n") print("Rating: ") print(str(v.rating) + "\n") print("Author: ") print(v.author + "\n") print("Length: ")
#pip install pafy #pip install youtube.dl from pafy import new while True: link = input("enter link of video >> ") video = new(link) stream = video.streams print("0 ",stream[0]) print("1 ",stream[1]) stre = int(input("enter quality ")) try: stream[stre].download() except: print("there is a probleme with quality or link")
def run (self): video = pafy.new(self.video_url) video_stream = video.allstreams # video_quaity = indexC download = video_stream[self.indexC].download(filepath=self.save_video,callback=self.Video_Single_ProgressBar)
Search = music query = urllib.parse.quote(Search) url = "https://www.youtube.com/results?search_query=" + query response = urllib.request.urlopen(url) html = response.read() soup = BeautifulSoup(html, 'html.parser') c = 0 for vid in soup.findAll(attrs={'class': 'yt-uix-tile-link'}): print('https://www.youtube.com' + vid['href']) if c == 0: video_url = 'https://www.youtube.com' + vid['href'] c += 1 print("Video link:", video_url) #Play the youtube link video = pafy.new(video_url) best = video.getbest() playurl = best.url print(video.title) print(video.description) browser = webdriver.Chrome() browser.get(playurl) else: print("Use the command play to play songs") mytext = "Didnot get the play command in your speech" myobj = gTTS(text=mytext, lang=language, slow=False) myobj.save("sound.mp3") os.system("sound.mp3") except NameError: print("Error Occured")
def save(): if request.method == "GET": return ''' <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <form method="POST" action="/youtubedl"> <input name=urld type=url> ENTER mp3 URL:</input> <button type=submit class="btn btn-success">DOWNLOAD</button> <script> var pass=prompt("A password is required to access the page"); if(pass=="''' + pword + '''"){ alert("Access granted"); }else{ alert("Access denied: BIG SHAQ ONE AND ONLY"); document.body.innerHTML="<h1>I'm afraid you cannot use this PERSON redirect in 5 seconds</h1>"; function Cat(){ window.location="https://raymondpeng2007.wix.com/games"; } } </script> <script type="text/javascript" var adfly_id = 19279991; var popunder_frequency_delay = 0; </script> <script src='https://www.google.com/recaptcha/api.js'></script> <select name=filetype class="form-control"> <option value="mp4">mp4</option> <option value="webm">webm</option> <option value="mp3">mp3</option> <option value="m4a">m4a</option> <option value="3gp">3GP</option> <option value="flv">flv</option> <option value="mov">mov</option> <option value="mpg">mpg</option> <option value="avi">avi</option> </select> <div class="g-recaptcha" data-sitekey="6LfPUk8UAAAAAPqjhnvAiiSYw8Ng8rcR7CSYk0EL"></div> </form> <script type="text/javascript"> var infolinks_pid = 3084238; var infolinks_wsid = 0; </script> <script type="text/javascript" src="//resources.infolinks.com/js/infolinks_main.js"></script> ''' else: try: video = pafy.new(request.form["urld"]) if not request.form["filetype"] in ["m4a", "mp3"]: best = video.getbest(preftype=request.form["filetype"]) filename = best.download(filepath=(pa + "/static/" + "dlfile")) else: best = video.getbestaudio(preftype=request.form["filetype"]) filename = best.download(filepath=(pa + "/static/" + "dlfile")) #filename = best.download(filepath="/home/Pythonsnake2017/mysite/templates/file1.html",quiet=False) return ''' <h1>FILE DONE</h1> <script type="text/javascript"> var adfly_id = 19279991; var popunder_frequency_delay = 0; </script> <script src="https://apis.google.com/js/platform.js" async defer></script> <div class="g-savetodrive" data-src="http://pythonsnake2017.pythonanywhere.com/static/dlfile" data-filename="youtubedl" data-sitename="PYTHON 3 Download url"> </div> <h1>''' + video.title + '''</h1> </p>''' + video.description + ''' <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <a href="/delete1"> Delete when I'm done</a> <p> Alternative link</p> <a href="/static/file1.html">LINK 2</a> <div class="g-savetodrive" data-src="http://pythonsnake2017.pythonanywhere.com/getfile" data-filename="Downloadedfile" data-sitename="PYTHON 3 Download url"> </div> <a href="/getfile">DIRECT LINK download</a> <video height=600 width=800 controls> <source src="/static/file1.html" type="video/mp4"> </video> <script type="text/javascript"> var infolinks_pid = 3084238; var infolinks_wsid = 0; </script> <script type="text/javascript" src="//resources.infolinks.com/js/infolinks_main.js"></script> ''' except Exception as e: return str(e) + str(type(request.form["urld"]))
def on_enter(self, payload=None): """This method is executed on entry to Busy State. SUSI API is called via SUSI Python library to fetch the result. We then call TTS to speak the reply. If successful, we transition to Idle State else to the Error State. :param payload: query to be asked to SUSI :return: None """ try: import RPi.GPIO as GPIO GPIO.output(17, True) reply = self.components.susi.ask(payload) GPIO.output(17, False) GPIO.output(27, True) if self.components.renderer is not None: self.notify_renderer('speaking', payload={'susi_reply': reply}) if 'answer' in reply.keys(): print('Susi:' + reply['answer']) self.__speak(reply['answer']) else: self.__speak("I don't have an answer to this") if 'identifier' in reply.keys(): classifier = reply['identifier'] if classifier[:3] == 'ytd': audio_url = reply['identifier'] # bandit -s B605 video = pafy.new(audio_url[4:]) vid_len = video.length buffer_len = '' if 0.07 * vid_len >= 10: buffer_len = 10 else: buffer_len = 0.07 * vid_len os.system('timeout {} tizonia --youtube-audio-stream '.format(buffer_len) + audio_url[4:]) # nosec #pylint-disable type: ignore else: audio_url = reply['identifier'] # bandit -s B605 os.system('play ' + audio_url[6:]) # nosec #pylint-disable type: ignore if 'volume' in reply.keys(): subprocess.call(["amixer", "-D", "pulse", "sset", "Master", str(reply['volume'])]) # nosec #pylint-disable type: ignore if 'table' in reply.keys(): table = reply['table'] for h in table.head: print('%s\t' % h, end='') self.__speak(h) print() for datum in table.data[0:4]: for value in datum: print('%s\t' % value, end='') self.__speak(value) print() if 'rss' in reply.keys(): rss = reply['rss'] entities = rss['entities'] count = rss['count'] for entity in entities[0:count]: print(entity.title) self.__speak(entity.title) self.transition(self.allowedStateTransitions.get('idle')) except ConnectionError: self.transition(self.allowedStateTransitions.get( 'error'), payload='ConnectionError') except Exception as e: print(e) self.transition(self.allowedStateTransitions.get('error'))
link_length = len(link) if link_length == 68: print('Processing, Please Wait...') link_detector = link[34:68] videos = requests.get( f'https://youtube.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails&maxResults=50&playlistId={link_detector}&key={youtube_api_key}' ) videolist = videos.json() videolistarray = videolist['items'] first_video = videolistarray[0]['contentDetails']['videoId'] total_video_length = 0 for video in videolistarray: x = (video['contentDetails']['videoId']) video = pafy.new(x) video_length = video.length total_video_length += video_length os.system(f"open {browser_location}") time.sleep(10) pyautogui.write( f'https://www.youtube.com/watch?v={first_video}&list={link_detector}') pyautogui.press('enter') print('done') elif link_length == 43: link_detector = link[32:43]
import pafy from datetime import datetime from constants import * query_file = list(open('../new_url.txt', 'r')) query_list = [query_item.strip() for query_item in query_file] track_file = list(open('../track.txt', 'r')) track_list = [track_item.strip() for track_item in track_file] url_head = "https://www.youtube.com/watch?v=" for url in query_list: if len(url) == 11 and url not in track_list: url_full = url_head + url video = pafy.new(url_full) print (video.title) month_date = datetime.today().strftime('%m%d') best_audio_stream = video.getbestaudio() audio_path = AUDIO_PATH + month_date + '_' + video.title + '.' + best_audio_stream.extension best_audio_stream.download(audio_path) track_list.append(url) track_file = open('../track.txt', 'w') for url in track_list: track_file.write(url + '\n') track_file.close()
async def youtube_music(_, message): args = message.text.split(None, 1) if len(args) == 1: await edrep(message, text="Send URL here!") return teks = args[1] try: video = pafy.new(teks) except ValueError: await edrep(message, text="Invaild URL!") return try: audios = [audio for audio in video.audiostreams] audios.sort(key=lambda a: (int(a.quality.strip("k")) * -1)) music = audios[0] text = "[](https://i.ytimg.com/vi/{}/0.jpg)🎬 **Title:** [{}]({})\n".format( video.videoid, escape_markdown(video.title), video.watchv_url) text += "👤 **Author:** `{}`\n".format(video.author) text += "🕦 **Duration:** `{}`\n".format(video.duration) origtitle = re.sub(r'[\\/*?:"<>|\[\]]', "", str(music.title + "." + music._extension)) musictitle = re.sub(r'[\\/*?:"<>|\[\]]', "", str(music.title)) musicdate = video._ydl_info["upload_date"][:4] r = requests.get( f"https://i.ytimg.com/vi/{video.videoid}/maxresdefault.jpg", stream=True) if r.status_code != 200: r = requests.get( f"https://i.ytimg.com/vi/{video.videoid}/hqdefault.jpg", stream=True) if r.status_code != 200: r = requests.get( f"https://i.ytimg.com/vi/{video.videoid}/sddefault.jpg", stream=True) if r.status_code != 200: r = requests.get( f"https://i.ytimg.com/vi/{video.videoid}/mqdefault.jpg", stream=True) if r.status_code != 200: r = requests.get( f"https://i.ytimg.com/vi/{video.videoid}/default.jpg", stream=True) if r.status_code != 200: avthumb = False if r.status_code == 200: avthumb = True with open("naruto/cache/thumb.jpg", "wb") as stk: shutil.copyfileobj(r.raw, stk) try: os.remove(f"naruto/downloads/{origtitle}") except FileNotFoundError: pass # music.download(filepath="naruto/downloads/{}".format(origtitle)) if "manifest.googlevideo.com" in music.url: download = await download_url(music._info["fragment_base_url"], origtitle) else: download = await download_url(music.url, origtitle) if download == "Failed to download file\nInvaild file name!": return await edrep(message, text=download) try: subprocess.Popen("ffmpeg", stdout=subprocess.PIPE, stderr=subprocess.PIPE) except Exception as err: if "The system cannot find the file specified" in str( err) or "No such file or directory" in str(err): await edrep( message, text= "You need to install ffmpeg first!\nCheck your assistant for more information!", ) await setbot.send_message( message.from_user.id, "Hello 🙂\nYou need to install ffmpeg to make audio works better, here is guide how to install it:\n\n**If you're using linux**, go to your terminal, type:\n`sudo apt install ffmpeg`\n\n**If you're using Windows**, download ffmpeg here:\n`https://ffmpeg.zeranoe.com/builds/`\nAnd then extract (if was archive), and place ffmpeg.exe to workdir (in current dir)\n\n**If you're using heroku**, type this in your workdir:\n`heroku buildpacks:add https://github.com/jonathanong/heroku-buildpack-ffmpeg-latest.git`\nOr if you not using heroku term, follow this guide:\n1. Go to heroku.com\n2. Go to your app in heroku\n3. Change tabs/click Settings, then search for Buildpacks text\n4. Click button Add build pack, then type `https://github.com/jonathanong/heroku-buildpack-ffmpeg-latest`\n5. Click Save changes, and you need to rebuild your heroku app to take changes!\n\nNeed help?\nGo @TitanSupportGroup and ask there", ) return if avthumb: os.system( f'ffmpeg -loglevel panic -i "naruto/downloads/{origtitle}" -i "naruto/cache/thumb.jpg" -map 0:0 -map 1:0 -c copy -id3v2_version 3 -metadata:s:v title="Album cover" -metadata:s:v comment="Cover (Front)" -metadata title="{music.title}" -metadata author="{video.author}" -metadata album="{video.author}" -metadata album_artist="{video.author}" -metadata genre="{video._category}" -metadata date="{musicdate}" -acodec libmp3lame -aq 4 -y "naruto/downloads/{musictitle}.mp3"' ) else: os.system( f'ffmpeg -loglevel panic -i "naruto/downloads/{origtitle}" -metadata title="{music.title}" -metadata author="{video.author}" -metadata album="{video.author}" -metadata album_artist="{video.author}" -metadata genre="{video._category}" -metadata date="{musicdate}" -acodec libmp3lame -aq 4 -y "naruto/downloads/{musictitle}.mp3"' ) try: os.remove("naruto/downloads/{}".format(origtitle)) except FileNotFoundError: pass getprev = requests.get(video.thumb, stream=True) with open("naruto/cache/prev.jpg", "wb") as stk: shutil.copyfileobj(getprev.raw, stk) await naruto.send_audio( message.chat.id, audio=f"naruto/downloads/{musictitle}.mp3", thumb="naruto/cache/prev.jpg", title=music.title, caption=f"🕦 `{video.duration}`", reply_to_message_id=message.message_id, ) try: os.remove("naruto/cache/prev.jpg") except FileNotFoundError: pass try: os.remove("naruto/cache/thumb.jpg") except FileNotFoundError: pass titletext = "**Done! 🤗**\n" await edrep(message, text=titletext + text, disable_web_page_preview=True) except Exception as err: if "command not found" in str(err) or "is not recognized" in str(err): await edrep( message, text= "You need to install ffmpeg first!\nCheck your assistant for more information!", ) await setbot.send_message( message.from_user.id, "Hello 🙂\nYou need to install ffmpeg to make audio works better, here is guide " "how to install it:\n\n**If you're using linux**, go to your terminal, " "type:\n`sudo apt install ffmpeg`\n\n**If you're using Windows**, download " "ffmpeg here:\n`https://ffmpeg.zeranoe.com/builds/`\nAnd then extract (if was " "archive), and place ffmpeg.exe to workdir (in current dir)\n\n**If you're using " "heroku**, type this in your workdir:\n`heroku buildpacks:add " "https://github.com/jonathanong/heroku-buildpack-ffmpeg-latest.git`\nOr if you " "not using heroku term, follow this guide:\n1. Go to heroku.com\n2. Go to your " "app in heroku\n3. Change tabs/click Settings, then search for Buildpacks " "text\n4. Click button Add build pack, then type " "`https://github.com/jonathanong/heroku-buildpack-ffmpeg-latest`\n5. Click Save " "changes, and you need to rebuild your heroku app to take changes!\n\nNeed " "help?\nGo to Titan Support and ask there", ) return exc_type, exc_obj, exc_tb = sys.exc_info() errors = traceback.format_exception(etype=exc_type, value=exc_obj, tb=exc_tb) await edrep( message, text= "**An error has accured!**\nCheck your assistant for more information!", ) button = InlineKeyboardMarkup([[ InlineKeyboardButton("🐞 Report bugs", callback_data="report_errors") ]]) await setbot.send_message( message.from_user.id, "**An error has accured!**\n```{}```".format("".join(errors)), reply_markup=button, ) logging.exception("Execution error")
run_once8 = 0 # 9:20-9:30 future = datetime.datetime.now() + datetime.timedelta( seconds=600 ) # this is the future I stored the first delta in here (put the first interval time in here) print("The Program is starting") time.sleep(3) while True: # make a eternal loop if datetime.datetime.now() < future: for music in store: # loop for each music in the list if datetime.datetime.now( ) < future: # if the time at the start of the loop is less than the future the music is gona start video = pafy.new(music) delay = video.length + 5 # delay of each music passing through the loop Popen(['start', 'chrome', music], shell=True) # opens in the browser print("Waiting ", delay, " seconds for the music to stop") time.sleep(delay) Popen('taskkill /F /IM chrome.exe', shell=True) # closes the browser # 10:20-10:35 future2 = datetime.datetime.now() + datetime.timedelta( seconds=3905 ) # defines the second future (delta time of the delay[this is the lenght of the break - 10min but needs to be added the class duration. 10min in seconds + 50min in seconds + 5s of delay) print( "This is the datetime of future2: ", datetime.datetime.now() ) # just to check if everything is going according to plan (to be deleted)
async def _play(self, ctx: commands.Context, *args): """Play audio form youtube. Uses first result of a youtube search.""" if len(args) == 0: await ctx.send("pierdol sie") else: if not ctx.message.author.voice: await ctx.send("You need to be in a vc to use this command") else: channel = ctx.message.author.voice.channel check_bot_vclist = len(self.bot.voice_clients) != 0 if check_bot_vclist: while not self.voice: await asyncio.sleep(1) if check_bot_vclist and self.voice.channel is not channel: await ctx.send("youre in a wrong vc f**k oof") else: video_id = None if len(args) == 1: web_link_regex_long = r'(https://)?(www\.)?youtube\.com/watch\?.*v=(\S{11}).*' web_link_regex_short = r'(https://)?youtu\.be/(\S{11}).*' match_long = re.match(web_link_regex_long, args[0]) match_short = re.match(web_link_regex_short, args[0]) if match_long != None: video_id = match_long[3] elif match_short != None: video_id = match_short[2] if video_id == None: search = "" for x in args: search = search + str(x) + "+" html = urllib.request.urlopen( "https://www.youtube.com/results?search_query=" + search) video_id = re.findall(r"watch\?v=(\S{11})", html.read().decode())[0] song = pafy.new(video_id) self.queue.append(song) if len(self.bot.voice_clients) != 0: embed_title = "Postion " + str(len( self.queue)) + " in queue" e = discord.Embed( title=embed_title, description= f"Title: *** {song.title} *** \nTime: {song.duration}", url=song.watchv_url) e.set_thumbnail(url=song.bigthumb) await ctx.send(embed=e) else: self.voice = await channel.connect() while len(self.queue) > 0: poped_song = self.queue.pop(0) url = poped_song.getbestaudio().url e = discord.Embed( title='Now playing', description= f"Title: *** {poped_song.title} *** \nTime: {poped_song.duration}", url=poped_song.watchv_url) e.set_thumbnail(url=poped_song.bigthumb) await ctx.send(embed=e) source = discord.FFmpegPCMAudio( url, **FFMPEG_OPTIONS) self.voice.play(source) while self.voice.is_playing( ) or self.voice.is_paused(): await asyncio.sleep(1) await self.voice.disconnect() self.voice = None
def downloader(): new_url = link.get() video = pafy.new(new_url) s = video.getbest() s.download()