Files
dow-markdown/dowmd.py

117 lines
4.9 KiB
Python
Raw Normal View History

2024-04-13 17:21:59 +08:00
# encoding:utf-8
2024-05-07 15:10:27 +08:00
import re
2024-04-13 17:21:59 +08:00
import plugins
from bridge.reply import Reply, ReplyType
2024-08-03 14:30:17 +08:00
from lib import itchat
2024-08-05 18:42:38 +08:00
from plugins import *
from config import conf
2024-08-05 18:42:38 +08:00
2024-04-13 17:21:59 +08:00
@plugins.register(
2024-08-03 11:20:57 +08:00
name="dow_markdown",
2024-05-07 15:10:27 +08:00
desire_priority=66,
2024-08-02 16:50:44 +08:00
desc="优化markdown返回结果中的图片和网址链接。",
version="0.6",
2024-08-02 16:50:44 +08:00
author="Kubbo",
2024-08-03 19:47:19 +08:00
hidden=False
2024-04-13 17:21:59 +08:00
)
2024-08-03 11:20:57 +08:00
class dow_markdown(Plugin):
2024-04-13 17:21:59 +08:00
def __init__(self):
super().__init__()
try:
self.config =super().loading_config()
2024-08-03 14:30:17 +08:00
self.handlers[Event.ON_HANDLE_CONTEXT] = self.on_handle_context
2024-08-03 12:27:40 +08:00
self.handlers[Event.ON_DECORATE_REPLY] = self.on_decorate_reply
2024-08-03 02:27:37 +08:00
logger.info("[dow_markdown] inited.")
2024-04-13 17:21:59 +08:00
except Exception as e:
2024-08-03 02:27:37 +08:00
logger.warn("[dow_markdown] init failed, ignore.")
2024-04-13 17:21:59 +08:00
raise e
2024-08-05 18:42:38 +08:00
def on_handle_context(self, e_context: EventContext):
send_msg = e_context["context"]
2024-08-03 14:30:17 +08:00
try:
2024-08-03 19:56:11 +08:00
text = send_msg["content"]
if any(word in send_msg["content"] for word in [".画", ".sd"]):
2024-08-05 18:42:38 +08:00
receiver = send_msg.get("receiver")
itchat.send("我正在绘画中,可能需要多等待一会,请稍后...", toUserName=receiver)
logger.info("[WX] sendMsg={}, receiver={}".format(text, receiver))
e_context.action = EventAction.BREAK_PASS
except Exception as e:
2024-08-05 18:42:38 +08:00
text = send_msg["content"]
2024-08-03 19:56:11 +08:00
logger.warn(f"[dow_markdown] on_handle_context failed, content={text}, error={e}")
2024-08-03 14:30:17 +08:00
finally:
2024-08-03 14:55:41 +08:00
e_context.action = EventAction.CONTINUE
2024-08-05 18:42:38 +08:00
2024-04-13 17:21:59 +08:00
def on_decorate_reply(self, e_context: EventContext):
if e_context["reply"].type != ReplyType.TEXT:
return
2024-08-05 18:42:38 +08:00
logger.info("[on_decorate_reply] yooooooooooooooooo")
2024-04-13 17:21:59 +08:00
try:
2024-05-07 15:10:27 +08:00
content = e_context["reply"].content.strip()
# 避免图片无法下载时,重复调用插件导致没有响应的问题
2024-06-02 23:51:25 +08:00
if content.startswith("[DOWNLOAD_ERROR]"):
2024-05-07 15:10:27 +08:00
return
2024-08-05 18:42:38 +08:00
content_arr = [m for m in content.split("<br>") if m.strip()]
if len(content_arr) > 0:
for index, msg in enumerate(content_arr):
self.handle_send(msg, e_context, index == len(content_arr) - 1)
2024-05-07 15:10:27 +08:00
except Exception as e:
2024-08-05 18:42:38 +08:00
logger.warn(f"[dow_markdown] on_decorate_reply failed, error={e}")
2024-05-07 15:10:27 +08:00
finally:
e_context.action = EventAction.CONTINUE
2024-08-05 18:42:38 +08:00
2024-04-13 17:21:59 +08:00
def get_help_text(self, **kwargs):
2024-08-03 02:28:04 +08:00
return "优化返回结果中的图片和网址链接。"
2024-08-05 18:42:38 +08:00
def handle_send(self, content, e_context, is_last):
host = os.environ.get('DIFY_API_BASE', '')
2024-08-05 18:42:38 +08:00
if host.endswith('/v1'):
host = host[:-3]
if 'coze' == conf().get('model'):
host = "https://s.coze.cn/t/"
format_content = self.format_content(content)
parts = re.split(r'&分块&', format_content)
2024-08-05 18:42:38 +08:00
parts = [p for p in parts if p.strip()]
channel = e_context["channel"]
context = e_context["context"]
logger.info("[handle_send] parts={}".format(parts))
if len(parts) > 0:
for index, part in enumerate(parts):
reply = Reply(content=part.strip(), type=ReplyType.TEXT)
if re.search(r"\.(gif|jpg|png|jpeg|webp)", part):
reply.type = ReplyType.IMAGE_URL
reply.content = self.extract_url(part.strip(), host)
2024-08-06 10:07:07 +08:00
elif re.search(r"\.(mp4)", part):
reply.type = ReplyType.VIDEO_URL
reply.content = self.extract_url(part.strip(), host)
try:
if index == len(parts) - 1 and is_last:
e_context["reply"] = reply
e_context.action = EventAction.BREAK_PASS
else:
channel.send(reply, context)
except Exception as e:
source_type = {ReplyType.IMAGE_URL: "图片", ReplyType.VIDEO_URL: "视频"}[reply.type]
itchat.send(f"[{source_type}]加载失败", toUserName=context.get("receiver"))
logger.warn("[dow_markdown] handle_send failed, error={}".format(e))
def extract_url(self, text, host):
text = text.strip()
if text.endswith(")"):
text = text[:-1]
if not text.startswith('http'):
if text.startswith('/t/') and 'coze' == conf().get('model'):
text = text[3:]
text = host + text
logger.info("[extract_url] text={}".format(text))
return text
def format_content(self, content):
regex_pattern = self.config.get("regex_pattern",r"\!\[([^\]]*)\]\(?([^)\\\s]+)\)?")
replacement_pattern = self.config.get("replacement_pattern",r"&分块&\2&分块&")
content = re.sub(regex_pattern, replacement_pattern, content)
content = re.sub(r"\\n", "\n", content)
return content