No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

keyword.py 4.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. # encoding:utf-8
  2. import json
  3. import os
  4. import requests
  5. import plugins
  6. from bridge.context import ContextType
  7. from bridge.reply import Reply, ReplyType
  8. from common.log import logger
  9. from plugins import *
  10. @plugins.register(
  11. name="Keyword",
  12. desire_priority=900,
  13. hidden=True,
  14. desc="关键词匹配过滤",
  15. version="0.1",
  16. author="fengyege.top",
  17. )
  18. class Keyword(Plugin):
  19. def __init__(self):
  20. super().__init__()
  21. try:
  22. curdir = os.path.dirname(__file__)
  23. config_path = os.path.join(curdir, "config.json")
  24. conf = None
  25. if not os.path.exists(config_path):
  26. logger.debug(f"[keyword]不存在配置文件{config_path}")
  27. conf = {"keyword": {}}
  28. with open(config_path, "w", encoding="utf-8") as f:
  29. json.dump(conf, f, indent=4)
  30. else:
  31. logger.debug(f"[keyword]加载配置文件{config_path}")
  32. with open(config_path, "r", encoding="utf-8") as f:
  33. conf = json.load(f)
  34. # 加载关键词
  35. self.keyword = conf["keyword"]
  36. logger.info("[keyword] {}".format(self.keyword))
  37. self.handlers[Event.ON_HANDLE_CONTEXT] = self.on_handle_context
  38. logger.info("[keyword] inited.")
  39. except Exception as e:
  40. logger.warn("[keyword] init failed, ignore or see https://github.com/zhayujie/chatgpt-on-wechat/tree/master/plugins/keyword .")
  41. raise e
  42. def on_handle_context(self, e_context: EventContext):
  43. if e_context["context"].type != ContextType.TEXT:
  44. return
  45. content = e_context["context"].content.strip()
  46. logger.debug("[keyword] on_handle_context. content: %s" % content)
  47. if content in self.keyword:
  48. logger.info(f"[keyword] 匹配到关键字【{content}】")
  49. reply_text = self.keyword[content]
  50. # 判断匹配内容的类型
  51. if (reply_text.startswith("http://") or reply_text.startswith("https://")) and any(reply_text.endswith(ext) for ext in [".jpg", ".webp", ".jpeg", ".png", ".gif", ".img"]):
  52. # 如果是以 http:// 或 https:// 开头,且".jpg", ".jpeg", ".png", ".gif", ".img"结尾,则认为是图片 URL。
  53. reply = Reply()
  54. reply.type = ReplyType.IMAGE_URL
  55. reply.content = reply_text
  56. elif (reply_text.startswith("http://") or reply_text.startswith("https://")) and any(reply_text.endswith(ext) for ext in [".pdf", ".doc", ".docx", ".xls", "xlsx",".zip", ".rar"]):
  57. # 如果是以 http:// 或 https:// 开头,且".pdf", ".doc", ".docx", ".xls", "xlsx",".zip", ".rar"结尾,则下载文件到tmp目录并发送给用户
  58. file_path = "tmp"
  59. if not os.path.exists(file_path):
  60. os.makedirs(file_path)
  61. file_name = reply_text.split("/")[-1] # 获取文件名
  62. file_path = os.path.join(file_path, file_name)
  63. response = requests.get(reply_text)
  64. with open(file_path, "wb") as f:
  65. f.write(response.content)
  66. #channel/wechat/wechat_channel.py和channel/wechat_channel.py中缺少ReplyType.FILE类型。
  67. reply = Reply()
  68. reply.type = ReplyType.FILE
  69. reply.content = file_path
  70. elif (reply_text.startswith("http://") or reply_text.startswith("https://")) and any(reply_text.endswith(ext) for ext in [".mp4"]):
  71. # 如果是以 http:// 或 https:// 开头,且".mp4"结尾,则下载视频到tmp目录并发送给用户
  72. reply = Reply()
  73. reply.type = ReplyType.VIDEO_URL
  74. reply.content = reply_text
  75. else:
  76. # 否则认为是普通文本
  77. reply = Reply()
  78. reply.type = ReplyType.TEXT
  79. reply.content = reply_text
  80. e_context["reply"] = reply
  81. e_context.action = EventAction.BREAK_PASS # 事件结束,并跳过处理context的默认逻辑
  82. def get_help_text(self, **kwargs):
  83. help_text = "关键词过滤"
  84. return help_text