Merge pull request #1090 from NumberSir/main

fix: bilibili_sub, azur_draw_card
This commit is contained in:
HibiKier 2022-09-16 19:14:19 +08:00 committed by GitHub
commit 504f78dd49
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 57 deletions

View File

@ -208,7 +208,9 @@ async def get_sub_status(id_: int, sub_type: str) -> Optional[str]:
elif sub_type == "season": elif sub_type == "season":
return await _get_season_status(id_) return await _get_season_status(id_)
except ResponseCodeError: except ResponseCodeError:
return f"Id{id_} 获取信息失败...请检查订阅Id是否存在或稍后再试..." logger.error(f"Id{id_} 获取信息失败...请检查订阅Id是否存在或稍后再试...")
return None
# return f"Id{id_} 获取信息失败...请检查订阅Id是否存在或稍后再试..."
# except Exception as e: # except Exception as e:
# logger.error(f"获取订阅状态发生预料之外的错误 id_{id_} {type(e)}{e}") # logger.error(f"获取订阅状态发生预料之外的错误 id_{id_} {type(e)}{e}")
# return "发生了预料之外的错误..请稍后再试或联系管理员....." # return "发生了预料之外的错误..请稍后再试或联系管理员....."

View File

@ -1,7 +1,8 @@
import contextlib
import random import random
import dateparser import dateparser
from lxml import etree from lxml import etree
from typing import List, Optional from typing import List, Optional, Tuple
from urllib.parse import unquote from urllib.parse import unquote
from pydantic import ValidationError from pydantic import ValidationError
from nonebot.log import logger from nonebot.log import logger
@ -12,7 +13,6 @@ from .base_handle import BaseHandle, BaseData, UpEvent as _UpEvent, UpChar as _U
from ..config import draw_config from ..config import draw_config
from ..util import remove_prohibited_str, cn2py from ..util import remove_prohibited_str, cn2py
from utils.image_utils import BuildImage from utils.image_utils import BuildImage
import asyncio
try: try:
import ujson as json import ujson as json
@ -29,7 +29,7 @@ class AzurChar(BaseData):
class UpChar(_UpChar): class UpChar(_UpChar):
type_: str # 舰娘类型 type_: str # 舰娘类型
class UpEvent(_UpEvent): class UpEvent(_UpEvent):
@ -53,7 +53,9 @@ class AzurHandle(BaseHandle[AzurChar]):
type_ = ["维修", "潜艇", "重巡", "轻航", "航母"] type_ = ["维修", "潜艇", "重巡", "轻航", "航母"]
up_pool_flag = pool_name == "活动" up_pool_flag = pool_name == "活动"
# Up # Up
up_ship = [x for x in self.UP_EVENT.up_char if x.zoom > 0] up_ship = (
[x for x in self.UP_EVENT.up_char if x.zoom > 0] if self.UP_EVENT else []
)
# print(up_ship) # print(up_ship)
acquire_char = None acquire_char = None
if up_ship and up_pool_flag: if up_ship and up_pool_flag:
@ -61,19 +63,15 @@ class AzurHandle(BaseHandle[AzurChar]):
# 初始化概率 # 初始化概率
cur_ = up_ship[0].zoom / 100 cur_ = up_ship[0].zoom / 100
for i in range(len(up_ship)): for i in range(len(up_ship)):
try: with contextlib.suppress(IndexError):
up_zoom.append((cur_, cur_ + up_ship[i+1].zoom / 100)) up_zoom.append((cur_, cur_ + up_ship[i + 1].zoom / 100))
cur_ += up_ship[i+1].zoom / 100 cur_ += up_ship[i + 1].zoom / 100
except IndexError:
pass
rand = random.random() rand = random.random()
# 抽取up # 抽取up
for i, zoom in enumerate(up_zoom): for i, zoom in enumerate(up_zoom):
if zoom[0] <= rand <= zoom[1]: if zoom[0] <= rand <= zoom[1]:
try: with contextlib.suppress(IndexError):
acquire_char = [x for x in self.ALL_CHAR if x.name == up_ship[i].name][0] acquire_char = [x for x in self.ALL_CHAR if x.name == up_ship[i].name][0]
except IndexError:
pass
# 没有up或者未抽取到up # 没有up或者未抽取到up
if not acquire_char: if not acquire_char:
star = self.get_star( star = self.get_star(
@ -92,9 +90,6 @@ class AzurHandle(BaseHandle[AzurChar]):
]) ])
return acquire_char return acquire_char
# async def draw(self, count: int, **kwargs) -> Message:
# return await asyncio.get_event_loop().run_in_executor(None, self._draw, count)
async def draw(self, count: int, **kwargs) -> Message: async def draw(self, count: int, **kwargs) -> Message:
index2card = self.get_cards(count, **kwargs) index2card = self.get_cards(count, **kwargs)
cards = [card[0] for card in index2card] cards = [card[0] for card in index2card]
@ -162,22 +157,22 @@ class AzurHandle(BaseHandle[AzurChar]):
return return
dom = etree.HTML(result, etree.HTMLParser()) dom = etree.HTML(result, etree.HTMLParser())
contents = dom.xpath( contents = dom.xpath(
"//div[@class='resp-tabs-container']/div[@class='resp-tab-content']" "//div[@class='mw-body-content mw-content-ltr']/div[@class='mw-parser-output']"
) )
for index, content in enumerate(contents): for index, content in enumerate(contents):
char_list = content.xpath("./table/tbody/tr[2]/td/div/div/div/div") char_list = content.xpath("./div[@id='CardSelectTr']/div")
for char in char_list: for char in char_list:
try: try:
name = char.xpath("./a/@title")[0] name = char.xpath("./div/a/@title")[0]
frame = char.xpath("./div/a/img/@alt")[0] frame = char.xpath("./div/div/a/img/@alt")[0]
avatar = char.xpath("./a/img/@srcset")[0] avatar = char.xpath("./div/a/img/@srcset")[0]
except IndexError: except IndexError:
continue continue
member_dict = { member_dict = {
"名称": remove_prohibited_str(name), "名称": remove_prohibited_str(name),
"头像": unquote(str(avatar).split(" ")[-2]), "头像": unquote(str(avatar).split(" ")[-2]),
"星级": self.parse_star(frame), "星级": self.parse_star(frame),
"类型": self.parse_type(index), "类型": char.xpath("./@data-param1")[0].split(",")[1],
} }
info[member_dict["名称"]] = member_dict info[member_dict["名称"]] = member_dict
# 更新额外信息 # 更新额外信息
@ -225,48 +220,21 @@ class AzurHandle(BaseHandle[AzurChar]):
@staticmethod @staticmethod
def parse_star(star: str) -> int: def parse_star(star: str) -> int:
if star in ["舰娘头像外框普通.png", "舰娘头像外框白色.png"]: if star in {"舰娘头像外框普通.png", "舰娘头像外框白色.png"}:
return 1 return 1
elif star in ["舰娘头像外框稀有.png", "舰娘头像外框蓝色.png"]: elif star in {"舰娘头像外框稀有.png", "舰娘头像外框蓝色.png"}:
return 2 return 2
elif star in ["舰娘头像外框精锐.png", "舰娘头像外框紫色.png"]: elif star in {"舰娘头像外框精锐.png", "舰娘头像外框紫色.png"}:
return 3 return 3
elif star in ["舰娘头像外框超稀有.png", "舰娘头像外框金色.png"]: elif star in {"舰娘头像外框超稀有.png", "舰娘头像外框金色.png"}:
return 4 return 4
elif star in ["舰娘头像外框海上传奇.png", "舰娘头像外框彩色.png"]: elif star in {"舰娘头像外框海上传奇.png", "舰娘头像外框彩色.png"}:
return 5 return 5
elif star in [ elif star in {"舰娘头像外框最高方案.png", "舰娘头像外框决战方案.png", "舰娘头像外框超稀有META.png", "舰娘头像外框精锐META.png"}:
"舰娘头像外框最高方案.png",
"舰娘头像外框决战方案.png",
"舰娘头像外框超稀有META.png",
"舰娘头像外框精锐META.png",
]:
return 6 return 6
else: else:
return 6 return 6
@staticmethod
def parse_type(index: int) -> str:
azur_types = [
"驱逐",
"轻巡",
"重巡",
"超巡",
"战巡",
"战列",
"航母",
"航站",
"轻航",
"重炮",
"维修",
"潜艇",
"运输",
]
try:
return azur_types[index]
except IndexError:
return azur_types[0]
async def update_up_char(self): async def update_up_char(self):
url = "https://wiki.biligame.com/blhx/游戏活动表" url = "https://wiki.biligame.com/blhx/游戏活动表"
result = await self.get_url(url) result = await self.get_url(url)
@ -290,7 +258,7 @@ class AzurHandle(BaseHandle[AzurChar]):
up_chars = [] up_chars = []
for ship in ships: for ship in ships:
name = ship.xpath("./tbody/tr/td[2]/p/a/@title")[0] name = ship.xpath("./tbody/tr/td[2]/p/a/@title")[0]
type_ = ship.xpath("./tbody/tr/td[2]/p/small/text()")[0] # 舰船类型 type_ = ship.xpath("./tbody/tr/td[2]/p/small/text()")[0] # 舰船类型
try: try:
p = float(str(ship.xpath(".//sup/text()")[0]).strip("%")) p = float(str(ship.xpath(".//sup/text()")[0]).strip("%"))
except (IndexError, ValueError): except (IndexError, ValueError):
@ -298,7 +266,9 @@ class AzurHandle(BaseHandle[AzurChar]):
star = self.parse_star( star = self.parse_star(
ship.xpath("./tbody/tr/td[1]/div/div/div/a/img/@alt")[0] ship.xpath("./tbody/tr/td[1]/div/div/div/a/img/@alt")[0]
) )
up_chars.append(UpChar(name=name, star=star, limited=False, zoom=p, type_=type_)) up_chars.append(
UpChar(name=name, star=star, limited=False, zoom=p, type_=type_)
)
self.UP_EVENT = UpEvent( self.UP_EVENT = UpEvent(
title=title, title=title,
pool_img="", pool_img="",