Changed Google-Search to Youtube (fix)

This commit is contained in:
Lukas Blacha
2023-02-08 12:39:56 +01:00
parent 08934559b8
commit e51f75c57c

View File

@@ -92,18 +92,7 @@ else:
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}"
p = {"search_query": query}
# Spoof a user agent header or the request will immediately fail
h = {"User-Agent": "Mozilla/5.0"}
with aiohttp.ClientSession() as client:
with client.get("https://www.youtube.com/results", params=p, headers=h) as resp:
dom = resp.text()
# open("debug.html", "w").write(dom)
found = re.findall(r'href"\/watch\?v=([a-zA-Z0-9_-]{11})', dom)
url = f"https://youtu.be/{found[0]}"
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.
@@ -231,9 +220,29 @@ else:
@bot.slash_command()
async def youtube(ctx: discord.ApplicationContext, query: str):
"""Returns a google link for a query."""
await ctx.respond(f"Google Result for: `{query}`", view=Youtube(query))
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)
print(re.findall(r"watch\?v=(\S{11})", dom))
found = re.findall(r"watch\?v=(\S{11})", dom)[0]
url = f"https://www.youtube.com/watch?v={found}"
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)
ctx.voice_client.play(
player, after=lambda e: print(f"Player error: {e}") if e else None
)
except discord.HTTPException as err:
raise commands.CommandError(err)
finally:
await ctx.send(f"{success}Now playing: `{player.title}`\nRequested by {ctx.author.mention}")
@play.before_invoke
@@ -247,7 +256,7 @@ else:
elif ctx.voice_client.is_playing():
ctx.voice_client.stop()
"""
@bot.event
async def on_application_command_error(ctx, error):
print(f"[on_application_command_error]\n{ctx.author}\n{error}")
@@ -272,6 +281,5 @@ else:
print(f"[on_command_error]\n{ctx.author}\n{error}")
embed = Embed(title=f"{error}", color=15158332)
await ctx.send(embed=embed)
"""
bot.run(token=args.token, reconnect=True)