update 0.0.6.0

This commit is contained in:
HibiKier
2021-11-04 16:11:50 +08:00
parent 21c1950898
commit 19d650c35d
217 changed files with 8213 additions and 5697 deletions
+368
View File
@@ -0,0 +1,368 @@
import random
from nonebot import on_command, on_regex
from services.log import logger
from models.sign_group_user import SignGroupUser
from nonebot.message import run_postprocessor
from nonebot.matcher import Matcher
from typing import Optional, Type
from gino.exceptions import UninitializedError
from utils.utils import (
is_number,
get_message_text,
get_message_imgs,
)
from nonebot.typing import T_State
from nonebot.adapters.cqhttp import (
Bot,
MessageEvent,
GroupMessageEvent,
PrivateMessageEvent,
Message,
Event,
)
from .data_source import (
get_setu_list,
get_luoxiang,
search_online_setu,
get_setu_urls,
find_img_index,
gen_message,
check_local_exists_or_download,
add_data_to_database,
get_setu_count,
)
from nonebot.adapters.cqhttp.exception import ActionFailed
from configs.config import Config, NICKNAME
from utils.manager import withdraw_message_manager
import re
try:
import ujson as json
except ModuleNotFoundError:
import json
__zx_plugin_name__ = "色图"
__plugin_usage__ = f"""
usage:
搜索 lolicon 图库,每日色图time...
指令:
色图: 随机本地色图
色图r: 随机在线十张r18涩图
色图 [id]: 本地指定id色图
色图 *[tags]: 在线搜索指定tag色图
色图r *[tags]: 同上
[1-9]张涩图: 本地随机色图连发
[1-9]张[tags]的涩图: 指定tag色图连发
示例:色图 萝莉|少女 白丝|黑丝
示例:色图 萝莉 猫娘
注:
tag至多取前20项,| 为或,萝莉|少女=萝莉或者少女
""".strip()
__plugin_des__ = "不要小看涩图啊混蛋!"
__plugin_cmd__ = ["色图 ?[id]", "色图 ?[tags]", "色图r ?[tags]", "[1-9]张?[tags]色图"]
__plugin_type__ = ("来点好康的",)
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 9,
"default_status": True,
"limit_superuser": False,
"cmd": ["色图", "涩图", "瑟图"],
}
__plugin_block_limit__ = {}
__plugin_cd_limit__ = {
"rst": "您冲的太快了,请稍后再冲.",
}
__plugin_configs__ = {
"WITHDRAW_SETU_MESSAGE": {
"value": (0, 1),
"help": "自动撤回,参1:延迟撤回色图时间(秒),0 为关闭 | 参2:监控聊天类型,0(私聊) 1(群聊) 2(群聊+私聊)",
"default_value": (0, 1),
},
"ONLY_USE_LOCAL_SETU": {
"value": False,
"help": "仅仅使用本地色图,不在线搜索",
"default_value": False,
},
"INITIAL_SETU_PROBABILITY": {
"value": 0.7,
"help": "初始色图概率,总概率 = 初始色图概率 + 好感度",
"default_value": 0.7
},
"DOWNLOAD_SETU": {
"value": True,
"help": "是否存储下载的色图,使用本地色图可以加快图片发送速度",
"default_value": True
},
"TIMEOUT": {
"value": 10,
"help": "色图下载超时限制(秒)",
"default_value": 10
}
}
Config.add_plugin_config(
"pixiv",
"PIXIV_NGINX_URL",
"i.pixiv.re",
help_="Pixiv反向代理"
)
setu_data_list = []
@run_postprocessor
async def do_something(
matcher: Matcher,
exception: Optional[Exception],
bot: Bot,
event: Event,
state: T_State,
):
global setu_data_list
if isinstance(event, MessageEvent):
if matcher.module == "send_setu":
# 添加数据至数据库
try:
await add_data_to_database(setu_data_list)
logger.info("色图数据自动存储数据库成功...")
setu_data_list = []
except UninitializedError:
pass
setu = on_command(
"色图", aliases={"涩图", "不够色", "来一发", "再来点", "色图r"}, priority=5, block=True
)
setu_reg = on_regex("(.*)[份|发|张|个|次|点](.*)[瑟|色|涩]图$", priority=5, block=True)
find_setu = on_command("查色图", priority=5, block=True)
@setu.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
msg = get_message_text(event.json())
if isinstance(event, GroupMessageEvent):
impression = (
await SignGroupUser.ensure(event.user_id, event.group_id)
).impression
luox = get_luoxiang(impression)
if luox:
await setu.finish(luox)
r18 = 0
num = 1
# 是否看r18
if state["_prefix"]["raw_command"] == "色图r" and isinstance(
event, PrivateMessageEvent
):
r18 = 1
num = 10
elif state["_prefix"]["raw_command"] == "色图r" and isinstance(
event, GroupMessageEvent
):
await setu.finish(
random.choice(["这种不好意思的东西怎么可能给这么多人看啦", "羞羞脸!给我滚出克私聊!", "变态变态变态变态大变态!"])
)
# 有 数字 的话先尝试本地色图id
if msg and is_number(msg):
setu_list, code = await get_setu_list(int(msg), r18=r18)
if code != 200:
await setu.finish(setu_list[0], at_sender=True)
setu_img, code = await check_local_exists_or_download(setu_list[0])
msg_id = await setu.send(gen_message(setu_list[0]) + setu_img, at_sender=True)
logger.info(
f"(USER {event.user_id}, GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 发送色图 {setu_list[0].local_id}.png"
)
if msg_id:
withdraw_message_manager.withdraw_message(
event,
msg_id["message_id"],
Config.get_config("send_setu", "WITHDRAW_SETU_MESSAGE"),
)
return
await send_setu_handle(setu, event, state["_prefix"]["raw_command"], msg, num, r18)
num_key = {
"一": 1,
"二": 2,
"两": 2,
"双": 2,
"三": 3,
"四": 4,
"五": 5,
"六": 6,
"七": 7,
"八": 8,
"九": 9,
}
@setu_reg.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
if isinstance(event, GroupMessageEvent):
impression = (
await SignGroupUser.ensure(event.user_id, event.group_id)
).impression
luox = get_luoxiang(impression)
if luox:
await setu.finish(luox, at_sender=True)
msg = get_message_text(event.json())
num = 1
msg = re.search(r"(.*)[份发张个次点](.*)[瑟涩色]图", msg)
# 解析 tags 以及 num
if msg:
num = msg.group(1)
tags = msg.group(2)
if tags:
tags = tags[:-1] if tags[-1] == "的" else tags
if num:
num = num[-1]
if num_key.get(num):
num = num_key[num]
elif is_number(num):
try:
num = int(num)
except ValueError:
num = 1
else:
num = 1
else:
return
await send_setu_handle(setu_reg, event, "色图", tags, num, 0)
@find_setu.args_parser
async def _(bot: Bot, event: MessageEvent, state: T_State):
if str(event.message) == "取消":
await find_setu.finish("取消了操作", at_sender=True)
imgs = get_message_imgs(event.json())
if not imgs:
await find_setu.reject("不搞错了,俺要图!")
state["img"] = imgs[0]
@find_setu.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
if get_message_text(event.json()) in ["帮助"]:
await find_setu.finish("通过图片获取本地色图id\n\t示例:查色图(图片)")
imgs = get_message_imgs(event.json())
if imgs:
state["img"] = imgs[0]
@find_setu.got("img", prompt="速速来图!")
async def _(bot: Bot, event: MessageEvent, state: T_State):
img = state["img"]
await find_setu.send(await find_img_index(img, event.user_id), at_sender=True)
async def send_setu_handle(
matcher: Type[Matcher],
event: MessageEvent,
command: str,
msg: str,
num: int,
r18: int,
):
global setu_data_list
# 非 id,在线搜索
tags = msg.split()
# 真寻的色图?怎么可能
if f"{NICKNAME}" in tags:
await matcher.finish("咳咳咳,虽然我很可爱,但是我木有自己的色图~~~有的话记得发我一份呀")
# 本地先拿图,下载失败补上去
setu_list, code = None, 200
setu_count = await get_setu_count(r18)
if (
not Config.get_config("send_setu", "ONLY_USE_LOCAL_SETU") and tags
) or setu_count <= 0:
# 先尝试获取在线图片
urls, text_list, add_databases_list, code = await get_setu_urls(
tags, num, r18, command
)
for x in add_databases_list:
setu_data_list.append(x)
# 未找到符合的色图,想来本地应该也没有
if code == 401:
await setu.finish(urls[0], at_sender=True)
if code == 200:
for i in range(len(urls)):
try:
setu_img, index = await search_online_setu(urls[i])
# 下载成功的话
if index != -1:
logger.info(
f"(USER {event.user_id}, GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 发送色图 {index}.png"
)
msg_id = await matcher.send(
Message(f"{text_list[i]}\n{setu_img}")
)
else:
if setu_list is None:
setu_list, code = await get_setu_list(tags=tags, r18=r18)
if code != 200:
await setu.finish(setu_list[0], at_sender=True)
if setu_list:
setu_image = random.choice(setu_list)
setu_list.remove(setu_image)
msg_id = await matcher.send(
Message(
gen_message(setu_image)
+ (
await check_local_exists_or_download(setu_image)
)[0]
)
)
logger.info(
f"(USER {event.user_id}, GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 发送本地色图 {setu_image.local_id}.png"
)
else:
msg_id = await matcher.send(text_list[i] + "\n" + setu_img)
if msg_id:
withdraw_message_manager.withdraw_message(
event,
msg_id["message_id"],
Config.get_config("send_setu", "WITHDRAW_SETU_MESSAGE"),
)
except ActionFailed:
await matcher.finish("坏了,这张图色过头了,我自己看看就行了!", at_sender=True)
return
if code != 200:
await matcher.finish("网络连接失败...", at_sender=True)
# 本地无图
if setu_list is None:
setu_list, code = await get_setu_list(tags=tags, r18=r18)
if code != 200:
await matcher.finish(setu_list[0], at_sender=True)
# 开始发图
for _ in range(num):
if not setu_list:
await setu.finish("坏了,已经没图了,被榨干了!")
setu_image = random.choice(setu_list)
setu_list.remove(setu_image)
try:
msg_id = await matcher.send(
Message(
gen_message(setu_image)
+ (await check_local_exists_or_download(setu_image))[0]
)
)
withdraw_message_manager.withdraw_message(
event,
msg_id["message_id"],
Config.get_config("send_setu", "WITHDRAW_SETU_MESSAGE"),
)
logger.info(
f"(USER {event.user_id}, GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 发送本地色图 {setu_image.local_id}.png"
)
except ActionFailed:
await matcher.finish("坏了,这张图色过头了,我自己看看就行了!", at_sender=True)
+276
View File
@@ -0,0 +1,276 @@
from configs.path_config import IMAGE_PATH
from utils.message_builder import image
from services.log import logger
from aiohttp.client_exceptions import ClientConnectorError
from utils.image_utils import get_img_hash, compressed_image
from asyncpg.exceptions import UniqueViolationError
from utils.utils import get_local_proxy
from asyncio.exceptions import TimeoutError
from typing import List, Optional
from configs.config import NICKNAME, Config
from ..model import Setu
import aiohttp
import aiofiles
import asyncio
import os
import random
try:
import ujson as json
except ModuleNotFoundError:
import json
url = "https://api.lolicon.app/setu/v2"
path = "_setu/"
r18_path = "_r18/"
# 获取url
async def get_setu_urls(
tags: List[str], num: int = 1, r18: int = 0, command: str = ""
) -> "List[str], List[str], List[tuple], int":
tags = tags[:3] if len(tags) > 3 else tags
params = {
"r18": r18, # 添加r18参数 0为否,1为是,2为混合
"tag": tags, # 若指定tag
"num": 100, # 一次返回的结果数量
"size": ["original"],
}
async with aiohttp.ClientSession() as session:
for count in range(3):
logger.info(f"get_setu_url: count --> {count}")
try:
async with session.get(
url, proxy=get_local_proxy(), timeout=Config.get_config("send_setu", "TIMEOUT"), params=params
) as response:
if response.status == 200:
data = await response.json()
if not data["error"]:
data = data["data"]
(
urls,
text_list,
add_databases_list,
) = await asyncio.get_event_loop().run_in_executor(
None, _setu_data_process, data, command
)
num = num if num < len(data) else len(data)
random_idx = random.sample(range(len(data)), num)
x_urls = []
x_text_lst = []
for x in random_idx:
x_urls.append(urls[x])
x_text_lst.append(text_list[x])
if not x_urls:
return ["没找到符合条件的色图..."], [], [], 401
return x_urls, x_text_lst, add_databases_list, 200
else:
return ["没找到符合条件的色图..."], [], [], 401
except (TimeoutError, ClientConnectorError):
pass
return ["我网线被人拔了..QAQ"], [], [], 999
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6;"
" rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
"Referer": "https://www.pixiv.net",
}
async def search_online_setu(
url_: str, id_: Optional[int] = None, path_: Optional[str] = None
) -> "MessageSegment, int":
"""
下载色图
:param url_: 色图url
:param id_: 本地id
:param path_: 存储路径
"""
ws_url = Config.get_config("pixiv", "PIXIV_NGINX_URL")
if ws_url:
url_ = url_.replace("i.pixiv.cat", ws_url)
async with aiohttp.ClientSession(headers=headers) as session:
for i in range(3):
logger.info(f"search_online_setu --> {i}")
try:
async with session.get(url_, proxy=get_local_proxy(), timeout=Config.get_config("send_setu", "TIMEOUT")) as res:
if res.status == 200:
index = random.randint(1, 100000) if id_ is None else id_
path_ = "temp" if not path_ else path_
file = f"{index}_temp_setu.jpg" if not path_ else f"{index}.jpg"
if not os.path.exists(f"{IMAGE_PATH}/{path_}"):
os.mkdir(f"{IMAGE_PATH}/{path_}")
async with aiofiles.open(
f"{IMAGE_PATH}/{path_}/{file}", "wb"
) as f:
try:
await f.write(await res.read())
except TimeoutError:
continue
if id_ is not None:
if (
os.path.getsize(f"{IMAGE_PATH}/{path_}/{index}.jpg")
> 1024 * 1024 * 1.5
):
compressed_image(
f"{IMAGE_PATH}/{path_}/{index}.jpg",
)
logger.info(f"下载 lolicon图片 {url_} 成功, id:{index}")
return image(file, path_), index
else:
logger.warning(f"访问 lolicon图片 {url_} 失败 status:{res.status}")
# return '\n这图好难下载啊!QAQ', -1, False
except (TimeoutError, ClientConnectorError):
pass
return "图片被小怪兽恰掉啦..!QAQ", -1
# 检测本地是否有id涩图,无的话则下载
async def check_local_exists_or_download(setu_image: Setu) -> "MessageSegment, int":
path_ = None
id_ = None
if Config.get_config("send_setu", "DOWNLOAD_SETU"):
id_ = setu_image.local_id
if setu_image.is_r18:
path_ = "_r18"
else:
path_ = path
if os.path.exists(f"{IMAGE_PATH}/{path_}/{setu_image.local_id}.jpg"):
return image(f"{setu_image.local_id}.jpg", path_), 200
return await search_online_setu(setu_image.img_url, id_, path_)
# 添加涩图数据到数据库
async def add_data_to_database(lst: List[tuple]):
tmp = []
for x in lst:
if x not in tmp:
tmp.append(x)
if tmp:
for x in tmp:
try:
r18 = 1 if "R-18" in x[5] else 0
idx = await Setu.get_image_count(r18)
await Setu.add_setu_data(
idx,
x[0],
x[1],
x[2],
x[3],
x[4],
x[5],
)
except UniqueViolationError:
pass
# 拿到本地色图列表
async def get_setu_list(
index: Optional[int] = None, tags: Optional[List[str]] = None, r18: int = 0
) -> "list, int":
if index:
image_count = await Setu.get_image_count(r18) - 1
if index < 0 or index > image_count:
return [f"超过当前上下限!({image_count})"], 999
image_list = [await Setu.query_image(index, r18=r18)]
elif tags:
image_list = await Setu.query_image(tags=tags, r18=r18)
else:
image_list = await Setu.query_image(r18=r18)
if not image_list:
return ["没找到符合条件的色图..."], 998
return image_list, 200
# 初始化消息
def gen_message(setu_image: Setu, img_msg: bool = False) -> str:
local_id = setu_image.local_id
title = setu_image.title
author = setu_image.author
pid = setu_image.pid
return (
f"id:{local_id}\n"
f"title:{title}\n"
f"author:{author}\n"
f"PID:{pid}\n"
f"{image(f'{local_id}', f'{r18_path if setu_image.is_r18 else path}') if img_msg else ''}"
)
# 罗翔老师!
def get_luoxiang(impression):
probability = (
impression + Config.get_config("send_setu", "INITIAL_SETU_PROBABILITY") * 100
)
if probability < random.randint(1, 101):
return (
"我为什么要给你发这个?"
+ image(random.choice(os.listdir(IMAGE_PATH + "luoxiang/")), "luoxiang")
+ f"\n(快向{NICKNAME}签到提升好感度吧!)"
)
return None
async def get_setu_count(r18: int) -> int:
"""
获取色图数量
:param r18: r18类型
"""
return await Setu.get_image_count(r18)
async def find_img_index(img_url, user_id):
async with aiohttp.ClientSession() as session:
async with session.get(img_url, proxy=get_local_proxy(), timeout=Config.get_config("send_setu", "TIMEOUT")) as res:
async with aiofiles.open(
IMAGE_PATH + f"temp/{user_id}_find_setu_index.jpg", "wb"
) as f:
await f.write(await res.read())
img_hash = str(get_img_hash(IMAGE_PATH + f"temp/{user_id}_find_setu_index.jpg"))
setu_img = await Setu.get_image_in_hash(img_hash)
if setu_img:
return (
f"id:{setu_img.local_id}\n"
f"title:{setu_img.title}\n"
f"author:{setu_img.author}\n"
f"PID:{setu_img.pid}"
)
return "该图不在色图库中或色图库未更新!"
# 处理色图数据
def _setu_data_process(data: dict, command: str) -> "list, list, list":
urls = []
text_list = []
add_databases_list = []
for i in range(len(data)):
img_url = data[i]["urls"]["original"]
img_url = (
img_url.replace("i.pixiv.cat", "i.pximg.net")
if "i.pixiv.cat" in img_url
else img_url
)
title = data[i]["title"]
author = data[i]["author"]
pid = data[i]["pid"]
urls.append(img_url)
text_list.append(f"title:{title}\nauthor:{author}\nPID:{pid}")
tags = []
for j in range(len(data[i]["tags"])):
tags.append(data[i]["tags"][j])
if command != "色图r":
if "R-18" in tags:
tags.remove("R-18")
add_databases_list.append(
(
title,
author,
pid,
"",
img_url,
",".join(tags),
)
)
return urls, text_list, add_databases_list