Example #1
0
def run(command, args, voice_instance):
    if command == "play":
        search_query = " ".join(args)
        result = YoutubeSearch(search_query, max_results=10).to_dict()[0]

        video_title = result["title"]
        url_suffix = result["url_suffix"]

        url = f"https://www.youtube.com/{url_suffix}"
        video = pafy.new(url)
        best = video.getbest()
        play_url = best.url

        voice_instance.say(f"playing {video_title}")
        voice_instance.play_media(play_url)
Example #2
0
 async def play(self, ctx, *, message):
     song_there = os.path.isfile(r"./music_download1.mp3")
     try:
         if song_there:
             os.remove(r"./music_download1.mp3")
     except PermissionError:
         await ctx.send("Song already playing!")
     results = YoutubeSearch(str(message), max_results=1).to_dict()
     id = results[0].get("id")
     id = "https://www.youtube.com/watch?v=" + str(id)
     with youtube_dl.YoutubeDL(ydl_opts) as ydl:
         ydl.download([id])
     voice = await ctx.author.voice.channel.connect()
     await voice.play(discord.FFmpegPCMAudio(r"./music_download1.mp3"))
     await ctx.send("Playback Started!")
Example #3
0
async def yt_search(video_q):
    query = video_q.pattern_match.group(1)
    if not query:
        await video_q.edit("`Enter query to search`")
    await video_q.edit("`Processing...`")
    try:
        results = json.loads(YoutubeSearch(query, max_results=7).to_json())
    except KeyError:
        return await video_q.edit(
            "`Youtube Search gone retard.\nCan't search this query!`")
    output = f"**Search Query:**\n`{query}`\n\n**Results:**\n\n"
    for i in results["videos"]:
        output += (
            f"● `{i['title']}`\nhttps://www.youtube.com{i['url_suffix']}\n\n")
    await video_q.edit(output, link_preview=False)
Example #4
0
    async def ytcmd(self, message):
        """текст или реплай"""
        text = utils.get_args_raw(message)
        if not text:
            reply = await message.get_reply_message()
            if not reply:
                await message.delete()
                return
            text = reply.raw_text
        results = YoutubeSearch(text, max_results=10).to_dict()
        out = f'Найдено по запросу: {text}'
        for r in results:
            out += f'\n\n<a href="https://www.youtube.com/{r["link"]}">{r["title"]}</a>'

        await message.edit(out)
Example #5
0
async def yt_search(video_q):
    query = video_q.pattern_match.group(1)
    if not query:
        await video_q.edit("`Enter query to search`")
    await video_q.edit("`Processing...`")
    try:
        results = json.loads(YoutubeSearch(query, max_results=7).to_json())
    except KeyError:
        return await video_q.edit(
            "`Pencarian Youtube menjadi lambat.\nTidak dapat mencari kueri ini!`"
        )
    output = f"**Kueri Pencarian:**\n`{query}`\n\n**Hasil:**\n\n"
    for i in results["videos"]:
        output += f"● `{i['title']}`\nhttps://www.youtube.com{i['url_suffix']}\n\n"
    await video_q.edit(output, link_preview=False)
Example #6
0
async def inline_id_handler(event: events.InlineQuery.Event):
    builder = event.builder
    testinput = event.pattern_match.group(1)
    urllib.parse.quote_plus(testinput)
    results = []
    moi = YoutubeSearch(testinput, max_results=9).to_dict()
    if not moi:
        resultm = builder.article(
            title="No Results Found.",
            description="Check Your Spelling / Keyword",
            text="**Please, Search Again With Correct Keyword, Thank you !**",
            buttons=[
                [
                    Button.switch_inline("Search Again",
                                         query="yt ",
                                         same_peer=True)
                ],
            ],
        )
        await event.answer([resultm])
        return
    for moon in moi:
        hmm = moon["id"]
        mo = f"https://www.youtube.com/watch?v={hmm}"
        kek = f"https://www.youtube.com/watch?v={hmm}"
        stark_name = moon["title"]
        stark_chnnl = moon["channel"]
        total_stark = moon["duration"]
        stark_views = moon["views"]
        moon["long_desc"]
        kekme = f"https://img.youtube.com/vi/{hmm}/hqdefault.jpg"
        okayz = f"**Title :** `{stark_name}` \n**Link :** `{kek}` \n**Channel :** `{stark_chnnl}` \n**Views :** `{stark_views}` \n**Duration :** `{total_stark}`"
        hmmkek = f"Video Name : {stark_name} \nChannel : {stark_chnnl} \nDuration : {total_stark} \nViews : {stark_views}"
        results.append(await event.builder.document(
            file=kekme,
            title=stark_name,
            description=hmmkek,
            text=okayz,
            include_media=True,
            buttons=[
                [
                    Button.switch_inline("Search Again",
                                         query="yt ",
                                         same_peer=True)
                ],
            ],
        ))
    await event.answer(results)
