Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

409 lines
17KB

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