diff options
| -rw-r--r-- | cogs/web.py | 82 |
1 files changed, 39 insertions, 43 deletions
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 @@ | |||
| 1 | import discord | 1 | import discord |
| 2 | from discord import Embed | ||
| 2 | from discord.ext import commands | 3 | from discord.ext import commands |
| 3 | import requests | 4 | import requests |
| 4 | from bs4 import BeautifulSoup | 5 | from bs4 import BeautifulSoup |
| @@ -9,53 +10,48 @@ class Web(commands.Cog): | |||
| 9 | def __init__(self, bot): | 10 | def __init__(self, bot): |
| 10 | self.bot = bot | 11 | self.bot = bot |
| 11 | 12 | ||
| 12 | @commands.command(name='web', description='Search the web using DuckDuckGo') | 13 | @commands.slash_command( |
| 13 | async def web(self, ctx, *, query: str): | 14 | name="web", |
| 14 | """Search the web using DuckDuckGo and return top results.""" | 15 | description="Search the web using DuckDuckGo" |
| 15 | message = await ctx.send("🔍 Searching the web...") | 16 | ) |
| 16 | 17 | async def web( | |
| 18 | self, | ||
| 19 | ctx: discord.ApplicationContext, | ||
| 20 | query: str | ||
| 21 | ): | ||
| 22 | await ctx.defer(ephemeral=True) | ||
| 17 | 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'} | 23 | 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'} |
| 18 | url = f"https://duckduckgo.com/html/?q={query}" | 24 | url = f"https://duckduckgo.com/html/?q={query}" |
| 19 | 25 | response = requests.get(url, headers=headers) | |
| 20 | try: | 26 | |
| 21 | response = requests.get(url, headers=headers) | 27 | if response.status_code == 200: |
| 22 | response.raise_for_status() | ||
| 23 | |||
| 24 | soup = BeautifulSoup(response.text, 'html.parser') | 28 | soup = BeautifulSoup(response.text, 'html.parser') |
| 25 | links = soup.find_all('a', class_='result__a') | 29 | links = soup.find_all('a', class_='result__a') |
| 26 | 30 | if links: | |
| 27 | if not links: | 31 | embed = Embed(title="Search Results", description=f"Top results for: {query}", color=0x1E90FF) |
| 28 | return await message.edit(content="❌ No results found.") | 32 | view = discord.ui.View(disable_on_timeout=True) |
| 29 | 33 | for i, link in enumerate(links[:5], start=1): | |
| 30 | # Create a list of results | 34 | title = link.text |
| 31 | results = [] | 35 | if link.get('href').startswith('https://www.youtube.com/'): |
| 32 | for i, link in enumerate(links[:5], start=1): | 36 | try: |
| 33 | title = link.text.strip() | 37 | parsed_url = urllib.parse.urlparse(link.get('href')) |
| 34 | href = link.get('href', '') | 38 | video_id = urllib.parse.parse_qs(parsed_url.query).get('v', [None])[0] |
| 35 | 39 | if video_id: | |
| 36 | # Handle YouTube links specially | 40 | yt = pytube.YouTube(f'https://www.youtube.com/watch?v={video_id}') |
| 37 | if href.startswith('https://www.youtube.com/'): | 41 | title = yt.title |
| 38 | try: | 42 | except Exception: |
| 39 | video_id = urllib.parse.parse_qs( | 43 | pass |
| 40 | urllib.parse.urlparse(href).query | 44 | embed.add_field(name=f"Result {i}", value=f"[{title}]({link.get('href')})", inline=False) |
| 41 | ).get('v', [None])[0] | 45 | button = discord.ui.Button(label=f"Send Result {i}") |
| 42 | 46 | async def button_callback(interaction: discord.Interaction, link=link): | |
| 43 | if video_id: | 47 | await interaction.response.send_message(link.get('href')) |
| 44 | yt = pytube.YouTube(f'https://www.youtube.com/watch?v={video_id}') | 48 | button.callback = button_callback |
| 45 | title = yt.title | 49 | view.add_item(button) |
| 46 | except Exception as e: | 50 | await ctx.respond(embed=embed, view=view, ephemeral=True) |
| 47 | print(f"Error fetching YouTube title: {e}") | 51 | else: |
| 48 | 52 | await ctx.respond(content="No results found.", ephemeral=True) | |
| 49 | results.append(f"**{i}.** [{title}]({href})") | 53 | else: |
| 50 | 54 | await ctx.respond(content=f"Error: {response.status_code}", ephemeral=True) | |
| 51 | # Send the results | ||
| 52 | results_text = "\n\n".join(results) | ||
| 53 | await message.edit(content=f"🔍 **Search results for: {query}**\n\n{results_text}") | ||
| 54 | |||
| 55 | except requests.RequestException as e: | ||
| 56 | await message.edit(content=f"❌ Error performing search: {e}") | ||
| 57 | except Exception as e: | ||
| 58 | await message.edit(content=f"❌ An unexpected error occurred: {e}") | ||
| 59 | 55 | ||
| 60 | def setup(bot): | 56 | def setup(bot): |
| 61 | bot.add_cog(Web(bot)) | 57 | bot.add_cog(Web(bot)) |
