Skip to content

Commit

Permalink
Merge pull request #34 from lenlino/dev
Browse files Browse the repository at this point in the history
enka.networkの対応
  • Loading branch information
lenlino authored Dec 23, 2023
2 parents a5233a3 + d58a142 commit 4986893
Show file tree
Hide file tree
Showing 8 changed files with 119 additions and 23 deletions.
29 changes: 17 additions & 12 deletions commands/CardCommand.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,15 +153,16 @@ async def uid_change_modal_callback(modal_interaction):
await interaction.response.send_modal(modal)

async def set_uid(changed_uid):
info = await get_json_from_url(f"https://api.mihomo.me/sr_info/{changed_uid}")
if "detail" not in info:
embed.description = f"{i18n.t('message.nickname', locale=lang)} {info['detailInfo']['nickname']}\nUID: {info['detailInfo']['uid']}"
nonlocal uid
nonlocal user_detail_dict
nonlocal json_parsed
user_detail_dict = info
uid = info['detailInfo']['uid']
json_parsed = await get_json_from_url(f"https://api.mihomo.me/sr_info_parsed/{uid}?lang={lang}")
nonlocal uid
nonlocal user_detail_dict
nonlocal json_parsed
json_parsed = await get_json_from_url(changed_uid, lang)

if "detail" not in json_parsed:
embed.description = f"{i18n.t('message.nickname', locale=lang)} {json_parsed['player']['nickname']}\nUID: {json_parsed['player']['uid']}"