Example #7
0
async def ytplay(requested_by, query):
    global playing
    ydl_opts = {"format": "bestaudio"}
    m = await app.send_message(sudo_chat_id,
                               text=f"Searching for `{query}` on YouTube")
    try:
        results = YoutubeSearch(query, max_results=1).to_dict()
        link = f"https://youtube.com{results[0]['url_suffix']}"
        title = results[0]["title"]
        thumbnail = results[0]["thumbnails"][0]
        duration = results[0]["duration"]
        views = results[0]["views"]
        if time_to_seconds(duration) >= 1800:  # duration limit
            await m.edit("Bruh! Only songs within 30 Mins")
            playing = False
            return
    except Exception as e:
        await m.edit(
            "Found Literally Nothing!, You Should Work On Your English.")
        playing = False
        print(str(e))
        return
    await m.edit("Processing Thumbnail.")
    await generate_cover(requested_by, title, views, duration, thumbnail)
    await m.edit("Downloading Music.")
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        info_dict = ydl.extract_info(link, download=False)
        audio_file = ydl.prepare_filename(info_dict)
        ydl.process_info(info_dict)
        os.rename(audio_file, "audio.webm")
    await m.delete()
    m = await app.send_photo(
        chat_id=sudo_chat_id,
        caption=f"Playing [{title}]({link}) Via YouTube",
        photo="final.png",
        reply_markup=InlineKeyboardMarkup(
            [[InlineKeyboardButton("Skip", callback_data="end")]]),
        parse_mode="markdown",
    )
    os.remove("final.png")
    s = await asyncio.create_subprocess_shell(
        "mpv audio.webm --no-video",
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
    )
    await s.wait()
    await m.delete()
    playing = False
def yt_search(term):
    """Efetua a busca no youtube pelo termo informado"""
    results = YoutubeSearch(term, max_results=10).to_dict()
    videos = [{
        'url': item['url_suffix'],
        'title': f"{item['title']} ({item['duration']})"
    } for item in results]
    for index, video in enumerate(videos):
        print(f'{index:02} - {video["title"]}')
    else:
        print()

    if not videos:
        print(f"* YOUTUBE NÃO RETORNOU DADOS PARA A PESQUISA '{term}'")

    return videos
Example #9
0
async def yt_search(video_q):
    """For .yt command, do a YouTube search from Telegram."""
    query = video_q.pattern_match.group(1)
    if not query:
        await video_q.edit("`Enter query to search`")
    await video_q.edit("`Processing...`")
    try:
        results = json.loads(YoutubeSearch(query, max_results=7).to_json())
    except KeyError:
        return await video_q.edit(
            "`Sorry master i couldn't find something related to this query!`"
        )
    output = f"**Search Query:**\n`{query}`\n\n**Results:**\n\n"
    for i in results["videos"]:
        output += f"--> `{i['title']}`\nhttps://www.youtube.com{i['url_suffix']}\n\n"
    await video_q.edit(output, link_preview=False)
Example #10
0
async def song_search(event, query, max_results, details=False):
    try:
        results = json.loads(
            YoutubeSearch(query, max_results=max_results).to_json())
    except KeyError:
        return await eor(event, "Unable to find relevant search query.")
    x = ""
    for i in results["videos"]:
        x += f"https://www.youtube.com{i['url_suffix']}\n"
        if details:
            title = f"{i['title']}"
            views = f"{i['views']}"
            duration = f"{i['duration']}"
            thumb = f"{i['thumbnails'][0]}"
            return x, title, views, duration, thumb
    return x
Example #11
0
async def hmm(ytwala):
    query = ytwala.pattern_match.group(1)
    if not query:
        await edit_or_reply(ytwala, "`Enter query to search`")
    await edit_or_reply(ytwala, "`Processing...`")
    try:
        results = json.loads(YoutubeSearch(query, max_results=7).to_json())
    except KeyError:
        return await edit_or_reply(
            ytwala, "Unable to find relevant search queries...")
    output = f"**Search Query:**\n`{query}`\n\n**Results:**\n\n"
    for i in results["videos"]:
        output += (
            f"--> `{i['title']}`\nhttps://www.youtube.com{i['url_suffix']}\n\n"
        )
    await edit_or_reply(ytwala, output, link_preview=False)
