aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--cogs/web.py61
1 files changed, 61 insertions, 0 deletions
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 @@
1import discord
2from discord.ext import commands
3import requests
4from bs4 import BeautifulSoup
5import urllib.parse
6import pytube
7
8class Web(commands.Cog):
9 def __init__(self, bot):
10 self.bot = bot
11
12 @commands.command(name='web', description='Search the web using DuckDuckGo')
13 async def web(self, ctx, *, query: str):
14 """Search the web using DuckDuckGo and return top results."""
15 message = await ctx.send("🔍 Searching the web...")
16
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'}
18 url = f"https://duckduckgo.com/html/?q={query}"
19
20 try:
21 response = requests.get(url, headers=headers)
22 response.raise_for_status()
23
24 soup = BeautifulSoup(response.text, 'html.parser')
25 links = soup.find_all('a', class_='result__a')
26
27 if not links:
28 return await message.edit(content="❌ No results found.")
29
30 # Create a list of results
31 results = []
32 for i, link in enumerate(links[:5], start=1):
33 title = link.text.strip()
34 href = link.get('href', '')
35
36 # Handle YouTube links specially
37 if href.startswith('https://www.youtube.com/'):
38 try:
39 video_id = urllib.parse.parse_qs(
40 urllib.parse.urlparse(href).query
41 ).get('v', [None])[0]
42
43 if video_id:
44 yt = pytube.YouTube(f'https://www.youtube.com/watch?v={video_id}')
45 title = yt.title
46 except Exception as e:
47 print(f"Error fetching YouTube title: {e}")
48
49 results.append(f"**{i}.** [{title}]({href})")
50
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
60def setup(bot):
61 bot.add_cog(Web(bot))