選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

keyword.py 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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(
  40. "[keyword] init failed, ignore or see https://github.com/zhayujie/chatgpt-on-wechat/tree/master/plugins/keyword ."
  41. )
  42. raise e
  43. def on_handle_context(self, e_context: EventContext):
  44. if e_context["context"].type != ContextType.TEXT:
  45. return
  46. content = e_context["context"].content.strip()
  47. logger.debug("[keyword] on_handle_context. content: %s" % content)
  48. if content in self.keyword:
  49. logger.debug(f"[keyword] 匹配到关键字【{content}】")
  50. reply_text = self.keyword[content]
  51. reply = Reply()
  52. reply.type = ReplyType.TEXT
  53. reply.content = reply_text
  54. e_context["reply"] = reply
  55. e_context.action = EventAction.BREAK_PASS # 事件结束,并跳过处理context的默认逻辑
  56. def get_help_text(self, **kwargs):
  57. help_text = "关键词过滤"
  58. return help_text