aboutsummaryrefslogtreecommitdiffstats
path: root/cogs/web.py
blob: 5e9d06950cd839c566634b93c460eb08ba94dac9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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))