Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

289 lines
13KB

  1. import plugins
  2. from bridge.context import ContextType
  3. from bridge.reply import Reply, ReplyType
  4. from plugins import *
  5. from .midjourney import MJBot
  6. from .summary import LinkSummary
  7. from bridge import bridge
  8. from common.expired_dict import ExpiredDict
  9. from common import const
  10. import os
  11. from .utils import Util
  12. @plugins.register(
  13. name="linkai",
  14. desc="A plugin that supports knowledge base and midjourney drawing.",
  15. version="0.1.0",
  16. author="https://link-ai.tech",
  17. desire_priority=99
  18. )
  19. class LinkAI(Plugin):
  20. def __init__(self):
  21. super().__init__()
  22. self.handlers[Event.ON_HANDLE_CONTEXT] = self.on_handle_context
  23. self.config = super().load_config()
  24. if not self.config:
  25. # 未加载到配置,使用模板中的配置
  26. self.config = self._load_config_template()
  27. if self.config:
  28. self.mj_bot = MJBot(self.config.get("midjourney"))
  29. self.sum_config = {}
  30. if self.config:
  31. self.sum_config = self.config.get("summary")
  32. logger.info(f"[LinkAI] inited, config={self.config}")
  33. def on_handle_context(self, e_context: EventContext):
  34. """
  35. 消息处理逻辑
  36. :param e_context: 消息上下文
  37. """
  38. if not self.config:
  39. return
  40. context = e_context['context']
  41. if context.type not in [ContextType.TEXT, ContextType.IMAGE, ContextType.IMAGE_CREATE, ContextType.FILE, ContextType.SHARING]:
  42. # filter content no need solve
  43. return
  44. if context.type in [ContextType.FILE, ContextType.IMAGE] and self._is_summary_open(context):
  45. # 文件处理
  46. context.get("msg").prepare()
  47. file_path = context.content
  48. if not LinkSummary().check_file(file_path, self.sum_config):
  49. return
  50. if context.type != ContextType.IMAGE:
  51. _send_info(e_context, "正在为你加速生成摘要,请稍后")
  52. res = LinkSummary().summary_file(file_path)
  53. if not res:
  54. _set_reply_text("因为神秘力量无法获取内容,请稍后再试吧", e_context, level=ReplyType.TEXT)
  55. return
  56. summary_text = res.get("summary")
  57. if context.type != ContextType.IMAGE:
  58. USER_FILE_MAP[_find_user_id(context) + "-sum_id"] = res.get("summary_id")
  59. summary_text += "\n\n💬 发送 \"开启对话\" 可以开启与文件内容的对话"
  60. _set_reply_text(summary_text, e_context, level=ReplyType.TEXT)
  61. os.remove(file_path)
  62. return
  63. if (context.type == ContextType.SHARING and self._is_summary_open(context)) or \
  64. (context.type == ContextType.TEXT and LinkSummary().check_url(context.content)):
  65. if not LinkSummary().check_url(context.content):
  66. return
  67. _send_info(e_context, "正在为你加速生成摘要,请稍后")
  68. res = LinkSummary().summary_url(context.content)
  69. if not res:
  70. _set_reply_text("因为神秘力量无法获取文章内容,请稍后再试吧~", e_context, level=ReplyType.TEXT)
  71. return
  72. _set_reply_text(res.get("summary") + "\n\n💬 发送 \"开启对话\" 可以开启与文章内容的对话", e_context, level=ReplyType.TEXT)
  73. USER_FILE_MAP[_find_user_id(context) + "-sum_id"] = res.get("summary_id")
  74. return
  75. mj_type = self.mj_bot.judge_mj_task_type(e_context)
  76. if mj_type:
  77. # MJ作图任务处理
  78. self.mj_bot.process_mj_task(mj_type, e_context)
  79. return
  80. if context.content.startswith(f"{_get_trigger_prefix()}linkai"):
  81. # 应用管理功能
  82. self._process_admin_cmd(e_context)
  83. return
  84. if context.type == ContextType.TEXT and context.content == "开启对话" and _find_sum_id(context):
  85. # 文本对话
  86. _send_info(e_context, "正在为你开启对话,请稍后")
  87. res = LinkSummary().summary_chat(_find_sum_id(context))
  88. if not res:
  89. _set_reply_text("开启对话失败,请稍后再试吧", e_context)
  90. return
  91. USER_FILE_MAP[_find_user_id(context) + "-file_id"] = res.get("file_id")
  92. _set_reply_text("💡你可以问我关于这篇文章的任何问题,例如:\n\n" + res.get("questions") + "\n\n发送 \"退出对话\" 可以关闭与文章的对话", e_context, level=ReplyType.TEXT)
  93. return
  94. if context.type == ContextType.TEXT and context.content == "退出对话" and _find_file_id(context):
  95. del USER_FILE_MAP[_find_user_id(context) + "-file_id"]
  96. bot = bridge.Bridge().find_chat_bot(const.LINKAI)
  97. bot.sessions.clear_session(context["session_id"])
  98. _set_reply_text("对话已退出", e_context, level=ReplyType.TEXT)
  99. return
  100. if context.type == ContextType.TEXT and _find_file_id(context):
  101. bot = bridge.Bridge().find_chat_bot(const.LINKAI)
  102. context.kwargs["file_id"] = _find_file_id(context)
  103. reply = bot.reply(context.content, context)
  104. e_context["reply"] = reply
  105. e_context.action = EventAction.BREAK_PASS
  106. return
  107. if self._is_chat_task(e_context):
  108. # 文本对话任务处理
  109. self._process_chat_task(e_context)
  110. # 插件管理功能
  111. def _process_admin_cmd(self, e_context: EventContext):
  112. context = e_context['context']
  113. cmd = context.content.split()
  114. if len(cmd) == 1 or (len(cmd) == 2 and cmd[1] == "help"):
  115. _set_reply_text(self.get_help_text(verbose=True), e_context, level=ReplyType.INFO)
  116. return
  117. if len(cmd) == 2 and (cmd[1] == "open" or cmd[1] == "close"):
  118. # 知识库开关指令
  119. if not Util.is_admin(e_context):
  120. _set_reply_text("需要管理员权限执行", e_context, level=ReplyType.ERROR)
  121. return
  122. is_open = True
  123. tips_text = "开启"
  124. if cmd[1] == "close":
  125. tips_text = "关闭"
  126. is_open = False
  127. conf()["use_linkai"] = is_open
  128. bridge.Bridge().reset_bot()
  129. _set_reply_text(f"LinkAI对话功能{tips_text}", e_context, level=ReplyType.INFO)
  130. return
  131. if len(cmd) == 3 and cmd[1] == "app":
  132. # 知识库应用切换指令
  133. if not context.kwargs.get("isgroup"):
  134. _set_reply_text("该指令需在群聊中使用", e_context, level=ReplyType.ERROR)
  135. return
  136. if not Util.is_admin(e_context):
  137. _set_reply_text("需要管理员权限执行", e_context, level=ReplyType.ERROR)
  138. return
  139. app_code = cmd[2]
  140. group_name = context.kwargs.get("msg").from_user_nickname
  141. group_mapping = self.config.get("group_app_map")
  142. if group_mapping:
  143. group_mapping[group_name] = app_code
  144. else:
  145. self.config["group_app_map"] = {group_name: app_code}
  146. # 保存插件配置
  147. super().save_config(self.config)
  148. _set_reply_text(f"应用设置成功: {app_code}", e_context, level=ReplyType.INFO)
  149. return
  150. if len(cmd) == 3 and cmd[1] == "sum" and (cmd[2] == "open" or cmd[2] == "close"):
  151. # 知识库开关指令
  152. if not Util.is_admin(e_context):
  153. _set_reply_text("需要管理员权限执行", e_context, level=ReplyType.ERROR)
  154. return
  155. is_open = True
  156. tips_text = "开启"
  157. if cmd[2] == "close":
  158. tips_text = "关闭"
  159. is_open = False
  160. if not self.sum_config:
  161. _set_reply_text(f"插件未启用summary功能,请参考以下链添加插件配置\n\nhttps://github.com/zhayujie/chatgpt-on-wechat/blob/master/plugins/linkai/README.md", e_context, level=ReplyType.INFO)
  162. else:
  163. self.sum_config["enabled"] = is_open
  164. _set_reply_text(f"文章总结功能{tips_text}", e_context, level=ReplyType.INFO)
  165. return
  166. _set_reply_text(f"指令错误,请输入{_get_trigger_prefix()}linkai help 获取帮助", e_context,
  167. level=ReplyType.INFO)
  168. return
  169. def _is_summary_open(self, context) -> bool:
  170. if not self.sum_config or not self.sum_config.get("enabled"):
  171. return False
  172. if context.kwargs.get("isgroup") and not self.sum_config.get("group_enabled"):
  173. return False
  174. support_type = self.sum_config.get("type")
  175. if not support_type:
  176. return True
  177. if context.type.name not in support_type:
  178. return False
  179. return True
  180. # LinkAI 对话任务处理
  181. def _is_chat_task(self, e_context: EventContext):
  182. context = e_context['context']
  183. # 群聊应用管理
  184. return self.config.get("group_app_map") and context.kwargs.get("isgroup")
  185. def _process_chat_task(self, e_context: EventContext):
  186. """
  187. 处理LinkAI对话任务
  188. :param e_context: 对话上下文
  189. """
  190. context = e_context['context']
  191. # 群聊应用管理
  192. group_name = context.get("msg").from_user_nickname
  193. app_code = self._fetch_group_app_code(group_name)
  194. if app_code:
  195. context.kwargs['app_code'] = app_code
  196. def _fetch_group_app_code(self, group_name: str) -> str:
  197. """
  198. 根据群聊名称获取对应的应用code
  199. :param group_name: 群聊名称
  200. :return: 应用code
  201. """
  202. group_mapping = self.config.get("group_app_map")
  203. if group_mapping:
  204. app_code = group_mapping.get(group_name) or group_mapping.get("ALL_GROUP")
  205. return app_code
  206. def get_help_text(self, verbose=False, **kwargs):
  207. trigger_prefix = _get_trigger_prefix()
  208. help_text = "用于集成 LinkAI 提供的知识库、Midjourney绘画、文档总结、联网搜索等能力。\n\n"
  209. if not verbose:
  210. return help_text
  211. help_text += f'📖 知识库\n - 群聊中指定应用: {trigger_prefix}linkai app 应用编码\n'
  212. help_text += f' - {trigger_prefix}linkai open: 开启对话\n'
  213. help_text += f' - {trigger_prefix}linkai close: 关闭对话\n'
  214. help_text += f'\n例如: \n"{trigger_prefix}linkai app Kv2fXJcH"\n\n'
  215. help_text += f"🎨 绘画\n - 生成: {trigger_prefix}mj 描述词1, 描述词2.. \n - 放大: {trigger_prefix}mju 图片ID 图片序号\n - 变换: {trigger_prefix}mjv 图片ID 图片序号\n - 重置: {trigger_prefix}mjr 图片ID"
  216. help_text += f"\n\n例如:\n\"{trigger_prefix}mj a little cat, white --ar 9:16\"\n\"{trigger_prefix}mju 11055927171882 2\""
  217. help_text += f"\n\"{trigger_prefix}mjv 11055927171882 2\"\n\"{trigger_prefix}mjr 11055927171882\""
  218. help_text += f"\n\n💡 文档总结和对话\n - 开启: {trigger_prefix}linkai sum open\n - 使用: 发送文件、公众号文章等可生成摘要,并与内容对话"
  219. return help_text
  220. def _load_config_template(self):
  221. logger.debug("No LinkAI plugin config.json, use plugins/linkai/config.json.template")
  222. try:
  223. plugin_config_path = os.path.join(self.path, "config.json.template")
  224. if os.path.exists(plugin_config_path):
  225. with open(plugin_config_path, "r", encoding="utf-8") as f:
  226. plugin_conf = json.load(f)
  227. plugin_conf["midjourney"]["enabled"] = False
  228. plugin_conf["summary"]["enabled"] = False
  229. return plugin_conf
  230. except Exception as e:
  231. logger.exception(e)
  232. def _send_info(e_context: EventContext, content: str):
  233. reply = Reply(ReplyType.TEXT, content)
  234. channel = e_context["channel"]
  235. channel.send(reply, e_context["context"])
  236. def _find_user_id(context):
  237. if context["isgroup"]:
  238. return context.kwargs.get("msg").actual_user_id
  239. else:
  240. return context["receiver"]
  241. def _set_reply_text(content: str, e_context: EventContext, level: ReplyType = ReplyType.ERROR):
  242. reply = Reply(level, content)
  243. e_context["reply"] = reply
  244. e_context.action = EventAction.BREAK_PASS
  245. def _get_trigger_prefix():
  246. return conf().get("plugin_trigger_prefix", "$")
  247. def _find_sum_id(context):
  248. return USER_FILE_MAP.get(_find_user_id(context) + "-sum_id")
  249. def _find_file_id(context):
  250. user_id = _find_user_id(context)
  251. if user_id:
  252. return USER_FILE_MAP.get(user_id + "-file_id")
  253. USER_FILE_MAP = ExpiredDict(conf().get("expires_in_seconds") or 60 * 30)