def get_song_link_youtube(song_name):
    print(song_name)
    """
    Takes a song name and returns a link to a youtube video with a given song
    :param song_name:
    :return: link to a video with given song
    """
    try:
        from youtube_search import YoutubeSearch
    except:
        print("[!] Please install required modules")
        exit()

    results = YoutubeSearch("pink floyd " + song_name, max_results=1).to_dict()

    return "https://www.youtube.com/" + results[0]["link"]
Example #13
0
def urlFromQuery(query):
    try:
        results = YoutubeSearch(query, max_results=5).to_json()
    except requests.exceptions.ConnectionError:
        print(
            "There was an error connecting to YouTube. Check Proxy/Internet settings."
        )
        sys.exit()
    data = json.loads(results)
    results = data['videos']
    videos = [v for v in results]
    for vid in videos:
        if "lyric" in vid['title'].lower():
            url = "https://www.youtube.com" + vid["link"]
            return url
    return "https://www.youtube.com" + videos[0]["link"]
def get_playlist_link_youtube(album_name):
    """
    Takes name of an music album and returns youtube link to is
    :param album_name:
    :return:
    """
    try:
        from youtube_search import YoutubeSearch
    except:
        print("[!] Please install required modules")
        exit()

    results = YoutubeSearch("pink floyd " + album_name + " playlist",
                            max_results=1).to_dict()

    return "https://www.youtube.com/" + results[0]["link"]
def search(strng):  #Fetch link
    os.system('cls')
    global title
    global yt_link
    #search_query = (input("Search for a video :  ")) -> depreciated
    try:
        search_result = YoutubeSearch(str(strng), max_results=1).to_dict()
        for results in search_result:
            for k, v in results.items():
                if k == 'url_suffix':
                    yt_link = (prefix_link + v)
                if k == 'title':
                    title = v
        window['status'].update("Ready: ✓")
    except:
        print("put something in the search field!")
Example #16
0
def add_playlist(request):
    cur_user = playlist_user.objects.get(username=request.user)

    if (request.POST['title'], ) not in cur_user.playlist_song_set.values_list(
            'song_title', ):

        songdic = (YoutubeSearch(request.POST['title'],
                                 max_results=1).to_dict())[0]
        song__albumsrc = songdic['thumbnails'][0]
        cur_user.playlist_song_set.create(
            song_title=request.POST['title'],
            song_dur=request.POST['duration'],
            song_albumsrc=song__albumsrc,
            song_channel=request.POST['channel'],
            song_date_added=request.POST['date'],
            song_youtube_id=request.POST['songid'])
Example #17
0
def find_youtube_urls(title):
	try:
		from youtube_search import YoutubeSearch 
	except ImportError:
		print("No module named 'youtube' found") 
	#print(title)
	#print("Sugesstion")
	# for q in search(query1, tld="com", num=10, stop=1, pause=2):
	# 	#print(q)
	# 	related_urls.append(q)
	results = YoutubeSearch(title,max_results=1).to_dict()
	sleep(3)
	print ("results:",results)
	print ("json: ",results[0]["link"])
	link_res = "https://youtube.com"+results[0]["link"]
	return link_res
Example #18
0
    async def play(self, ctx: Context, *, query: str = None):
        if not ctx.guild:
            raise OutOfServer()
        if not ctx.author.voice:
            raise OutOfVoiceChannel()

        guild: Guild = ctx.guild
        clients = self.clients

        if guild.id not in clients:
            client: VoiceClient = await ctx.author.voice.channel.connect()
            clients[guild.id] = client
        else:
            client = clients[guild.id]

        if not query:
            if client.is_paused():
                client.resume()
                await ctx.send(embed=alert("▶️ Resumed").get_embed())
                return
            raise InvalidArgs("Tell me what to play!")

        await ctx.send(embed=alert(f"🔎 Searching for '{query}'").get_embed())
        results = YoutubeSearch(query).to_dict()
        url = f"https://youtube.com{results[0]['url_suffix']}"
        title = results[0]["title"]

        player = await YTDLSource.from_url(url, loop=self.bot.loop)

        if results[0]["thumbnails"]:
            image = results[0]["thumbnails"][0]
        else:
            image = None

        await ctx.send(embed=Embed(
            f"Now playing {title}",
            description=url,
            colour=Colour.red(),
            image=image,
        ).get_embed())

        if client.is_playing():
            client.stop()

        client.play(player,
                    after=lambda e: print("Player error: %s" % e)
                    if e else None)
