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.

188 líneas
8.5KB

  1. # encoding:utf-8
  2. import json
  3. import os
  4. from bridge.bridge import Bridge
  5. from bridge.context import ContextType
  6. from bridge.reply import Reply, ReplyType
  7. from common import const
  8. from config import conf
  9. import plugins
  10. from plugins import *
  11. from common.log import logger
  12. class RolePlay():
  13. def __init__(self, bot, sessionid, desc, wrapper=None):
  14. self.bot = bot
  15. self.sessionid = sessionid
  16. self.wrapper = wrapper or "%s" # 用于包装用户输入
  17. self.desc = desc
  18. self.bot.sessions.build_session(self.sessionid, system_prompt=self.desc)
  19. def reset(self):
  20. self.bot.sessions.clear_session(self.sessionid)
  21. def action(self, user_action):
  22. session = self.bot.sessions.build_session(self.sessionid)
  23. if session.system_prompt != self.desc: # 目前没有触发session过期事件,这里先简单判断,然后重置
  24. session.set_system_prompt(self.desc)
  25. prompt = self.wrapper % user_action
  26. return prompt
  27. @plugins.register(name="Role", desire_priority=0, namecn="角色扮演", desc="为你的Bot设置预设角色", version="1.0", author="lanvent")
  28. class Role(Plugin):
  29. def __init__(self):
  30. super().__init__()
  31. curdir = os.path.dirname(__file__)
  32. config_path = os.path.join(curdir, "roles.json")
  33. try:
  34. with open(config_path, "r", encoding="utf-8") as f:
  35. config = json.load(f)
  36. self.tags = { tag:(desc,[]) for tag,desc in config["tags"].items()}
  37. self.roles = {}
  38. for role in config["roles"]:
  39. self.roles[role["title"].lower()] = role
  40. for tag in role["tags"]:
  41. if tag not in self.tags:
  42. logger.warning(f"[Role] unknown tag {tag} ")
  43. self.tags[tag] = (tag, [])
  44. self.tags[tag][1].append(role)
  45. for tag in list(self.tags.keys()):
  46. if len(self.tags[tag][1]) == 0:
  47. logger.debug(f"[Role] no role found for tag {tag} ")
  48. del self.tags[tag]
  49. if len(self.roles) == 0:
  50. raise Exception("no role found")
  51. self.handlers[Event.ON_HANDLE_CONTEXT] = self.on_handle_context
  52. self.roleplays = {}
  53. logger.info("[Role] inited")
  54. except Exception as e:
  55. if isinstance(e, FileNotFoundError):
  56. logger.warn(f"[Role] init failed, {config_path} not found, ignore or see https://github.com/zhayujie/chatgpt-on-wechat/tree/master/plugins/role .")
  57. else:
  58. logger.warn("[Role] init failed, ignore or see https://github.com/zhayujie/chatgpt-on-wechat/tree/master/plugins/role .")
  59. raise e
  60. def get_role(self, name, find_closest=True, min_sim = 0.35):
  61. name = name.lower()
  62. found_role = None
  63. if name in self.roles:
  64. found_role = name
  65. elif find_closest:
  66. import difflib
  67. def str_simularity(a, b):
  68. return difflib.SequenceMatcher(None, a, b).ratio()
  69. max_sim = min_sim
  70. max_role = None
  71. for role in self.roles:
  72. sim = str_simularity(name, role)
  73. if sim >= max_sim:
  74. max_sim = sim
  75. max_role = role
  76. found_role = max_role
  77. return found_role
  78. def on_handle_context(self, e_context: EventContext):
  79. if e_context['context'].type != ContextType.TEXT:
  80. return
  81. bottype = Bridge().get_bot_type("chat")
  82. if bottype not in (const.CHATGPT, const.OPEN_AI):
  83. return
  84. bot = Bridge().get_bot("chat")
  85. content = e_context['context'].content[:]
  86. clist = e_context['context'].content.split(maxsplit=1)
  87. desckey = None
  88. customize = False
  89. sessionid = e_context['context']['session_id']
  90. trigger_prefix = conf().get('plugin_trigger_prefix', "$")
  91. if clist[0] == f"{trigger_prefix}停止扮演":
  92. if sessionid in self.roleplays:
  93. self.roleplays[sessionid].reset()
  94. del self.roleplays[sessionid]
  95. reply = Reply(ReplyType.INFO, "角色扮演结束!")
  96. e_context['reply'] = reply
  97. e_context.action = EventAction.BREAK_PASS
  98. return
  99. elif clist[0] == f"{trigger_prefix}角色":
  100. desckey = "descn"
  101. elif clist[0].lower() == f"{trigger_prefix}role":
  102. desckey = "description"
  103. elif clist[0] == f"{trigger_prefix}设定扮演":
  104. customize = True
  105. elif clist[0] == f"{trigger_prefix}角色类型":
  106. if len(clist) >1:
  107. tag = clist[1].strip()
  108. help_text = "角色列表:\n"
  109. for key,value in self.tags.items():
  110. if value[0] == tag:
  111. tag = key
  112. break
  113. if tag == "所有":
  114. for role in self.roles.values():
  115. help_text += f"{role['title']}: {role['remark']}\n"
  116. elif tag in self.tags:
  117. for role in self.tags[tag][1]:
  118. help_text += f"{role['title']}: {role['remark']}\n"
  119. else:
  120. help_text = f"未知角色类型。\n"
  121. help_text += "目前的角色类型有: \n"
  122. help_text += ",".join([self.tags[tag][0] for tag in self.tags])+"\n"
  123. else:
  124. help_text = f"请输入角色类型。\n"
  125. help_text += "目前的角色类型有: \n"
  126. help_text += ",".join([self.tags[tag][0] for tag in self.tags])+"\n"
  127. reply = Reply(ReplyType.INFO, help_text)
  128. e_context['reply'] = reply
  129. e_context.action = EventAction.BREAK_PASS
  130. return
  131. elif sessionid not in self.roleplays:
  132. return
  133. logger.debug("[Role] on_handle_context. content: %s" % content)
  134. if desckey is not None:
  135. if len(clist) == 1 or (len(clist) > 1 and clist[1].lower() in ["help", "帮助"]):
  136. reply = Reply(ReplyType.INFO, self.get_help_text(verbose=True))
  137. e_context['reply'] = reply
  138. e_context.action = EventAction.BREAK_PASS
  139. return
  140. role = self.get_role(clist[1])
  141. if role is None:
  142. reply = Reply(ReplyType.ERROR, "角色不存在")
  143. e_context['reply'] = reply
  144. e_context.action = EventAction.BREAK_PASS
  145. return
  146. else:
  147. self.roleplays[sessionid] = RolePlay(bot, sessionid, self.roles[role][desckey], self.roles[role].get("wrapper","%s"))
  148. reply = Reply(ReplyType.INFO, f"预设角色为 {role}:\n"+self.roles[role][desckey])
  149. e_context['reply'] = reply
  150. e_context.action = EventAction.BREAK_PASS
  151. elif customize == True:
  152. self.roleplays[sessionid] = RolePlay(bot, sessionid, clist[1], "%s")
  153. reply = Reply(ReplyType.INFO, f"角色设定为:\n{clist[1]}")
  154. e_context['reply'] = reply
  155. e_context.action = EventAction.BREAK_PASS
  156. else:
  157. prompt = self.roleplays[sessionid].action(content)
  158. e_context['context'].type = ContextType.TEXT
  159. e_context['context'].content = prompt
  160. e_context.action = EventAction.BREAK
  161. def get_help_text(self, verbose=False, **kwargs):
  162. help_text = "让机器人扮演不同的角色。\n"
  163. if not verbose:
  164. return help_text
  165. trigger_prefix = conf().get('plugin_trigger_prefix', "$")
  166. help_text = f"使用方法:\n{trigger_prefix}角色"+" 预设角色名: 设定角色为{预设角色名}。\n"+f"{trigger_prefix}role"+" 预设角色名: 同上,但使用英文设定。\n"
  167. help_text += f"{trigger_prefix}设定扮演"+" 角色设定: 设定自定义角色人设为{角色设定}。\n"
  168. help_text += f"{trigger_prefix}停止扮演: 清除设定的角色。\n"
  169. help_text += f"{trigger_prefix}角色类型"+" 角色类型: 查看某类{角色类型}的所有预设角色,为所有时输出所有预设角色。\n"
  170. help_text += "\n目前的角色类型有: \n"
  171. help_text += ",".join([self.tags[tag][0] for tag in self.tags])+"。\n"
  172. help_text += f"\n命令例子: \n{trigger_prefix}角色 写作助理\n"
  173. help_text += f"{trigger_prefix}角色类型 所有\n"
  174. help_text += f"{trigger_prefix}停止扮演\n"
  175. return help_text