From 0c62cc8b27989c443bec69c59536ea2f09c4df07 Mon Sep 17 00:00:00 2001 From: omg-xtao <100690902+omg-xtao@users.noreply.github.com> Date: Wed, 14 Sep 2022 22:23:07 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20=E6=89=B9=E9=87=8F=E4=BF=AE?= =?UTF-8?q?=E5=A4=8D=E4=BB=A3=E7=A0=81BUG?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ⚙️ 获取 Redis cookies 池函数从 `zrevrange` 替代为 `zrange` 🐛 修复 fakeredis 无效 📝优化文本描述 🎨 提高代码质量 Co-authored-by: 洛水居室 --- core/base/redisdb.py | 4 ++-- core/cookies/cache.py | 25 +++++++++---------------- plugins/genshin/uid.py | 8 ++++---- plugins/system/errorhandler.py | 5 ++++- tests/test_artifact.py | 5 +++-- 5 files changed, 22 insertions(+), 25 deletions(-) diff --git a/core/base/redisdb.py b/core/base/redisdb.py index f79b55c..aa9f866 100644 --- a/core/base/redisdb.py +++ b/core/base/redisdb.py @@ -35,8 +35,8 @@ class RedisDB(Service): await self.ping() except (KeyboardInterrupt, SystemExit): pass - except BaseException as exc: - logger.warning("尝试连接 [red]Redis[/] 失败,使用 [red]fakeredis[/] 模拟", exc, extra={'markup': True}) + except Exception as exc: + logger.exception("尝试连接 [red]Redis[/] 失败,使用 [red]fakeredis[/] 模拟", exc_info=exc, extra={'markup': True}) self.client = fakeredis.aioredis.FakeRedis() await self.ping() diff --git a/core/cookies/cache.py b/core/cookies/cache.py index 3c65b09..7b36900 100644 --- a/core/cookies/cache.py +++ b/core/cookies/cache.py @@ -18,9 +18,9 @@ class PublicCookiesCache: def get_public_cookies_queue_name(self, region: RegionEnum): if region == RegionEnum.HYPERION: - return self.score_qname + ":yuanshen" + return f"{self.score_qname}:yuanshen" elif region == RegionEnum.HOYOLAB: - return self.score_qname + ":genshin" + return f"{self.score_qname}:genshin" else: raise RegionNotFoundError(region.name) @@ -47,11 +47,9 @@ class PublicCookiesCache: if isinstance(uid, int): score_maps = {f"{uid}": 0} elif isinstance(uid, list): - score_maps = {} - for i in uid: - score_maps[f"{i}"] = 0 + score_maps = {f"{i}": 0 for i in uid} else: - raise TypeError(f"uid variable type error") + raise TypeError("uid variable type error") async with self.client.pipeline(transaction=True) as pipe: # nx:只添加新元素。不要更新已经存在的元素 await pipe.zadd(qname, score_maps, nx=True) @@ -65,16 +63,11 @@ class PublicCookiesCache: :return: """ qname = self.get_public_cookies_queue_name(region) - scores = await self.client.zrevrange(qname, 0, self.end, withscores=True, score_cast_func=int) - if len(scores) > 0: - def take_score(elem): - return elem[1] - - scores.sort(key=take_score) - key = scores[0][0] - score = scores[0][1] - else: + scores = await self.client.zrange(qname, 0, self.end, withscores=True, score_cast_func=int) + if len(scores) <= 0: raise CookiesCachePoolExhausted + key = scores[0][0] + score = scores[0][1] async with self.client.pipeline(transaction=True) as pipe: await pipe.zincrby(qname, 1, key) await pipe.execute() @@ -95,7 +88,7 @@ class PublicCookiesCache: return await pipe.execute() async def incr_by_user_times(self, user_id: Union[List[int], int]): - qname = self.user_times_qname + f":{user_id}" + qname = f"{self.user_times_qname}:{user_id}" times = await self.client.incrby(qname) if times <= 1: await self.client.expire(qname, self.user_times_ttl) diff --git a/plugins/genshin/uid.py b/plugins/genshin/uid.py index 6200e15..673efb9 100644 --- a/plugins/genshin/uid.py +++ b/plugins/genshin/uid.py @@ -50,7 +50,7 @@ class SetUserUid(Plugin.Conversation, BasePlugin.Conversation): cookies_command_data = AddUserCommandData() context.chat_data["add_uid_command_data"] = cookies_command_data text = f'你好 {user.mention_markdown_v2()} ' \ - f'{escape_markdown("!请输入通行证UID,BOT将会通过通行证UID查找游戏UID。请选择要绑定的服务器!或回复退出取消操作")}' + f'{escape_markdown("!请输入通行证UID(非游戏UID),BOT将会通过通行证UID查找游戏UID。请选择要绑定的服务器!或回复退出取消操作")}' reply_keyboard = [['米游社', 'HoYoLab'], ["退出"]] await message.reply_markdown_v2(text, reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)) return CHECK_SERVER @@ -83,9 +83,9 @@ class SetUserUid(Plugin.Conversation, BasePlugin.Conversation): except CookiesNotFoundError: pass else: - await message.reply_text("你已经绑定Cookie,无法继续下一步") + await message.reply_text("你已经通过 Cookie 绑定了账号,无法继续下一步") return ConversationHandler.END - await message.reply_text("请输入你的通行证UID", reply_markup=ReplyKeyboardRemove()) + await message.reply_text("请输入你的通行证UID(非游戏UID)", reply_markup=ReplyKeyboardRemove()) return CHECK_UID @conversation.state(state=CHECK_UID) @@ -102,7 +102,7 @@ class SetUserUid(Plugin.Conversation, BasePlugin.Conversation): try: hoyolab_uid = int(message.text) except ValueError: - await message.reply_text("Cookies格式有误,请检查", reply_markup=ReplyKeyboardRemove()) + await message.reply_text("UID 格式有误,请检查", reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END try: cookies = await self.public_cookies_service.get_cookies(user.id, region) diff --git a/plugins/system/errorhandler.py b/plugins/system/errorhandler.py index 58ec834..3c143a3 100644 --- a/plugins/system/errorhandler.py +++ b/plugins/system/errorhandler.py @@ -61,8 +61,11 @@ class ErrorHandler(Plugin): if 'make sure that only one bot instance is running' in tb_string: logger.error("其他机器人在运行,请停止!") return + if 'Message is not modified' in tb_string: + logger.error("消息未修改") + return await context.bot.send_document(chat_id=notice_chat_id, document=open(log_file, "rb"), - caption="Error report.") + caption=f"Error: \"{context.error.__class__.__name__}\"") except (BadRequest, Forbidden) as exc: logger.error("发送日记失败") logger.exception(exc) diff --git a/tests/test_artifact.py b/tests/test_artifact.py index d98b25e..ff5c0cc 100644 --- a/tests/test_artifact.py +++ b/tests/test_artifact.py @@ -1,5 +1,6 @@ import logging +import aiofiles import pytest import pytest_asyncio from flaky import flaky @@ -35,8 +36,8 @@ class TestArtifactOcrRate: @staticmethod @flaky(3, 1) async def test_ocr_artifact(artifact_rate): - with open("tests/data/test_artifact.jpg", "rb") as f: - photo = f.read() + 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