user_detail_dict = json_parsed
uid = json_parsed['player']['uid']
selecter.options = []
for index, i in enumerate(json_parsed["characters"]):
selecter.append_option(
Expand All @@ -171,10 +172,14 @@ async def set_uid(changed_uid):
embed.description += "\n" + i18n.t("message.error_no_chara_set", locale=lang)
else:
await ctx.edit(view=get_view())
elif info["detail"] == "Queue timeout":
embed.description = i18n.t("message.error_queue_timeout", locale=lang)
else:
elif json_parsed["detail"] == 400 or json_parsed["detail"] == 404:
embed.description = i18n.t("message.error_not_exist_uid", locale=lang)
elif json_parsed["detail"] == 429 or json_parsed["detail"] == 500 or json_parsed["detail"] == 503:
embed.description = i18n.t("message.error_general_error", locale=lang)
elif json_parsed["detail"] == 424:
embed.description = i18n.t("message.error_game_maintenance_error", locale=lang)
else:
embed.description = i18n.t("message.error_queue_timeout", locale=lang)

await ctx.edit(embed=embed)

Expand Down
2 changes: 1 addition & 1 deletion generate/templates/one.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
async def generate_panel(uid="805477392", chara_id=1, is_hideUID=False, calculating_standard="compatibility"):
font_color = "#f0eaca"
touka_color = "#191919"
json = await get_json_from_url(f"https://api.mihomo.me/sr_info_parsed/{uid}?lang=jp")
json = await get_json_from_url(uid, "jp")
helta_json = json["characters"][int(chara_id)]
img = Image.open(f"{get_file_path()}/assets/bkg.png").convert(
'RGBA')
Expand Down
2 changes: 1 addition & 1 deletion generate/templates/two.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ async def generate_panel(uid="805477392", chara_id=1, is_hideUID=False, calculat
lang="jp", is_hide_roll=False):
font_color = "#f0eaca"
touka_color = "#191919"
json = await get_json_from_url(f"https://api.mihomo.me/sr_info_parsed/{uid}?lang={lang}")
json = await get_json_from_url(uid, lang)
if lang == "jp" or lang == "cn" or lang == "cht":
light_cone_name_limit = 9
chara_name_limit = 5
Expand Down
96 changes: 89 additions & 7 deletions generate/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,12 @@

import aiohttp
from PIL import Image
from starrailres import Index
from starrailres.models.info import CharacterBasicInfo, LevelInfo, LightConeBasicInfo, SubAffixBasicInfo, RelicBasicInfo

conn = aiohttp.TCPConnector(limit_per_host=1)


async def get_image_from_url(url: str):
replaced_path = url.replace("https://raw.githubusercontent.com/Mar-7th/StarRailRes/master/", "")
if url.startswith("https://raw.githubusercontent.com/Mar-7th/StarRailRes/master/") and os.path.exists(
Expand All @@ -23,10 +26,92 @@ async def get_image_from_url(url: str):
return f"{os.path.dirname(os.path.abspath(__file__))}/{replaced_path}"


async def get_json_from_url(url: str):
async def get_json_from_url(uid: str, lang: str):
result_json = None
async with aiohttp.ClientSession(connector_owner=False, connector=conn) as session:
async with session.get(url) as response:
return await response.json()
async with session.get(f"https://api.mihomo.me/sr_info_parsed/{uid}?lang={lang}") as response:
if response.status == 200:
result_json = await response.json()
if "detail" in result_json or result_json is None:
filepath = pathlib.Path(f"{os.path.dirname(os.path.abspath(__file__))}/StarRailRes/index_min/{lang}")
index = Index(filepath)
async with aiohttp.ClientSession(connector_owner=False, connector=conn) as session:
async with session.get(f"https://enka.network/api/hsr/uid/{uid}") as response:
if response.status != 200:
result_json["detail"] = response.status
return
enka_result_json = await response.json()
detail_info_json = enka_result_json["detailInfo"]
record_info_json = detail_info_json["recordInfo"]
result_json = {
"player": {
"uid": enka_result_json["uid"],
"nickname": detail_info_json["nickname"],
"level": detail_info_json["level"],
"world_level": detail_info_json["worldLevel"],
"friend_count": detail_info_json["friendCount"],
"avatar": index.get_avatar_info(detail_info_json["headIcon"]),
"signature": detail_info_json.get("signature", ""),
"is_display": detail_info_json["isDisplayAvatar"],
"space_info": {
"memory_data": {
"level": record_info_json.get("scheduleMaxLevel", 0),
"chaos_id": 0,
"chaos_level": 0
},
"universe_level": record_info_json["maxRogueChallengeScore"],
"challenge_data": {
"maze_group_id": 0,
"maze_group_index": 0,
"pre_maze_group_index": record_info_json.get("scheduleMaxLevel", 0)
},
"pass_area_progress": record_info_json["maxRogueChallengeScore"],
"light_cone_count": record_info_json["equipmentCount"],
"avatar_count": record_info_json["avatarCount"],
"achievement_count": record_info_json["achievementCount"]
}
}
}
characters_list = []
for characters in detail_info_json["avatarDetailList"]:
skill_list = []
for skilltree in characters["skillTreeList"]:
skill_list.append(LevelInfo(id=str(skilltree["pointId"]), level=int(skilltree["level"])))

if "equipment" in characters:
equipment = characters["equipment"]
basic_light_cone = LightConeBasicInfo(id=str(equipment["tid"]), rank=int(equipment["rank"]),
level=int(equipment["level"]),
promotion=equipment["promotion"])
else:
basic_light_cone = None

basic_relics = []
for relic in characters["relicList"]:
subaffix_list = []
for subaffix in relic["subAffixList"]:
subaffix_list.append(SubAffixBasicInfo(id=str(subaffix["affixId"]), cnt=subaffix.get("cnt", 0),
step=subaffix.get("step", 0)))
basic_relics.append(RelicBasicInfo(
id=str(relic["tid"]),
level=relic["level"],
main_affix_id=str(relic["mainAffixId"]),
sub_affix_info=subaffix_list,
))
charabase_json = index.get_character_info(CharacterBasicInfo(
id=str(characters["avatarId"]),
rank=characters.get("rank", 0),
level=characters["level"],
promotion=characters["promotion"],
skill_tree_levels=skill_list,
light_cone=basic_light_cone,
relics=basic_relics,
))
if charabase_json:
from msgspec import to_builtins
characters_list.append(to_builtins(charabase_json))
result_json["characters"] = characters_list
return result_json


def get_json_from_json(json_list, key, value):
Expand Down Expand Up @@ -91,7 +176,6 @@ async def get_relic_score(chara_id, relic_json):

result_json["score"] = main_affix_score * 0.5 + sub_affix_score * 0.5
result_json["sub_formulas"] = sub_affix_formulas

# 合計
return result_json

Expand Down Expand Up @@ -185,7 +269,7 @@ def get_score_rank(chara_id, uid, score):
df = pd.read_json(json_path, orient='columns')
else:
df = pd.DataFrame({"score": {}, "rank": {}})
uid = str(uid)+'u'
uid = str(uid) + 'u'
before_score = df["score"].get(uid, 0)
df.loc[uid] = [score, 0]
df['rank'] = df['score'].rank(ascending=False, method='min')
Expand All @@ -204,5 +288,3 @@ def get_score_rank(chara_id, uid, score):
result['data_count'] = len(df)

return result


2 changes: 2 additions & 0 deletions i18n/message.en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ en:
error_uid_not_set: "UID not set"
error_queue_timeout: "API server is down. Please wait until recovery. (Queue timeout)"
error_not_exist_uid: "UID is not specified or does not exist."
error_general_error: "An error occurred within the API server."
error_game_maintenance_error: "The game is under maintenance."
error_no_chara_set: "Character not set"
change_uid: "Change UID"
nickname: "Nickname: "
Expand Down
4 changes: 3 additions & 1 deletion i18n/message.jp.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ jp:
generating: "生成中..."
uid_not_set: "UID未設定"
error_uid_not_set: "UIDが設定されていません。"
error_queue_timeout: "APIサーバーがダウンしています。復旧までお待ちください。 (Queue timeout)"
error_queue_timeout: "APIサーバーがダウンしています。復旧までお待ちください。"
error_not_exist_uid: "未設定もしくは存在しないUIDです。"
error_general_error: "APIサーバー内でエラーが発生しました。再度お試しください。"
error_game_maintenance_error: "ゲームがメンテナンス中のため利用できません。メンテナンス終了までお待ちください。"
error_no_chara_set: "キャラクターがセットされていません。"
change_uid: "UID変更"
nickname: "ニックネーム: "
Expand Down
5 changes: 5 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@
async def init_bot():
await utils.DataBase.init()
status_update_task.start()
os.chdir('generate')
os.system("git clone --filter=blob:none --no-checkout https://github.com/Mar-7th/StarRailRes.git")
os.chdir('StarRailRes')
os.system("git sparse-checkout set index_min")
os.system("git checkout")


@bot.event
Expand Down
2 changes: 1 addition & 1 deletion utils/DataBase.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,5 +50,5 @@ async def setdatabase(userid, id, value, table="honkai_user"):
if rows is None:
await conn.execute('INSERT INTO honkai_user (id) VALUES ($1);', (str(userid)))
rows = await conn.fetchrow('SELECT uid from honkai_user where id = $1;', (str(userid)))
await conn.execute(f'UPDATE {table} SET {id} = $1 WHERE "id" = $2;', value, str(userid))
await conn.execute(f'UPDATE {table} SET {id} = $1 WHERE "id" = $2;', int(value), str(userid))
return rows[0]

0 comments on commit 4986893

Please sign in to comment.