From 1560cc34553068ad6c91ec7af9b81ecbce706189 Mon Sep 17 00:00:00 2001 From: SamlonDev Date: Tue, 20 May 2025 06:22:16 +0200 Subject: web search module --- cogs/web.py | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 cogs/web.py (limited to 'cogs/web.py') diff --git a/cogs/web.py b/cogs/web.py new file mode 100644 index 0000000..5e9d069 --- /dev/null +++ b/cogs/web.py @@ -0,0 +1,61 @@ +import discord +from discord.ext import commands +import requests +from bs4 import BeautifulSoup +import urllib.parse +import pytube + +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...") + + 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() + + 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}") + +def setup(bot): + bot.add_cog(Web(bot)) -- cgit v1.2.3