g1mp/plugins/url_title_sniffer.py

130 lines
5.4 KiB
Python
Raw Permalink Normal View History

2025-02-13 06:35:15 +00:00
# -*- coding: utf-8 -*-
2025-02-13 04:55:42 +00:00
"""
2025-02-13 06:35:15 +00:00
IRC3 Bot Plugin: URL Title Fetcher
2025-02-15 01:16:18 +00:00
A plugin for IRC3 bots that monitors chat messages for URLs, fetches their webpage titles, and displays them
with formatted styling in the chat. Provides visual enhancement to URL sharing in IRC channels.
2025-02-13 06:35:15 +00:00
Features:
2025-02-15 01:16:18 +00:00
- Asynchronous URL processing using aiohttp for efficient network operations
- Robust HTML parsing with lxml for accurate title extraction
- Configurable message styling with color and formatting options
- Built-in exclusion of YouTube URLs to avoid conflicts with dedicated YouTube plugins
- Error handling for network and parsing operations
- Proper resource cleanup through session management
- Queue-based processing system with strict rate limiting
2025-02-15 01:16:18 +00:00
Dependencies:
- aiohttp: For asynchronous HTTP requests
- irc3: Core IRC bot functionality
- ircstyle: IRC text formatting utilities
- lxml: HTML parsing capabilities
2025-02-15 01:48:30 +00:00
Author: Zodiac
2025-02-15 01:16:18 +00:00
Date: 2025-02-14
2025-02-13 04:55:42 +00:00
"""
import re
import time
2025-02-13 04:55:42 +00:00
import aiohttp
2025-02-15 01:16:18 +00:00
import ircstyle
2025-02-13 04:55:42 +00:00
from lxml import html
import irc3
from irc3 import event
2025-02-15 01:48:30 +00:00
from irc3.compat import Queue
2025-02-15 01:16:18 +00:00
from plugins.services.permissions import check_ignore
2025-02-13 04:55:42 +00:00
2025-02-13 06:35:15 +00:00
@irc3.plugin
2025-02-13 04:55:42 +00:00
class URLTitlePlugin:
2025-02-15 01:16:18 +00:00
"""Plugin for fetching and displaying webpage titles from URLs shared in IRC messages.
Monitors IRC messages for URLs, retrieves their webpage titles, and posts formatted responses
back to the channel. Supports styled text output with configurable formatting options.
2025-02-13 04:55:42 +00:00
Attributes:
2025-02-15 01:16:18 +00:00
bot (irc3.IrcBot): Reference to the main IRC bot instance
session (aiohttp.ClientSession): Persistent HTTP session for making web requests
url_pattern (re.Pattern): Compiled regex for URL detection in messages
2025-02-15 01:48:30 +00:00
queue (Queue): Processing queue for URL handling tasks
last_processed (float): Timestamp of last successful URL processing
2025-02-13 04:55:42 +00:00
"""
def __init__(self, bot):
2025-02-15 01:48:30 +00:00
"""Initialize plugin with bot instance and set up components."""
2025-02-13 04:55:42 +00:00
self.bot = bot
self.session = aiohttp.ClientSession(loop=self.bot.loop)
2025-02-15 01:16:18 +00:00
self.url_pattern = re.compile(r"https?://[^\s<>\"']+|www\.[^\s<>\"']+")
2025-02-15 01:48:30 +00:00
self.queue = Queue()
self.last_processed = 0 # Initialize to epoch start
2025-02-15 01:48:30 +00:00
self.bot.create_task(self.process_queue())
2025-02-13 04:55:42 +00:00
@event(irc3.rfc.PRIVMSG)
2025-02-15 01:16:18 +00:00
@check_ignore
2025-02-13 04:55:42 +00:00
async def on_privmsg(self, mask, event, target, data):
2025-02-15 01:48:30 +00:00
"""Handle incoming messages and enqueue URLs for processing."""
2025-02-15 01:16:18 +00:00
urls = self.url_pattern.findall(data)
2025-02-13 04:55:42 +00:00
for url in urls:
2025-02-15 01:16:18 +00:00
if "youtube.com" in url.lower() or "youtu.be" in url.lower():
continue
2025-02-15 01:48:30 +00:00
self.queue.put_nowait((target, url))
async def process_queue(self):
"""Process URLs from the queue with strict 5-second cooldown between requests."""
2025-02-15 01:48:30 +00:00
while True:
target, url = await self.queue.get()
2025-02-13 04:55:42 +00:00
try:
current_time = time.time()
elapsed = current_time - self.last_processed
if elapsed < 5:
self.bot.log.info(f"Rate limited: Waiting {5 - elapsed:.1f}s to process {url}")
continue
2025-02-13 04:55:42 +00:00
title = await self.fetch_title(url)
if title:
2025-02-15 01:16:18 +00:00
formatted_message = self.format_message(title, url)
2025-02-13 04:55:42 +00:00
await self.bot.privmsg(target, formatted_message)
self.last_processed = time.time() # Update after successful processing
2025-02-13 04:55:42 +00:00
except Exception as e:
self.bot.log.error(f"Error processing URL {url}: {e}")
2025-02-15 01:48:30 +00:00
finally:
self.queue.task_done()
2025-02-13 04:55:42 +00:00
2025-02-15 01:16:18 +00:00
def format_message(self, title, url):
2025-02-15 01:48:30 +00:00
"""Create a styled IRC message containing the webpage title and source URL."""
2025-02-15 01:16:18 +00:00
prefix = ircstyle.style("", fg="cyan", bold=True, reset=True)
title_label = ircstyle.style("Title", fg="blue", bold=True, reset=True)
title_text = ircstyle.style(title, fg="green", italics=True, underline=True, reset=True)
separator = ircstyle.style("", fg="grey", bold=True, reset=True)
url_label = ircstyle.style("Source", fg="blue", bold=True, underline=True, reset=True)
url_text = ircstyle.style(url, fg="cyan", italics=True, reset=True)
suffix = ircstyle.style("", fg="cyan", bold=True, reset=True)
2025-02-13 04:55:42 +00:00
2025-02-15 01:16:18 +00:00
return f"{prefix} {title_label}: {title_text} {separator} {url_label}: {url_text} {suffix}"
2025-02-13 04:55:42 +00:00
2025-02-15 01:16:18 +00:00
async def fetch_title(self, url):
2025-02-15 01:48:30 +00:00
"""Retrieve the title of a webpage using asynchronous HTTP requests."""
2025-02-15 01:16:18 +00:00
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
async with self.session.get(url, headers=headers, timeout=10) as response:
response.raise_for_status()
content = await response.text()
tree = html.fromstring(content)
title = tree.findtext(".//title")
return title.strip() if title else "No title found"
2025-02-13 04:55:42 +00:00
async def close(self):
2025-02-15 01:16:18 +00:00
"""Clean up resources by closing the HTTP session."""
2025-02-13 04:55:42 +00:00
await self.session.close()
def __del__(self):
2025-02-15 01:16:18 +00:00
"""Ensure proper cleanup when the plugin is destroyed."""
self.bot.create_task(self.close())