mirror of
https://github.com/zhenxun-org/zhenxun_bot.git
synced 2026-10-01 09:39:59 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8c4b515093 | ||
|
|
6d43989a4d | ||
|
|
fb1f15bcb4 | ||
|
|
81ad585a18 | ||
|
|
eb3bd2b4a6 | ||
|
|
e401914790 | ||
|
|
fef5dadaba | ||
|
|
c1348d08ed | ||
|
|
fbd7c568d9 | ||
|
|
2941774913 | ||
|
|
b96d910401 | ||
|
|
9275d0782b | ||
|
|
7acc6cf6af | ||
|
|
d380a9aacc | ||
|
|
495377da13 | ||
|
|
218eed4068 | ||
|
|
1e9c99dec1 | ||
|
|
0326bc2831 |
@@ -1,4 +1,4 @@
|
|||||||
<div align=center><img width="320" height="320" src="https://raw.githubusercontent.com/HibiKier/zhenxun_bot/main/docs/zhenxun.jpg"/></div>
|
<div align=center><img width="320" height="320" src="https://raw.githubusercontent.com/HibiKier/zhenxun_bot/main/logo.png"/></div>
|
||||||
|
|
||||||

|

|
||||||

|

|
||||||
@@ -321,6 +321,17 @@ python bot.py
|
|||||||
|
|
||||||
## 更新
|
## 更新
|
||||||
|
|
||||||
|
### 2021/11/29 \[v0.0.6.4]
|
||||||
|
|
||||||
|
* 新增cos图撤回配置项
|
||||||
|
* 新增默认群权限配置项
|
||||||
|
* 修复权限等级类配置无法正常应用
|
||||||
|
|
||||||
|
### 2021/11/24 \[v0.0.6.3]
|
||||||
|
|
||||||
|
* 修复在线搜索色图出错
|
||||||
|
* 修复pix无法正确获取HIBIAPI
|
||||||
|
|
||||||
### 2021/11/23 \[v0.0.6.2]
|
### 2021/11/23 \[v0.0.6.2]
|
||||||
|
|
||||||
* 替换cos API
|
* 替换cos API
|
||||||
|
|||||||
+1
-1
@@ -1 +1 @@
|
|||||||
__version__: v0.0.6.2
|
__version__: v0.0.6.4
|
||||||
|
|||||||
@@ -92,11 +92,14 @@ def init_plugins_config(data_path):
|
|||||||
if user_config_file.exists():
|
if user_config_file.exists():
|
||||||
with open(user_config_file, "r", encoding="utf8") as f:
|
with open(user_config_file, "r", encoding="utf8") as f:
|
||||||
_data = _yaml.load(f)
|
_data = _yaml.load(f)
|
||||||
|
# 数据替换
|
||||||
for plugin in Config.keys():
|
for plugin in Config.keys():
|
||||||
_tmp_data[plugin] = {}
|
_tmp_data[plugin] = {}
|
||||||
for k in Config[plugin].keys():
|
for k in Config[plugin].keys():
|
||||||
if _data.get(plugin) and k in _data[plugin].keys():
|
if _data.get(plugin) and k in _data[plugin].keys():
|
||||||
Config.set_config(plugin, k, _data[plugin][k])
|
Config.set_config(plugin, k, _data[plugin][k])
|
||||||
|
if level2module := Config.get_level2module(plugin, k):
|
||||||
|
admin_manager.set_admin_level(level2module, _data[plugin][k])
|
||||||
_tmp_data[plugin][k] = Config.get_config(plugin, k)
|
_tmp_data[plugin][k] = Config.get_config(plugin, k)
|
||||||
Config.save()
|
Config.save()
|
||||||
temp_file = Path() / "configs" / "temp_config.yaml"
|
temp_file = Path() / "configs" / "temp_config.yaml"
|
||||||
@@ -145,3 +148,4 @@ def init_plugins_config(data_path):
|
|||||||
logger.error(f"生成简易配置注释错误 {type(e)}:{e}")
|
logger.error(f"生成简易配置注释错误 {type(e)}:{e}")
|
||||||
if temp_file.exists():
|
if temp_file.exists():
|
||||||
temp_file.unlink()
|
temp_file.unlink()
|
||||||
|
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ class ConfigsManager:
|
|||||||
name: Optional[str] = None,
|
name: Optional[str] = None,
|
||||||
help_: Optional[str] = None,
|
help_: Optional[str] = None,
|
||||||
default_value: Optional[str] = None,
|
default_value: Optional[str] = None,
|
||||||
_override: bool = False
|
_override: bool = False,
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
为插件添加一个配置,不会被覆盖,只有第一个生效
|
为插件添加一个配置,不会被覆盖,只有第一个生效
|
||||||
@@ -61,6 +61,7 @@ class ConfigsManager:
|
|||||||
"name": name.strip() if isinstance(name, str) else name,
|
"name": name.strip() if isinstance(name, str) else name,
|
||||||
"help": help_.strip() if isinstance(help_, str) else help_,
|
"help": help_.strip() if isinstance(help_, str) else help_,
|
||||||
"default_value": default_value,
|
"default_value": default_value,
|
||||||
|
"level_module": _module,
|
||||||
}
|
}
|
||||||
|
|
||||||
def remove_plugin_config(self, module: str):
|
def remove_plugin_config(self, module: str):
|
||||||
@@ -119,6 +120,17 @@ class ConfigsManager:
|
|||||||
return self._data[module][key]["value"]
|
return self._data[module][key]["value"]
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
def get_level2module(self, module: str, key: str) -> Optional[str]:
|
||||||
|
"""
|
||||||
|
获取指定key所绑定的module,一般为权限等级
|
||||||
|
:param module: 模块名
|
||||||
|
:param key: 配置名称
|
||||||
|
:return:
|
||||||
|
"""
|
||||||
|
if self._data.get(module) is not None:
|
||||||
|
if self._data[module].get(key) is not None:
|
||||||
|
return self._data[module][key].get("level_module")
|
||||||
|
|
||||||
def get(self, key: str):
|
def get(self, key: str):
|
||||||
"""
|
"""
|
||||||
获取插件配置数据
|
获取插件配置数据
|
||||||
@@ -158,3 +170,4 @@ class ConfigsManager:
|
|||||||
|
|
||||||
def __getitem__(self, key):
|
def __getitem__(self, key):
|
||||||
return self._data[key]
|
return self._data[key]
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ from nonebot.typing import T_State
|
|||||||
from nonebot.adapters.cqhttp import Bot, MessageEvent
|
from nonebot.adapters.cqhttp import Bot, MessageEvent
|
||||||
from utils.message_builder import image
|
from utils.message_builder import image
|
||||||
from services.log import logger
|
from services.log import logger
|
||||||
|
from utils.manager import withdraw_message_manager
|
||||||
|
from configs.config import Config
|
||||||
|
|
||||||
__zx_plugin_name__ = "coser"
|
__zx_plugin_name__ = "coser"
|
||||||
__plugin_usage__ = """
|
__plugin_usage__ = """
|
||||||
@@ -21,6 +23,13 @@ __plugin_settings__ = {
|
|||||||
"limit_superuser": False,
|
"limit_superuser": False,
|
||||||
"cmd": ["cos", "coser", "括丝", "COS", "Cos", "cOS", "coS"],
|
"cmd": ["cos", "coser", "括丝", "COS", "Cos", "cOS", "coS"],
|
||||||
}
|
}
|
||||||
|
__plugin_configs__ = {
|
||||||
|
"WITHDRAW_COS_MESSAGE": {
|
||||||
|
"value": (0, 1),
|
||||||
|
"help": "自动撤回,参1:延迟撤回色图时间(秒),0 为关闭 | 参2:监控聊天类型,0(私聊) 1(群聊) 2(群聊+私聊)",
|
||||||
|
"default_value": (0, 1),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
coser = on_command(
|
coser = on_command(
|
||||||
"cos", aliases={"coser", "括丝", "COS", "Cos", "cOS", "coS"}, priority=5, block=True
|
"cos", aliases={"coser", "括丝", "COS", "Cos", "cOS", "coS"}, priority=5, block=True
|
||||||
@@ -33,7 +42,13 @@ url = "http://iw233.cn/API/cos.php"
|
|||||||
@coser.handle()
|
@coser.handle()
|
||||||
async def _(bot: Bot, event: MessageEvent, state: T_State):
|
async def _(bot: Bot, event: MessageEvent, state: T_State):
|
||||||
try:
|
try:
|
||||||
await coser.send(image(url))
|
msg_id = await coser.send(image(url))
|
||||||
|
withdraw_message_manager.withdraw_message(
|
||||||
|
event,
|
||||||
|
msg_id["message_id"],
|
||||||
|
Config.get_config("coser", "WITHDRAW_COS_MESSAGE"),
|
||||||
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await coser.send("你cos给我看!")
|
await coser.send("你cos给我看!")
|
||||||
logger.error(f"coser 发送了未知错误 {type(e)}:{e}")
|
logger.error(f"coser 发送了未知错误 {type(e)}:{e}")
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ from urllib.parse import unquote
|
|||||||
from services.log import logger
|
from services.log import logger
|
||||||
from .util import remove_prohibited_str
|
from .util import remove_prohibited_str
|
||||||
from utils.http_utils import AsyncHttpx
|
from utils.http_utils import AsyncHttpx
|
||||||
|
from httpx import ConnectTimeout, CloseError
|
||||||
import bs4
|
import bs4
|
||||||
import re
|
import re
|
||||||
try:
|
try:
|
||||||
@@ -57,9 +58,12 @@ async def update_info(url: str, game_name: str, info_list: list = None) -> 'dict
|
|||||||
data[name] = member_dict
|
data[name] = member_dict
|
||||||
logger.info(f'{name} is update...')
|
logger.info(f'{name} is update...')
|
||||||
data = await _last_check(data, game_name)
|
data = await _last_check(data, game_name)
|
||||||
except TimeoutError:
|
except (TimeoutError, ConnectTimeout, CloseError):
|
||||||
logger.warning(f'更新 {game_name} 超时...')
|
logger.warning(f'更新 {game_name} 超时...')
|
||||||
return {}, 999
|
return {}, 999
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"更新 {game_name} 未知错误 {type(e)}:{e}")
|
||||||
|
return {}, 998
|
||||||
with open(DRAW_PATH + f'{game_name}.json', 'w', encoding='utf8') as wf:
|
with open(DRAW_PATH + f'{game_name}.json', 'w', encoding='utf8') as wf:
|
||||||
wf.write(json.dumps(data, ensure_ascii=False, indent=4))
|
wf.write(json.dumps(data, ensure_ascii=False, indent=4))
|
||||||
return data, 200
|
return data, 200
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ from bs4 import BeautifulSoup
|
|||||||
from .util import remove_prohibited_str
|
from .util import remove_prohibited_str
|
||||||
from utils.http_utils import AsyncHttpx
|
from utils.http_utils import AsyncHttpx
|
||||||
from services.log import logger
|
from services.log import logger
|
||||||
|
from httpx import ConnectTimeout, CloseError
|
||||||
import asyncio
|
import asyncio
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -50,9 +51,12 @@ async def update_requests_info(game_name: str):
|
|||||||
data = add_to_data(data, x, game_name)
|
data = add_to_data(data, x, game_name)
|
||||||
logger.info(f"{key} is update...")
|
logger.info(f"{key} is update...")
|
||||||
data = await _last_check(data, game_name)
|
data = await _last_check(data, game_name)
|
||||||
except TimeoutError:
|
except (TimeoutError, ConnectTimeout, CloseError):
|
||||||
logger.warning(f"更新 {game_name} 超时...")
|
logger.warning(f"更新 {game_name} 超时...")
|
||||||
return {}, 999
|
return {}, 999
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"更新 {game_name} 未知错误 {type(e)}:{e}")
|
||||||
|
return {}, 998
|
||||||
with open(DRAW_PATH + f"{game_name}.json", "w", encoding="utf8") as wf:
|
with open(DRAW_PATH + f"{game_name}.json", "w", encoding="utf8") as wf:
|
||||||
json.dump(data, wf, ensure_ascii=False, indent=4)
|
json.dump(data, wf, ensure_ascii=False, indent=4)
|
||||||
return data, 200
|
return data, 200
|
||||||
@@ -150,6 +154,8 @@ async def _async_update_fgo_extra_info(url: str, key: str, _id: str, semaphore):
|
|||||||
x = {key: {}}
|
x = {key: {}}
|
||||||
x[key]["入手方式"] = obtain
|
x[key]["入手方式"] = obtain
|
||||||
return x
|
return x
|
||||||
except TimeoutError:
|
except (TimeoutError, ConnectTimeout, CloseError):
|
||||||
logger.warning(f"访问{url}{_id} 第 {i}次 超时...已再次访问")
|
logger.warning(f"访问{url}{_id} 第 {i}次 超时...已再次访问")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"访问{url}{_id} 第 {i}次 未知错误 {type(e)}:{e}...已再次访问")
|
||||||
return {}
|
return {}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ from .util import remove_prohibited_str
|
|||||||
from urllib.parse import unquote
|
from urllib.parse import unquote
|
||||||
from services.log import logger
|
from services.log import logger
|
||||||
from utils.http_utils import AsyncHttpx
|
from utils.http_utils import AsyncHttpx
|
||||||
|
from httpx import ConnectTimeout, CloseError
|
||||||
import bs4
|
import bs4
|
||||||
import asyncio
|
import asyncio
|
||||||
|
|
||||||
@@ -36,10 +37,13 @@ async def update_simple_info(url: str, game_name: str) -> 'dict, int':
|
|||||||
except AttributeError:
|
except AttributeError:
|
||||||
continue
|
continue
|
||||||
for char in contents[1:]:
|
for char in contents[1:]:
|
||||||
data = await retrieve_char_data(char, game_name, data, index)
|
try:
|
||||||
|
data = await retrieve_char_data(char, game_name, data, index)
|
||||||
|
except AttributeError:
|
||||||
|
continue
|
||||||
index += 1
|
index += 1
|
||||||
data = await _last_check(data, game_name)
|
data = await _last_check(data, game_name)
|
||||||
except TimeoutError:
|
except (TimeoutError, ConnectTimeout, CloseError):
|
||||||
logger.warning(f'更新 {game_name} 超时...')
|
logger.warning(f'更新 {game_name} 超时...')
|
||||||
return {}, 999
|
return {}, 999
|
||||||
with open(DRAW_PATH + f'{game_name}.json', 'w', encoding='utf8') as wf:
|
with open(DRAW_PATH + f'{game_name}.json', 'w', encoding='utf8') as wf:
|
||||||
@@ -127,7 +131,6 @@ async def retrieve_char_data(char: bs4.element.Tag, game_name: str, data: dict,
|
|||||||
'名称': remove_prohibited_str(char.find('a')['title']),
|
'名称': remove_prohibited_str(char.find('a')['title']),
|
||||||
'星级': 3 - index}
|
'星级': 3 - index}
|
||||||
if game_name == 'azur':
|
if game_name == 'azur':
|
||||||
print(char)
|
|
||||||
char = char.find('div').find('div').find('div').find('div')
|
char = char.find('div').find('div').find('div').find('div')
|
||||||
avatar_img = char.find('a').find('img')
|
avatar_img = char.find('a').find('img')
|
||||||
try:
|
try:
|
||||||
@@ -186,7 +189,9 @@ async def _async_update_azur_extra_info(key: str, semaphore):
|
|||||||
x = {key: {'获取途径': []}}
|
x = {key: {'获取途径': []}}
|
||||||
logger.warning(f'碧蓝航线获取额外信息错误 {key}...{[]}')
|
logger.warning(f'碧蓝航线获取额外信息错误 {key}...{[]}')
|
||||||
return x
|
return x
|
||||||
except TimeoutError:
|
except (TimeoutError, ConnectTimeout, CloseError):
|
||||||
logger.warning(f'访问 https://wiki.biligame.com/blhx/{key} 第 {i}次 超时...已再次访问')
|
logger.warning(f'访问 https://wiki.biligame.com/blhx/{key} 第 {i}次 超时/失败...已再次访问')
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f'访问 https://wiki.biligame.com/blhx/{key} 第 {i}次 未知错误 {type(e)}:{e}...已再次访问')
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ async def _(bot: Bot, event: MessageEvent, state: T_State):
|
|||||||
if length == 0:
|
if length == 0:
|
||||||
logger.warning(f"图库 {path} 为空,调用取消!")
|
logger.warning(f"图库 {path} 为空,调用取消!")
|
||||||
await send_img.finish("该图库中没有图片噢")
|
await send_img.finish("该图库中没有图片噢")
|
||||||
index = img_id if img_id else str(random.randint(0, length))
|
index = img_id if img_id else str(random.randint(0, length - 1))
|
||||||
if not is_number(index):
|
if not is_number(index):
|
||||||
return
|
return
|
||||||
if int(index) > length - 1 or int(index) < 0:
|
if int(index) > length - 1 or int(index) < 0:
|
||||||
|
|||||||
@@ -1,13 +1,5 @@
|
|||||||
from configs.config import Config
|
from configs.config import Config
|
||||||
from services.log import logger
|
|
||||||
from .model.omega_pixiv_illusts import OmegaPixivIllusts
|
|
||||||
from pathlib import Path
|
|
||||||
from nonebot import Driver
|
|
||||||
from typing import List
|
|
||||||
from datetime import datetime
|
|
||||||
import nonebot
|
import nonebot
|
||||||
import asyncio
|
|
||||||
import os
|
|
||||||
|
|
||||||
|
|
||||||
__zx_plugin_name__ = "更新扩展图库Omega [Hidden]"
|
__zx_plugin_name__ = "更新扩展图库Omega [Hidden]"
|
||||||
@@ -67,69 +59,4 @@ Config.add_plugin_config(
|
|||||||
|
|
||||||
nonebot.load_plugins("plugins/pix_gallery")
|
nonebot.load_plugins("plugins/pix_gallery")
|
||||||
|
|
||||||
driver: Driver = nonebot.get_driver()
|
|
||||||
|
|
||||||
|
|
||||||
@driver.on_startup
|
|
||||||
async def _init_omega_pixiv_illusts():
|
|
||||||
omega_pixiv_illusts = None
|
|
||||||
for file in os.listdir("."):
|
|
||||||
if "omega_pixiv_illusts" in file and ".sql" in file:
|
|
||||||
omega_pixiv_illusts = Path() / file
|
|
||||||
if omega_pixiv_illusts:
|
|
||||||
with open(omega_pixiv_illusts, "r", encoding="utf8") as f:
|
|
||||||
lines = f.readlines()
|
|
||||||
tasks = []
|
|
||||||
length = len([x for x in lines if "INSERT INTO" in x.upper()])
|
|
||||||
all_pid = await OmegaPixivIllusts.get_all_pid()
|
|
||||||
index = 0
|
|
||||||
logger.info("检测到OmegaPixivIllusts数据库,准备开始更新....")
|
|
||||||
for line in lines:
|
|
||||||
if "INSERT INTO" in line.upper():
|
|
||||||
index += 1
|
|
||||||
tasks.append(
|
|
||||||
asyncio.ensure_future(_tasks(line, all_pid, length, index))
|
|
||||||
)
|
|
||||||
await asyncio.gather(*tasks)
|
|
||||||
omega_pixiv_illusts.unlink()
|
|
||||||
|
|
||||||
|
|
||||||
async def _tasks(line: str, all_pid: List[int], length: int, index: int):
|
|
||||||
data = line.split("VALUES", maxsplit=1)[-1].strip()
|
|
||||||
if data.startswith("("):
|
|
||||||
data = data[1:]
|
|
||||||
if data.endswith(");"):
|
|
||||||
data = data[:-2]
|
|
||||||
x = data.split(maxsplit=3)
|
|
||||||
pid = int(x[1][:-1].strip())
|
|
||||||
if pid in all_pid:
|
|
||||||
logger.info(f"添加OmegaPixivIllusts图库数据已存在 ---> pid:{pid}")
|
|
||||||
return
|
|
||||||
uid = int(x[2][:-1].strip())
|
|
||||||
x = x[3].split(", '")
|
|
||||||
title = x[0].strip()[1:-1]
|
|
||||||
tmp = x[1].split(", ")
|
|
||||||
author = tmp[0].strip()[:-1]
|
|
||||||
nsfw_tag = int(tmp[1])
|
|
||||||
width = int(tmp[2])
|
|
||||||
height = int(tmp[3])
|
|
||||||
tags = x[2][:-1]
|
|
||||||
url = x[3][:-1]
|
|
||||||
if await OmegaPixivIllusts.add_image_data(
|
|
||||||
pid,
|
|
||||||
title,
|
|
||||||
width,
|
|
||||||
height,
|
|
||||||
url,
|
|
||||||
uid,
|
|
||||||
author,
|
|
||||||
nsfw_tag,
|
|
||||||
tags,
|
|
||||||
datetime.min,
|
|
||||||
datetime.min,
|
|
||||||
):
|
|
||||||
logger.info(
|
|
||||||
f"成功添加OmegaPixivIllusts图库数据 pid:{pid} 本次预计存储 {length} 张,已更新第 {index} 张"
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
logger.info(f"添加OmegaPixivIllusts图库数据已存在 ---> pid:{pid}")
|
|
||||||
|
|||||||
@@ -30,7 +30,10 @@ headers = {
|
|||||||
"Referer": "https://www.pixiv.net",
|
"Referer": "https://www.pixiv.net",
|
||||||
}
|
}
|
||||||
|
|
||||||
HIBIAPI = None
|
HIBIAPI = Config.get_config("hibiapi", "HIBIAPI")
|
||||||
|
if not HIBIAPI:
|
||||||
|
HIBIAPI = "https://api.obfs.dev"
|
||||||
|
HIBIAPI = HIBIAPI[:-1] if HIBIAPI[-1] == "/" else HIBIAPI
|
||||||
|
|
||||||
|
|
||||||
async def start_update_image_url(
|
async def start_update_image_url(
|
||||||
@@ -47,9 +50,6 @@ async def start_update_image_url(
|
|||||||
pic_count = 0
|
pic_count = 0
|
||||||
tasks = []
|
tasks = []
|
||||||
semaphore = asyncio.Semaphore(10)
|
semaphore = asyncio.Semaphore(10)
|
||||||
if not HIBIAPI:
|
|
||||||
HIBIAPI = Config.get_config("hibiapi", "HIBIAPI")
|
|
||||||
HIBIAPI = HIBIAPI[:-1] if HIBIAPI[-1] else HIBIAPI
|
|
||||||
for keyword in current_keyword:
|
for keyword in current_keyword:
|
||||||
for page in range(1, 110):
|
for page in range(1, 110):
|
||||||
if keyword.startswith("uid:"):
|
if keyword.startswith("uid:"):
|
||||||
@@ -390,3 +390,6 @@ def _check_black(img_urls: List[str], black: List[str]) -> bool:
|
|||||||
if b in img_url:
|
if b in img_url:
|
||||||
return False
|
return False
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -4,9 +4,16 @@ from nonebot.permission import SUPERUSER
|
|||||||
from nonebot.typing import T_State
|
from nonebot.typing import T_State
|
||||||
from .data_source import start_update_image_url
|
from .data_source import start_update_image_url
|
||||||
from .model.pixiv_keyword_user import PixivKeywordUser
|
from .model.pixiv_keyword_user import PixivKeywordUser
|
||||||
|
from .model.omega_pixiv_illusts import OmegaPixivIllusts
|
||||||
from .model.pixiv import Pixiv
|
from .model.pixiv import Pixiv
|
||||||
from nonebot.adapters.cqhttp import Bot, MessageEvent
|
from nonebot.adapters.cqhttp import Bot, MessageEvent
|
||||||
import time
|
import time
|
||||||
|
from services.log import logger
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import List
|
||||||
|
from datetime import datetime
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
|
||||||
|
|
||||||
__zx_plugin_name__ = "pix检查更新 [Superuser]"
|
__zx_plugin_name__ = "pix检查更新 [Superuser]"
|
||||||
@@ -36,6 +43,8 @@ check_not_update_uid_pid = on_command(
|
|||||||
block=True,
|
block=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
check_omega = on_command("检测omega图库", permission=SUPERUSER, priority=1, block=True)
|
||||||
|
|
||||||
|
|
||||||
@start_update.handle()
|
@start_update.handle()
|
||||||
async def _(bot: Bot, event: MessageEvent, state: T_State):
|
async def _(bot: Bot, event: MessageEvent, state: T_State):
|
||||||
@@ -130,3 +139,66 @@ async def _(bot: Bot, event: MessageEvent, state: T_State):
|
|||||||
f"累计更新PID {pid_count} 个\n"
|
f"累计更新PID {pid_count} 个\n"
|
||||||
f"累计更新图片 {pic_count} 张" + "\n耗时:{:.2f}秒".format((time.time() - start_time))
|
f"累计更新图片 {pic_count} 张" + "\n耗时:{:.2f}秒".format((time.time() - start_time))
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@check_omega.handle()
|
||||||
|
async def _(bot: Bot, event: MessageEvent, state: T_State):
|
||||||
|
async def _tasks(line: str, all_pid: List[int], length: int, index: int):
|
||||||
|
data = line.split("VALUES", maxsplit=1)[-1].strip()
|
||||||
|
if data.startswith("("):
|
||||||
|
data = data[1:]
|
||||||
|
if data.endswith(");"):
|
||||||
|
data = data[:-2]
|
||||||
|
x = data.split(maxsplit=3)
|
||||||
|
pid = int(x[1][:-1].strip())
|
||||||
|
if pid in all_pid:
|
||||||
|
logger.info(f"添加OmegaPixivIllusts图库数据已存在 ---> pid:{pid}")
|
||||||
|
return
|
||||||
|
uid = int(x[2][:-1].strip())
|
||||||
|
x = x[3].split(", '")
|
||||||
|
title = x[0].strip()[1:-1]
|
||||||
|
tmp = x[1].split(", ")
|
||||||
|
author = tmp[0].strip()[:-1]
|
||||||
|
nsfw_tag = int(tmp[1])
|
||||||
|
width = int(tmp[2])
|
||||||
|
height = int(tmp[3])
|
||||||
|
tags = x[2][:-1]
|
||||||
|
url = x[3][:-1]
|
||||||
|
if await OmegaPixivIllusts.add_image_data(
|
||||||
|
pid,
|
||||||
|
title,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
url,
|
||||||
|
uid,
|
||||||
|
author,
|
||||||
|
nsfw_tag,
|
||||||
|
tags,
|
||||||
|
datetime.min,
|
||||||
|
datetime.min,
|
||||||
|
):
|
||||||
|
logger.info(
|
||||||
|
f"成功添加OmegaPixivIllusts图库数据 pid:{pid} 本次预计存储 {length} 张,已更新第 {index} 张"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
logger.info(f"添加OmegaPixivIllusts图库数据已存在 ---> pid:{pid}")
|
||||||
|
omega_pixiv_illusts = None
|
||||||
|
for file in os.listdir("."):
|
||||||
|
if "omega_pixiv_illusts" in file and ".sql" in file:
|
||||||
|
omega_pixiv_illusts = Path() / file
|
||||||
|
if omega_pixiv_illusts:
|
||||||
|
with open(omega_pixiv_illusts, "r", encoding="utf8") as f:
|
||||||
|
lines = f.readlines()
|
||||||
|
tasks = []
|
||||||
|
length = len([x for x in lines if "INSERT INTO" in x.upper()])
|
||||||
|
all_pid = await OmegaPixivIllusts.get_all_pid()
|
||||||
|
index = 0
|
||||||
|
logger.info("检测到OmegaPixivIllusts数据库,准备开始更新....")
|
||||||
|
for line in lines:
|
||||||
|
if "INSERT INTO" in line.upper():
|
||||||
|
index += 1
|
||||||
|
tasks.append(
|
||||||
|
asyncio.ensure_future(_tasks(line, all_pid, length, index))
|
||||||
|
)
|
||||||
|
await asyncio.gather(*tasks)
|
||||||
|
omega_pixiv_illusts.unlink()
|
||||||
|
|||||||
@@ -1,133 +0,0 @@
|
|||||||
# # -*- coding: utf-8 -*-
|
|
||||||
# from typing import Dict
|
|
||||||
#
|
|
||||||
# from aiohttp.client_exceptions import ClientError
|
|
||||||
# from nonebot.plugin import on_command, on_message
|
|
||||||
# from nonebot.adapters.cqhttp import Bot, MessageEvent, GroupMessageEvent
|
|
||||||
# from nonebot.typing import T_State
|
|
||||||
# from services.log import logger
|
|
||||||
# from utils.utils import get_message_text, get_message_imgs
|
|
||||||
# from configs.config import Config
|
|
||||||
# from nonebot.rule import to_me
|
|
||||||
#
|
|
||||||
#
|
|
||||||
#
|
|
||||||
# __zx_plugin_name__ = "识图"
|
|
||||||
# __plugin_usage__ = """
|
|
||||||
# usage:
|
|
||||||
# 识别图片 [二次元图片]
|
|
||||||
# 指令:
|
|
||||||
# 识图 [图片]
|
|
||||||
# """.strip()
|
|
||||||
# __plugin_des__ = "以图搜图,看破本源"
|
|
||||||
# __plugin_cmd__ = ["识图"]
|
|
||||||
# __plugin_type__ = ("一些工具",)
|
|
||||||
# __plugin_version__ = 0.1
|
|
||||||
# __plugin_author__ = "synodriver"
|
|
||||||
# __plugin_settings__ = {
|
|
||||||
# "level": 5,
|
|
||||||
# "default_status": True,
|
|
||||||
# "limit_superuser": False,
|
|
||||||
# "cmd": ["识图"],
|
|
||||||
# }
|
|
||||||
# __plugin_configs__ = {
|
|
||||||
# "MAX_FIND_IMAGE_COUNT": {"value": 3, "help": "识图返回的最大结果数", "default_value": 3}
|
|
||||||
# }
|
|
||||||
#
|
|
||||||
#
|
|
||||||
# async def get_des(url: str, mode: str, user_id: int):
|
|
||||||
# """
|
|
||||||
# :param url: 图片链接
|
|
||||||
# :param mode: 图源
|
|
||||||
# :param user_id: 用户 id
|
|
||||||
# """
|
|
||||||
# if mode == "iqdb":
|
|
||||||
# async for msg in get_des_iqdb(url):
|
|
||||||
# yield msg
|
|
||||||
# elif mode == "ex":
|
|
||||||
# async for msg in get_des_ex(url):
|
|
||||||
# yield msg
|
|
||||||
# elif mode == "trace":
|
|
||||||
# async for msg in get_des_trace(url):
|
|
||||||
# yield msg
|
|
||||||
# elif mode == "yandex":
|
|
||||||
# async for msg in get_des_yandex(url):
|
|
||||||
# yield msg
|
|
||||||
# elif mode.startswith("asc"):
|
|
||||||
# async for msg in get_des_asc(url, user_id):
|
|
||||||
# yield msg
|
|
||||||
# else:
|
|
||||||
# async for msg in get_des_sau(url, user_id):
|
|
||||||
# yield msg
|
|
||||||
#
|
|
||||||
#
|
|
||||||
# setu = on_command("识图", aliases={"search"}, block=True, priority=5)
|
|
||||||
#
|
|
||||||
#
|
|
||||||
# @setu.handle()
|
|
||||||
# async def handle_first_receive(bot: Bot, event: MessageEvent, state: T_State):
|
|
||||||
# msg = get_message_text(event.json())
|
|
||||||
# imgs = get_message_imgs(event.json())
|
|
||||||
# if imgs:
|
|
||||||
# state["setu"] = imgs[0]
|
|
||||||
# if msg:
|
|
||||||
# state["mod"] = msg
|
|
||||||
#
|
|
||||||
#
|
|
||||||
# # ex/nao/trace/iqdb/ascii2d
|
|
||||||
# # @setu.got("mod", prompt="从哪里查找呢? ex/nao/trace/iqdb/ascii2d")
|
|
||||||
# # async def get_func(bot: Bot, event: MessageEvent, state: dict):
|
|
||||||
# # pass
|
|
||||||
#
|
|
||||||
#
|
|
||||||
# @setu.args_parser
|
|
||||||
# async def get_setu(bot: Bot, event: MessageEvent, state: T_State):
|
|
||||||
# imgs = get_message_imgs(event.json())
|
|
||||||
# msg = get_message_text(event.json())
|
|
||||||
# if not imgs:
|
|
||||||
# await setu.reject()
|
|
||||||
# if msg:
|
|
||||||
# state["mod"] = msg
|
|
||||||
# state["setu"] = imgs[0]
|
|
||||||
#
|
|
||||||
#
|
|
||||||
# @setu.got("setu", prompt="图呢?")
|
|
||||||
# async def get_setu(bot: Bot, event: MessageEvent, state: T_State):
|
|
||||||
# """
|
|
||||||
# 发现没有的时候要发问
|
|
||||||
# :return:
|
|
||||||
# """
|
|
||||||
# url: str = state["setu"]
|
|
||||||
# mod: str = state["mod"] if state.get("mod") else "nao" # 模式
|
|
||||||
# try:
|
|
||||||
# await bot.send(event=event, message="正在处理图片")
|
|
||||||
# idx = 1
|
|
||||||
# async for msg in get_des(url, mod, event.user_id):
|
|
||||||
# if msg:
|
|
||||||
# await bot.send(event=event, message=msg)
|
|
||||||
# if idx == Config.get_config(
|
|
||||||
# "nonebot_plugin_picsearcher", "MAX_FIND_IMAGE_COUNT"
|
|
||||||
# ):
|
|
||||||
# break
|
|
||||||
# idx += 1
|
|
||||||
# if id == 1:
|
|
||||||
# await bot.send(event=event, message="没找着.")
|
|
||||||
# logger.info(
|
|
||||||
# f"(USER {event.user_id}, GROUP "
|
|
||||||
# f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'}) 识图:{url}"
|
|
||||||
# )
|
|
||||||
# # image_data: List[Tuple] = await get_pic_from_url(url)
|
|
||||||
# # await setu.finish("hso")
|
|
||||||
# except IndexError:
|
|
||||||
# # await bot.send(event, traceback.format_exc())
|
|
||||||
# await setu.finish("参数错误")
|
|
||||||
# except ClientError:
|
|
||||||
# await setu.finish("连接失败")
|
|
||||||
#
|
|
||||||
#
|
|
||||||
#
|
|
||||||
#
|
|
||||||
#
|
|
||||||
#
|
|
||||||
#
|
|
||||||
#
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
|
|
||||||
API_URL_SAUCENAO = 'https://saucenao.com/search.php'
|
|
||||||
API_URL_ASCII2D = 'https://ascii2d.net/search/url/'
|
|
||||||
API_URL_IQDB = 'https://iqdb.org/'
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
from utils.user_agent import get_user_agent
|
|
||||||
from utils.utils import get_local_proxy
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
async def get_saucenao_identify_result(url: str) -> Result.DictListResult:
|
|
||||||
fetcher = HttpFetcher(timeout=10, flag='search_image_saucenao', headers=HEADERS)
|
|
||||||
|
|
||||||
if not API_KEY:
|
|
||||||
logger.opt(colors=True).warning(f'<r>Saucenao API KEY未配置</r>, <y>无法使用Saucenao API进行识图!</y>')
|
|
||||||
return Result.DictListResult(error=True, info='Saucenao API KEY未配置', result=[])
|
|
||||||
|
|
||||||
__payload = {'output_type': 2,
|
|
||||||
'api_key': API_KEY,
|
|
||||||
'testmode': 1,
|
|
||||||
'numres': 6,
|
|
||||||
'db': 999,
|
|
||||||
'url': url}
|
|
||||||
saucenao_result = await fetcher.get_json(url=API_URL_SAUCENAO, params=__payload)
|
|
||||||
if saucenao_result.error:
|
|
||||||
logger.warning(f'get_saucenao_identify_result failed, Network error: {saucenao_result.info}')
|
|
||||||
return Result.DictListResult(error=True, info=f'Network error: {saucenao_result.info}', result=[])
|
|
||||||
|
|
||||||
__result_json = saucenao_result.result
|
|
||||||
|
|
||||||
if __result_json['header']['status'] != 0:
|
|
||||||
logger.error(f"get_saucenao_identify_result failed, DataSource error, "
|
|
||||||
f"status code: {__result_json['header']['status']}")
|
|
||||||
return Result.DictListResult(
|
|
||||||
error=True, info=f"DataSource error, status code: {__result_json['header']['status']}", result=[])
|
|
||||||
|
|
||||||
__result = []
|
|
||||||
for __item in __result_json['results']:
|
|
||||||
try:
|
|
||||||
if int(float(__item['header']['similarity'])) < 75:
|
|
||||||
continue
|
|
||||||
else:
|
|
||||||
__result.append({'similarity': __item['header']['similarity'],
|
|
||||||
'thumbnail': __item['header']['thumbnail'],
|
|
||||||
'index_name': __item['header']['index_name'],
|
|
||||||
'ext_urls': __item['data']['ext_urls']})
|
|
||||||
except Exception as res_err:
|
|
||||||
logger.warning(f"get_saucenao_identify_result failed: {repr(res_err)}, can not resolve results")
|
|
||||||
continue
|
|
||||||
return Result.DictListResult(error=False, info='Success', result=__result)
|
|
||||||
@@ -41,7 +41,7 @@ async def get_setu_urls(
|
|||||||
url, timeout=Config.get_config("send_setu", "TIMEOUT"), params=params
|
url, timeout=Config.get_config("send_setu", "TIMEOUT"), params=params
|
||||||
)
|
)
|
||||||
if response.status_code == 200:
|
if response.status_code == 200:
|
||||||
data = await response.json()
|
data = response.json()
|
||||||
if not data["error"]:
|
if not data["error"]:
|
||||||
data = data["data"]
|
data = data["data"]
|
||||||
(
|
(
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
"models",
|
"models",
|
||||||
"basic_plugins",
|
"basic_plugins",
|
||||||
"utils",
|
"utils",
|
||||||
|
"services"
|
||||||
],
|
],
|
||||||
"add_file": [],
|
"add_file": [],
|
||||||
"delete_file": []
|
"delete_file": []
|
||||||
|
|||||||
@@ -2,9 +2,15 @@ from typing import Optional, List, Union, Dict
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from .data_class import StaticData
|
from .data_class import StaticData
|
||||||
from utils.utils import get_matchers, get_bot
|
from utils.utils import get_matchers, get_bot
|
||||||
|
from configs.config import Config
|
||||||
import nonebot
|
import nonebot
|
||||||
|
|
||||||
|
|
||||||
|
Config.add_plugin_config(
|
||||||
|
"group_manager", "DEFAULT_GROUP_LEVEL", 5, help_="默认群权限", default_value=5
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class GroupManager(StaticData):
|
class GroupManager(StaticData):
|
||||||
"""
|
"""
|
||||||
群权限 | 功能 | 聊天时间 管理器
|
群权限 | 功能 | 聊天时间 管理器
|
||||||
@@ -274,7 +280,7 @@ class GroupManager(StaticData):
|
|||||||
参数:
|
参数:
|
||||||
:param group_id: 群号
|
:param group_id: 群号
|
||||||
"""
|
"""
|
||||||
default_group_level = 5 # Config.get_config("group_manager")
|
default_group_level = Config.get_config("group_manager", "DEFAULT_GROUP_LEVEL")
|
||||||
if not default_group_level:
|
if not default_group_level:
|
||||||
default_group_level = 5
|
default_group_level = 5
|
||||||
if not self._data["group_manager"].get(group_id):
|
if not self._data["group_manager"].get(group_id):
|
||||||
@@ -293,3 +299,4 @@ class GroupManager(StaticData):
|
|||||||
del self._data["super"]["close_plugins"]
|
del self._data["super"]["close_plugins"]
|
||||||
return _x
|
return _x
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user