import discord import os from datetime import datetime from typing import List import html class TranscriptGenerator: """工单转录生成器""" @staticmethod async def generate_transcript(channel: discord.TextChannel, messages_limit: int = 100) -> str: """ 生成频道的HTML转录文件 Args: channel: Discord 文本频道 messages_limit: 要获取的最大消息数 Returns: HTML格式的转录内容 """ # 获取频道历史记录 messages = [] async for message in channel.history(limit=messages_limit, oldest_first=True): messages.append(message) # 生成HTML html_content = TranscriptGenerator._create_html(messages, channel) return html_content @staticmethod def _create_html(messages: List[discord.Message], channel: discord.TextChannel) -> str: """创建HTML转录文件""" messages_html = "" for msg in messages: # 处理消息内容 content = html.escape(msg.content) if msg.content else "" # 处理附件 attachments_html = "" if msg.attachments: for attachment in msg.attachments: attachments_html += f'
📎 {html.escape(attachment.filename)}
' # 处理嵌入 embeds_html = "" if msg.embeds: for embed in msg.embeds: embed_title = html.escape(embed.title) if embed.title else "" embed_desc = html.escape(embed.description) if embed.description else "" if embed_title or embed_desc: embeds_html += f'''
{f'
{embed_title}
' if embed_title else ''} {f'
{embed_desc}
' if embed_desc else ''}
''' # 构建消息HTML timestamp = msg.created_at.strftime("%Y-%m-%d %H:%M:%S") avatar_url = msg.author.display_avatar.url if msg.author.display_avatar else "https://cdn.discordapp.com/embed/avatars/0.png" messages_html += f'''
avatar
{html.escape(str(msg.author))} {timestamp} {f'BOT' if msg.author.bot else ''}
{f'
{content}
' if content else ''} {attachments_html} {embeds_html}
''' # 完整的HTML模板 html_template = f''' 工单转录 - {html.escape(channel.name)}

🎫 工单转录

频道: {html.escape(channel.name)}

生成时间: {datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")} UTC

消息总数: {len(messages)}

{messages_html}
''' return html_template @staticmethod async def save_transcript(html_content: str, filename: str) -> str: """ 保存转录文件 Args: html_content: HTML内容 filename: 文件名 Returns: 文件路径 """ # 创建 transcripts 目录 os.makedirs("transcripts", exist_ok=True) filepath = os.path.join("transcripts", filename) with open(filepath, 'w', encoding='utf-8') as f: f.write(html_content) return filepath