Example #19
0
    async def youtubesearch(self, ctx, *, searchterm):
        try:
            apikey = key
            results = YoutubeSearch(searchterm, max_results=10).to_json()
            thingy = json.loads(results)["videos"][0]["id"]
            thumbnail = json.loads(results)["videos"][0]["thumbnails"][0]
            link = f"https://www.youtube.com/watch?v={thingy}"
            data = requests.get(
                f"https://www.googleapis.com/youtube/v3/videos?part=contentDetails,statistics&id={thingy}&key={apikey}"
            ).json()
            try:
                views = data["items"][0]["statistics"]["viewCount"]
            except Exception:
                views = 0

            try:
                likes = data["items"][0]["statistics"]["likeCount"]
            except Exception:
                likes = 0
            try:
                dislikes = data["items"][0]["statistics"]["dislikeCount"]
            except Exception:
                dislikes = 0
            descriptiondata = requests.get(
                f"https://www.googleapis.com/youtube/v3/videos?part=snippet&id={thingy}&key={apikey}"
            ).json()
            try:
                description = descriptiondata["items"][0]["snippet"][
                    "description"]
                if len(description) > 1500:
                    description = "Description is too long to display"
            except Exception:
                description = "No Description"
            title = descriptiondata["items"][0]["snippet"]["title"]
            embed = discord.Embed(title=title,
                                  url=link,
                                  description=description,
                                  color=0xff0000)
            embed.set_thumbnail(url=thumbnail)
            embed.add_field(name="Stats",
                            value=f"This video ({title}) has **" +
                            str(f"{int(views):,}") + "** views, **" +
                            str(f"{int(likes):,}") + "** likes and **" +
                            str(f"{int(dislikes):,}") + "** dislikes")
            await ctx.send(embed=embed)
        except Exception as e:
            await ctx.send("An error occurred `" + str(e) + "`")
Example #20
0
async def yt_search(event):
    """ For .yt command, do a YouTube search from Telegram. """

    if event.is_reply and not event.pattern_match.group(2):
        query = await event.get_reply_message()
        query = str(query.message)
    else:
        query = str(event.pattern_match.group(2))

    if not query:
        return await event.edit(
            "**Responda a uma mensagem ou passe uma consulta para pesquisar!**"
        )

    await event.edit("**Processando...**")

    if event.pattern_match.group(1) != "":
        counter = int(event.pattern_match.group(1))
        if counter > 10:
            counter = int(10)
        if counter <= 0:
            counter = int(1)
    else:
        counter = int(3)

    try:
        results = json.loads(
            YoutubeSearch(query, max_results=counter).to_json())
    except KeyError:
        return await event.edit(
            "**Youtube está louco!.\nNão é possível pesquisar esta consulta!**"
        )

    output = f"**Consulta de pesquisa:**\n`{query}`\n\n**Resultados:**\n"

    for i in results["videos"]:
        try:
            title = i["title"]
            link = "https://youtube.com" + i["url_suffix"]
            channel = i["channel"]
            duration = i["duration"]
            views = i["views"]
            output += f"[{title}]({link})\nCanal: `{channel}`\nDuração: {duration} | {views}\n\n"
        except IndexError:
            break

    await event.edit(output, link_preview=False)
async def yt_search(event):
    """ For .yt command, do a YouTube search from Telegram. """

    if event.is_reply and not event.pattern_match.group(2):
        query = await event.get_reply_message()
        query = str(query.message)
    else:
        query = str(event.pattern_match.group(2))

    if not query:
        return await event.edit("`Reply to a message or pass a query to search!`")

    await event.edit("`Processing...`")

    if event.pattern_match.group(1) != "":
        counter = int(event.pattern_match.group(1))
        if counter > 10:
            counter = int(10)
        if counter <= 0:
            counter = int(1)
    else:
        counter = int(3)

    try:
        results = json.loads(
            YoutubeSearch(
                query,
                max_results=counter).to_json())
    except KeyError:
        return await event.edit(
            "`Youtube Search gone retard.\nCan't search this query!`"
        )

    output = f"**Search Query:**\n`{query}`\n\n**Results:**\n"

    for i in results["videos"]:
        try:
            title = i["title"]
            link = "https://youtube.com" + i["url_suffix"]
            channel = i["channel"]
            duration = i["duration"]
            views = i["views"]
            output += f"[{title}]({link})\nChannel: `{channel}`\nDuration: {duration} | {views}\n\n"
        except IndexError:
            break

    await event.edit(output, link_preview=False)
