Skip to content

Commit

Permalink
Update maimai apidata
Browse files Browse the repository at this point in the history
  • Loading branch information
DoroWolf committed Jul 24, 2024
1 parent 7520aa0 commit 9e4ac94
Show file tree
Hide file tree
Showing 7 changed files with 54 additions and 61 deletions.
4 changes: 3 additions & 1 deletion modules/maimai/chunithm.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,10 +142,12 @@ async def _(msg: Bot.MessageSession, username: str = None):
if not username:
await msg.finish(msg.locale.t("chunithm.message.user_unbound", prefix=msg.prefixes[0]))
payload = {'username': username}
use_cache = True
else:
payload = {'username': username}
use_cache = False

img = await generate_best30_text(msg, payload)
img = await generate_best30_text(msg, payload, use_cache)
await msg.finish([BImage(img)])


Expand Down
5 changes: 1 addition & 4 deletions modules/maimai/libraries/chunithm_apidata.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ async def get_record(msg: Bot.MessageSession, payload: dict, use_cache: bool = T
with open(cache_path, 'w') as f:
json.dump(data, f)
return data
except ValueError as e:
except Exception as e:
if str(e).startswith('400'):
if "qq" in payload:
await msg.finish(msg.locale.t("maimai.message.user_unbound.qq"))
Expand All @@ -53,9 +53,6 @@ async def get_record(msg: Bot.MessageSession, payload: dict, use_cache: bool = T
await msg.finish(msg.locale.t("maimai.message.forbidden"))
else:
Logger.error(traceback.format_exc())
raise e
except Exception as e:
Logger.error(traceback.format_exc())
if use_cache and os.path.exists(cache_path):
try:
with open(cache_path, 'r') as f:
Expand Down
6 changes: 3 additions & 3 deletions modules/maimai/libraries/chunithm_utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from datetime import datetime

from core.builtins import Plain
from core.builtins import Bot, Plain
from core.utils.image import msgchain2image
from .chunithm_apidata import get_record

Expand Down Expand Up @@ -51,8 +51,8 @@ def get_diff(diff):
return level


async def generate_best30_text(msg, payload):
data = await get_record(msg, payload)
async def generate_best30_text(msg: Bot.MessageSession, payload: dict, use_cache: bool = True):
data = await get_record(msg, payload, use_cache)
b30_records = data["records"]["b30"]
r10_records = data["records"]["r10"]

Expand Down
33 changes: 10 additions & 23 deletions modules/maimai/libraries/maimaidx_apidata.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,6 @@ async def search_by_alias(input_: str) -> list:
async def get_record(msg: Bot.MessageSession, payload: dict, use_cache: bool = True) -> Optional[str]:
cache_path = os.path.join(cache_dir, f"{msg.target.sender_id.replace('|', '_')}_maimaidx_record.json")
url = f"https://www.diving-fish.com/api/maimaidxprober/query/player"
if 'username' in payload:
use_cache = False
try:
data = await post_url(url,
data=json.dumps(payload),
Expand All @@ -152,7 +150,7 @@ async def get_record(msg: Bot.MessageSession, payload: dict, use_cache: bool = T
with open(cache_path, 'w') as f:
json.dump(data, f)
return data
except ValueError as e:
except Exception as e:
if str(e).startswith('400'):
if "qq" in payload:
await msg.finish(msg.locale.t("maimai.message.user_unbound.qq"))
Expand All @@ -163,8 +161,8 @@ async def get_record(msg: Bot.MessageSession, payload: dict, use_cache: bool = T
await msg.finish(msg.locale.t("maimai.message.forbidden.eula"))
else:
await msg.finish(msg.locale.t("maimai.message.forbidden"))
except Exception as e:
Logger.error(traceback.format_exc())
else:
Logger.error(traceback.format_exc())
if use_cache and os.path.exists(cache_path):
try:
with open(cache_path, 'r') as f:
Expand All @@ -182,8 +180,6 @@ async def get_song_record(msg: Bot.MessageSession, payload: dict, sid: Union[str
if DEVELOPER_TOKEN:
cache_path = os.path.join(cache_dir, f"{msg.target.sender_id.replace('|', '_')}_maimaidx_song_record.json")
url = f"https://www.diving-fish.com/api/maimaidxprober/dev/player/record"
if 'username' in payload:
use_cache = False
try:
if 'username' in payload:
await get_record(msg, payload, use_cache=False)
Expand All @@ -208,11 +204,11 @@ async def get_song_record(msg: Bot.MessageSession, payload: dict, sid: Union[str
with open(cache_path, 'w') as f:
json.dump(backup_data, f)
return data
except ValueError as e:
except Exception as e:
if str(e).startswith('400'):
raise ConfigValueError(msg.locale.t('error.config.invalid'))
except Exception as e:
Logger.error(traceback.format_exc())
else:
Logger.error(traceback.format_exc())
if use_cache and os.path.exists(cache_path):
try:
with open(cache_path, 'r') as f:
Expand All @@ -231,8 +227,6 @@ async def get_total_record(msg: Bot.MessageSession, payload: dict, utage: bool =
use_cache: bool = True) -> Optional[str]:
cache_path = os.path.join(cache_dir, f"{msg.target.sender_id.replace('|', '_')}_maimaidx_total_record.json")
url = f"https://www.diving-fish.com/api/maimaidxprober/query/plate"
if 'username' in payload:
use_cache = False
payload['version'] = versions
try:
data = await post_url(url,
Expand All @@ -246,7 +240,7 @@ async def get_total_record(msg: Bot.MessageSession, payload: dict, utage: bool =
if not utage:
data = {'verlist': [d for d in data['verlist'] if d.get('id', 0) < 100000]} # 过滤宴谱
return data
except ValueError as e:
except Exception as e:
if str(e).startswith('400'):
if "qq" in payload:
await msg.finish(msg.locale.t("maimai.message.user_unbound.qq"))
Expand All @@ -259,9 +253,6 @@ async def get_total_record(msg: Bot.MessageSession, payload: dict, utage: bool =
await msg.finish(msg.locale.t("maimai.message.forbidden"))
else:
Logger.error(traceback.format_exc())
raise e
except Exception as e:
Logger.error(traceback.format_exc())
if use_cache and os.path.exists(cache_path):
try:
with open(cache_path, 'r') as f:
Expand All @@ -277,10 +268,9 @@ async def get_total_record(msg: Bot.MessageSession, payload: dict, utage: bool =


async def get_plate(msg: Bot.MessageSession, payload: dict, version: str, use_cache: bool = True) -> Optional[str]:
cache_path = os.path.join(cache_dir, f"{msg.target.sender_id.replace('|', '_')}_maimaidx_{version}_plate.json")
version = '舞' if version == '覇' else version # “覇者”属于舞代
cache_path = os.path.join(cache_dir, f"{msg.target.sender_id.replace('|', '_')}_maimaidx_plate_{version}.json")
url = f"https://www.diving-fish.com/api/maimaidxprober/query/plate"
if 'username' in payload:
use_cache = False
try:
data = await post_url(url,
data=json.dumps(payload),
Expand All @@ -291,7 +281,7 @@ async def get_plate(msg: Bot.MessageSession, payload: dict, version: str, use_ca
with open(cache_path, 'w') as f:
json.dump(data, f)
return data
except ValueError as e:
except Exception as e:
if str(e).startswith('400'):
if "qq" in payload:
await msg.finish(msg.locale.t("maimai.message.user_unbound.qq"))
Expand All @@ -304,9 +294,6 @@ async def get_plate(msg: Bot.MessageSession, payload: dict, version: str, use_ca
await msg.finish(msg.locale.t("maimai.message.forbidden"))
else:
Logger.error(traceback.format_exc())
raise e
except Exception as e:
Logger.error(traceback.format_exc())
if use_cache and os.path.exists(cache_path):
try:
with open(cache_path, 'r') as f:
Expand Down
5 changes: 3 additions & 2 deletions modules/maimai/libraries/maimaidx_best50.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import ujson as json
from PIL import Image, ImageDraw, ImageFont, ImageFilter

from core.builtins import Bot
from .maimaidx_music import get_cover_len5_id, TotalList
from .maimaidx_apidata import get_record
from .maimaidx_utils import compute_rating, calc_dxstar
Expand Down Expand Up @@ -291,8 +292,8 @@ def getDir(self):
return self.img


async def generate(msg, payload) -> Tuple[Optional[Image.Image], bool]:
resp = await get_record(msg, payload)
async def generate(msg: Bot.MessageSession, payload: dict, use_cache: bool = True) -> Tuple[Optional[Image.Image], bool]:
resp = await get_record(msg, payload, use_cache)
sd_best = BestList(35)
dx_best = BestList(15)
dx: List[Dict] = resp["charts"]["dx"]
Expand Down
32 changes: 14 additions & 18 deletions modules/maimai/libraries/maimaidx_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,14 +301,14 @@ async def generate_best50_text(msg: Bot.MessageSession, payload: dict) -> Messag
await msg.finish(msg.locale.t("error.config.webrender.invalid"))


async def get_rank(msg: Bot.MessageSession, payload: dict):
async def get_rank(msg: Bot.MessageSession, payload: dict, use_cache: bool = True):
time = msg.ts2strftime(datetime.now().timestamp(), timezone=False)

url = f"https://www.diving-fish.com/api/maimaidxprober/rating_ranking"
rank_data = await get_url(url, 200, fmt='json')
rank_data = sorted(rank_data, key=lambda x: x['ra'], reverse=True) # 根据rating排名并倒序

player_data = await get_record(msg, payload)
player_data = await get_record(msg, payload, use_cache)
username = player_data['username']

rating = 0
Expand Down Expand Up @@ -350,18 +350,15 @@ async def get_rank(msg: Bot.MessageSession, payload: dict):
surpassing_rate="{:.2f}".format(surpassing_rate)))


async def get_player_score(msg: Bot.MessageSession, payload: dict, input_id: str) -> str:
async def get_player_score(msg: Bot.MessageSession, payload: dict, input_id: str, use_cache: bool = True) -> str:
if int(input_id) >= 100000:
await msg.finish(msg.locale.t("maimai.message.info.utage"))

music = (await total_list.get()).by_id(input_id)
level_scores = {level: [] for level in range(len(music['level']))} # 获取歌曲难度列表

try:
if 'username' in payload:
res = await get_song_record(msg, payload, use_cache=False)
else:
res = await get_song_record(msg, payload)
res = await get_song_record(msg, payload, input_id, use_cache)
for sid, records in res.items():
if str(sid) == input_id:
for entry in records:
Expand All @@ -381,10 +378,7 @@ async def get_player_score(msg: Bot.MessageSession, payload: dict, input_id: str
(diffs[level_index], achievements, score_rank, combo_rank, sync_rank, dxscore, dxscore_max)
)
except Exception:
if 'username' in payload:
res = await get_total_record(msg, payload, use_cache=False)
else:
res = await get_total_record(msg, payload)
res = await get_total_record(msg, payload, True, use_cache)
records = res["verlist"]

for entry in records:
Expand Down Expand Up @@ -422,11 +416,12 @@ async def get_player_score(msg: Bot.MessageSession, payload: dict, input_id: str
return '\n'.join(output_lines)


async def get_level_process(msg: Bot.MessageSession, payload: dict, level: str, goal: str) -> tuple[str, bool]:
async def get_level_process(msg: Bot.MessageSession, payload: dict, level: str, goal: str,
use_cache: bool = True) -> tuple[str, bool]:
song_played = []
song_remain = []

res = await get_total_record(msg, payload)
res = await get_total_record(msg, payload, use_cache=use_cache)
verlist = res["verlist"]

goal = goal.upper() # 输入强制转换为大写以适配字典
Expand Down Expand Up @@ -495,11 +490,12 @@ async def get_level_process(msg: Bot.MessageSession, payload: dict, level: str,
return output, get_img


async def get_score_list(msg: Bot.MessageSession, payload: dict, level: str, page: int) -> tuple[str, bool]:
res = await get_total_record(msg, payload)
async def get_score_list(msg: Bot.MessageSession, payload: dict, level: str, page: int,
use_cache: bool = True) -> tuple[str, bool]:
res = await get_total_record(msg, payload, use_cache=use_cache)
records = res["verlist"]

player_data = await get_record(msg, payload)
player_data = await get_record(msg, payload, use_cache)
song_list = []
for song in records:
if song['level'] == level:
Expand Down Expand Up @@ -533,7 +529,7 @@ async def get_score_list(msg: Bot.MessageSession, payload: dict, level: str, pag
return res, get_img


async def get_plate_process(msg: Bot.MessageSession, payload: dict, plate: str) -> tuple[str, bool]:
async def get_plate_process(msg: Bot.MessageSession, payload: dict, plate: str, use_cache: bool = True) -> tuple[str, bool]:
song_played = []
song_remain_basic = []
song_remain_advanced = []
Expand Down Expand Up @@ -564,7 +560,7 @@ async def get_plate_process(msg: Bot.MessageSession, payload: dict, plate: str)
else:
await msg.finish(msg.locale.t('maimai.message.plate.plate_not_found'))

res = await get_plate(msg, payload, version)
res = await get_plate(msg, payload, version, use_cache)
verlist = res["verlist"]

if goal in ['將', '者']:
Expand Down
30 changes: 20 additions & 10 deletions modules/maimai/maimai.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,13 +225,13 @@ async def _(msg: Bot.MessageSession, username: str = None):
if not username:
await msg.finish(msg.locale.t("maimai.message.user_unbound", prefix=msg.prefixes[0]))
payload = {'username': username, 'b50': True}
use_cache = True
else:
payload = {'username': username, 'b50': True}
try:
img = await generate(msg, payload)
await msg.finish([BImage(img)])
except BaseException:
Logger.error(traceback.format_exc())
use_cache = False

img = await generate(msg, payload, use_cache)
await msg.finish([BImage(img)])


@mai.command('id <id> [-c] {{maimai.help.id}}')
Expand Down Expand Up @@ -395,10 +395,12 @@ async def query_song_info(msg, query, username):
if not username:
await msg.finish(msg.locale.t("maimai.message.user_unbound", prefix=msg.prefixes[0]))
payload = {'username': username}
use_cache = True
else:
payload = {'username': username}
use_cache = False

output = await get_player_score(msg, payload, sid)
output = await get_player_score(msg, payload, sid, use_cache)
await msg.finish(await get_info(music, Plain(output)))


Expand All @@ -416,13 +418,15 @@ async def query_plate(msg, plate, username):
if not username:
await msg.finish(msg.locale.t("maimai.message.user_unbound", prefix=msg.prefixes[0]))
payload = {'username': username}
use_cache = True
else:
payload = {'username': username}
use_cache = False

if plate in ['真将', '真將'] or (plate[1] == '者' and plate[0] != '霸'):
await msg.finish(msg.locale.t('maimai.message.plate.plate_not_found'))

output, get_img = await get_plate_process(msg, payload, plate)
output, get_img = await get_plate_process(msg, payload, plate, use_cache)

if get_img:
img = await msgchain2image([Plain(output)], msg)
Expand Down Expand Up @@ -453,15 +457,17 @@ async def query_process(msg, level, goal, username):
if not username:
await msg.finish(msg.locale.t("maimai.message.user_unbound", prefix=msg.prefixes[0]))
payload = {'username': username}
use_cache = True
else:
payload = {'username': username}
use_cache = False

if level not in level_list:
await msg.finish(msg.locale.t("maimai.message.level_invalid"))
if goal.upper() not in goal_list:
await msg.finish(msg.locale.t("maimai.message.goal_invalid"))

output, get_img = await get_level_process(msg, payload, level, goal)
output, get_img = await get_level_process(msg, payload, level, goal, use_cache)

if get_img:
img = await msgchain2image([Plain(output)])
Expand All @@ -483,10 +489,12 @@ async def _(msg: Bot.MessageSession, username: str = None):
if not username:
await msg.finish(msg.locale.t("maimai.message.user_unbound", prefix=msg.prefixes[0]))
payload = {'username': username}
use_cache = True
else:
payload = {'username': username}
use_cache = False

await get_rank(msg, payload)
await get_rank(msg, payload, use_cache)


@mai.command('scorelist <level> [-p <page>] [-u <username>] {{maimai.help.scorelist}}',
Expand All @@ -505,10 +513,12 @@ async def _(msg: Bot.MessageSession, level: str):
if not username:
await msg.finish(msg.locale.t("maimai.message.user_unbound", prefix=msg.prefixes[0]))
payload = {'username': username}
use_cache = True
else:
payload = {'username': username}
use_cache = False

output, get_img = await get_score_list(msg, payload, level, page)
output, get_img = await get_score_list(msg, payload, level, page, use_cache)

if get_img:
img = await msgchain2image([Plain(output)])
Expand Down

0 comments on commit 9e4ac94

Please sign in to comment.