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.

461 line
20KB

  1. # encoding:utf-8
  2. import json
  3. import os
  4. import random
  5. import string
  6. from typing import Tuple
  7. import plugins
  8. from bridge.bridge import Bridge
  9. from bridge.context import ContextType
  10. from bridge.reply import Reply, ReplyType
  11. from common import const
  12. from config import conf, load_config, global_config
  13. from plugins import *
  14. # 定义指令集
  15. COMMANDS = {
  16. "help": {
  17. "alias": ["help", "帮助"],
  18. "desc": "回复此帮助",
  19. },
  20. "helpp": {
  21. "alias": ["help", "帮助"], # 与help指令共用别名,根据参数数量区分
  22. "args": ["插件名"],
  23. "desc": "回复指定插件的详细帮助",
  24. },
  25. "auth": {
  26. "alias": ["auth", "认证"],
  27. "args": ["口令"],
  28. "desc": "管理员认证",
  29. },
  30. "model": {
  31. "alias": ["model", "模型"],
  32. "desc": "查看和设置全局模型",
  33. },
  34. "set_openai_api_key": {
  35. "alias": ["set_openai_api_key"],
  36. "args": ["api_key"],
  37. "desc": "设置你的OpenAI私有api_key",
  38. },
  39. "reset_openai_api_key": {
  40. "alias": ["reset_openai_api_key"],
  41. "desc": "重置为默认的api_key",
  42. },
  43. "set_gpt_model": {
  44. "alias": ["set_gpt_model"],
  45. "desc": "设置你的私有模型",
  46. },
  47. "reset_gpt_model": {
  48. "alias": ["reset_gpt_model"],
  49. "desc": "重置你的私有模型",
  50. },
  51. "gpt_model": {
  52. "alias": ["gpt_model"],
  53. "desc": "查询你使用的模型",
  54. },
  55. "id": {
  56. "alias": ["id", "用户"],
  57. "desc": "获取用户id", # wechaty和wechatmp的用户id不会变化,可用于绑定管理员
  58. },
  59. "reset": {
  60. "alias": ["reset", "重置会话"],
  61. "desc": "重置会话",
  62. },
  63. }
  64. ADMIN_COMMANDS = {
  65. "resume": {
  66. "alias": ["resume", "恢复服务"],
  67. "desc": "恢复服务",
  68. },
  69. "stop": {
  70. "alias": ["stop", "暂停服务"],
  71. "desc": "暂停服务",
  72. },
  73. "reconf": {
  74. "alias": ["reconf", "重载配置"],
  75. "desc": "重载配置(不包含插件配置)",
  76. },
  77. "resetall": {
  78. "alias": ["resetall", "重置所有会话"],
  79. "desc": "重置所有会话",
  80. },
  81. "scanp": {
  82. "alias": ["scanp", "扫描插件"],
  83. "desc": "扫描插件目录是否有新插件",
  84. },
  85. "plist": {
  86. "alias": ["plist", "插件"],
  87. "desc": "打印当前插件列表",
  88. },
  89. "setpri": {
  90. "alias": ["setpri", "设置插件优先级"],
  91. "args": ["插件名", "优先级"],
  92. "desc": "设置指定插件的优先级,越大越优先",
  93. },
  94. "reloadp": {
  95. "alias": ["reloadp", "重载插件"],
  96. "args": ["插件名"],
  97. "desc": "重载指定插件配置",
  98. },
  99. "enablep": {
  100. "alias": ["enablep", "启用插件"],
  101. "args": ["插件名"],
  102. "desc": "启用指定插件",
  103. },
  104. "disablep": {
  105. "alias": ["disablep", "禁用插件"],
  106. "args": ["插件名"],
  107. "desc": "禁用指定插件",
  108. },
  109. "installp": {
  110. "alias": ["installp", "安装插件"],
  111. "args": ["仓库地址或插件名"],
  112. "desc": "安装指定插件",
  113. },
  114. "uninstallp": {
  115. "alias": ["uninstallp", "卸载插件"],
  116. "args": ["插件名"],
  117. "desc": "卸载指定插件",
  118. },
  119. "updatep": {
  120. "alias": ["updatep", "更新插件"],
  121. "args": ["插件名"],
  122. "desc": "更新指定插件",
  123. },
  124. "debug": {
  125. "alias": ["debug", "调试模式", "DEBUG"],
  126. "desc": "开启机器调试日志",
  127. },
  128. }
  129. # 定义帮助函数
  130. def get_help_text(isadmin, isgroup):
  131. help_text = "通用指令:\n"
  132. for cmd, info in COMMANDS.items():
  133. if cmd == "auth": # 不提示认证指令
  134. continue
  135. if cmd == "id" and conf().get("channel_type", "wx") not in ["wxy", "wechatmp"]:
  136. continue
  137. alias = ["#" + a for a in info["alias"][:1]]
  138. help_text += f"{','.join(alias)} "
  139. if "args" in info:
  140. args = [a for a in info["args"]]
  141. help_text += f"{' '.join(args)}"
  142. help_text += f": {info['desc']}\n"
  143. # 插件指令
  144. plugins = PluginManager().list_plugins()
  145. help_text += "\n目前可用插件有:"
  146. for plugin in plugins:
  147. if plugins[plugin].enabled and not plugins[plugin].hidden:
  148. namecn = plugins[plugin].namecn
  149. help_text += "\n%s:" % namecn
  150. help_text += PluginManager().instances[plugin].get_help_text(verbose=False).strip()
  151. if ADMIN_COMMANDS and isadmin:
  152. help_text += "\n\n管理员指令:\n"
  153. for cmd, info in ADMIN_COMMANDS.items():
  154. alias = ["#" + a for a in info["alias"][:1]]
  155. help_text += f"{','.join(alias)} "
  156. if "args" in info:
  157. args = [a for a in info["args"]]
  158. help_text += f"{' '.join(args)}"
  159. help_text += f": {info['desc']}\n"
  160. return help_text
  161. @plugins.register(
  162. name="Godcmd",
  163. desire_priority=999,
  164. hidden=True,
  165. desc="为你的机器人添加指令集,有用户和管理员两种角色,加载顺序请放在首位,初次运行后插件目录会生成配置文件, 填充管理员密码后即可认证",
  166. version="1.0",
  167. author="lanvent",
  168. )
  169. class Godcmd(Plugin):
  170. def __init__(self):
  171. super().__init__()
  172. config_path = os.path.join(os.path.dirname(__file__), "config.json")
  173. gconf = super().load_config()
  174. if not gconf:
  175. if not os.path.exists(config_path):
  176. gconf = {"password": "", "admin_users": []}
  177. with open(config_path, "w") as f:
  178. json.dump(gconf, f, indent=4)
  179. if gconf["password"] == "":
  180. self.temp_password = "".join(random.sample(string.digits, 4))
  181. logger.info("[Godcmd] 因未设置口令,本次的临时口令为%s。" % self.temp_password)
  182. else:
  183. self.temp_password = None
  184. custom_commands = conf().get("clear_memory_commands", [])
  185. for custom_command in custom_commands:
  186. if custom_command and custom_command.startswith("#"):
  187. custom_command = custom_command[1:]
  188. if custom_command and custom_command not in COMMANDS["reset"]["alias"]:
  189. COMMANDS["reset"]["alias"].append(custom_command)
  190. self.password = gconf["password"]
  191. self.admin_users = gconf["admin_users"] # 预存的管理员账号,这些账号不需要认证。itchat的用户名每次都会变,不可用
  192. self.isrunning = True # 机器人是否运行中
  193. self.handlers[Event.ON_HANDLE_CONTEXT] = self.on_handle_context
  194. logger.info("[Godcmd] inited")
  195. def on_handle_context(self, e_context: EventContext):
  196. context_type = e_context["context"].type
  197. if context_type != ContextType.TEXT:
  198. if not self.isrunning:
  199. e_context.action = EventAction.BREAK_PASS
  200. return
  201. content = e_context["context"].content
  202. logger.debug("[Godcmd] on_handle_context. content: %s" % content)
  203. if content.startswith("#"):
  204. if len(content) == 1:
  205. reply = Reply()
  206. reply.type = ReplyType.ERROR
  207. reply.content = f"空指令,输入#help查看指令列表\n"
  208. e_context["reply"] = reply
  209. e_context.action = EventAction.BREAK_PASS
  210. return
  211. # msg = e_context['context']['msg']
  212. channel = e_context["channel"]
  213. user = e_context["context"]["receiver"]
  214. session_id = e_context["context"]["session_id"]
  215. isgroup = e_context["context"].get("isgroup", False)
  216. bottype = Bridge().get_bot_type("chat")
  217. bot = Bridge().get_bot("chat")
  218. # 将命令和参数分割
  219. command_parts = content[1:].strip().split()
  220. cmd = command_parts[0]
  221. args = command_parts[1:]
  222. isadmin = False
  223. if user in self.admin_users:
  224. isadmin = True
  225. ok = False
  226. result = "string"
  227. if any(cmd in info["alias"] for info in COMMANDS.values()):
  228. cmd = next(c for c, info in COMMANDS.items() if cmd in info["alias"])
  229. if cmd == "auth":
  230. ok, result = self.authenticate(user, args, isadmin, isgroup)
  231. elif cmd == "help" or cmd == "helpp":
  232. if len(args) == 0:
  233. ok, result = True, get_help_text(isadmin, isgroup)
  234. else:
  235. # This can replace the helpp command
  236. plugins = PluginManager().list_plugins()
  237. query_name = args[0].upper()
  238. # search name and namecn
  239. for name, plugincls in plugins.items():
  240. if not plugincls.enabled:
  241. continue
  242. if query_name == name or query_name == plugincls.namecn:
  243. ok, result = True, PluginManager().instances[name].get_help_text(isgroup=isgroup, isadmin=isadmin, verbose=True)
  244. break
  245. if not ok:
  246. result = "插件不存在或未启用"
  247. elif cmd == "model":
  248. if not isadmin and not self.is_admin_in_group(e_context["context"]):
  249. ok, result = False, "需要管理员权限执行"
  250. elif len(args) == 0:
  251. ok, result = True, "当前模型为: " + str(conf().get("model"))
  252. elif len(args) == 1:
  253. if args[0] not in const.MODEL_LIST:
  254. ok, result = False, "模型名称不存在"
  255. else:
  256. conf()["model"] = args[0]
  257. Bridge().reset_bot()
  258. ok, result = True, "模型设置为: " + str(conf().get("model"))
  259. elif cmd == "id":
  260. ok, result = True, user
  261. elif cmd == "set_openai_api_key":
  262. if len(args) == 1:
  263. user_data = conf().get_user_data(user)
  264. user_data["openai_api_key"] = args[0]
  265. ok, result = True, "你的OpenAI私有api_key已设置为" + args[0]
  266. else:
  267. ok, result = False, "请提供一个api_key"
  268. elif cmd == "reset_openai_api_key":
  269. try:
  270. user_data = conf().get_user_data(user)
  271. user_data.pop("openai_api_key")
  272. ok, result = True, "你的OpenAI私有api_key已清除"
  273. except Exception as e:
  274. ok, result = False, "你没有设置私有api_key"
  275. elif cmd == "set_gpt_model":
  276. if len(args) == 1:
  277. user_data = conf().get_user_data(user)
  278. user_data["gpt_model"] = args[0]
  279. ok, result = True, "你的GPT模型已设置为" + args[0]
  280. else:
  281. ok, result = False, "请提供一个GPT模型"
  282. elif cmd == "gpt_model":
  283. user_data = conf().get_user_data(user)
  284. model = conf().get("model")
  285. if "gpt_model" in user_data:
  286. model = user_data["gpt_model"]
  287. ok, result = True, "你的GPT模型为" + str(model)
  288. elif cmd == "reset_gpt_model":
  289. try:
  290. user_data = conf().get_user_data(user)
  291. user_data.pop("gpt_model")
  292. ok, result = True, "你的GPT模型已重置"
  293. except Exception as e:
  294. ok, result = False, "你没有设置私有GPT模型"
  295. elif cmd == "reset":
  296. if bottype in [const.OPEN_AI, const.CHATGPT, const.CHATGPTONAZURE, const.LINKAI, const.BAIDU, const.XUNFEI]:
  297. bot.sessions.clear_session(session_id)
  298. channel.cancel_session(session_id)
  299. ok, result = True, "会话已重置"
  300. else:
  301. ok, result = False, "当前对话机器人不支持重置会话"
  302. logger.debug("[Godcmd] command: %s by %s" % (cmd, user))
  303. elif any(cmd in info["alias"] for info in ADMIN_COMMANDS.values()):
  304. if isadmin:
  305. if isgroup:
  306. ok, result = False, "群聊不可执行管理员指令"
  307. else:
  308. cmd = next(c for c, info in ADMIN_COMMANDS.items() if cmd in info["alias"])
  309. if cmd == "stop":
  310. self.isrunning = False
  311. ok, result = True, "服务已暂停"
  312. elif cmd == "resume":
  313. self.isrunning = True
  314. ok, result = True, "服务已恢复"
  315. elif cmd == "reconf":
  316. load_config()
  317. ok, result = True, "配置已重载"
  318. elif cmd == "resetall":
  319. if bottype in [const.OPEN_AI, const.CHATGPT, const.CHATGPTONAZURE, const.LINKAI,
  320. const.BAIDU, const.XUNFEI]:
  321. channel.cancel_all_session()
  322. bot.sessions.clear_all_session()
  323. ok, result = True, "重置所有会话成功"
  324. else:
  325. ok, result = False, "当前对话机器人不支持重置会话"
  326. elif cmd == "debug":
  327. logger.setLevel("DEBUG")
  328. ok, result = True, "DEBUG模式已开启"
  329. elif cmd == "plist":
  330. plugins = PluginManager().list_plugins()
  331. ok = True
  332. result = "插件列表:\n"
  333. for name, plugincls in plugins.items():
  334. result += f"{plugincls.name}_v{plugincls.version} {plugincls.priority} - "
  335. if plugincls.enabled:
  336. result += "已启用\n"
  337. else:
  338. result += "未启用\n"
  339. elif cmd == "scanp":
  340. new_plugins = PluginManager().scan_plugins()
  341. ok, result = True, "插件扫描完成"
  342. PluginManager().activate_plugins()
  343. if len(new_plugins) > 0:
  344. result += "\n发现新插件:\n"
  345. result += "\n".join([f"{p.name}_v{p.version}" for p in new_plugins])
  346. else:
  347. result += ", 未发现新插件"
  348. elif cmd == "setpri":
  349. if len(args) != 2:
  350. ok, result = False, "请提供插件名和优先级"
  351. else:
  352. ok = PluginManager().set_plugin_priority(args[0], int(args[1]))
  353. if ok:
  354. result = "插件" + args[0] + "优先级已设置为" + args[1]
  355. else:
  356. result = "插件不存在"
  357. elif cmd == "reloadp":
  358. if len(args) != 1:
  359. ok, result = False, "请提供插件名"
  360. else:
  361. ok = PluginManager().reload_plugin(args[0])
  362. if ok:
  363. result = "插件配置已重载"
  364. else:
  365. result = "插件不存在"
  366. elif cmd == "enablep":
  367. if len(args) != 1:
  368. ok, result = False, "请提供插件名"
  369. else:
  370. ok, result = PluginManager().enable_plugin(args[0])
  371. elif cmd == "disablep":
  372. if len(args) != 1:
  373. ok, result = False, "请提供插件名"
  374. else:
  375. ok = PluginManager().disable_plugin(args[0])
  376. if ok:
  377. result = "插件已禁用"
  378. else:
  379. result = "插件不存在"
  380. elif cmd == "installp":
  381. if len(args) != 1:
  382. ok, result = False, "请提供插件名或.git结尾的仓库地址"
  383. else:
  384. ok, result = PluginManager().install_plugin(args[0])
  385. elif cmd == "uninstallp":
  386. if len(args) != 1:
  387. ok, result = False, "请提供插件名"
  388. else:
  389. ok, result = PluginManager().uninstall_plugin(args[0])
  390. elif cmd == "updatep":
  391. if len(args) != 1:
  392. ok, result = False, "请提供插件名"
  393. else:
  394. ok, result = PluginManager().update_plugin(args[0])
  395. logger.debug("[Godcmd] admin command: %s by %s" % (cmd, user))
  396. else:
  397. ok, result = False, "需要管理员权限才能执行该指令"
  398. else:
  399. trigger_prefix = conf().get("plugin_trigger_prefix", "$")
  400. if trigger_prefix == "#": # 跟插件聊天指令前缀相同,继续递交
  401. return
  402. ok, result = False, f"未知指令:{cmd}\n查看指令列表请输入#help \n"
  403. reply = Reply()
  404. if ok:
  405. reply.type = ReplyType.INFO
  406. else:
  407. reply.type = ReplyType.ERROR
  408. reply.content = result
  409. e_context["reply"] = reply
  410. e_context.action = EventAction.BREAK_PASS # 事件结束,并跳过处理context的默认逻辑
  411. elif not self.isrunning:
  412. e_context.action = EventAction.BREAK_PASS
  413. def authenticate(self, userid, args, isadmin, isgroup) -> Tuple[bool, str]:
  414. if isgroup:
  415. return False, "请勿在群聊中认证"
  416. if isadmin:
  417. return False, "管理员账号无需认证"
  418. if len(args) != 1:
  419. return False, "请提供口令"
  420. password = args[0]
  421. if password == self.password:
  422. self.admin_users.append(userid)
  423. global_config["admin_users"].append(userid)
  424. return True, "认证成功"
  425. elif password == self.temp_password:
  426. self.admin_users.append(userid)
  427. global_config["admin_users"].append(userid)
  428. return True, "认证成功,请尽快设置口令"
  429. else:
  430. return False, "认证失败"
  431. def get_help_text(self, isadmin=False, isgroup=False, **kwargs):
  432. return get_help_text(isadmin, isgroup)
  433. def is_admin_in_group(self, context):
  434. if context["isgroup"]:
  435. return context.kwargs.get("msg").actual_user_id in global_config["admin_users"]
  436. return False