quote-rss-plugin/utils/rss_generator.py

40 lines
1.8 KiB
Python
Raw Normal View History

2025-08-13 18:49:19 +08:00
from datetime import datetime
from typing import Dict, Any, List
import xml.etree.ElementTree as ET
class RSSGenerator:
"""RSS XML生成器"""
def __init__(self, title: str, description: str, link: str, language: str = "zh-cn"):
self.title = title
self.description = description
self.link = link
self.language = language
2025-08-13 22:48:17 +08:00
def generate_rss(self, items: List[Dict[str, Any]], motdTitle: str = None) -> str:
2025-08-13 18:49:19 +08:00
"""生成RSS XML"""
# 创建根元素
rss = ET.Element("rss", version="2.0")
channel = ET.SubElement(rss, "channel")
# 频道信息
2025-08-13 22:48:17 +08:00
ET.SubElement(channel, "title").text = motdTitle or self.title
2025-08-13 18:49:19 +08:00
ET.SubElement(channel, "description").text = self.description
ET.SubElement(channel, "link").text = self.link
ET.SubElement(channel, "language").text = self.language
ET.SubElement(channel, "lastBuildDate").text = datetime.now().strftime("%a, %d %b %Y %H:%M:%S +0800")
# 添加文章项目
for item_data in items:
item = ET.SubElement(channel, "item")
ET.SubElement(item, "title").text = item_data.get("title", "")
ET.SubElement(item, "description").text = item_data.get("description", "")
ET.SubElement(item, "link").text = item_data.get("link", self.link)
ET.SubElement(item, "pubDate").text = item_data.get("pub_date", datetime.now().strftime("%a, %d %b %Y %H:%M:%S +0800"))
if "guid" in item_data:
ET.SubElement(item, "guid").text = item_data["guid"]
# 转换为字符串
xml_str = ET.tostring(rss, encoding='unicode', method='xml')
return f'<?xml version="1.0" encoding="UTF-8"?>\n{xml_str}'