🐛 批量修复代码BUG

⚙️ 获取 Redis cookies 池函数从 `zrevrange` 替代为 `zrange`
🐛 修复 fakeredis 无效
📝优化文本描述
🎨 提高代码质量

Co-authored-by: 洛水居室 <luoshuijs@outlook.com>
This commit is contained in:
omg-xtao 2022-09-14 22:23:07 +08:00 committed by 洛水居室
parent 340741543a
commit 0c62cc8b27
No known key found for this signature in database
GPG Key ID: C9DE87DA724B88FC
5 changed files with 22 additions and 25 deletions

View File

@ -35,8 +35,8 @@ class RedisDB(Service):
await self.ping() await self.ping()
except (KeyboardInterrupt, SystemExit): except (KeyboardInterrupt, SystemExit):
pass pass
except BaseException as exc: except Exception as exc:
logger.warning("尝试连接 [red]Redis[/] 失败,使用 [red]fakeredis[/] 模拟", exc, extra={'markup': True}) logger.exception("尝试连接 [red]Redis[/] 失败,使用 [red]fakeredis[/] 模拟", exc_info=exc, extra={'markup': True})
self.client = fakeredis.aioredis.FakeRedis() self.client = fakeredis.aioredis.FakeRedis()
await self.ping() await self.ping()

View File

@ -18,9 +18,9 @@ class PublicCookiesCache:
def get_public_cookies_queue_name(self, region: RegionEnum): def get_public_cookies_queue_name(self, region: RegionEnum):
if region == RegionEnum.HYPERION: if region == RegionEnum.HYPERION:
return self.score_qname + ":yuanshen" return f"{self.score_qname}:yuanshen"
elif region == RegionEnum.HOYOLAB: elif region == RegionEnum.HOYOLAB:
return self.score_qname + ":genshin" return f"{self.score_qname}:genshin"
else: else:
raise RegionNotFoundError(region.name) raise RegionNotFoundError(region.name)
@ -47,11 +47,9 @@ class PublicCookiesCache:
if isinstance(uid, int): if isinstance(uid, int):
score_maps = {f"{uid}": 0} score_maps = {f"{uid}": 0}
elif isinstance(uid, list): elif isinstance(uid, list):
score_maps = {} score_maps = {f"{i}": 0 for i in uid}
for i in uid:
score_maps[f"{i}"] = 0
else: else:
raise TypeError(f"uid variable type error") raise TypeError("uid variable type error")
async with self.client.pipeline(transaction=True) as pipe: async with self.client.pipeline(transaction=True) as pipe:
# nx:只添加新元素。不要更新已经存在的元素 # nx:只添加新元素。不要更新已经存在的元素
await pipe.zadd(qname, score_maps, nx=True) await pipe.zadd(qname, score_maps, nx=True)
@ -65,16 +63,11 @@ class PublicCookiesCache:
:return: :return:
""" """
qname = self.get_public_cookies_queue_name(region) qname = self.get_public_cookies_queue_name(region)
scores = await self.client.zrevrange(qname, 0, self.end, withscores=True, score_cast_func=int) scores = await self.client.zrange(qname, 0, self.end, withscores=True, score_cast_func=int)
if len(scores) > 0: if len(scores) <= 0:
def take_score(elem): raise CookiesCachePoolExhausted
return elem[1]
scores.sort(key=take_score)
key = scores[0][0] key = scores[0][0]
score = scores[0][1] score = scores[0][1]
else:
raise CookiesCachePoolExhausted
async with self.client.pipeline(transaction=True) as pipe: async with self.client.pipeline(transaction=True) as pipe:
await pipe.zincrby(qname, 1, key) await pipe.zincrby(qname, 1, key)
await pipe.execute() await pipe.execute()
@ -95,7 +88,7 @@ class PublicCookiesCache:
return await pipe.execute() return await pipe.execute()
async def incr_by_user_times(self, user_id: Union[List[int], int]): 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) times = await self.client.incrby(qname)
if times <= 1: if times <= 1:
await self.client.expire(qname, self.user_times_ttl) await self.client.expire(qname, self.user_times_ttl)