Example #22
0
async def ytp(client: Client, message_: Message):
    requested_by = message_.from_user.first_name
    chat_id=message_.chat.id
    text = message_.text.split(" ", 1)
    query = text[1]
    res = await message_.reply_text(f"Searching for `{query}` on You Tube")
    try:
        results = YoutubeSearch(query, max_results=1).to_dict()
        link = f"https://youtube.com{results[0]['url_suffix']}"
        title = results[0]["title"]
        thumbnail = results[0]["thumbnails"][0]
        duration = results[0]["duration"]
        views = results[0]["views"]
    except Exception as e:
        await res.edit(
            "Found Literally Nothing!, You Should Work On Your English."
        )
Example #23
0
def videoFunction(search, video_sentence_count, no_video):
    results = YoutubeSearch(search, max_results=no_video).to_json()
    results = json.loads(results)
    filtered_results = []
    for result in results['videos']:
        v = result['id']
        transcript_flag = True
        try:
            transcript_list = YouTubeTranscriptApi.list_transcripts(v)
        except:
            print("no transcripts")
            transcript_flag = False

        if transcript_flag:
            try:
                transcript = transcript_list.find_manually_created_transcript(
                    ['en', 'en-UK', 'en-US'])
            except:
                print("no transcript")
                transcript_flag = False

        if transcript_flag:
            transcript_proto = transcript.fetch()
            final_transcript = ''
            for obj in transcript_proto:
                final_transcript += obj['text'] + ' '

            key_words = keywords(final_transcript, ratio=0.1)

            parser = PlaintextParser.from_string(final_transcript,
                                                 Tokenizer("english"))
            stemmer = Stemmer(LANGUAGE)

            summarizer = Summarizer(stemmer)
            summarizer.stop_words = get_stop_words(LANGUAGE)

            summary = ''
            for sentence in summarizer(parser.document, video_sentence_count):
                summary += str(sentence)

            result['summary'] = summary
            result['id'] = result['id'].split('&')[0]
            result['keywords'] = key_words
            filtered_results.append(result)

    return filtered_results
Example #24
0
def youtube():
    from youtube_search import YoutubeSearch
    # search_terms=["malayalam funny","malayalam trending" ,"comedy malayalam", "fun"]
    # search_term=random.choice(search_terms)
    # results = YoutubeSearch(search_term, max_results=10).to_dict()
    count = 0
    for i in range(10):
        search_terms = [
            "malayalam trending",
            "fun",
            "laugh",
            "corona updates",
        ]
        search_term = random.choice(search_terms)
        results = YoutubeSearch(search_term, max_results=10).to_dict()
        title = results[i]["title"]
        channel = results[i]["channel"]
        views = results[i]["views"]
        print(type(views))
        views = str(views)
        if ',' in views.lower() or 'views' in views.lower():
            views = re.sub(",", "", views)
            views = re.sub(" views", "", views)
        print(views)
        views = (int(views) / 1000000)
        format(views, '.2f')
        views = (str(views) + " M")
        duration = results[i]["duration"]
        id = results[i]["id"]
        link = "https://www.youtube.com" + results[i]["url_suffix"]
        if verify("youtube", id) == False:
            message = title + "*\n➖️➖️➖️➖️➖️➖️➖️➖️➖️➖️\nChannel: " + channel + "\nViews: " + str(
                views) + "\nDuration: " + str(duration) + "\nLink: " + link
            admin("yt" + random_id(), "yt", message)
            # send_message(title+"\nChannel: "+channel+"\nViews: "+str(views)+"\nDuration: "+str(duration)+"\nLink: "+link)
            count += 1
            # if admin("yt"+random_id(),"yt",message):
            # 	print("reached nope")
            # 	count=0
            # 	continue
        else:
            continue
        if count == 3:
            msg = "end"
            admin(msg, msg, msg)
            break
