优化 圣遗物查询 和 部分代码 (#49)

优化 圣遗物查询 和 部分代码
This commit is contained in:
omg-xtao 2022-06-18 18:02:56 +08:00 committed by GitHub
parent 46136b1c25
commit a19035fa5a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 45 additions and 76 deletions

View File

@ -5,13 +5,10 @@ import httpx
def get_format_sub_item(artifact_attr: dict):
msg = ""
for i in artifact_attr["sub_item"]:
msg += f'{i["name"]:\u3000<6}{i["value"]}\n'
return msg
return "".join(f'{i["name"]:\u3000<6} | {i["value"]}\n' for i in artifact_attr["sub_item"])
def get_yiyan(get_yiyan_num):
def get_comment(get_rate_num):
data = {"1": ["破玩意谁能用啊,谁都用不了吧", "喂了吧,这东西做狗粮还能有点用", "抽卡有保底,圣遗物没有下限",
"未来可期呢(笑)", "你出门一定很安全", "你是不是得罪米哈游了?", "……宁就是班尼特本特?",
"丢人!你给我退出提瓦特(", "不能说很糟糕,只能说特别不好"],
@ -27,7 +24,7 @@ def get_yiyan(get_yiyan_num):
"怕不是以后开宝箱只能开出卷心菜", "吃了吗?没吃的话,吃我一拳", "我觉得这个游戏有问题", "这合理吗",
"这东西没啥用,给我吧(柠檬)", " "]}
try:
data_ = int(float(get_yiyan_num))
data_ = int(float(get_rate_num))
except ValueError:
data_ = 0
if data_ == 100:

View File

