Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

75 lines
2.8KB

  1. # encoding:utf-8
  2. import json
  3. import os
  4. import plugins
  5. from bridge.context import ContextType
  6. from bridge.reply import Reply, ReplyType
  7. from common.log import logger
  8. from plugins import *
  9. @plugins.register(
  10. name="Keyword",
  11. desire_priority=900,
  12. hidden=True,
  13. desc="关键词匹配过滤",
  14. version="0.1",
  15. author="fengyege.top",
  16. )
  17. class Keyword(Plugin):
  18. def __init__(self):
  19. super().__init__()
  20. try:
  21. curdir = os.path.dirname(__file__)
  22. config_path = os.path.join(curdir, "config.json")
  23. conf = None
  24. if not os.path.exists(config_path):
  25. logger.debug(f"[keyword]不存在配置文件{config_path}")
  26. conf = {"keyword": {}}
  27. with open(config_path, "w", encoding="utf-8") as f:
  28. json.dump(conf, f, indent=4)
  29. else:
  30. logger.debug(f"[keyword]加载配置文件{config_path}")
  31. with open(config_path, "r", encoding="utf-8") as f:
  32. conf = json.load(f)
  33. # 加载关键词
  34. self.keyword = conf["keyword"]
  35. logger.info("[keyword] {}".format(self.keyword))
  36. self.handlers[Event.ON_HANDLE_CONTEXT] = self.on_handle_context
  37. logger.info("[keyword] inited.")
  38. except Exception as e:
  39. logger.warn("[keyword] init failed, ignore or see https://github.com/zhayujie/chatgpt-on-wechat/tree/master/plugins/keyword .")
  40. raise e
  41. def on_handle_context(self, e_context: EventContext):
  42. if e_context["context"].type != ContextType.TEXT:
  43. return
  44. content = e_context["context"].content.strip()
  45. logger.debug("[keyword] on_handle_context. content: %s" % content)
  46. if content in self.keyword:
  47. logger.debug(f"[keyword] 匹配到关键字【{content}】")
  48. reply_text = self.keyword[content]
  49. # 判断匹配内容的类型
  50. if (reply_text.startswith("http://") or reply_text.startswith("https://")) and any(reply_text.endswith(ext) for ext in [".jpg", ".jpeg", ".png", ".gif", ".webp"]):
  51. # 如果是以 http:// 或 https:// 开头,且.jpg/.jpeg/.png/.gif结尾,则认为是图片 URL
  52. reply = Reply()
  53. reply.type = ReplyType.IMAGE_URL
  54. reply.content = reply_text
  55. else:
  56. # 否则认为是普通文本
  57. reply = Reply()
  58. reply.type = ReplyType.TEXT
  59. reply.content = reply_text
  60. e_context["reply"] = reply
  61. e_context.action = EventAction.BREAK_PASS # 事件结束,并跳过处理context的默认逻辑
  62. def get_help_text(self, **kwargs):
  63. help_text = "关键词过滤"
  64. return help_text