From eee39a5190f0a9847750e0acadf197dcfadbeb82 Mon Sep 17 00:00:00 2001 From: SamlonDev Date: Tue, 20 May 2025 14:18:02 +0200 Subject: remake web.py --- cogs/web.py | 82 +++++++++++++++++++++++++++++-------------------------------- 1 file changed, 39 insertions(+), 43 deletions(-) (limited to 'cogs') diff --git a/cogs/web.py b/cogs/web.py index 5e9d069..bea684b 100644 --- a/cogs/web.py +++ b/cogs/web.py @@ -1,4 +1,5 @@ import discord +from discord import Embed from discord.ext import commands import requests from bs4 import BeautifulSoup @@ -9,53 +10,48 @@ class Web(commands.Cog): def __init__(self, bot): self.bot = bot - @commands.command(name='web', description='Search the web using DuckDuckGo') - async def web(self, ctx, *, query: str): - """Search the web using DuckDuckGo and return top results.""" - message = await ctx.send("🔍 Searching the web...") - + @commands.slash_command( + name="web", + description="Search the web using DuckDuckGo" + ) + async def web( + self, + ctx: discord.ApplicationContext, + query: str + ): + await ctx.defer(ephemeral=True) headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} url = f"https://duckduckgo.com/html/?q={query}" - - try: - response = requests.get(url, headers=headers) - response.raise_for_status() - + response = requests.get(url, headers=headers) + + if response.status_code == 200: soup = BeautifulSoup(response.text, 'html.parser') links = soup.find_all('a', class_='result__a') - - if not links: - return await message.edit(content="❌ No results found.") - - # Create a list of results - results = [] - for i, link in enumerate(links[:5], start=1): - title = link.text.strip() - href = link.get('href', '') - - # Handle YouTube links specially - if href.startswith('https://www.youtube.com/'): - try: - video_id = urllib.parse.parse_qs( - urllib.parse.urlparse(href).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 as e: - print(f"Error fetching YouTube title: {e}") - - results.append(f"**{i}.** [{title}]({href})") - - # Send the results - results_text = "\n\n".join(results) - await message.edit(content=f"🔍 **Search results for: {query}**\n\n{results_text}") - - except requests.RequestException as e: - await message.edit(content=f"❌ Error performing search: {e}") - except Exception as e: - await message.edit(content=f"❌ An unexpected error occurred: {e}") + 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/'): + 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) + else: + await ctx.respond(content="No results found.", ephemeral=True) + else: + await ctx.respond(content=f"Error: {response.status_code}", ephemeral=True) def setup(bot): bot.add_cog(Web(bot)) -- cgit v1.2.3