@ -1,10 +1,11 @@
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.constants import ChatAction, ParseMode
from telegram.ext import CallbackContext, ConversationHandler, CommandHandler, CallbackQueryHandler
from telegram.ext import CallbackContext, ConversationHandler, CommandHandler, CallbackQueryHandler, MessageHandler, \
filters
from telegram.helpers import escape_markdown
from logger import Log
from model.apihelper.artifact import ArtifactORCRate, get_yiyan, get_format_sub_item
from model.apihelper.artifact import ArtifactORCRate, get_comment, get_format_sub_item
from plugins.base import BasePlugins
from plugins.errorhandler import conversation_error_handler
from service import BaseService
@ -16,33 +17,15 @@ class ArtifactRate(BasePlugins):
"""
圣遗物评分
"""
STAR_KEYBOARD = [[InlineKeyboardButton("1", callback_data="artifact_orc_rate_data|star|1"),
InlineKeyboardButton("2", callback_data="artifact_orc_rate_data|star|2"),
InlineKeyboardButton("3", callback_data="artifact_orc_rate_data|star|3"),
InlineKeyboardButton("4", callback_data="artifact_orc_rate_data|star|4"),
InlineKeyboardButton("5", callback_data="artifact_orc_rate_data|star|5")]]
STAR_KEYBOARD = [[
InlineKeyboardButton(
f"{i}", callback_data=f"artifact_orc_rate_data|star|{i}") for i in range(1, 6)
]]
LEVEL_KEYBOARD = [[InlineKeyboardButton("1", callback_data="artifact_orc_rate_data|level|1"),
InlineKeyboardButton("2", callback_data="artifact_orc_rate_data|level|2"),
InlineKeyboardButton("3", callback_data="artifact_orc_rate_data|level|3"),
InlineKeyboardButton("4", callback_data="artifact_orc_rate_data|level|4"),
InlineKeyboardButton("5", callback_data="artifact_orc_rate_data|level|5")],
[InlineKeyboardButton("6", callback_data="artifact_orc_rate_data|level|6"),
InlineKeyboardButton("7", callback_data="artifact_orc_rate_data|level|7"),
InlineKeyboardButton("8", callback_data="artifact_orc_rate_data|level|8"),
InlineKeyboardButton("9", callback_data="artifact_orc_rate_data|level|9"),
InlineKeyboardButton("10", callback_data="artifact_orc_rate_data|level|0")],
[InlineKeyboardButton("11", callback_data="artifact_orc_rate_data|level|11"),
InlineKeyboardButton("12", callback_data="artifact_orc_rate_data|level|12"),
InlineKeyboardButton("13", callback_data="artifact_orc_rate_data|level|13"),
InlineKeyboardButton("14", callback_data="artifact_orc_rate_data|level|14"),
InlineKeyboardButton("15", callback_data="artifact_orc_rate_data|level|15")],
[InlineKeyboardButton("16", callback_data="artifact_orc_rate_data|level|16"),
InlineKeyboardButton("17", callback_data="artifact_orc_rate_data|level|17"),
InlineKeyboardButton("18", callback_data="artifact_orc_rate_data|level|18"),
InlineKeyboardButton("19", callback_data="artifact_orc_rate_data|level|19"),
InlineKeyboardButton("20", callback_data="artifact_orc_rate_data|level|20")]
]
LEVEL_KEYBOARD = [[
InlineKeyboardButton(
f"{i * 5 + j}", callback_data=f"artifact_orc_rate_data|level|{i * 5 + j}") for j in range(1, 6)
] for i in range(0, 5)]
def __init__(self, service: BaseService):
super().__init__(service)
@ -51,14 +34,15 @@ class ArtifactRate(BasePlugins):
@staticmethod
def create_conversation_handler(service: BaseService):
artifact_rate = ArtifactRate(service)
artifact_rate_handler = ConversationHandler(
entry_points=[CommandHandler('artifact_rate', artifact_rate.command_start)],
return ConversationHandler(
entry_points=[CommandHandler('artifact_rate', artifact_rate.command_start),
MessageHandler(filters.Regex(r"^圣遗物评分(.*)"), artifact_rate.command_start),
MessageHandler(filters.CaptionRegex(r"^圣遗物评分(.*)"), artifact_rate.command_start)],
states={
artifact_rate.COMMAND_RESULT: [CallbackQueryHandler(artifact_rate.command_result)]
},
fallbacks=[CommandHandler('cancel', artifact_rate.cancel)]
)
return artifact_rate_handler
async def get_rate(self, artifact_attr: dict) -> str:
rate_result_req = await self.artifact_rate.rate_artifact(artifact_attr)
@ -68,15 +52,16 @@ class ArtifactRate(BasePlugins):
return artifact_attr.get("message", "API请求错误")
return "API请求错误"
rate_result = rate_result_req.json()
format_result = "*圣遗物评分结果*\n" \
return "*圣遗物评分结果*\n" \
f"主属性:{escape_markdown(artifact_attr['main_item']['name'], version=2)}\n" \
f"{escape_markdown(get_format_sub_item(artifact_attr), version=2)}" \
f'`--------------------`\n' \
f"总分:{escape_markdown(rate_result['total_percent'], version=2)}\n" \
f"主词条:{escape_markdown(rate_result['main_percent'], version=2)}\n" \
f"副词条:{escape_markdown(rate_result['sub_percent'], version=2)}\n" \
f"{escape_markdown(get_yiyan(rate_result['total_percent']), version=2)}\n" \
f'`--------------------`\n' \
f"{escape_markdown(get_comment(rate_result['total_percent']), version=2)}\n" \
"_评分、识图均来自 genshin\\.pub_"
return format_result
@conversation_error_handler
async def command_start(self, update: Update, context: CallbackContext) -> int:
@ -85,13 +70,13 @@ class ArtifactRate(BasePlugins):
Log.info(f"用户 {user.full_name}[{user.id}] 圣遗物评分命令请求")
context.user_data["artifact_attr"] = None
reply_to_message = message.reply_to_message
if reply_to_message is None:
if message.photo:
photo_file = await message.photo[-1].get_file() # 草 居然第一张是预览图我人都麻了
elif reply_to_message is None or not reply_to_message.photo:
await message.reply_text("图呢?")
return ConversationHandler.END
if len(reply_to_message.photo) == 0:
await message.reply_text("图呢?")
return ConversationHandler.END
photo_file = await reply_to_message.photo[-1].get_file() # 草 居然第一张是预览图我人都麻了
else:
photo_file = await reply_to_message.photo[-1].get_file()
photo_byte = await photo_file.download_as_bytearray()
artifact_attr_req = await self.artifact_rate.get_artifact_attr(photo_byte)
if artifact_attr_req.status_code != 200:

View File

@ -28,7 +28,6 @@ class AdminService:
await self.repository.add_admin(user_id)
except IntegrityError as error:
Log.warning(f"{user_id} 已经存在数据库 \n", error)
pass
admin_list = await self.repository.get_admin()
for config_admin in config.ADMINISTRATORS:
admin_list.append(config_admin["user_id"])

View File

@ -49,10 +49,7 @@ class QuestionData:
def __init__(self, question_id: int = 0, question: str = "", answer: List[AnswerData] = None):
self.question_id = question_id
self.question = question
if answer is None:
self.answer = []
else:
self.answer = answer
self.answer = [] if answer is None else answer
def json_dumps(self):
data = {

View File

@ -61,14 +61,14 @@ class RedisCache:
async def del_all_question(self):
qname = "quiz:question"
keys = await self.client.keys(qname + "*")
keys = await self.client.keys(f"{qname}*")
if keys is not None:
for key in keys:
await self.client.delete(key)
async def del_all_answer(self):
qname = "quiz:answer"
keys = await self.client.keys(qname + "*")
keys = await self.client.keys(f"{qname}*")
if keys is not None:
for key in keys:
await self.client.delete(key)

View File

@ -51,13 +51,13 @@ class TemplateService:
"""
start_time = time.time()
template = self.get_template(template_path, template_name, auto_escape)
template_data["res_path"] = "file://" + self._current_dir
template_data["res_path"] = f"file://{self._current_dir}"
html = await template.render_async(**template_data)
Log.debug(f"{template_name} 模板渲染使用了 {str(time.time() - start_time)}")
browser = await self.browser.get_browser()
start_time = time.time()
page = await browser.new_page(viewport=viewport)
await page.goto("file://" + template.filename)
await page.goto(f"file://{template.filename}")
await page.set_content(html, wait_until="networkidle")
png_data = await page.screenshot(full_page=full_page)
await page.close()

View File

@ -35,16 +35,13 @@ class Wiki:
# weapon_info = await self.weapons.get_weapon_info(weapon_url)
if index % 5 == 0:
result_list = await asyncio.gather(*task_list)
for result in result_list:
if isinstance(result, dict):
weapons_list.append(result)
weapons_list.extend(result for result in result_list if isinstance(result, dict))
task_list.clear()
if index % 10 == 0 and index != 0:
Log.info(f"现在已经获取到 {index} 把武器信息")
result_list = await asyncio.gather(*task_list)
for result in result_list:
if isinstance(result, dict):
weapons_list.append(result)
weapons_list.extend(result for result in result_list if isinstance(result, dict))
Log.info("写入武器信息到Redis")
self._weapons_list = weapons_list
await self._del_one("weapon")
@ -59,16 +56,13 @@ class Wiki:
task_list.append(self.characters.get_characters(characters_url))
if index % 5 == 0:
result_list = await asyncio.gather(*task_list)
for result in result_list:
if isinstance(result, dict):
characters_list.append(result)
characters_list.extend(result for result in result_list if isinstance(result, dict))
task_list.clear()
if index % 10 == 0 and index != 0:
Log.info(f"现在已经获取到 {index} 个角色信息")
result_list = await asyncio.gather(*task_list)
for result in result_list:
if isinstance(result, dict):
characters_list.append(result)
characters_list.extend(result for result in result_list if isinstance(result, dict))
Log.info("写入角色信息到Redis")
self._characters_list = characters_list
await self._del_one("characters")
@ -106,10 +100,7 @@ class Wiki:
await self.init()
if len(self._weapons_list) == 0:
return {}
for weapon in self._weapons_list:
if weapon["name"] == name:
return weapon
return {}
return next((weapon for weapon in self._weapons_list if weapon["name"] == name), {})
async def get_weapons_name_list(self) -> list:
await self.init()