Example #25
0
    async def get_youtube_url(self, search_param: str,
                              message: discord.Message) -> str:
        """
        Returns a YouTube url given search params and a discord Message object.

        :param search_param: The search parameters to use on YouTube
        :param message: A discord message object to respond to
        :return: A YouTube url to download songs from
        """
        response = json.loads(
            YoutubeSearch(search_param, max_results=1).to_json())['videos'][0]
        title = response['title']
        duration = response['duration']
        url_suffix = response['url_suffix']
        url = 'https://www.youtube.com{}'.format(url_suffix)
        await message.channel.send(f'Found video: {title} ({duration})\n{url}')
        return url
Example #26
0
def update_tracks_with_urls(args):

	
	# IMPORTATION DES DISCOGRAPHIES
	tracks_filename = args.tracks_filename
	with open(tracks_filename) as json_file: 
		tracks = json.load(json_file)


	TRACKS_GOOD = []
	# FIND URLS
	for iditem,item in enumerate(tracks):

		if "youtube" not in item:

			artist = item["artist_str"]
			songname = item["name"]
			request = artist + " - " + songname
			#print(request,flush=True)
			
			try:
				search_results = YoutubeSearch(request, max_results=1).to_dict()
				item["youtube"] = search_results
				pct = round(((iditem+1)/len(tracks)),2) * 100
				pct = str(pct)+"%"
				to_print_a = "counter : " + str(iditem + 1) + "/" + str(len(tracks)) 
				to_print_b = "progression : " + pct
				to_print_c = request
				duration = search_results[0]["duration"]
				views = search_results[0]["views"]
				to_print_d = views + ", " + duration
				to_print = to_print_a + " | " + to_print_b + " | " + to_print_c + " | " + to_print_d
				print(to_print,flush=True)
				TRACKS_GOOD.append(item)
			except:
				to_print = "Cannot print, problem! request failed : " + request
				print(to_print,flush=True)

	# SAVE DISCOGRAPHIES
	print("Saving results in discographies json",flush=True)
	with open(tracks_filename, 'w') as outfile:
		json.dump(TRACKS_GOOD, outfile,indent=4, sort_keys=True)

	

	return None
Example #27
0
    def youtube(self, data):
        if not data["args"]:
            return "Error: youtube needs a message. Try: !h echo"

        try:
            title = " ".join(data["args"])
            result = YoutubeSearch(title, max_results=1).to_dict()
            if len(result) < 1:
                msg = "No videos found"
            else:
                msg = result[0][
                    "title"] + " : " + "https://youtube.com" + result[0][
                        "url_suffix"]
        except:
            msg = "No videos found"

        return msg
Example #28
0
def search(request):
    if request.method == 'POST':

        add_playlist(request)
        return HttpResponse("")
    try:
        search = request.GET.get('search')
        song = YoutubeSearch(search, max_results=10).to_dict()
        song_li = [song[:10:2], song[1:10:2]]
        # print(song_li)
    except:
        return redirect('/')

    return render(request, 'search.html', {
        'CONTAINER': song_li,
        'song': song_li[0][0]['id']
    })
Example #29
0
def download(arg):
    if re.compile(r'https?://(?:www\.)?.+').match(arg):
        r = requests.get(arg)
        title = fromstring(r.content).findtext('.//title')
        url = arg
    else:
        result = YoutubeSearch(arg, max_results=1).to_dict()[0]
        title = result['title']
        url = 'https://www.youtube.com' + result["url_suffix"]
    ydl_opts = {
        'outtmpl': f'songs/{title}.%(ext)s',
        'format': 'bestaudio/best',
    }
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download([url])

    return title
Example #30
0
async def play(ctx,*,query):
    search = YoutubeSearch(query,max_results=1).to_dict()[0]
    url = "https://youtube.com"+search["url_suffix"]
    voice_channel = ctx.author.voice.channel
    if voice_channel != None:
        ytdlpopen = subprocess.Popen(["youtube-dl","--quiet","--audio-format","flac","-o","-",url],stdout=subprocess.PIPE)
        try:
            vc = await voice_channel.connect()
        except:
            vc = ctx.guild.voice_client
        try:
            vc.play(discord.FFmpegOpusAudio(ytdlpopen.stdout,pipe=True))
            await ctx.reply(f"Playing `{search['title']}` by `{search['channel']}`")
        except discord.errors.ClientException:
            await ctx.send("Already playing a song!")
        while vc.is_playing():
            await asyncio.sleep(0.1)
        await vc.disconnect()