From a2b5b10625126b7e98643af9fe40569c9e004047 Mon Sep 17 00:00:00 2001 From: salmonik Date: Sat, 18 Apr 2026 00:24:50 +0200 Subject: refactor + preparing bot for public use Signed-off-by: salmonik --- cogs/web.py | 41 +++++++++++++++++++++-------------------- 1 file changed, 21 insertions(+), 20 deletions(-) (limited to 'cogs/web.py') diff --git a/cogs/web.py b/cogs/web.py index fcec8f9..e003399 100644 --- a/cogs/web.py +++ b/cogs/web.py @@ -9,27 +9,27 @@ from discord.ext import commands import requests from bs4 import BeautifulSoup import urllib.parse -import pytube +import yt_dlp import logging logger = logging.getLogger(__name__) + class Web(commands.Cog): def __init__(self, bot): self.bot = bot def _extract_youtube_title(self, url): """Extract YouTube video title if URL is a YouTube link.""" - if not url.startswith('https://www.youtube.com/'): + if "youtube.com/watch" not in url: return None - + logger.info("youtube link") try: - parsed_url = urllib.parse.urlparse(url) - 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}') - return yt.title + ydl_opts = {"quiet": True, "nowarnings": True} + with yt_dlp.YoutubeDL(ydl_opts) as ydl: + info = ydl.extract_info(url, download=False) + return info.get("title") if info else None except Exception: pass return None @@ -37,10 +37,10 @@ class Web(commands.Cog): def _create_button(self, index, link): """Create a button for sending search result.""" button = discord.ui.Button(label=f"Send Result {index}") - + async def button_callback(interaction: discord.Interaction): - await interaction.response.send_message(link.get('href')) - + await interaction.response.send_message(link.get("href")) + button.callback = button_callback return button @@ -48,17 +48,17 @@ class Web(commands.Cog): """Process search results and create embed with buttons.""" 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 - youtube_title = self._extract_youtube_title(link.get('href')) + youtube_title = self._extract_youtube_title(link.get("href")) if youtube_title: title = youtube_title - + embed.add_field(name=f"Result {i}", value=f"[{title}]({link.get('href')})", inline=False) button = self._create_button(i, link) view.add_item(button) - + return embed, view @commands.slash_command( @@ -71,7 +71,7 @@ class Web(commands.Cog): 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'} + 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"} encoded_query = urllib.parse.quote_plus(query) url = f"https://duckduckgo.com/html/?q={encoded_query}" response = requests.get(url, headers=headers) @@ -83,9 +83,9 @@ class Web(commands.Cog): logger.error(f"Error: {response.status_code}") return - soup = BeautifulSoup(response.text, 'html.parser') - links = soup.find_all('a', class_='result__a') - + soup = BeautifulSoup(response.text, "html.parser") + links = soup.find_all("a", class_="result__a") + if not links: await ctx.respond(content="No results found.", ephemeral=True) logger.warning("No results found") @@ -95,5 +95,6 @@ class Web(commands.Cog): await ctx.respond(embed=embed, view=view, ephemeral=True) logger.info("Search results sent") + def setup(bot): - bot.add_cog(Web(bot)) + bot.add_cog(Web(bot)) \ No newline at end of file -- cgit v1.2.3