Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

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