From 15bc2b2724a98da57672ef74771c5696c160428e Mon Sep 17 00:00:00 2001 From: xtaodada Date: Fri, 4 Nov 2022 17:56:37 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A5=20Delete=20Artifact=20Rate?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/apihelper/artifact.py | 104 ---------------------- plugins/genshin/artifact_rate.py | 147 ------------------------------- tests/test_artifact.py | 48 ---------- 3 files changed, 299 deletions(-) delete mode 100644 modules/apihelper/artifact.py delete mode 100644 plugins/genshin/artifact_rate.py delete mode 100644 tests/test_artifact.py diff --git a/modules/apihelper/artifact.py b/modules/apihelper/artifact.py deleted file mode 100644 index 66564392..00000000 --- a/modules/apihelper/artifact.py +++ /dev/null @@ -1,104 +0,0 @@ -from base64 import b64encode -from random import choice - -import httpx - - -def get_format_sub_item(artifact_attr: dict): - return "".join(f'{i["name"]:\u3000<6} | {i["value"]}\n' for i in artifact_attr["sub_item"]) - - -def get_comment(get_rate_num): - data = { - "1": [ - "破玩意谁能用啊,谁都用不了吧", - "喂了吧,这东西做狗粮还能有点用", - "抽卡有保底,圣遗物没有下限", - "未来可期呢(笑)", - "你出门一定很安全", - "你是不是得罪米哈游了?", - "……宁就是班尼特本特?", - "丢人!你给我退出提瓦特(", - "不能说很糟糕,只能说特别不好", - ], - "2": [ - "淡如清泉镇的圣水,莫得提升", - "你怎么不强化啊?", - "嗯嗯嗯好好好可以可以可以挺好挺好(敷衍)", - "这就是日常,下一个", - "洗洗还能吃(bushi)", - "下次一定行……?", - "派蒙平静地点了个赞", - "不知道该说什么,就当留个纪念吧", - ], - "3": ["不能说有质变,只能说有提升", "过渡用的话没啥问题,大概", "再努努力吧", "嗯,差不多能用", "这很合理", "达成成就“合格圣遗物”", "嗯,及格了,过渡用挺好的", "中规中矩,有待提升"], - "4": [ - "以普遍理性而论,很好", - "算是个很不戳的圣遗物了!", - "很好,很有精神!", - "再努努力,超越一下自己", - "感觉可以戴着它大杀四方了", - "这就是大佬背包里的平均水平吧", - "先锁上呗,这波不亏", - "达成成就“高分圣遗物”", - "这波对输出有很大提升啊(认真)", - "我也想拥有这种分数的圣遗物(切实)", - ], - "5": [ - "多吃点好的,出门注意安全", - "晒吧,欧不可耻,只是可恨", - "没啥好说的,让我自闭一会", - "达成成就“高分圣遗物”", - "怕不是以后开宝箱只能开出卷心菜", - "吃了吗?没吃的话,吃我一拳", - "我觉得这个游戏有问题", - "这合理吗", - "这东西没啥用,给我吧(柠檬)", - "??? ????", - ], - } - try: - data_ = int(float(get_rate_num)) - except ValueError: - data_ = 0 - if data_ == 100: - return choice(data["5"]) - return choice(data[str(data_ // 20 + 1)]) - - -class ArtifactOcrRate: - OCR_URL = "https://api.genshin.pub/api/v1/app/ocr" - RATE_URL = "https://api.genshin.pub/api/v1/relic/rate" - HEADERS = { - "authority": "api.genshin.pub", - "accept": "application/json, text/plain, */*", - "accept-language": "zh-CN,zh;q=0.9,zh-Hans;q=0.8,und;q=0.7,en;q=0.6,zh-Hant;q=0.5,ja;q=0.4", - "content-type": "application/json;charset=UTF-8", - "dnt": "1", - "origin": "https://genshin.pub", - "referer": "https://genshin.pub/", - "sec-ch-ua": '"Chromium";v="104", " Not A;Brand";v="99"', - "sec-ch-ua-mobile": "?0", - "sec-ch-ua-platform": '"Windows"', - "sec-fetch-dest": "empty", - "sec-fetch-mode": "cors", - "sec-fetch-site": "same-site", - "sec-gpc": "1", - "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) " - "Chrome/104.0.5112.115 Safari/537.36", - } - - def __init__(self): - self.client = httpx.AsyncClient(headers=self.HEADERS) - - async def close(self): - await self.client.aclose() - - async def get_artifact_attr(self, photo_byte): - b64_str = b64encode(photo_byte).decode() - req = await self.client.post(self.OCR_URL, json={"image": b64_str}, timeout=8) - return req - - async def rate_artifact(self, artifact_attr: dict): - req = await self.client.post(self.RATE_URL, json=artifact_attr, timeout=8) - return req diff --git a/plugins/genshin/artifact_rate.py b/plugins/genshin/artifact_rate.py deleted file mode 100644 index b596a276..00000000 --- a/plugins/genshin/artifact_rate.py +++ /dev/null @@ -1,147 +0,0 @@ -from typing import Optional, Tuple - -from telegram import File, InlineKeyboardButton, InlineKeyboardMarkup, Update -from telegram.constants import ChatAction, ParseMode -from telegram.ext import CallbackContext, ConversationHandler, filters -from telegram.helpers import escape_markdown - -from core.baseplugin import BasePlugin -from core.plugin import Plugin, conversation, handler -from modules.apihelper.artifact import ArtifactOcrRate, get_comment, get_format_sub_item -from utils.decorators.error import error_callable -from utils.decorators.restricts import restricts -from utils.log import logger - -COMMAND_RESULT = 1 - - -class ArtifactRate(Plugin.Conversation, BasePlugin.Conversation): - """圣遗物评分""" - - STAR_KEYBOARD = [ - [InlineKeyboardButton(f"{i}", callback_data=f"artifact_ocr_rate_data|star|{i}") for i in range(1, 6)] - ] - - LEVEL_KEYBOARD = [ - [ - InlineKeyboardButton(f"{i * 5 + j}", callback_data=f"artifact_ocr_rate_data|level|{i * 5 + j}") - for j in range(1, 6) - ] - for i in range(0, 4) - ] - - def __init__(self): - self.artifact_rate = ArtifactOcrRate() - - async def get_rate(self, artifact_attr: dict) -> str: - rate_result_req = await self.artifact_rate.rate_artifact(artifact_attr) - if rate_result_req.status_code != 200: - if rate_result_req.status_code == 400: - artifact_attr = rate_result_req.json() - return artifact_attr.get("message", "API请求错误") - return "API请求错误,请稍后再试" - rate_result = rate_result_req.json() - 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"`--------------------`\n" - f"{escape_markdown(get_comment(rate_result['total_percent']), version=2)}\n" - "_评分、识图均来自 genshin\\.pub_" - ) - - @conversation.entry_point - @handler.command(command="artifact_rate", filters=filters.ChatType.PRIVATE, block=True) - @handler.message(filters=filters.Regex(r"^圣遗物评分(.*)"), block=True) - @handler.message(filters=filters.CaptionRegex(r"^圣遗物评分(.*)"), block=True) - @error_callable - @restricts(return_data=ConversationHandler.END) - async def command_start(self, update: Update, context: CallbackContext) -> int: - message = update.effective_message - user = update.effective_user - logger.info(f"用户 {user.full_name}[{user.id}] 圣遗物评分命令请求") - context.user_data["artifact_attr"] = None - photo_file: Optional[File] = None - if message is None: - return ConversationHandler.END - message_data = message if message.reply_to_message is None else message.reply_to_message - - if message_data.photo is not None and len(message_data.photo) >= 1: - photo_file = await message_data.photo[-1].get_file() # 草 居然第一张是预览图我人都麻了 - elif message_data.document is not None: - document = message_data.document - if "image" not in document.mime_type: - await message.reply_text("错误的图片类型") - return ConversationHandler.END - if document.file_size >= 5242880: - await message.reply_text("图片太大啦") - return ConversationHandler.END - photo_file = await document.get_file() - if photo_file is None: - await message.reply_text("图呢?") - return ConversationHandler.END - 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: - if artifact_attr_req.status_code == 400: - artifact_attr = artifact_attr_req.json() - await message.reply_text(artifact_attr.get("message", "API请求错误,请稍后再试")) - return ConversationHandler.END - await message.reply_text("API请求错误,请稍后再试") - return ConversationHandler.END - artifact_attr = artifact_attr_req.json() - context.user_data["artifact_attr"] = artifact_attr - if artifact_attr.get("star") is None: - await message.reply_text("无法识别圣遗物星级,请选择圣遗物星级", reply_markup=InlineKeyboardMarkup(self.STAR_KEYBOARD)) - return COMMAND_RESULT - if artifact_attr.get("level") is None: - await message.reply_text("无法识别圣遗物等级,请选择圣遗物等级", reply_markup=InlineKeyboardMarkup(self.LEVEL_KEYBOARD)) - return COMMAND_RESULT - reply_message = await message.reply_text("识图成功!\n" "正在评分中...") - rate_text = await self.get_rate(artifact_attr) - await reply_message.edit_text(rate_text, parse_mode=ParseMode.MARKDOWN_V2) - return ConversationHandler.END - - @conversation.state(state=COMMAND_RESULT) - @handler.callback_query() - @error_callable - async def command_result(self, update: Update, context: CallbackContext) -> int: - query = update.callback_query - artifact_attr = context.user_data.get("artifact_attr") - await query.answer() - if artifact_attr is None: - await query.edit_message_text("数据错误,请重新发送图片") - return ConversationHandler.END - - def get_callback_data(callback_query_data: str) -> Tuple[str, int]: - _data = callback_query_data.split("|") - _key_name = _data[1] - try: - _value = int(_data[2]) - except ValueError: - _value = -1 - return _key_name, _value - - await query.message.reply_chat_action(ChatAction.TYPING) - key_name, value = get_callback_data(query.data) - if key_name == "level": - artifact_attr["level"] = value - elif key_name == "star": - artifact_attr["star"] = value - else: - await query.edit_message_text("数据错误,请重新发送图片") - return ConversationHandler.END - if artifact_attr.get("level") is None: - await query.edit_message_text("无法识别圣遗物等级,请选择圣遗物等级", reply_markup=InlineKeyboardMarkup(self.LEVEL_KEYBOARD)) - return COMMAND_RESULT - if artifact_attr.get("star") is None: - await query.edit_message_text("无法识别圣遗物星级,请选择圣遗物星级", reply_markup=InlineKeyboardMarkup(self.STAR_KEYBOARD)) - return COMMAND_RESULT - await query.edit_message_text("正在评分中...") - rate_text = await self.get_rate(artifact_attr) - await query.edit_message_text(rate_text, parse_mode=ParseMode.MARKDOWN_V2) - return ConversationHandler.END diff --git a/tests/test_artifact.py b/tests/test_artifact.py deleted file mode 100644 index f60adbe9..00000000 --- a/tests/test_artifact.py +++ /dev/null @@ -1,48 +0,0 @@ -import logging - -import aiofiles -import pytest -import pytest_asyncio -from flaky import flaky - -from modules.apihelper.artifact import ArtifactOcrRate - -LOGGER = logging.getLogger(__name__) - - -@pytest_asyncio.fixture -async def artifact_rate(): - _artifact_rate = ArtifactOcrRate() - yield _artifact_rate - await _artifact_rate.close() - - -# noinspection PyShadowingNames -@pytest.mark.asyncio -class TestArtifactOcrRate: - @staticmethod - @flaky(3, 1) - async def test_rate_artifact(artifact_rate): - artifact_attr = { - "name": "翠绿的猎人之冠", - "pos": "理之冠", - "star": 5, - "level": 20, - "main_item": {"type": "cr", "name": "暴击率", "value": "31.1%"}, - "sub_item": [ - {"type": "hp", "name": "生命值", "value": "9.3%"}, - {"type": "df", "name": "防御力", "value": "46"}, - {"type": "atk", "name": "攻击力", "value": "49"}, - {"type": "cd", "name": "暴击伤害", "value": "10.9%"}, - ], - } - assert await artifact_rate.rate_artifact(artifact_attr) - - @staticmethod - @flaky(3, 1) - async def test_ocr_artifact(artifact_rate): - async with aiofiles.open("tests/data/test_artifact.jpg", mode="rb") as f: - photo = await f.read() - data = await artifact_rate.get_artifact_attr(photo) - LOGGER.info(data.text) - assert data.status_code == 200