Skip to content

Commit

Permalink
🚀0.4.3
Browse files Browse the repository at this point in the history
  • Loading branch information
Agnes4m committed Aug 31, 2024
1 parent ba921a7 commit b21f1ee
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 59 deletions.
2 changes: 1 addition & 1 deletion nonebot_plugin_bilifan/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@


driver = get_driver()
__version__ = "0.4.1"
__version__ = "0.4.3"
__plugin_meta__ = PluginMetadata(
name="bilifan",
description="b站粉丝牌~",
Expand Down
39 changes: 20 additions & 19 deletions nonebot_plugin_bilifan/src/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def sign(data: Union[str, dict]) -> str:

class SingableDict(dict):
@property
def sorted(self): # noqa: A003
def sorted(self):
"""returns a alphabetically sorted version of `self`"""
return dict(sorted(self.items()))

Expand All @@ -52,25 +52,27 @@ def decorate(func):
async def wrapper(*args, **kwargs):
count = 0
func.isRetryable = False
log = logger.bind(user=f"{args[0].u.name}")
while True:
try:
result = await func(*args, **kwargs)
except Exception as E:
except Exception as e:
count += 1
if type(E) == BiliApiError: # noqa: E721
if E.code == 1011040:
raise E # noqa: TRY201
if E.code == 10030:
if isinstance(e, BiliApiError):
if e.code == 1011040:
raise e
elif e.code == 10030:
await asyncio.sleep(10)
elif E.code == -504:
elif e.code == -504:
pass
else:
raise E # noqa: TRY201
raise e
if count > tries:
logger.error(f"API {urlparse(args[1]).path} 调用出现异常: {E!s}")
raise E # noqa: TRY201
# log.error(f"API {urlparse(args[1]).path} 调用出现异常: {str(E)},重试中,第{count}次重试")
await asyncio.sleep(interval)
log.error(f"API {urlparse(args[1]).path} 调用出现异常: {str(e)}")
raise e
else:
# log.error(f"API {urlparse(args[1]).path} 调用出现异常: {str(e)},重试中,第{count}次重试")
await asyncio.sleep(interval)
func.isRetryable = True
else:
if func.isRetryable:
Expand Down Expand Up @@ -109,7 +111,7 @@ def __str__(self):


class BiliApi:
headers = { # noqa: RUF012
headers = {
"User-Agent": "Mozilla/5.0 BiliDroid/6.73.1 ([email protected]) os/android model/Mi 10 Pro mobi_app/android build/6731100 channel/xiaomi innerVer/6731110 osVer/12 network/2",
}
from .user import BiliUser
Expand All @@ -120,7 +122,7 @@ def __init__(self, u: BiliUser, s: ClientSession):

def __check_response(self, resp: dict) -> dict:
if resp["code"] != 0 or ("mode_info" in resp["data"] and resp["message"] != ""):
raise BiliApiError(resp["code"], resp["message"])
logger.warning(BiliApiError(resp["code"], resp["message"]))
return resp["data"]

@retry()
Expand Down Expand Up @@ -156,7 +158,8 @@ async def getFansMedalandRoomID(self) -> dict: # type: ignore
if first_flag and data["special_list"]:
for item in data["special_list"]:
# 强制把正在佩戴的牌子加入任务列表
item["medal"]["today_feed"] = 0
# 8月15日删除
# item["medal"]["today_feed"] = 0
yield item # type: ignore
self.u.wearedMedal = data["special_list"][0] # type: ignore
first_flag = False
Expand Down Expand Up @@ -484,12 +487,10 @@ async def wearMedal(self, medal_id: int):
self.headers.update(
{
"Content-Type": "application/x-www-form-urlencoded",
},
}
)
return await self.__post(
url,
data=SingableDict(data).signed,
headers=self.headers,
url, data=SingableDict(data).signed, headers=self.headers
)

async def getGroups(self):
Expand Down
51 changes: 13 additions & 38 deletions nonebot_plugin_bilifan/src/user.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import asyncio
import uuid
import random
from datetime import datetime, timedelta

from aiohttp import ClientSession, ClientTimeout
Expand Down Expand Up @@ -326,48 +325,24 @@ async def watchinglive(self):
log.info("每日观看直播任务关闭")
return
HEART_MAX = self.config["WATCHINGLIVE"]
if self.config["WHACHASYNER"]:
log.info(f"每日{HEART_MAX}分钟任务开始")
heartNum = 0
while True:
log.info(f"每日{HEART_MAX}分钟任务开始")
n = 0
for medal in self.medalsNeedDo:
n += 1
for heartNum in range(1, HEART_MAX + 1):
tasks = []
for medal in self.medalsNeedDo:
tasks.append(
self.api.heartbeat(
medal["room_info"]["room_id"], medal["medal"]["target_id"]
)
tasks.append(
self.api.heartbeat(
medal["room_info"]["room_id"], medal["medal"]["target_id"]
)
await asyncio.gather(*tasks)
heartNum += 1
)
await asyncio.gather(*tasks)
if heartNum % 5 == 0:
log.info(
f"{' '.join([medal['anchor_info']['nick_name'] for medal in self.medalsNeedDo[:5]])} 等共 {len(self.medalsNeedDo)} 个房间的第{heartNum}次心跳包已发送({heartNum}/{HEART_MAX})",
)
await asyncio.sleep(60)
if heartNum >= HEART_MAX:
break
log.success(f"每日{HEART_MAX}分钟任务完成")
else:
log.info(f"每日{HEART_MAX}分钟任务开始")
medalsNeedDoList = list(self.medalsNeedDo)
# 使用shuffle函数随机排序
random.shuffle(medalsNeedDoList)
n = 0
for medal in medalsNeedDoList:
n += 1
for heartNum in range(1, HEART_MAX + 1):
tasks = []
tasks.append(
self.api.heartbeat(
medal["room_info"]["room_id"], medal["medal"]["target_id"]
)
f"{medal['anchor_info']['nick_name']}{heartNum}次心跳包已发送({n}/{len(self.medalsNeedDo)})",
)
await asyncio.gather(*tasks)
if heartNum % 5 == 0:
log.info(
f"{medal['anchor_info']['nick_name']}{heartNum}次心跳包已发送({n}/{len(self.medalsNeedDo)})"
)
await asyncio.sleep(60)
log.success(f"每日{HEART_MAX}分钟任务完成")
log.info("SUCCESS", f"每日{HEART_MAX}分钟任务完成")

async def signInGroups(self):
if not self.config["SIGNINGROUP"]:
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "nonebot_plugin_bilifan"
version = "0.4.2"
version = "0.4.3"
description = "刷站粉丝牌子的机器人插件"
authors = ["Agnes_Digital <[email protected]>"]
license = "GPLv3"
Expand Down

0 comments on commit b21f1ee

Please sign in to comment.