新增IRC协议相关的全套工具模块,包括: - 核心协议解析与CTCP处理 - 消息发送缓存与文本 sanitize - 账号配置管理与运行时状态 - 命令处理与权限控制 - 服务发现与诊断工具 - 多账号网关与配置加载
94 lines
2.7 KiB
Python
94 lines
2.7 KiB
Python
from __future__ import annotations
|
|
|
|
import re
|
|
from typing import Any
|
|
|
|
from yuxi.channels.models import ChannelResponse
|
|
|
|
_TABLE_SEP_RE = re.compile(r"^\|?[:\- ]+\|")
|
|
|
|
|
|
def format_outbound(response: ChannelResponse) -> dict[str, Any]:
|
|
return {
|
|
"target": response.identity.channel_chat_id,
|
|
"text": response.content,
|
|
}
|
|
|
|
|
|
def convert_markdown_tables(text: str, table_mode: str = "off") -> str:
|
|
if table_mode == "off":
|
|
return text
|
|
|
|
lines = text.split("\n")
|
|
result: list[str] = []
|
|
in_table = False
|
|
table_rows: list[list[str]] = []
|
|
|
|
for line in lines:
|
|
stripped = line.strip()
|
|
is_table_line = bool(stripped.startswith("|") and stripped.endswith("|"))
|
|
|
|
if is_table_line and _TABLE_SEP_RE.match(stripped):
|
|
in_table = True
|
|
continue
|
|
|
|
if is_table_line:
|
|
if not in_table:
|
|
in_table = True
|
|
cells = [c.strip() for c in stripped.strip("|").split("|")]
|
|
table_rows.append(cells)
|
|
else:
|
|
if in_table:
|
|
result.append(_render_table_plain(table_rows, table_mode))
|
|
table_rows.clear()
|
|
in_table = False
|
|
result.append(line)
|
|
|
|
if in_table and table_rows:
|
|
result.append(_render_table_plain(table_rows, table_mode))
|
|
|
|
return "\n".join(result)
|
|
|
|
|
|
def _render_table_plain(rows: list[list[str]], table_mode: str) -> str:
|
|
if not rows:
|
|
return ""
|
|
|
|
col_widths = _compute_column_widths(rows)
|
|
|
|
if table_mode == "plain":
|
|
out_lines = []
|
|
for row in rows:
|
|
padded = [cell.ljust(col_widths[i]) if i < len(col_widths) else cell for i, cell in enumerate(row)]
|
|
out_lines.append(" ".join(padded))
|
|
return "\n".join(out_lines)
|
|
|
|
if table_mode == "list":
|
|
out_lines = []
|
|
headers = rows[0] if rows else []
|
|
for i, row in enumerate(rows):
|
|
if i == 0 and len(rows) > 1:
|
|
out_lines.append(f"--- {', '.join(headers)} ---")
|
|
continue
|
|
items = []
|
|
for j, cell in enumerate(row):
|
|
header = headers[j] if j < len(headers) else f"col{j}"
|
|
items.append(f"{header}: {cell}")
|
|
out_lines.append("\n".join(items))
|
|
if i < len(rows) - 1:
|
|
out_lines.append("")
|
|
return "\n".join(out_lines)
|
|
|
|
return ""
|
|
|
|
|
|
def _compute_column_widths(rows: list[list[str]]) -> list[int]:
|
|
if not rows:
|
|
return []
|
|
col_count = max(len(row) for row in rows)
|
|
widths = [0] * col_count
|
|
for row in rows:
|
|
for i, cell in enumerate(row):
|
|
widths[i] = max(widths[i], len(cell))
|
|
return widths
|