441 lines
18KB

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