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.

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