From 72abc43db8f732743c65d6f6a820369ab8665766 Mon Sep 17 00:00:00 2001 From: salmonik Date: Wed, 4 Feb 2026 16:19:22 +0100 Subject: more asynchronous work and other minor improvements --- cogs/web.py | 89 +++++++++++++++++++++++++++++++++++++++---------------------- 1 file changed, 57 insertions(+), 32 deletions(-) (limited to 'cogs/web.py') diff --git a/cogs/web.py b/cogs/web.py index a9f8fbb..fcec8f9 100644 --- a/cogs/web.py +++ b/cogs/web.py @@ -18,6 +18,49 @@ class Web(commands.Cog): def __init__(self, bot): self.bot = bot + def _extract_youtube_title(self, url): + """Extract YouTube video title if URL is a YouTube link.""" + if not url.startswith('https://www.youtube.com/'): + return None + + logger.info("youtube link") + try: + parsed_url = urllib.parse.urlparse(url) + video_id = urllib.parse.parse_qs(parsed_url.query).get('v', [None])[0] + if video_id: + yt = pytube.YouTube(f'https://www.youtube.com/watch?v={video_id}') + return yt.title + except Exception: + pass + return None + + def _create_button(self, index, link): + """Create a button for sending search result.""" + button = discord.ui.Button(label=f"Send Result {index}") + + async def button_callback(interaction: discord.Interaction): + await interaction.response.send_message(link.get('href')) + + button.callback = button_callback + return button + + def _process_search_results(self, links, query): + """Process search results and create embed with buttons.""" + embed = Embed(title="Search Results", description=f"Top results for: {query}", color=0x1E90FF) + view = discord.ui.View(disable_on_timeout=True) + + for i, link in enumerate(links[:5], start=1): + title = link.text + youtube_title = self._extract_youtube_title(link.get('href')) + if youtube_title: + title = youtube_title + + embed.add_field(name=f"Result {i}", value=f"[{title}]({link.get('href')})", inline=False) + button = self._create_button(i, link) + view.add_item(button) + + return embed, view + @commands.slash_command( name="web", description="Search the web using DuckDuckGo" @@ -35,40 +78,22 @@ class Web(commands.Cog): logger.info(f"Query: {query}") - if response.status_code == 200: - soup = BeautifulSoup(response.text, 'html.parser') - links = soup.find_all('a', class_='result__a') - if links: - embed = Embed(title="Search Results", description=f"Top results for: {query}", color=0x1E90FF) - view = discord.ui.View(disable_on_timeout=True) - for i, link in enumerate(links[:5], start=1): - title = link.text - if link.get('href').startswith('https://www.youtube.com/'): - logger.info("youtube link") - try: - parsed_url = urllib.parse.urlparse(link.get('href')) - video_id = urllib.parse.parse_qs(parsed_url.query).get('v', [None])[0] - if video_id: - yt = pytube.YouTube(f'https://www.youtube.com/watch?v={video_id}') - title = yt.title - except Exception: - pass - - embed.add_field(name=f"Result {i}", value=f"[{title}]({link.get('href')})", inline=False) - button = discord.ui.Button(label=f"Send Result {i}") - - async def button_callback(interaction: discord.Interaction, link=link): - await interaction.response.send_message(link.get('href')) - button.callback = button_callback - view.add_item(button) - await ctx.respond(embed=embed, view=view, ephemeral=True) - logger.info("Search results sent") - else: - await ctx.respond(content="No results found.", ephemeral=True) - logger.warning("No results found") - else: + if response.status_code != 200: await ctx.respond(content=f"Error: {response.status_code}", ephemeral=True) logger.error(f"Error: {response.status_code}") + return + + soup = BeautifulSoup(response.text, 'html.parser') + links = soup.find_all('a', class_='result__a') + + if not links: + await ctx.respond(content="No results found.", ephemeral=True) + logger.warning("No results found") + return + + embed, view = self._process_search_results(links, query) + await ctx.respond(embed=embed, view=view, ephemeral=True) + logger.info("Search results sent") def setup(bot): bot.add_cog(Web(bot)) -- cgit v1.2.3