Added youtube_search method

This commit is contained in:
Lukas Blacha
2023-02-08 12:47:08 +01:00
parent 6993fde7d8
commit 53f175379f

View File

@@ -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
)