View File

@ -50,7 +50,7 @@ class SetUserUid(Plugin.Conversation, BasePlugin.Conversation):
cookies_command_data = AddUserCommandData() cookies_command_data = AddUserCommandData()
context.chat_data["add_uid_command_data"] = cookies_command_data context.chat_data["add_uid_command_data"] = cookies_command_data
text = f'你好 {user.mention_markdown_v2()} ' \ text = f'你好 {user.mention_markdown_v2()} ' \
f'{escape_markdown("请输入通行证UIDBOT将会通过通行证UID查找游戏UID。请选择要绑定的服务器或回复退出取消操作")}' f'{escape_markdown("请输入通行证UID非游戏UIDBOT将会通过通行证UID查找游戏UID。请选择要绑定的服务器或回复退出取消操作")}'
reply_keyboard = [['米游社', 'HoYoLab'], ["退出"]] reply_keyboard = [['米游社', 'HoYoLab'], ["退出"]]
await message.reply_markdown_v2(text, reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)) await message.reply_markdown_v2(text, reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True))
return CHECK_SERVER return CHECK_SERVER
@ -83,9 +83,9 @@ class SetUserUid(Plugin.Conversation, BasePlugin.Conversation):
except CookiesNotFoundError: except CookiesNotFoundError:
pass pass
else: else:
await message.reply_text("你已经绑定Cookie,无法继续下一步") await message.reply_text("你已经通过 Cookie 绑定了账号,无法继续下一步")
return ConversationHandler.END return ConversationHandler.END
await message.reply_text("请输入你的通行证UID", reply_markup=ReplyKeyboardRemove()) await message.reply_text("请输入你的通行证UID非游戏UID", reply_markup=ReplyKeyboardRemove())
return CHECK_UID return CHECK_UID
@conversation.state(state=CHECK_UID) @conversation.state(state=CHECK_UID)
@ -102,7 +102,7 @@ class SetUserUid(Plugin.Conversation, BasePlugin.Conversation):
try: try:
hoyolab_uid = int(message.text) hoyolab_uid = int(message.text)
except ValueError: except ValueError:
await message.reply_text("Cookies格式有误,请检查", reply_markup=ReplyKeyboardRemove()) await message.reply_text("UID 格式有误,请检查", reply_markup=ReplyKeyboardRemove())
return ConversationHandler.END return ConversationHandler.END
try: try:
cookies = await self.public_cookies_service.get_cookies(user.id, region) cookies = await self.public_cookies_service.get_cookies(user.id, region)

View File

@ -61,8 +61,11 @@ class ErrorHandler(Plugin):
if 'make sure that only one bot instance is running' in tb_string: if 'make sure that only one bot instance is running' in tb_string:
logger.error("其他机器人在运行,请停止!") logger.error("其他机器人在运行,请停止!")
return 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"), 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: except (BadRequest, Forbidden) as exc:
logger.error("发送日记失败") logger.error("发送日记失败")
logger.exception(exc) logger.exception(exc)

View File

@ -1,5 +1,6 @@
import logging import logging
import aiofiles
import pytest import pytest
import pytest_asyncio import pytest_asyncio
from flaky import flaky from flaky import flaky
@ -35,8 +36,8 @@ class TestArtifactOcrRate:
@staticmethod @staticmethod
@flaky(3, 1) @flaky(3, 1)
async def test_ocr_artifact(artifact_rate): async def test_ocr_artifact(artifact_rate):
with open("tests/data/test_artifact.jpg", "rb") as f: async with aiofiles.open("tests/data/test_artifact.jpg", mode="rb") as f:
photo = f.read() photo = await f.read()
data = await artifact_rate.get_artifact_attr(photo) data = await artifact_rate.get_artifact_attr(photo)
LOGGER.info(data.text) LOGGER.info(data.text)
assert data.status_code == 200 assert data.status_code == 200