From 53f175379f7491e7fd62b0544d00b006796c650b Mon Sep 17 00:00:00 2001 From: Lukas Blacha Date: Wed, 8 Feb 2023 12:47:08 +0100 Subject: [PATCH] Added youtube_search method --- Music-Bot.py | 40 +++++++++++++--------------------------- 1 file changed, 13 insertions(+), 27 deletions(-) diff --git a/Music-Bot.py b/Music-Bot.py index fd5c5ec..22ad30f 100644 --- a/Music-Bot.py +++ b/Music-Bot.py @@ -87,20 +87,17 @@ else: before_options="-threads 2", options=ffmpeg_options), data=data) - class Youtube(discord.ui.View): - def __init__(self, query: str): - super().__init__() - # We need to quote the query string to make a valid url. Discord will raise an error if it isn't valid. - query = quote_plus(query) - url = f"https://www.youtube.com/results?search_query={query}" - - # Link buttons cannot be made with the - # decorator, so we have to manually create one. - # We add the quoted url to the button, and add the button to the view. - self.add_item(discord.ui.Button(label="Click Here", url=url)) - - # Initializing the view and adding the button can actually be done in a one-liner at the start if preferred: - # super().__init__(discord.ui.Button(label="Click Here", url=url)) + async def youtube_search(search: str): + p = {"search_query": search} + # Spoof a user agent header or the request will immediately fail + h = {"User-Agent": "Mozilla/5.0"} + async with aiohttp.ClientSession() as client: + async with client.get("https://www.youtube.com/results", params=p, headers=h) as resp: + dom = await resp.text() + open("debug.html", "w").write(dom) + found = re.findall(r"watch\?v=(\S{11})", dom)[0] + url = f"https://www.youtube.com/watch?v={found}" + return url intents = discord.Intents.default() @@ -220,22 +217,11 @@ else: @bot.slash_command() - async def youtube(ctx, *, search): - p = {"search_query": search} - # Spoof a user agent header or the request will immediately fail - h = {"User-Agent": "Mozilla/5.0"} - async with aiohttp.ClientSession() as client: - async with client.get("https://www.youtube.com/results", params=p, headers=h) as resp: - dom = await resp.text() - open("debug.html", "w").write(dom) - found = re.findall(r"watch\?v=(\S{11})", dom)[0] - url = f"https://www.youtube.com/watch?v={found}" - print(url) - + async def youtube(ctx, *, search: str): async with ctx.typing(): await ctx.respond("🤖 Your song is queued for download... please wait ", ephemeral=True) try: - player = await YTDLSource.from_url(url, loop=bot.loop) + player = await YTDLSource.from_url(youtube_search(search=search), loop=bot.loop) ctx.voice_client.play( player, after=lambda e: print(f"Player error: {e}") if e else None )