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.

role.py 4.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  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. import plugins
  8. from plugins import *
  9. from common.log import logger
  10. class RolePlay():
  11. def __init__(self, bot, sessionid, desc, wrapper=None):
  12. self.bot = bot
  13. self.sessionid = sessionid
  14. bot.sessions.clear_session(sessionid)
  15. bot.sessions.build_session(sessionid, desc)
  16. self.wrapper = wrapper or "%s" # 用于包装用户输入
  17. def reset(self):
  18. self.bot.sessions.clear_session(self.sessionid)
  19. def action(self, user_action):
  20. prompt = self.wrapper % user_action
  21. return prompt
  22. @plugins.register(name="Role", desc="为你的Bot设置预设角色", version="1.0", author="lanvent", desire_priority= 0)
  23. class Role(Plugin):
  24. def __init__(self):
  25. super().__init__()
  26. curdir = os.path.dirname(__file__)
  27. config_path = os.path.join(curdir, "roles.json")
  28. try:
  29. with open(config_path, "r", encoding="utf-8") as f:
  30. config = json.load(f)
  31. self.roles = {role["title"].lower(): role for role in config["roles"]}
  32. if len(self.roles) == 0:
  33. raise Exception("no role found")
  34. self.handlers[Event.ON_HANDLE_CONTEXT] = self.on_handle_context
  35. self.roleplays = {}
  36. logger.info("[Role] inited")
  37. except FileNotFoundError:
  38. logger.error(f"[Role] init failed, {config_path} not found")
  39. except Exception as e:
  40. logger.error("[Role] init failed, exception: %s" % e)
  41. def get_role(self, name, find_closest=True):
  42. name = name.lower()
  43. found_role = None
  44. if name in self.roles:
  45. found_role = name
  46. elif find_closest:
  47. import difflib
  48. def str_simularity(a, b):
  49. return difflib.SequenceMatcher(None, a, b).ratio()
  50. max_sim = 0.0
  51. max_role = None
  52. for role in self.roles:
  53. sim = str_simularity(name, role)
  54. if sim >= max_sim:
  55. max_sim = sim
  56. max_role = role
  57. found_role = max_role
  58. return found_role
  59. def on_handle_context(self, e_context: EventContext):
  60. if e_context['context'].type != ContextType.TEXT:
  61. return
  62. bottype = Bridge().get_bot_type("chat")
  63. if bottype != "chatGPT":
  64. return
  65. bot = Bridge().get_bot("chat")
  66. content = e_context['context'].content[:]
  67. clist = e_context['context'].content.split(maxsplit=1)
  68. desckey = None
  69. sessionid = e_context['context']['session_id']
  70. if clist[0] == "$停止扮演":
  71. if sessionid in self.roleplays:
  72. self.roleplays[sessionid].reset()
  73. del self.roleplays[sessionid]
  74. reply = Reply(ReplyType.INFO, "角色扮演结束!")
  75. e_context['reply'] = reply
  76. e_context.action = EventAction.BREAK_PASS
  77. return
  78. elif clist[0] == "$角色":
  79. desckey = "descn"
  80. elif clist[0].lower() == "$role":
  81. desckey = "description"
  82. elif sessionid not in self.roleplays:
  83. return
  84. logger.debug("[Role] on_handle_context. content: %s" % content)
  85. if desckey is not None:
  86. if len(clist) == 1 or (len(clist) > 1 and clist[1].lower() in ["help", "帮助"]):
  87. reply = Reply(ReplyType.INFO, self.get_help_text())
  88. e_context['reply'] = reply
  89. e_context.action = EventAction.BREAK_PASS
  90. return
  91. role = self.get_role(clist[1])
  92. if role is None:
  93. reply = Reply(ReplyType.ERROR, "角色不存在")
  94. e_context['reply'] = reply
  95. e_context.action = EventAction.BREAK_PASS
  96. return
  97. else:
  98. self.roleplays[sessionid] = RolePlay(bot, sessionid, self.roles[role][desckey],self.roles[role].get("wrapper","%s"))
  99. reply = Reply(ReplyType.INFO, f"角色设定为 {role} :\n"+self.roles[role][desckey])
  100. e_context['reply'] = reply
  101. e_context.action = EventAction.BREAK_PASS
  102. else:
  103. prompt = self.roleplays[sessionid].action(content)
  104. e_context['context'].type = ContextType.TEXT
  105. e_context['context'].content = prompt
  106. e_context.action = EventAction.CONTINUE
  107. def get_help_text(self):
  108. help_text = "输入\"$角色 (角色名)\"或\"$role (角色名)\"为我设定角色吧,#reset 可以清除设定的角色。\n目前可用角色列表:\n"
  109. for role in self.roles:
  110. help_text += f"[{role}]: {self.roles[role]['remark']}\n"
  111. return help_text