Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

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