Archived
1
0
Fork 0
This repository has been archived on 2024-04-26. You can view files and clone it, but cannot push or open issues or pull requests.
akari-bot/modules/core/__init__.py

294 lines
12 KiB
Python
Raw Normal View History

2021-07-26 12:43:51 +00:00
import asyncio
import os
2021-08-21 15:58:07 +00:00
import sys
2021-07-30 07:05:58 +00:00
import time
2021-07-26 12:43:51 +00:00
2021-08-07 07:56:48 +00:00
import psutil
2021-09-10 18:05:27 +00:00
import ujson as json
2021-08-07 07:56:48 +00:00
2021-08-30 18:53:39 +00:00
from core.elements import MessageSession, Command
2021-08-07 07:56:48 +00:00
from core.loader import ModulesManager
from core.loader.decorator import command
2021-07-26 12:43:51 +00:00
from core.parser.command import CommandParser
2021-08-23 12:44:31 +00:00
from core.utils import PrivateAssets
2021-08-07 07:56:48 +00:00
from database import BotDBUtil
2021-02-01 15:13:11 +00:00
2021-07-19 16:12:29 +00:00
@command('module',
is_base_function=True,
2021-07-27 14:31:45 +00:00
need_admin=True,
2021-08-02 04:14:26 +00:00
help_doc=('~module enable (<module>...|all) {开启一个/多个或所有模块}',
'~module disable (<module>...|all) {关闭一个/多个或所有模块}'),
2021-09-10 18:05:27 +00:00
alias={'enable': 'module enable', 'disable': 'module disable'}, allowed_none=False
2021-07-26 12:43:51 +00:00
)
async def config_modules(msg: MessageSession):
2021-08-02 04:14:26 +00:00
alias = ModulesManager.return_modules_alias_map()
modules = ModulesManager.return_modules_list_as_dict()
wait_config = msg.parsed_msg['<module>']
wait_config_list = []
for module in wait_config:
if module not in wait_config_list:
if module in alias:
2021-08-02 04:20:07 +00:00
wait_config_list.append(alias[module])
2021-08-02 04:14:26 +00:00
else:
wait_config_list.append(module)
2021-07-26 12:43:51 +00:00
query = BotDBUtil.Module(msg)
msglist = []
2021-09-10 18:05:27 +00:00
recommend_modules_list = []
2021-07-26 12:43:51 +00:00
if msg.parsed_msg['enable']:
2021-09-10 18:05:27 +00:00
enable_list = []
2021-08-26 16:24:21 +00:00
if wait_config_list == ['all']:
for function in modules:
2021-09-03 19:19:07 +00:00
if not modules[function].need_superuser and not modules[function].is_base_function:
2021-09-10 18:05:27 +00:00
enable_list.append(function)
2021-08-26 16:24:21 +00:00
else:
for module in wait_config_list:
if module not in modules:
msglist.append(f'失败:“{module}”模块不存在')
else:
if modules[module].need_superuser and not msg.checkSuperUser():
msglist.append(f'失败:你没有打开“{module}”的权限。')
2021-09-03 19:19:07 +00:00
elif modules[module].is_base_function:
msglist.append(f'失败:“{module}”为基础模块。')
2021-08-26 16:24:21 +00:00
else:
2021-09-10 18:05:27 +00:00
enable_list.append(module)
recommend = modules[module].recommend_modules
if isinstance(recommend, str):
recommend_modules_list.append(recommend)
if isinstance(recommend, (list, tuple)):
for r in recommend:
recommend_modules_list.append(r)
if query.enable(enable_list):
for x in enable_list:
msglist.append(f'成功:打开模块“{x}')
2021-07-26 12:43:51 +00:00
elif msg.parsed_msg['disable']:
2021-09-10 18:05:27 +00:00
disable_list = []
2021-08-26 16:24:21 +00:00
if wait_config_list == ['all']:
for function in modules:
2021-09-10 18:05:27 +00:00
if not modules[function].need_superuser and not modules[function].is_base_function:
disable_list.append(function)
2021-08-26 16:24:21 +00:00
else:
for module in wait_config_list:
if module not in modules:
msglist.append(f'失败:“{module}”模块不存在')
else:
2021-09-10 18:05:27 +00:00
disable_list.append(module)
if query.disable(disable_list):
for x in disable_list:
msglist.append(f'成功:关闭模块“{x}')
if msglist is not None:
2021-07-26 12:43:51 +00:00
await msg.sendMessage('\n'.join(msglist))
2021-09-10 18:05:27 +00:00
if recommend_modules_list:
fmt_help_doc_list = []
for m in recommend_modules_list:
fmt_help_doc_list.append(f'模块{m}的帮助信息:\n' + CommandParser(modules[m]).return_formatted_help_doc())
confirm = await msg.waitConfirm('建议同时打开以下模块:\n' +
'\n'.join(recommend_modules_list) + '\n' +
'\n'.join(fmt_help_doc_list) +
'\n是否一并打开?')
if confirm:
if query.enable(recommend_modules_list):
msglist = []
for x in recommend_modules_list:
msglist.append(f'成功:打开模块“{x}')
await msg.sendMessage('\n'.join(msglist))
2021-07-26 12:43:51 +00:00
2021-07-26 12:43:51 +00:00
@command('help',
is_base_function=True,
2021-07-27 16:03:48 +00:00
help_doc=('~help {查看所有可用模块}',
'~help <module> {查看一个模块的详细信息}')
2021-07-26 12:43:51 +00:00
)
async def bot_help(msg: MessageSession):
module_list = ModulesManager.return_modules_list_as_dict()
alias = ModulesManager.return_modules_alias_map()
if msg.parsed_msg is not None:
msgs = []
help_name = msg.parsed_msg['<module>']
if help_name in alias:
2021-07-26 12:43:51 +00:00
help_name = alias[help_name]
if help_name in module_list:
2021-09-10 18:05:27 +00:00
help_ = CommandParser(module_list[help_name]).return_formatted_help_doc()
2021-07-26 12:43:51 +00:00
if help_ is not None:
msgs.append(help_)
if msgs:
await msg.sendMessage('\n'.join(msgs))
else:
2021-07-26 12:43:51 +00:00
help_msg = ['基础命令:']
2021-02-07 09:56:01 +00:00
essential = []
2021-07-26 12:43:51 +00:00
for x in module_list:
2021-08-30 18:53:39 +00:00
if isinstance(module_list[x], Command) and module_list[x].is_base_function:
2021-07-26 12:43:51 +00:00
essential.append(module_list[x].bind_prefix)
2021-02-07 09:56:01 +00:00
help_msg.append(' | '.join(essential))
2021-02-01 17:41:45 +00:00
help_msg.append('模块扩展命令:')
2021-02-07 09:56:01 +00:00
module = []
2021-07-26 12:43:51 +00:00
for x in module_list:
2021-08-25 11:45:03 +00:00
if x in BotDBUtil.Module(msg).check_target_enabled_module_list():
2021-07-26 12:43:51 +00:00
module.append(x)
2021-02-07 09:56:01 +00:00
help_msg.append(' | '.join(module))
print(help_msg)
2021-08-07 07:56:48 +00:00
help_msg.append(
2021-08-26 16:24:21 +00:00
'使用~help <对应模块名>查看详细信息。\n使用~modules查看所有的可用模块。\n你也可以通过查阅文档获取帮助:\nhttps://bot.teahou.se/wiki/')
2021-07-26 12:43:51 +00:00
help_msg.append('[本消息将在一分钟后撤回]')
send = await msg.sendMessage('\n'.join(help_msg))
await asyncio.sleep(60)
await send.delete()
2021-02-01 15:13:11 +00:00
2021-07-26 12:43:51 +00:00
@command('modules',
is_base_function=True,
2021-07-27 16:03:48 +00:00
help_doc='~modules {查看所有可用模块}'
2021-07-26 12:43:51 +00:00
)
async def modules_help(msg: MessageSession):
module_list = ModulesManager.return_modules_list_as_dict()
help_msg = ['当前可用的模块有:']
2021-02-07 09:56:01 +00:00
module = []
2021-07-26 12:43:51 +00:00
for x in module_list:
2021-09-03 19:19:07 +00:00
if not module_list[x].is_base_function and not module_list[x].need_superuser:
module.append(module_list[x].bind_prefix)
2021-02-10 14:11:26 +00:00
help_msg.append(' | '.join(module))
2021-08-07 07:56:48 +00:00
help_msg.append(
2021-08-26 16:24:21 +00:00
'使用~help <模块名>查看详细信息。\n你也可以通过查阅文档获取帮助:\nhttps://bot.teahou.se/wiki/')
2021-07-26 12:43:51 +00:00
help_msg.append('[本消息将在一分钟后撤回]')
send = await msg.sendMessage('\n'.join(help_msg))
await asyncio.sleep(60)
await send.delete()
2021-02-01 15:13:11 +00:00
2021-07-26 12:43:51 +00:00
@command('version',
is_base_function=True,
2021-07-27 16:03:48 +00:00
help_doc='~version {查看机器人的版本号}'
2021-07-26 12:43:51 +00:00
)
async def bot_version(msg: MessageSession):
2021-08-21 15:58:07 +00:00
version = os.path.abspath(PrivateAssets.path + '/version')
tag = os.path.abspath(PrivateAssets.path + '/version_tag')
2021-08-02 04:40:29 +00:00
open_version = open(version, 'r')
open_tag = open(tag, 'r')
msgs = f'当前运行的代码版本号为:{open_tag.read()}{open_version.read()}'
2021-07-26 12:43:51 +00:00
await msg.sendMessage(msgs, msgs)
2021-08-02 04:40:29 +00:00
open_version.close()
2021-03-05 16:08:10 +00:00
2021-07-31 12:27:36 +00:00
2021-08-01 14:46:06 +00:00
@command('ping',
2021-07-30 07:05:58 +00:00
is_base_function=True,
help_doc='~ping {获取机器人信息}'
)
async def ping(msg: MessageSession):
checkpermisson = msg.checkSuperUser()
result = "Pong!"
if checkpermisson:
Boot_Start = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(psutil.boot_time()))
time.sleep(0.5)
Cpu_usage = psutil.cpu_percent()
RAM = int(psutil.virtual_memory().total / (1024 * 1024))
RAM_percent = psutil.virtual_memory().percent
Swap = int(psutil.swap_memory().total / (1024 * 1024))
Swap_percent = psutil.swap_memory().percent
2021-08-01 14:46:06 +00:00
Disk = int(psutil.disk_usage('/').used / (1024 * 1024 * 1024))
DiskTotal = int(psutil.disk_usage('/').total / (1024 * 1024 * 1024))
2021-07-31 12:27:36 +00:00
"""
2021-07-30 07:05:58 +00:00
try:
GroupList = len(await app.groupList())
except Exception:
GroupList = '无法获取'
try:
FriendList = len(await app.friendList())
except Exception:
FriendList = '无法获取'
2021-07-31 12:27:36 +00:00
"""
2021-07-30 07:05:58 +00:00
BFH = r'%'
result += (f"\n系统运行时间:{Boot_Start}"
2021-07-31 12:27:36 +00:00
+ f"\n当前CPU使用率{Cpu_usage}{BFH}"
+ f"\n物理内存:{RAM}M 使用率:{RAM_percent}{BFH}"
+ f"\nSwap内存{Swap}M 使用率:{Swap_percent}{BFH}"
2021-08-01 14:46:06 +00:00
+ f"\n磁盘容量:{Disk}G/{DiskTotal}G"
2021-08-07 07:56:48 +00:00
# + f"\n已加入QQ群聊{GroupList}"
# + f" | 已添加QQ好友{FriendList}" """
)
2021-07-30 07:05:58 +00:00
await msg.sendMessage(result)
2021-03-05 16:08:10 +00:00
2021-07-31 12:27:36 +00:00
2021-07-26 12:43:51 +00:00
@command('admin',
is_base_function=True,
2021-07-27 14:31:45 +00:00
need_admin=True,
2021-09-10 18:05:27 +00:00
help_doc=('~admin add <UserID> {设置成员为机器人管理员}', '~admin del <UserID> {取消成员的机器人管理员}'), allowed_none=False
2021-07-26 12:43:51 +00:00
)
async def config_gu(msg: MessageSession):
if msg.parsed_msg['add']:
2021-08-25 15:15:20 +00:00
user = msg.parsed_msg['<UserID>']
2021-08-22 14:55:25 +00:00
if user and not BotDBUtil.SenderInfo(f"{msg.target.senderFrom}|{user}").check_TargetAdmin(msg.target.targetId):
2021-07-26 12:43:51 +00:00
if BotDBUtil.SenderInfo(f"{msg.target.senderFrom}|{user}").add_TargetAdmin(msg.target.targetId):
await msg.sendMessage("成功")
if msg.parsed_msg['del']:
2021-08-25 15:15:20 +00:00
user = msg.parsed_msg['<UserID>']
2021-07-26 12:43:51 +00:00
if user:
if BotDBUtil.SenderInfo(f"{msg.target.senderFrom}|{user}").remove_TargetAdmin(msg.target.targetId):
2021-07-27 14:31:45 +00:00
await msg.sendMessage("成功")
2021-08-21 15:58:07 +00:00
@command('add_su', need_superuser=True, help_doc='add_su <user>')
async def add_su(message: MessageSession):
user = message.parsed_msg['<user>']
print(message.parsed_msg)
if user:
if BotDBUtil.SenderInfo(user).edit('isSuperUser', True):
await message.sendMessage('成功')
@command('del_su', need_superuser=True, help_doc='del_su <user>')
async def del_su(message: MessageSession):
user = message.parsed_msg['<user>']
if user:
if BotDBUtil.SenderInfo(user).edit('isSuperUser', False):
await message.sendMessage('成功')
"""
@command('set_modules', need_superuser=True, help_doc='set_modules <>')
async def set_modules(display_msg: dict):
...
"""
@command('restart', need_superuser=True)
async def restart_bot(msg: MessageSession):
await msg.sendMessage('你确定吗?')
confirm = await msg.waitConfirm()
if confirm:
2021-08-22 14:55:25 +00:00
update = os.path.abspath(PrivateAssets.path + '/cache_restart_author')
2021-08-21 15:58:07 +00:00
write_version = open(update, 'w')
write_version.write(json.dumps({'From': msg.target.targetFrom, 'ID': msg.target.targetId}))
write_version.close()
await msg.sendMessage('已执行。')
python = sys.executable
os.execl(python, python, *sys.argv)
@command('update', need_superuser=True)
async def update_bot(msg: MessageSession):
await msg.sendMessage('你确定吗?')
confirm = await msg.waitConfirm()
if confirm:
result = os.popen('git pull', 'r')
await msg.sendMessage(result.read()[:-1])
@command('update&restart', need_superuser=True)
async def update_and_restart_bot(msg: MessageSession):
await msg.sendMessage('你确定吗?')
confirm = await msg.waitConfirm()
if confirm:
2021-08-22 14:55:25 +00:00
update = os.path.abspath(PrivateAssets.path + '/cache_restart_author')
2021-08-21 15:58:07 +00:00
write_version = open(update, 'w')
write_version.write(json.dumps({'From': msg.target.targetFrom, 'ID': msg.target.targetId}))
write_version.close()
result = os.popen('git pull', 'r')
await msg.sendMessage(result.read()[:-1])
python = sys.executable
os.execl(python, python, *sys.argv)
@command('echo', need_superuser=True, help_doc='echo <display_msg>')
async def echo_msg(msg: MessageSession):
await msg.sendMessage(msg.parsed_msg['<display_msg>'])