You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
преди 1 година
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  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.roles = {role["title"].lower(): role for role in config["roles"]}
  37. if len(self.roles) == 0:
  38. raise Exception("no role found")
  39. self.handlers[Event.ON_HANDLE_CONTEXT] = self.on_handle_context
  40. self.roleplays = {}
  41. logger.info("[Role] inited")
  42. except FileNotFoundError:
  43. logger.warn(f"[Role] init failed, {config_path} not found, ignore or see https://github.com/zhayujie/chatgpt-on-wechat/tree/master/plugins/role .")
  44. except Exception as e:
  45. logger.warn("[Role] init failed, exception: %s, ignore or see https://github.com/zhayujie/chatgpt-on-wechat/tree/master/plugins/role ." % e)
  46. def get_role(self, name, find_closest=True):
  47. name = name.lower()
  48. found_role = None
  49. if name in self.roles:
  50. found_role = name
  51. elif find_closest:
  52. import difflib
  53. def str_simularity(a, b):
  54. return difflib.SequenceMatcher(None, a, b).ratio()
  55. max_sim = 0.0
  56. max_role = None
  57. for role in self.roles:
  58. sim = str_simularity(name, role)
  59. if sim >= max_sim:
  60. max_sim = sim
  61. max_role = role
  62. found_role = max_role
  63. return found_role
  64. def on_handle_context(self, e_context: EventContext):
  65. if e_context['context'].type != ContextType.TEXT:
  66. return
  67. bottype = Bridge().get_bot_type("chat")
  68. if bottype not in (const.CHATGPT, const.OPEN_AI):
  69. return
  70. bot = Bridge().get_bot("chat")
  71. content = e_context['context'].content[:]
  72. clist = e_context['context'].content.split(maxsplit=1)
  73. desckey = None
  74. customize = False
  75. sessionid = e_context['context']['session_id']
  76. trigger_prefix = conf().get('plugin_trigger_prefix', "$")
  77. if clist[0] == f"{trigger_prefix}停止扮演":
  78. if sessionid in self.roleplays:
  79. self.roleplays[sessionid].reset()
  80. del self.roleplays[sessionid]
  81. reply = Reply(ReplyType.INFO, "角色扮演结束!")
  82. e_context['reply'] = reply
  83. e_context.action = EventAction.BREAK_PASS
  84. return
  85. elif clist[0] == f"{trigger_prefix}角色":
  86. desckey = "descn"
  87. elif clist[0].lower() == f"{trigger_prefix}role":
  88. desckey = "description"
  89. elif clist[0] == f"{trigger_prefix}设定扮演":
  90. customize = True
  91. elif sessionid not in self.roleplays:
  92. return
  93. logger.debug("[Role] on_handle_context. content: %s" % content)
  94. if desckey is not None:
  95. if len(clist) == 1 or (len(clist) > 1 and clist[1].lower() in ["help", "帮助"]):
  96. reply = Reply(ReplyType.INFO, self.get_help_text(verbose=True))
  97. e_context['reply'] = reply
  98. e_context.action = EventAction.BREAK_PASS
  99. return
  100. role = self.get_role(clist[1])
  101. if role is None:
  102. reply = Reply(ReplyType.ERROR, "角色不存在")
  103. e_context['reply'] = reply
  104. e_context.action = EventAction.BREAK_PASS
  105. return
  106. else:
  107. self.roleplays[sessionid] = RolePlay(bot, sessionid, self.roles[role][desckey], self.roles[role].get("wrapper","%s"))
  108. reply = Reply(ReplyType.INFO, f"预设角色为 {role}:\n"+self.roles[role][desckey])
  109. e_context['reply'] = reply
  110. e_context.action = EventAction.BREAK_PASS
  111. elif customize == True:
  112. self.roleplays[sessionid] = RolePlay(bot, sessionid, clist[1], "%s")
  113. reply = Reply(ReplyType.INFO, f"角色设定为:\n{clist[1]}")
  114. e_context['reply'] = reply
  115. e_context.action = EventAction.BREAK_PASS
  116. else:
  117. prompt = self.roleplays[sessionid].action(content)
  118. e_context['context'].type = ContextType.TEXT
  119. e_context['context'].content = prompt
  120. e_context.action = EventAction.BREAK
  121. def get_help_text(self, verbose=False, **kwargs):
  122. help_text = "让机器人扮演不同的角色。\n"
  123. if not verbose:
  124. return help_text
  125. trigger_prefix = conf().get('plugin_trigger_prefix', "$")
  126. help_text = f"使用方法:\n{trigger_prefix}角色"+" {预设角色名}: 设定为预设角色。\n"+f"{trigger_prefix}role"+" {预设角色名}: 同上,但使用英文设定。\n"
  127. help_text += f"{trigger_prefix}设定扮演"+" {角色设定}: 设定自定义角色人设。\n"
  128. help_text += f"{trigger_prefix}停止扮演: 清除设定的角色。\n"
  129. help_text += "\n目前可用的预设角色名列表: \n"
  130. for role in self.roles:
  131. help_text += f"{role}: {self.roles[role]['remark']}\n"
  132. help_text += f"\n命令例子: '{trigger_prefix}角色 写作助理'"
  133. return help_text