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.

290 satır
12KB

  1. # encoding:utf-8
  2. import json
  3. import os
  4. import traceback
  5. from typing import Tuple
  6. from bridge.bridge import Bridge
  7. from bridge.context import ContextType
  8. from bridge.reply import Reply, ReplyType
  9. from config import load_config
  10. import plugins
  11. from plugins import *
  12. from common.log import logger
  13. # 定义指令集
  14. COMMANDS = {
  15. "help": {
  16. "alias": ["help", "帮助"],
  17. "desc": "打印指令集合",
  18. },
  19. "auth": {
  20. "alias": ["auth", "认证"],
  21. "args": ["口令"],
  22. "desc": "管理员认证",
  23. },
  24. # "id": {
  25. # "alias": ["id", "用户"],
  26. # "desc": "获取用户id", #目前无实际意义
  27. # },
  28. "reset": {
  29. "alias": ["reset", "重置会话"],
  30. "desc": "重置会话",
  31. },
  32. }
  33. ADMIN_COMMANDS = {
  34. "resume": {
  35. "alias": ["resume", "恢复服务"],
  36. "desc": "恢复服务",
  37. },
  38. "stop": {
  39. "alias": ["stop", "暂停服务"],
  40. "desc": "暂停服务",
  41. },
  42. "reconf": {
  43. "alias": ["reconf", "重载配置"],
  44. "desc": "重载配置(不包含插件配置)",
  45. },
  46. "resetall": {
  47. "alias": ["resetall", "重置所有会话"],
  48. "desc": "重置所有会话",
  49. },
  50. "scanp": {
  51. "alias": ["scanp", "扫描插件"],
  52. "desc": "扫描插件目录是否有新插件",
  53. },
  54. "plist": {
  55. "alias": ["plist", "插件"],
  56. "desc": "打印当前插件列表",
  57. },
  58. "setpri": {
  59. "alias": ["setpri", "设置插件优先级"],
  60. "args": ["插件名", "优先级"],
  61. "desc": "设置指定插件的优先级,越大越优先",
  62. },
  63. "reloadp": {
  64. "alias": ["reloadp", "重载插件"],
  65. "args": ["插件名"],
  66. "desc": "重载指定插件配置",
  67. },
  68. "enablep": {
  69. "alias": ["enablep", "启用插件"],
  70. "args": ["插件名"],
  71. "desc": "启用指定插件",
  72. },
  73. "disablep": {
  74. "alias": ["disablep", "禁用插件"],
  75. "args": ["插件名"],
  76. "desc": "禁用指定插件",
  77. },
  78. "debug": {
  79. "alias": ["debug", "调试模式", "DEBUG"],
  80. "desc": "开启机器调试日志",
  81. },
  82. }
  83. # 定义帮助函数
  84. def get_help_text(isadmin, isgroup):
  85. help_text = "可用指令:\n"
  86. for cmd, info in COMMANDS.items():
  87. if cmd=="auth" and (isadmin or isgroup): # 群聊不可认证
  88. continue
  89. alias=["#"+a for a in info['alias']]
  90. help_text += f"{','.join(alias)} "
  91. if 'args' in info:
  92. args=["{"+a+"}" for a in info['args']]
  93. help_text += f"{' '.join(args)} "
  94. help_text += f": {info['desc']}\n"
  95. if ADMIN_COMMANDS and isadmin:
  96. help_text += "\n管理员指令:\n"
  97. for cmd, info in ADMIN_COMMANDS.items():
  98. alias=["#"+a for a in info['alias']]
  99. help_text += f"{','.join(alias)} "
  100. help_text += f": {info['desc']}\n"
  101. return help_text
  102. @plugins.register(name="Godcmd", desc="为你的机器人添加指令集,有用户和管理员两种角色,加载顺序请放在首位,初次运行后插件目录会生成配置文件, 填充管理员密码后即可认证", version="1.0", author="lanvent", desire_priority= 999)
  103. class Godcmd(Plugin):
  104. def __init__(self):
  105. super().__init__()
  106. curdir=os.path.dirname(__file__)
  107. config_path=os.path.join(curdir,"config.json")
  108. gconf=None
  109. if not os.path.exists(config_path):
  110. gconf={"password":"","admin_users":[]}
  111. with open(config_path,"w") as f:
  112. json.dump(gconf,f,indent=4)
  113. else:
  114. with open(config_path,"r") as f:
  115. gconf=json.load(f)
  116. self.password = gconf["password"]
  117. self.admin_users = gconf["admin_users"] # 预存的管理员账号,这些账号不需要认证 TODO: 用户名每次都会变,目前不可用
  118. self.isrunning = True # 机器人是否运行中
  119. self.handlers[Event.ON_HANDLE_CONTEXT] = self.on_handle_context
  120. logger.info("[Godcmd] inited")
  121. def on_handle_context(self, e_context: EventContext):
  122. context_type = e_context['context'].type
  123. if context_type != ContextType.TEXT:
  124. if not self.isrunning:
  125. e_context.action = EventAction.BREAK_PASS
  126. return
  127. content = e_context['context'].content
  128. logger.debug("[Godcmd] on_handle_context. content: %s" % content)
  129. if content.startswith("#"):
  130. # msg = e_context['context']['msg']
  131. user = e_context['context']['receiver']
  132. session_id = e_context['context']['session_id']
  133. isgroup = e_context['context']['isgroup']
  134. bottype = Bridge().get_bot_type("chat")
  135. bot = Bridge().get_bot("chat")
  136. # 将命令和参数分割
  137. command_parts = content[1:].split(" ")
  138. cmd = command_parts[0]
  139. args = command_parts[1:]
  140. isadmin=False
  141. if user in self.admin_users:
  142. isadmin=True
  143. ok=False
  144. result="string"
  145. if any(cmd in info['alias'] for info in COMMANDS.values()):
  146. cmd = next(c for c, info in COMMANDS.items() if cmd in info['alias'])
  147. if cmd == "auth":
  148. ok, result = self.authenticate(user, args, isadmin, isgroup)
  149. elif cmd == "help":
  150. ok, result = True, get_help_text(isadmin, isgroup)
  151. elif cmd == "id":
  152. ok, result = True, f"用户id=\n{user}"
  153. elif cmd == "reset":
  154. if bottype == "chatGPT":
  155. bot.sessions.clear_session(session_id)
  156. ok, result = True, "会话已重置"
  157. else:
  158. ok, result = False, "当前对话机器人不支持重置会话"
  159. logger.debug("[Godcmd] command: %s by %s" % (cmd, user))
  160. elif any(cmd in info['alias'] for info in ADMIN_COMMANDS.values()):
  161. if isadmin:
  162. if isgroup:
  163. ok, result = False, "群聊不可执行管理员指令"
  164. else:
  165. cmd = next(c for c, info in ADMIN_COMMANDS.items() if cmd in info['alias'])
  166. if cmd == "stop":
  167. self.isrunning = False
  168. ok, result = True, "服务已暂停"
  169. elif cmd == "resume":
  170. self.isrunning = True
  171. ok, result = True, "服务已恢复"
  172. elif cmd == "reconf":
  173. load_config()
  174. ok, result = True, "配置已重载"
  175. elif cmd == "resetall":
  176. if bottype == "chatGPT":
  177. bot.sessions.clear_all_session()
  178. ok, result = True, "重置所有会话成功"
  179. else:
  180. ok, result = False, "当前对话机器人不支持重置会话"
  181. elif cmd == "debug":
  182. logger.setLevel('DEBUG')
  183. ok, result = True, "DEBUG模式已开启"
  184. elif cmd == "plist":
  185. plugins = PluginManager().list_plugins()
  186. ok = True
  187. result = "插件列表:\n"
  188. for name,plugincls in plugins.items():
  189. result += f"{plugincls.name}_v{plugincls.version} {plugincls.priority} - "
  190. if plugincls.enabled:
  191. result += "已启用\n"
  192. else:
  193. result += "未启用\n"
  194. elif cmd == "scanp":
  195. new_plugins = PluginManager().scan_plugins()
  196. ok, result = True, "插件扫描完成"
  197. PluginManager().activate_plugins()
  198. if len(new_plugins) >0 :
  199. result += "\n发现新插件:\n"
  200. result += "\n".join([f"{p.name}_v{p.version}" for p in new_plugins])
  201. else :
  202. result +=", 未发现新插件"
  203. elif cmd == "setpri":
  204. if len(args) != 2:
  205. ok, result = False, "请提供插件名和优先级"
  206. else:
  207. ok = PluginManager().set_plugin_priority(args[0], int(args[1]))
  208. if ok:
  209. result = "插件" + args[0] + "优先级已设置为" + args[1]
  210. else:
  211. result = "插件不存在"
  212. elif cmd == "reloadp":
  213. if len(args) != 1:
  214. ok, result = False, "请提供插件名"
  215. else:
  216. ok = PluginManager().reload_plugin(args[0])
  217. if ok:
  218. result = "插件配置已重载"
  219. else:
  220. result = "插件不存在"
  221. elif cmd == "enablep":
  222. if len(args) != 1:
  223. ok, result = False, "请提供插件名"
  224. else:
  225. ok = PluginManager().enable_plugin(args[0])
  226. if ok:
  227. result = "插件已启用"
  228. else:
  229. result = "插件不存在"
  230. elif cmd == "disablep":
  231. if len(args) != 1:
  232. ok, result = False, "请提供插件名"
  233. else:
  234. ok = PluginManager().disable_plugin(args[0])
  235. if ok:
  236. result = "插件已禁用"
  237. else:
  238. result = "插件不存在"
  239. logger.debug("[Godcmd] admin command: %s by %s" % (cmd, user))
  240. else:
  241. ok, result = False, "需要管理员权限才能执行该指令"
  242. else:
  243. ok, result = False, f"未知指令:{cmd}\n查看指令列表请输入#help \n"
  244. reply = Reply()
  245. if ok:
  246. reply.type = ReplyType.INFO
  247. else:
  248. reply.type = ReplyType.ERROR
  249. reply.content = result
  250. e_context['reply'] = reply
  251. e_context.action = EventAction.BREAK_PASS # 事件结束,并跳过处理context的默认逻辑
  252. elif not self.isrunning:
  253. e_context.action = EventAction.BREAK_PASS
  254. def authenticate(self, userid, args, isadmin, isgroup) -> Tuple[bool,str] :
  255. if isgroup:
  256. return False,"请勿在群聊中认证"
  257. if isadmin:
  258. return False,"管理员账号无需认证"
  259. if len(self.password) == 0:
  260. return False,"未设置口令,无法认证"
  261. if len(args) != 1:
  262. return False,"请提供口令"
  263. password = args[0]
  264. if password == self.password:
  265. self.admin_users.append(userid)
  266. return True,"认证成功"
  267. else:
  268. return False,"认证失败"