Skip to content

Commit

Permalink
Update Genshin Cos plugin version and add support for ZZZ cos images
Browse files Browse the repository at this point in the history
  • Loading branch information
Cvandia committed Mar 30, 2024
1 parent 3c946e1 commit 596315f
Show file tree
Hide file tree
Showing 5 changed files with 90 additions and 52 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ _⭐基于Nonebot2的一款获取米游社cos的插件⭐_
<div align="center">


### 目前不仅有原神,现在支持崩坏3、星穹铁道、大别野的cos图
### 目前不仅有原神,现在支持崩坏3、星穹铁道、大别野、绝区零的cos图

</div>

Expand Down
34 changes: 22 additions & 12 deletions nonebot_plugin_genshin_cos/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
"unique_name": "genshin_cos",
"example": "保存cos:保存cos图片至本地文件",
"author": "divandia <106718176+Cvandia@users.noreply.github.com>",
"version": "0.2.8",
"version": "0.3.0",
},
)
logo = """<g>
Expand Down Expand Up @@ -88,7 +88,9 @@
"精品cos", aliases={"精品coser", "精品cos图"}, block=False, priority=5
)
search_cos = on_regex(
r"^搜索(原神|崩坏3|星穹铁道|大别野)cos[r]?[图]?(.+)?", block=False, priority=5
r"^搜索(原神|崩坏3|星穹铁道|大别野|绝区零)cos[r]?[图]?(.+)?",
block=False,
priority=5,
)
turn_aps = on_regex(
r"^(开启|关闭)每日推送(原神|崩坏3|星穹铁道|大别野)(\s)?(.+)?",
Expand Down Expand Up @@ -125,6 +127,8 @@ async def _(
search_class = Search(ForumType.DBYCOS, groups[0])
elif args[0] == "星穹铁道":
search_class = Search(ForumType.StarRailCos, groups[0])
elif args[0] == "绝区零":
search_class = Search(ForumType.ZZZ, groups[0])
else:
await search_cos.finish("暂不支持该类型")
await send_images(bot, matcher, groups, event, search_class)
Expand All @@ -149,6 +153,8 @@ async def _(event: GroupMessageEvent, args: Tuple[str, ...] = RegexGroup()):
await turn_aps.finish("未安装apscheduler插件,无法使用此功能")
mode = args[0]
game_type = args[1]
if game_type not in GENSHIN_NAME + DBY_NAME:
await turn_aps.finish("暂不支持其他类型的订阅,仅支持原神和大别野")
time = args[3]
aps_group_id = str(event.group_id)
MyConfig = CONFIG.copy()
Expand Down Expand Up @@ -205,6 +211,8 @@ async def _(
send_type = dbycos_hot
elif args[0] in STAR_RAIL:
send_type = starrail_hot
elif args[0] in ZZZ_NAME:
send_type = zzz_hot
else:
await hot_cos.finish("暂不支持该类型")
await send_images(bot, matcher, args, event, send_type)
Expand All @@ -229,12 +237,8 @@ async def _(

if args[0] in GENSHIN_NAME:
send_type = Rank(ForumType.GenshinCos, rank_type)
elif args[0] in HONKAI3RD_NAME:
send_type = Rank(ForumType.Honkai3rdPic, rank_type)
elif args[0] in DBY_NAME:
send_type = Rank(ForumType.DBYCOS, rank_type)
elif args[0] in STAR_RAIL:
send_type = Rank(ForumType.StarRailCos, rank_type)
else:
await rank_cos.finish("暂不支持该类型")
await send_images(bot, matcher, args, event, send_type)
Expand All @@ -255,6 +259,8 @@ async def _(
send_type = dbycos_latest_comment
elif args[0] in STAR_RAIL:
send_type = starrail_latest_comment
elif args[0] in ZZZ_NAME:
send_type = zzz_latest_comment
else:
await latest_cos.finish("暂不支持该类型")
await send_images(bot, matcher, args, event, send_type)
Expand All @@ -273,6 +279,8 @@ async def _(
send_type = honkai3rd_good
elif args[0] in DBY_NAME:
send_type = dbycos_good
elif args[0] in ZZZ_NAME:
send_type = zzz_good
elif args[0] in STAR_RAIL:
await good_cos.finish("星穹铁道暂不支持精品cos")
else:
Expand All @@ -292,6 +300,10 @@ async def got_type(game_type: str = ArgPlainText()):
hot = honkai3rd_hot
elif game_type in STAR_RAIL:
hot = starrail_hot
elif game_type in ZZZ_NAME:
hot = zzz_hot
else:
await download_cos.finish("暂不支持该类型")
image_urls = await hot.async_get_urls()
if not image_urls:
await download_cos.finish(f"没有找到{game_type}的cos图片")
Expand Down Expand Up @@ -330,10 +342,6 @@ async def aps_send(aps_goup_id: str):
send_type = genshin_rank_daily
elif game_type in DBY_NAME:
send_type = dbycos_rank_daily
elif game_type in HONKAI3RD_NAME:
send_type = honkai3rd_rank_daily
elif game_type in STAR_RAIL:
send_type = starrail_rank_daily
else:
continue
image_list = await send_type.async_get_urls(page_size=5)
Expand Down Expand Up @@ -387,8 +395,10 @@ async def send_images(
await matcher.send(f"获取{num}张图片中…请稍等")
msg_list = [MessageSegment.text(f"✅找到最新的一些{args[0]}图如下:✅")]
image_list = await send_type.async_get_urls()
'''random随机从列表中取出num个元素'''
image_list = [image_list[i] for i in random.sample(range(len(image_list)), num)]
"""random随机从列表中取出num个元素"""
image_list = [
image_list[i] for i in random.sample(range(len(image_list)), num)
]
if num > len(image_list):
await matcher.finish(
f"最多只能获取{len(image_list)}张图片", at_sender=True
Expand Down
32 changes: 17 additions & 15 deletions nonebot_plugin_genshin_cos/hoyospider.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ class GameType(Enum):
DBY = 5 # 大别野
StarRail = 6 # 星穹铁道
Honkai2 = 3 # 崩坏2
ZZZ = 8 # 绝区零


@unique
Expand All @@ -185,7 +186,7 @@ class ForumType(Enum):
StarRailPic = 56 # 星穹铁道同人图
StarRailCos = 62 # 星穹铁道cos
Honkai2Pic = 40 # 崩坏2同人图
TearsOfThemisPic = 38 # 泪水同人图
ZZZ = 65 # 绝区零


def get_gids(forum: str) -> GameType:
Expand All @@ -201,6 +202,7 @@ def get_gids(forum: str) -> GameType:
"StarRailPic": GameType.StarRail,
"Honkai2Pic": GameType.Honkai2,
"StarRailCos": GameType.StarRail,
"ZZZ": GameType.ZZZ,
}
return forum2gids[forum]

Expand Down Expand Up @@ -359,13 +361,14 @@ def sync_get_name(self, page_size: int = 20) -> List:
async def async_get_name(self, page_size: int = 20) -> List:
params = self.get_params(page_size)
return await self.async_name(params)


class Search(HoyoBasicSpider):
'''
"""
搜索帖子
url: https://bbs.mihoyo.com/ys/searchPost?keyword=原神
'''
"""

def __init__(self, forum_id: ForumType, keyword: str) -> None:
super().__init__()
self.api = self.base_url + "searchPosts"
Expand All @@ -375,31 +378,26 @@ def __init__(self, forum_id: ForumType, keyword: str) -> None:
self.keyword = keyword + "+cos"

def get_params(self, page_size: int) -> Dict:
params = {
"gids": self.gids,
"size": page_size,
"keyword": self.keyword
}
params = {"gids": self.gids, "size": page_size, "keyword": self.keyword}
return params

def sync_get_urls(self, page_size: int = 20) -> List:
params = self.get_params(page_size)
return self.sync_get(params, is_good=True)

async def async_get_urls(self, page_size: int = 20) -> List:
params = self.get_params(page_size)
return await self.async_get(params, is_good=True)

def sync_get_name(self, page_size: int = 20) -> List:
params = self.get_params(page_size)
return self.sync_name(params, is_good=True)

async def async_get_name(self, page_size: int = 20) -> List:
params = self.get_params(page_size)
return await self.async_name(params, is_good=True)



# 实例化对象

genshin_rank_daily = Rank(ForumType.GenshinCos, RankType.Daily)
Expand Down Expand Up @@ -430,4 +428,8 @@ async def async_get_name(self, page_size: int = 20) -> List:
dbycos_rank_daily = Rank(ForumType.DBYCOS, RankType.Daily)
dbycos_hot = Hot(ForumType.DBYCOS)
dbycos_good = Good(ForumType.DBYCOS)
dbycos_latest_comment = Latest(ForumType.DBYCOS, LatestType.LatestComment)
dbycos_latest_comment = Latest(ForumType.DBYCOS, LatestType.LatestComment)

zzz_hot = Hot(ForumType.ZZZ)
zzz_good = Good(ForumType.ZZZ)
zzz_latest_comment = Latest(ForumType.ZZZ, LatestType.LatestComment)
72 changes: 49 additions & 23 deletions nonebot_plugin_genshin_cos/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,14 @@
import httpx
from httpx import TimeoutException
from nonebot import get_driver
from nonebot.adapters.onebot.v11 import Bot, MessageEvent, GroupMessageEvent, MessageSegment, Message, GROUP_ADMIN, GROUP_OWNER
from nonebot.adapters.onebot.v11 import (
Bot,
MessageEvent,
GroupMessageEvent,
Message,
GROUP_ADMIN,
GROUP_OWNER,
)
from nonebot.exception import ActionFailed
from nonebot.log import logger
from nonebot.matcher import Matcher
Expand All @@ -18,15 +25,29 @@

# 拓展的异常类和函数
SUPER_PERMISSION = GROUP_ADMIN | GROUP_OWNER | SUPERUSER
GENSHIN_NAME = ["原神", 'OP', 'op', '欧泡', '⭕', '🅾️', '🅾️P', '🅾️p', '原', '圆', '原']
HONKAI3RD_NAME = ['崩坏3', '崩崩崩', '蹦蹦蹦', '崩坏三', '崩三', '崩崩崩三', '崩坏3rd', '崩坏3Rd', '崩坏3RD', '崩坏3rd',
'崩坏3RD', '崩坏3Rd']
DBY_NAME = ['大别野', 'DBY', 'dby']
STAR_RAIL = ['星穹铁道', '星穹', '崩铁', '铁道', '星铁', '穹p', '穹铁']
GENSHIN_NAME = ["原神", "OP", "op", "欧泡", "⭕", "🅾️", "🅾️P", "🅾️p", "原", "圆", "原"]
HONKAI3RD_NAME = [
"崩坏3",
"崩崩崩",
"蹦蹦蹦",
"崩坏三",
"崩三",
"崩崩崩三",
"崩坏3rd",
"崩坏3Rd",
"崩坏3RD",
"崩坏3rd",
"崩坏3RD",
"崩坏3Rd",
]
DBY_NAME = ["大别野", "DBY", "dby"]
STAR_RAIL = ["星穹铁道", "星穹", "崩铁", "铁道", "星铁", "穹p", "穹铁"]
ZZZ_NAME = ["绝区零", "绝零区", "绝零", "0", "零", "绝区", "0区"]


class WriteError(Exception):
"""写入错误"""

pass


Expand All @@ -52,7 +73,7 @@ def check_cd(user_id: int, user_data: Dict[str, datetime]) -> Tuple[bool, int, d
data = user_data
if str(user_id) not in data:
data[str(user_id)] = datetime.now()
if datetime.now() < data[f'{user_id}']:
if datetime.now() < data[f"{user_id}"]:
delta = (data[str(user_id)] - datetime.now()).seconds
return False, delta, data
else:
Expand All @@ -61,44 +82,49 @@ def check_cd(user_id: int, user_data: Dict[str, datetime]) -> Tuple[bool, int, d


async def download_from_urls(urls: List[str], path: Path):
'''
"""
下载图片
:param urls: 图片链接
:param path: 保存路径
:return: None
'''
"""
is_download_error = False
error_cnt = 0
success_cnt = 0
if not path.exists():
path.mkdir(parents=True)
if not path.is_dir():
raise WriteError('路径不是文件夹')
raise WriteError("路径不是文件夹")
async with httpx.AsyncClient() as client:
for url in urls:
try:
filename = url.split('/')[-1]
filename = url.split("/")[-1]
new_path = path / filename
rsp = await client.get(url)
content = rsp.content
with open(new_path, 'wb') as f:
with open(new_path, "wb") as f:
f.write(content)
except (httpx.ConnectError, httpx.RequestError, httpx.ReadTimeout, TimeoutException):
except (
httpx.ConnectError,
httpx.RequestError,
httpx.ReadTimeout,
TimeoutException,
):
is_download_error = True
error_cnt += 1
continue
if is_download_error:
raise WriteError(f'{error_cnt}张图片由于超时下载失败了')
raise WriteError(f"{error_cnt}张图片由于超时下载失败了")
success_cnt += 1
logger.success(f'下载{success_cnt}张成功')
logger.success(f"下载{success_cnt}张成功")


async def send_forward_msg(
bot: Bot,
event: MessageEvent,
name: str,
uin: str,
msgs: list,
bot: Bot,
event: MessageEvent,
name: str,
uin: str,
msgs: list,
) -> dict:
"""调用合并转发API
Expand Down Expand Up @@ -141,11 +167,11 @@ def to_json(msg: Message):


async def send_regular_msg(matcher: Matcher, messages: list):
'''
"""
发送常规消息
:param matcher: Matcher
:param messages: 消息列表
'''
"""
cnt = 1
for msg in messages:
try:
Expand All @@ -154,4 +180,4 @@ async def send_regular_msg(matcher: Matcher, messages: list):
await sleep(DELAY)
except ActionFailed:
if cnt <= 2:
await matcher.send('消息可能风控,请尝试更改为合并转发模式')
await matcher.send("消息可能风控,请尝试更改为合并转发模式")
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "nonebot-plugin-genshin-cos"
version = "0.2.8"
version = "0.3.0"
description = "米游社原神cos图获取"
authors = ["Cvandia <106718176+Cvandia@users.noreply.github.com>"]
license = "MIT"
Expand Down

0 comments on commit 596315f

Please sign in to comment.