├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.yml │ ├── bug_report_zh.yml │ ├── config.yml │ ├── feature_request.yml │ └── feature_request_zh.yml └── workflows │ ├── Delete.yml │ └── build.yml ├── .gitignore ├── LICENSE ├── README.md ├── examples ├── basic.py ├── data_persistence.py └── merge_data.py ├── mihomo ├── __init__.py ├── client.py ├── errors.py ├── models │ ├── __init__.py │ ├── base.py │ ├── character.py │ ├── combat.py │ ├── equipment.py │ ├── player.py │ ├── stat.py │ └── v1 │ │ ├── __init__.py │ │ ├── base.py │ │ ├── character.py │ │ ├── equipment.py │ │ └── player.py └── tools.py └── pyproject.toml /.github/ISSUE_TEMPLATE/bug_report.yml: -------------------------------------------------------------------------------- 1 | name: Bug Report 2 | description: "Report Mihomo bug" 3 | title: "[Bug] " 4 | labels: ["bug"] 5 | body: 6 | - type: checkboxes 7 | id: ensure 8 | attributes: 9 | label: Verify steps 10 | description: Before submitting, please check all the options below to confirm that you have read and understood the following requirements; otherwise, this issue will be closed. 11 | options: 12 | - label: I have read the [documentation](https://wiki.metacubex.one/) and understand the meaning of all the configuration items I have written, rather than just piling up seemingly useful options or default values. 13 | required: false 14 | - label: I have carefully reviewed the [documentation](https://wiki.metacubex.one/) and have not resolved the issue. 15 | required: false 16 | - label: I have searched the [Issue Tracker](……/) for the issue I want to raise and did not find it. 17 | required: false 18 | - label: I am a non-Chinese user. 19 | required: false 20 | - label: I have tested with the latest Alpha branch version, and the issue still persists. 21 | required: true 22 | - label: I have provided the server and client configuration files and processes that can reproduce the issue locally, rather than a sanitized complex client configuration file. 23 | required: true 24 | - label: I provided the simplest configuration that can be used to reproduce the errors in my report, rather than relying on remote servers or piling on a lot of unnecessary configurations for reproduction. 25 | required: true 26 | - label: I have provided complete logs, rather than just the parts I think are useful out of confidence in my own intelligence. 27 | required: true 28 | - label: I have directly reproduced the error using the Mihomo command-line program, rather than using other tools or scripts. 29 | required: true 30 | 31 | - type: dropdown 32 | attributes: 33 | label: Operating System 34 | description: "Please provide the type of operating system." 35 | multiple: true 36 | options: 37 | - MacOS 38 | - Windows 39 | - Linux 40 | - OpenBSD/FreeBSD 41 | - Android 42 | - type: input 43 | attributes: 44 | label: System Version 45 | description: "Please provide the version of the operating system where the issue occurred." 46 | validations: 47 | required: true 48 | - type: textarea 49 | attributes: 50 | label: Mihomo Version 51 | description: "Provide the output of the `mihomo -v` command." 52 | validations: 53 | required: true 54 | - type: textarea 55 | attributes: 56 | render: yaml 57 | label: Configuration File 58 | description: |- 59 | Please attach the Mihomo configuration file below. 60 | Make sure there is no sensitive information in the configuration file (such as server addresses, passwords, ports, etc.) 61 | Also, ensure that the configuration file can reproduce the error using the Mihomo command-line program locally (if it's a proxy protocol issue, make sure the local server can be used for reproduction). 62 | validations: 63 | required: true 64 | - type: textarea 65 | attributes: 66 | label: Description 67 | description: "Please provide a detailed description of the error." 68 | validations: 69 | required: true 70 | - type: textarea 71 | attributes: 72 | label: Reproduction Steps 73 | description: "Please provide the steps to reproduce the error." 74 | validations: 75 | required: true 76 | - type: textarea 77 | attributes: 78 | label: Logs 79 | description: "Attach the running logs of Mihomo Core below, with `log-level` set to `DEBUG`." 80 | render: shell -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report_zh.yml: -------------------------------------------------------------------------------- 1 | name: 错误反馈 2 | description: "提交 Mihomo 漏洞" 3 | title: "[Bug] " 4 | labels: ["bug"] 5 | body: 6 | - type: checkboxes 7 | id: ensure 8 | attributes: 9 | label: 验证步骤 10 | description: 在提交之前,请勾选以下选项以证明您已经阅读并理解了以下要求,否则该 issue 将被关闭。 11 | options: 12 | - label: 我已经阅读了 [文档](https://wiki.metacubex.one/),了解所有我编写的配置文件项的含义,而不是大量堆砌看似有用的选项或默认值。 13 | required: false 14 | - label: 我仔细看过 [文档](https://wiki.metacubex.one/) 并未解决问题 15 | required: false 16 | - label: 我已在 [Issue Tracker](……/) 中寻找过我要提出的问题,并且没有找到 17 | required: false 18 | - label: 我是中文用户,而非其他语言用户 19 | required: false 20 | - label: 我已经使用最新的 Alpha 分支版本测试过,问题依旧存在 21 | required: true 22 | - label: 我提供了可以在本地重现该问题的服务器、客户端配置文件与流程,而不是一个脱敏的复杂客户端配置文件。 23 | required: true 24 | - label: 我提供了可用于重现我报告的错误的最简配置,而不是依赖远程服务器或者堆砌大量对于复现无用的配置等。 25 | required: true 26 | - label: 我提供了完整的日志,而不是出于对自身智力的自信而仅提供了部分认为有用的部分。 27 | required: true 28 | - label: 我直接使用 Mihomo 命令行程序重现了错误,而不是使用其他工具或脚本。 29 | required: true 30 | 31 | - type: dropdown 32 | attributes: 33 | label: 操作系统 34 | description: 请提供操作系统类型 35 | multiple: true 36 | options: 37 | - MacOS 38 | - Windows 39 | - Linux 40 | - OpenBSD/FreeBSD 41 | - Android 42 | - type: input 43 | attributes: 44 | label: 系统版本 45 | description: 请提供出现问题的操作系统版本 46 | validations: 47 | required: true 48 | - type: textarea 49 | attributes: 50 | label: Mihomo 版本 51 | description: 提供 `mihomo -v` 命令的输出 52 | validations: 53 | required: true 54 | - type: textarea 55 | attributes: 56 | render: yaml 57 | label: 配置文件 58 | description: |- 59 | 在下方附上 Mihomo 配置文件 60 | 请确保配置文件中没有敏感信息(比如:服务器地址,密码,端口等) 61 | 以及确保可以在本地(如果是代理协议问题,请确保本地服务器可用于复现)使用 Mihomo 原始命令行程序重现错误的配置文件 62 | validations: 63 | required: true 64 | - type: textarea 65 | attributes: 66 | label: 描述 67 | description: 请提供错误的详细描述。 68 | validations: 69 | required: true 70 | - type: textarea 71 | attributes: 72 | label: 重现方式 73 | description: 请提供重现错误的步骤 74 | validations: 75 | required: true 76 | - type: textarea 77 | attributes: 78 | label: 日志 79 | description: 在下方附上 Mihomo Core 的运行日志,`log-level` 使用 `DEBUG` 80 | render: shell -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false 2 | contact_links: 3 | - name: mihomo Community Support 4 | url: https://github.com/MetaCubeX/mihomo/discussions 5 | about: Please ask and answer questions about mihomo here. 6 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.yml: -------------------------------------------------------------------------------- 1 | name: Feature Request 2 | description: Suggest improvements for this project 3 | title: "[Feature] " 4 | labels: ["enhancement"] 5 | body: 6 | - type: checkboxes 7 | id: ensure 8 | attributes: 9 | label: Verification Steps 10 | description: Before submitting, please check the following options to confirm that you have read and understood the requirements below; otherwise, this issue will be closed. 11 | options: 12 | - label: I have read the [documentation](https://wiki.metacubex.one/) and confirmed that this feature is not implemented 13 | required: false 14 | - label: I have searched for the feature request I want to propose in the [Issue Tracker](……/) and did not find it 15 | required: false 16 | - label: I am a non-Chinese user. 17 | required: false 18 | - type: textarea 19 | attributes: 20 | label: Description 21 | description: Please provide a detailed description of the feature, rather than vague statements. 22 | validations: 23 | required: true -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request_zh.yml: -------------------------------------------------------------------------------- 1 | name: 功能请求 2 | description: 为该项目提出建议 3 | title: "[Feature] " 4 | labels: ["enhancement"] 5 | body: 6 | - type: checkboxes 7 | id: ensure 8 | attributes: 9 | label: 验证步骤 10 | description: 在提交之前,请勾选以下选项以证明您已经阅读并理解了以下要求,否则该 issue 将被关闭。 11 | options: 12 | - label: 我已经阅读了 [文档](https://wiki.metacubex.one/),确认了该功能没有实现 13 | required: false 14 | - label: 我已在 [Issue Tracker](……/) 中寻找过我要提出的功能请求,并且没有找到 15 | required: false 16 | - label: 我是中文用户,而非其他语言用户 17 | required: false 18 | - type: textarea 19 | attributes: 20 | label: 描述 21 | description: 请提供对于该功能的详细描述,而不是莫名其妙的话术。 22 | validations: 23 | required: true -------------------------------------------------------------------------------- /.github/workflows/Delete.yml: -------------------------------------------------------------------------------- 1 | name: Delete old workflow 2 | on: 3 | workflow_dispatch: 4 | schedule: 5 | - cron: '0 0 * * 0' 6 | # Run monthly, at 00:00 on the 1st day of month. 7 | 8 | jobs: 9 | del_runs: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Delete workflow runs 13 | uses: GitRML/delete-workflow-runs@main 14 | with: 15 | token: ${{ secrets.AUTH_PAT }} 16 | repository: ${{ github.repository }} 17 | retain_days: 30 -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | on: 3 | workflow_dispatch: 4 | inputs: 5 | version: 6 | description: "Tag version to release" 7 | required: true 8 | 9 | permissions: 10 | contents: write 11 | packages: write 12 | 13 | jobs: 14 | release_archive: 15 | runs-on: ubuntu-latest 16 | if: github.repository == 'KT-Yeh/mihomo' 17 | 18 | steps: 19 | - name: Checkout 20 | uses: actions/checkout@v3 21 | with: 22 | submodules: true 23 | 24 | - name: Archive Release 25 | uses: thedoctor0/zip-release@0.7.1 26 | with: 27 | type: zip 28 | filename: 'mihomo_${{ github.ref_name }}.zip' 29 | exclusions: '*.git*' 30 | 31 | - name: Release 32 | uses: softprops/action-gh-release@v1 33 | with: 34 | generate_release_notes: true 35 | files: 'mihomo_${{ github.ref_name }}.zip' -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | venv 3 | build 4 | mihomo.egg-info 5 | *.ipynb -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2023 KT 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # mihomo 2 | A simple python pydantic model (type hint and autocompletion support) for Honkai: Star Rail parsed data from the Mihomo API. 3 | 4 | API url: https://api.mihomo.me/sr_info_parsed/{UID}?lang={LANG} 5 | 6 | ## Installation 7 | ``` 8 | pip install -U git+https://github.com/KT-Yeh/mihomo.git 9 | ``` 10 | 11 | ## Usage 12 | 13 | ### Basic 14 | There are two parsed data formats: 15 | - V1: 16 | - URL: https://api.mihomo.me/sr_info_parsed/800333171?lang=en&version=v1 17 | - Fetching: use `client.fetch_user_v1(800333171)` 18 | - Data model: `mihomo.models.v1.StarrailInfoParsedV1` 19 | - All models defined in `mihomo/models/v1` directory. 20 | - V2: 21 | - URL: https://api.mihomo.me/sr_info_parsed/800333171?lang=en 22 | - Fetching: use `client.fetch_user(800333171)` 23 | - Data model: `mihomo.models.StarrailInfoParsed` 24 | - All models defined in `mihomo/models` directory. 25 | 26 | If you don't want to use `client.get_icon_url` to get the image url everytime, you can use `client.fetch_user(800333171, replace_icon_name_with_url=True)` to get the parsed data with asset urls. 27 | 28 | ### Example 29 | ```py 30 | import asyncio 31 | 32 | from mihomo import Language, MihomoAPI 33 | from mihomo.models import StarrailInfoParsed 34 | from mihomo.models.v1 import StarrailInfoParsedV1 35 | 36 | client = MihomoAPI(language=Language.EN) 37 | 38 | 39 | async def v1(): 40 | data: StarrailInfoParsedV1 = await client.fetch_user_v1(800333171) 41 | 42 | print(f"Name: {data.player.name}") 43 | print(f"Level: {data.player.level}") 44 | print(f"Signature: {data.player.signature}") 45 | print(f"Achievements: {data.player_details.achievements}") 46 | print(f"Characters count: {data.player_details.characters}") 47 | print(f"Profile picture url: {client.get_icon_url(data.player.icon)}") 48 | for character in data.characters: 49 | print("-----------") 50 | print(f"Name: {character.name}") 51 | print(f"Rarity: {character.rarity}") 52 | print(f"Level: {character.level}") 53 | print(f"Avatar url: {client.get_icon_url(character.icon)}") 54 | print(f"Preview url: {client.get_icon_url(character.preview)}") 55 | print(f"Portrait url: {client.get_icon_url(character.portrait)}") 56 | 57 | 58 | async def v2(): 59 | data: StarrailInfoParsed = await client.fetch_user(800333171, replace_icon_name_with_url=True) 60 | 61 | print(f"Name: {data.player.name}") 62 | print(f"Level: {data.player.level}") 63 | print(f"Signature: {data.player.signature}") 64 | print(f"Profile picture url: {data.player.avatar.icon}") 65 | for character in data.characters: 66 | print("-----------") 67 | print(f"Name: {character.name}") 68 | print(f"Rarity: {character.rarity}") 69 | print(f"Portrait url: {character.portrait}") 70 | 71 | asyncio.run(v1()) 72 | asyncio.run(v2()) 73 | ``` 74 | 75 | ### Tools 76 | `from mihomo import tools` 77 | #### Remove Duplicate Character 78 | ```py 79 | data = await client.fetch_user(800333171) 80 | data = tools.remove_duplicate_character(data) 81 | ``` 82 | 83 | #### Merge Character Data 84 | ```py 85 | old_data = await client.fetch_user(800333171) 86 | 87 | # Change characters in game and wait for the API to refresh 88 | # ... 89 | 90 | new_data = await client.fetch_user(800333171) 91 | data = tools.merge_character_data(new_data, old_data) 92 | ``` 93 | 94 | ### Data Persistence 95 | Take pickle and json as an example 96 | ```py 97 | import pickle 98 | import zlib 99 | from mihomo import MihomoAPI, Language, StarrailInfoParsed 100 | 101 | client = MihomoAPI(language=Language.EN) 102 | data = await client.fetch_user(800333171) 103 | 104 | # Save 105 | pickle_data = zlib.compress(pickle.dumps(data)) 106 | print(len(pickle_data)) 107 | json_data = data.json(by_alias=True, ensure_ascii=False) 108 | print(len(json_data)) 109 | 110 | # Load 111 | data_from_pickle = pickle.loads(zlib.decompress(pickle_data)) 112 | data_from_json = StarrailInfoParsed.parse_raw(json_data) 113 | print(type(data_from_pickle)) 114 | print(type(data_from_json)) 115 | ``` 116 | -------------------------------------------------------------------------------- /examples/basic.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | 3 | from mihomo import Language, MihomoAPI 4 | from mihomo.models import StarrailInfoParsed 5 | from mihomo.models.v1 import StarrailInfoParsedV1 6 | 7 | client = MihomoAPI(language=Language.EN) 8 | 9 | 10 | async def v1(): 11 | data: StarrailInfoParsedV1 = await client.fetch_user_v1(800333171) 12 | 13 | print(f"Name: {data.player.name}") 14 | print(f"Level: {data.player.level}") 15 | print(f"Signature: {data.player.signature}") 16 | print(f"Achievements: {data.player_details.achievements}") 17 | print(f"Characters count: {data.player_details.characters}") 18 | print(f"Profile picture url: {client.get_icon_url(data.player.icon)}") 19 | for character in data.characters: 20 | print("-----------") 21 | print(f"Name: {character.name}") 22 | print(f"Rarity: {character.rarity}") 23 | print(f"Level: {character.level}") 24 | print(f"Avatar url: {client.get_icon_url(character.icon)}") 25 | print(f"Preview url: {client.get_icon_url(character.preview)}") 26 | print(f"Portrait url: {client.get_icon_url(character.portrait)}") 27 | 28 | 29 | async def v2(): 30 | data: StarrailInfoParsed = await client.fetch_user(800333171, replace_icon_name_with_url=True) 31 | 32 | print(f"Name: {data.player.name}") 33 | print(f"Level: {data.player.level}") 34 | print(f"Signature: {data.player.signature}") 35 | print(f"Profile picture url: {data.player.avatar.icon}") 36 | for character in data.characters: 37 | print("-----------") 38 | print(f"Name: {character.name}") 39 | print(f"Rarity: {character.rarity}") 40 | print(f"Portrait url: {character.portrait}") 41 | 42 | 43 | asyncio.run(v1()) 44 | asyncio.run(v2()) 45 | -------------------------------------------------------------------------------- /examples/data_persistence.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import pickle 3 | import zlib 4 | 5 | from mihomo import Language, MihomoAPI, StarrailInfoParsed 6 | 7 | 8 | async def main(): 9 | client = MihomoAPI(language=Language.EN) 10 | data = await client.fetch_user(800333171) 11 | 12 | # Save 13 | pickle_data = zlib.compress(pickle.dumps(data)) 14 | print(len(pickle_data)) 15 | json_data = data.json(by_alias=True, ensure_ascii=False) 16 | print(len(json_data)) 17 | 18 | # Load 19 | data_from_pickle = pickle.loads(zlib.decompress(pickle_data)) 20 | data_from_json = StarrailInfoParsed.parse_raw(json_data) 21 | print(type(data_from_pickle)) 22 | print(type(data_from_json)) 23 | 24 | 25 | asyncio.run(main()) 26 | -------------------------------------------------------------------------------- /examples/merge_data.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | 3 | from mihomo import Language, MihomoAPI, tools 4 | 5 | 6 | async def main(): 7 | client = MihomoAPI(language=Language.EN) 8 | old_data = await client.fetch_user(800333171) 9 | 10 | # Change characters in game and wait for the API to refresh 11 | # ... 12 | 13 | new_data = await client.fetch_user(800333171) 14 | data = tools.merge_character_data(new_data, old_data) 15 | 16 | print(data) 17 | 18 | 19 | asyncio.run(main()) 20 | -------------------------------------------------------------------------------- /mihomo/__init__.py: -------------------------------------------------------------------------------- 1 | from . import tools 2 | from .client import * 3 | from .errors import * 4 | from .models import * 5 | -------------------------------------------------------------------------------- /mihomo/client.py: -------------------------------------------------------------------------------- 1 | import typing 2 | from enum import Enum 3 | 4 | import aiohttp 5 | 6 | from . import tools 7 | from .errors import HttpRequestError, InvalidParams, UserNotFound 8 | from .models import StarrailInfoParsed 9 | from .models.v1 import StarrailInfoParsedV1 10 | 11 | 12 | class Language(Enum): 13 | CHT = "cht" 14 | CHS = "cn" 15 | DE = "de" 16 | EN = "en" 17 | ES = "es" 18 | FR = "fr" 19 | ID = "id" 20 | JP = "jp" 21 | KR = "kr" 22 | PT = "pt" 23 | RU = "ru" 24 | TH = "th" 25 | VI = "vi" 26 | 27 | 28 | class MihomoAPI: 29 | """ 30 | Represents an client for Mihomo API. 31 | 32 | Args: 33 | language (Language, optional): 34 | The language to use for API responses.Defaults to Language.CHT. 35 | 36 | Attributes: 37 | - BASE_URL (str): The base URL of the API. 38 | - ASSET_URL (str): The base URL for the asset files. 39 | 40 | """ 41 | 42 | BASE_URL: typing.Final[str] = "https://api.mihomo.me/sr_info_parsed" 43 | ASSET_URL: typing.Final[ 44 | str 45 | ] = "https://raw.githubusercontent.com/Mar-7th/StarRailRes/master" 46 | 47 | def __init__(self, language: Language = Language.CHT): 48 | self.lang = language 49 | 50 | async def request( 51 | self, 52 | uid: int | str, 53 | language: Language, 54 | *, 55 | params: dict[str, str] = {}, 56 | ) -> typing.Any: 57 | """ 58 | Makes an HTTP request to the API. 59 | 60 | Args: 61 | - uid (int | str): The user ID. 62 | - language (Language): The language to use for the API response. 63 | 64 | Returns: 65 | typing.Any: The response from the API. 66 | 67 | Raises: 68 | HttpRequestError: If the HTTP request fails. 69 | InvalidParams: If the API request contains invalid parameters. 70 | UserNotFound: If the requested user is not found. 71 | 72 | """ 73 | url = self.BASE_URL + "/" + str(uid) 74 | params.update({"lang": language.value}) 75 | 76 | async with aiohttp.ClientSession() as session: 77 | async with session.get(url, params=params) as response: 78 | match response.status: 79 | case 200: 80 | return await response.json(encoding="utf-8") 81 | case 400: 82 | try: 83 | data = await response.json(encoding="utf-8") 84 | except: 85 | raise InvalidParams() 86 | else: 87 | if isinstance(data, dict) and ( 88 | detail := data.get("detail") 89 | ): 90 | raise InvalidParams(detail) 91 | raise InvalidParams() 92 | case 404: 93 | raise UserNotFound() 94 | case _: 95 | raise HttpRequestError(response.status, str(response.reason)) 96 | 97 | async def fetch_user( 98 | self, 99 | uid: int, 100 | *, 101 | replace_icon_name_with_url: bool = False, 102 | ) -> StarrailInfoParsed: 103 | """ 104 | Fetches user data from the API. 105 | 106 | Args: 107 | - uid (`int`): The user ID. 108 | - replace_icon_name_with_url (`bool`): Whether to replace icon names with asset URLs. 109 | 110 | Returns: 111 | StarrailInfoParsed: The parsed user data from mihomo API. 112 | 113 | """ 114 | data = await self.request(uid, self.lang) 115 | if replace_icon_name_with_url is True: 116 | data = tools.replace_icon_name_with_url(data) 117 | data = StarrailInfoParsed.parse_obj(data) 118 | return data 119 | 120 | async def fetch_user_v1( 121 | self, 122 | uid: int, 123 | *, 124 | replace_icon_name_with_url: bool = False, 125 | ) -> StarrailInfoParsedV1: 126 | """ 127 | Fetches user data from the API using version 1 format. 128 | 129 | Args: 130 | - uid (`int`): The user ID. 131 | - replace_icon_name_with_url (`bool`): Whether to replace icon names with asset URLs. 132 | 133 | Returns: 134 | StarrailInfoParsedV1: The parsed user data from the Mihomo API (version 1). 135 | 136 | """ 137 | data = await self.request(uid, self.lang, params={"version": "v1"}) 138 | data = tools.remove_empty_dict(data) 139 | if replace_icon_name_with_url is True: 140 | data = tools.replace_icon_name_with_url(data) 141 | data = StarrailInfoParsedV1.parse_obj(data) 142 | data = tools.replace_trailblazer_name(data) 143 | return data 144 | 145 | def get_icon_url(self, icon: str) -> str: 146 | """ 147 | Gets the asset url for the given icon. 148 | 149 | Args: 150 | icon (str): The icon name. 151 | 152 | Returns: 153 | str: The asset url for the icon. 154 | 155 | """ 156 | return self.ASSET_URL + "/" + icon 157 | -------------------------------------------------------------------------------- /mihomo/errors.py: -------------------------------------------------------------------------------- 1 | class BaseException(Exception): 2 | """Base exception class.""" 3 | 4 | message: str = "" 5 | 6 | def __init__(self, message: str | None = None, *args: object) -> None: 7 | if message is not None: 8 | self.message = message 9 | super().__init__(self.message, *args) 10 | 11 | 12 | class HttpRequestError(BaseException): 13 | """Exception raised when an HTTP request fails.""" 14 | 15 | status: int = 0 16 | reason: str = "" 17 | 18 | def __init__( 19 | self, 20 | status: int, 21 | reason: str, 22 | message: str | None = None, 23 | *args: object, 24 | ) -> None: 25 | if not message: 26 | message = f"[{status}] {reason}" 27 | self.status = status 28 | self.reason = reason 29 | self.message = message 30 | super().__init__(message, *args) 31 | 32 | 33 | class UserNotFound(BaseException): 34 | """Exception raised when a user is not found.""" 35 | 36 | message = "User not found." 37 | 38 | 39 | class InvalidParams(BaseException): 40 | """Exception raised when invalid parameters are provided.""" 41 | 42 | message: str = "Invalid parameters" 43 | -------------------------------------------------------------------------------- /mihomo/models/__init__.py: -------------------------------------------------------------------------------- 1 | from .base import * 2 | from .character import * 3 | from .combat import * 4 | from .equipment import * 5 | from .player import * 6 | from .stat import * 7 | -------------------------------------------------------------------------------- /mihomo/models/base.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel, Field 2 | 3 | from .character import Character 4 | from .player import Player 5 | 6 | 7 | class StarrailInfoParsed(BaseModel): 8 | """ 9 | Mihomo parsed data 10 | 11 | Attributes: 12 | - player (`Player`): The player's info. 13 | - characters (list[`Character`]): The list of characters. 14 | """ 15 | 16 | player: Player 17 | """Player's basic info""" 18 | characters: list[Character] 19 | """The list of characters""" 20 | -------------------------------------------------------------------------------- /mihomo/models/character.py: -------------------------------------------------------------------------------- 1 | from typing import Any 2 | 3 | from pydantic import BaseModel, Field, root_validator 4 | 5 | from .combat import Element, Path, Trace, TraceTreeNode 6 | from .equipment import LightCone, Relic, RelicSet 7 | from .stat import Attribute, Property 8 | 9 | 10 | class Character(BaseModel): 11 | """ 12 | Represents a character. 13 | 14 | Attributes: 15 | - Basic info: 16 | - id (`str`): The character's ID. 17 | - name (`str`): The character's name. 18 | - rarity (`int`): The character's rarity. 19 | - level (`int`): The character's current level. 20 | - max_level (`int`): The maximum character level according to the current ascension phase. 21 | - ascension (`int`): Ascension phase. 22 | - eidolon (`int`): The character's eidolon rank. 23 | - eidolon_icons (list[`str`]): The list of character's eiodolon icons. 24 | - Image 25 | - icon (`str`): The character avatar image 26 | - preview (`str`): The character's preview image. 27 | - portrait (`str`): The character's portrait image. 28 | - Combat 29 | - path (`Path`): The character's path. 30 | - element (`Element`): The character's element. 31 | - traces (list[`Trace`]): The list of character's skill traces. 32 | - trace_tree (list[`TraceTreeNode]): The list of the character's skill traces. 33 | - Equipment 34 | - light_cone (`LightCone` | `None`): The character's light cone (weapon), or None if not applicable. 35 | - relics (list[`Relic`] | `None`): The list of character's relics, or None if not applicable. 36 | - relic_set (list[`RelicSet`] | `None`): The list of character's relic sets, or None if not applicable. 37 | - stats (list[`Stat`]): The list of character's stats. 38 | - Stats 39 | - attributes (list[`Attribute`]): The list of character's attributes. 40 | - additions (list[`Attribute`]): The list of character's additional attributes. 41 | - properties (list[`Property`]): The list of character's properties. 42 | """ 43 | 44 | id: str 45 | """Character's ID""" 46 | name: str 47 | """Character's name""" 48 | rarity: int 49 | """Character's rarity""" 50 | level: int 51 | """Character's level""" 52 | ascension: int = Field(..., alias="promotion") 53 | """Ascension phase""" 54 | eidolon: int = Field(..., alias="rank") 55 | """Character's eidolon rank""" 56 | eidolon_icons: list[str] = Field([], alias="rank_icons") 57 | """The list of character's eiodolon icons""" 58 | 59 | icon: str 60 | """Character avatar image""" 61 | preview: str 62 | """Character preview image""" 63 | portrait: str 64 | """Character portrait image""" 65 | 66 | path: Path 67 | """Character's path""" 68 | element: Element 69 | """Character's element""" 70 | traces: list[Trace] = Field(..., alias="skills") 71 | """The list of character's skill traces""" 72 | trace_tree: list[TraceTreeNode] = Field([], alias="skill_trees") 73 | """The list of the character's skill traces""" 74 | 75 | light_cone: LightCone | None = None 76 | """Character's light cone (weapon)""" 77 | relics: list[Relic] = [] 78 | """The list of character's relics""" 79 | relic_sets: list[RelicSet] = [] 80 | """The list of character's relic sets""" 81 | 82 | attributes: list[Attribute] 83 | """The list of character's attributes""" 84 | additions: list[Attribute] 85 | """The list of character's additional attributes""" 86 | properties: list[Property] 87 | """The list of character's properties""" 88 | 89 | @property 90 | def max_level(self) -> int: 91 | """The maximum character level according to the current ascension phase""" 92 | return 20 + 10 * self.ascension 93 | -------------------------------------------------------------------------------- /mihomo/models/combat.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | 3 | 4 | class Element(BaseModel): 5 | """ 6 | Represents an element. 7 | 8 | Attributes: 9 | - id (`str`): The ID of the element. 10 | - name (`str`): The name of the element. 11 | - color (`str`): The color of the element. 12 | - icon (`str`): The element icon. 13 | """ 14 | 15 | id: str 16 | """The ID of the element""" 17 | name: str 18 | """The name of the element""" 19 | color: str 20 | """The color of the element""" 21 | icon: str 22 | """The element icon""" 23 | 24 | 25 | class Path(BaseModel): 26 | """ 27 | Paths are congregations of Imaginary energy, with which the ideals harmonize. 28 | 29 | Attributes: 30 | - id (`str`): The ID of the path. 31 | - name (`str`): The name of the path. 32 | - icon (`str`): The path icon. 33 | """ 34 | 35 | id: str 36 | """The ID of the path""" 37 | name: str 38 | """The name of the path""" 39 | icon: str 40 | """The path icon""" 41 | 42 | 43 | class Trace(BaseModel): 44 | """ 45 | Represents a character's skill trace. 46 | 47 | Attributes: 48 | - id (`int`): The ID of the trace. 49 | - name (`str`): The name of the trace. 50 | - level (`int`): The current level of the trace. 51 | - max_level (`int`): The maximum level of the trace. 52 | - element (`Element` | None): The element of the trace, or None if not applicable. 53 | - type (`str`): The type of the trace. 54 | - type_text (`str`): The type text of the trace. 55 | - effect (`str`): The effect of the trace. 56 | - effect_text (`str`): The effect text of the trace. 57 | - simple_desc (`str`): The simple description of the trace. 58 | - desc (`str`): The detailed description of the trace. 59 | - icon (`str`): The trace icon. 60 | """ 61 | 62 | id: int 63 | """The ID of the trace""" 64 | name: str 65 | """The name of the trace""" 66 | level: int 67 | """The current level of the trace""" 68 | max_level: int 69 | """The maximum level of the trace""" 70 | element: Element | None = None 71 | """The element of the trace""" 72 | type: str 73 | """The type of the trace""" 74 | type_text: str 75 | """The type text of the trace""" 76 | effect: str 77 | """The effect of the trace""" 78 | effect_text: str 79 | """The effect text of the trace""" 80 | simple_desc: str 81 | """The simple description of the trace""" 82 | desc: str 83 | """The detailed description of the trace""" 84 | icon: str 85 | """The trace icon""" 86 | 87 | 88 | class TraceTreeNode(BaseModel): 89 | """ 90 | Represents a node in the trace skill tree of a character. 91 | 92 | Attributes: 93 | - id (`int`): The ID of the trace. 94 | - level (`int`): The level of the trace. 95 | - max_level (`int`): The max level of the trace. 96 | - icon (`str`): The icon of the trace. 97 | - anchor (`str`): The position of the trace tree node. 98 | - parent (`int` | `None`): The preceding node id of trace. 99 | """ 100 | 101 | id: int 102 | """The ID of the trace""" 103 | level: int 104 | """The level of the trace""" 105 | max_level: int 106 | """The max level of the trace""" 107 | icon: str 108 | """The icon of the trace""" 109 | anchor: str 110 | """The position of the trace tree node""" 111 | parent: int | None = None 112 | """The preceding node id of trace""" 113 | -------------------------------------------------------------------------------- /mihomo/models/equipment.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel, Field 2 | 3 | from .combat import Path 4 | from .stat import Attribute, MainAffix, Property, SubAffix 5 | 6 | 7 | class LightCone(BaseModel): 8 | """ 9 | Represents a light cone (weapon). 10 | 11 | Attributes: 12 | - id (`int`): The ID of the light cone. 13 | - name (`str`): The name of the light cone. 14 | - rarity (`int`): The rarity of the light cone. 15 | - superimpose (`int`): The superimpose rank of the light cone. 16 | - level (`int`): The current level of the light cone. 17 | - max_level (`int`): The maximum light cone level according to the current ascension phase. 18 | - ascension (`int`): The ascension phase of the light cone. 19 | - icon (`str`): The light cone icon image. 20 | - preview (`str`): The light cone preview image. 21 | - portrait (`str`): The light cone portrait image. 22 | - path (`Path`): The path of the light cone. 23 | - attributes (list[`Attribute`]): The list of attributes of the light cone. 24 | - properties (list[`Property`]): The list of properties of the light cone. 25 | """ 26 | 27 | id: int 28 | """The ID of the light cone""" 29 | name: str 30 | """The name of the light cone""" 31 | rarity: int 32 | """The rarity of the light cone""" 33 | superimpose: int = Field(..., alias="rank") 34 | """The superimpose rank of the light cone""" 35 | level: int 36 | """The level of the light cone""" 37 | ascension: int = Field(..., alias="promotion") 38 | """The ascension phase of the light cone""" 39 | icon: str 40 | """The light cone icon image""" 41 | preview: str 42 | """The light cone preview image""" 43 | portrait: str 44 | """The light cone portrait image""" 45 | path: Path 46 | """The path of the light cone""" 47 | attributes: list[Attribute] 48 | """The list of attributes of the light cone""" 49 | properties: list[Property] 50 | """The list of properties of the light cone""" 51 | 52 | @property 53 | def max_level(self) -> int: 54 | """The maximum light cone level according to the current ascension phase""" 55 | return 20 + 10 * self.ascension 56 | 57 | 58 | class Relic(BaseModel): 59 | """ 60 | Represents a relic. 61 | 62 | Attributes: 63 | - id (`int`): The ID of the relic. 64 | - name (`str`): The name of the relic. 65 | - set_id (`int`): The ID of the relic set. 66 | - set_name (`str`): The name of the relic set. 67 | - rarity (`int`): The rarity of the relic. 68 | - level (`int`): The level of the relic. 69 | - main_property (`MainAffix`): The main affix of the relic. 70 | - sub_property (list[`SubAffix`]): The list of sub-affixes of the relic. 71 | - icon (`str`): The relic icon. 72 | """ 73 | 74 | id: int 75 | """The ID of the relic""" 76 | name: str 77 | """The name of the relic""" 78 | set_id: int 79 | """The ID of the relic set""" 80 | set_name: str 81 | """The name of the relic set""" 82 | rarity: int 83 | """The rarity of the relic""" 84 | level: int 85 | """The level of the relic""" 86 | main_affix: MainAffix 87 | """The main affix of the relic""" 88 | sub_affixes: list[SubAffix] = Field([], alias="sub_affix") 89 | """The list of sub-affixes of the relic""" 90 | icon: str 91 | """The relic icon""" 92 | 93 | 94 | class RelicSet(BaseModel): 95 | """ 96 | Represents a set of relics. 97 | 98 | Attributes: 99 | - id (`int`): The ID of the relic set. 100 | - name (`str`): The name of the relic set. 101 | - icon (`str`): The icon of the relic set. 102 | - num (`int`): The number of relics in the set. 103 | - desc (`str`): The description of the relic set. 104 | - properties (list[`Property`]): The list of properties of the relic set. 105 | """ 106 | 107 | id: int 108 | """The ID of the relic set""" 109 | name: str 110 | """The name of the relic set""" 111 | icon: str 112 | """The icon of the relic set""" 113 | num: int 114 | """The number of relics in the set""" 115 | desc: str 116 | """The description of the relic set""" 117 | properties: list[Property] 118 | """The list of properties of the relic set""" 119 | -------------------------------------------------------------------------------- /mihomo/models/player.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel, Field, root_validator 2 | 3 | 4 | class Avatar(BaseModel): 5 | """Profile picture""" 6 | 7 | id: int 8 | name: str 9 | icon: str 10 | 11 | 12 | class ForgottenHall(BaseModel): 13 | """The progress of the Forgotten Hall 14 | 15 | Attributes: 16 | - memory (`int`): The progress of the memory. 17 | - memory_of_chaos_id (`int`): The ID of the memory of chaos, or None if not applicable. 18 | - memory_of_chaos (`int`): The progress of the memory of chaos, or None if not applicable. 19 | """ 20 | 21 | memory: int = Field(..., alias="level") 22 | """The progress of the memory (level)""" 23 | memory_of_chaos_id: int = Field(..., alias="chaos_id") 24 | """The ID of the memory of chaos (chaos_id)""" 25 | memory_of_chaos: int = Field(..., alias="chaos_level") 26 | """The progress of the memory of chaos (chaos_level)""" 27 | 28 | 29 | class Player(BaseModel): 30 | """ 31 | Player basic info 32 | 33 | Attributes: 34 | - uid (`int`): The player's uid. 35 | - name (`str`): The player's nickname. 36 | - level (`int`): The player's Trailblaze level. 37 | - world_level (`int`): The player's Equilibrium level. 38 | - friend_count (`int`): The number of friends. 39 | - avatar (`Avatar`): The player's profile picture. 40 | - signature (`str`): The player's bio. 41 | - is_display (`bool`): Is the player's profile display enabled. 42 | 43 | - forgotten_hall (`ForgottenHall` | None): The progress of the Forgotten Hall, or None if not applicable. 44 | - simulated_universes (`int`): The number of simulated universes passed. 45 | - light_cones (`int`): The number of light cones owned. 46 | - characters (`int`): The number of characters owned. 47 | - achievements (`int`): The number of achievements unlocked. 48 | """ 49 | 50 | uid: int 51 | """Player's uid""" 52 | name: str = Field(..., alias="nickname") 53 | """Player's nickname""" 54 | level: int 55 | """Trailblaze level""" 56 | world_level: int 57 | """Equilibrium level""" 58 | friend_count: int 59 | """Number of friends""" 60 | avatar: Avatar 61 | """Profile picture""" 62 | signature: str 63 | """Bio""" 64 | is_display: bool 65 | """Is the player's profile display enabled.""" 66 | 67 | forgotten_hall: ForgottenHall | None = Field(None, alias="memory_data") 68 | """The progress of the Forgotten Hall (memory_data)""" 69 | simulated_universes: int = Field(0, alias="universe_level") 70 | """Number of simulated universes passed (universe_level)""" 71 | light_cones: int = Field(0, alias="light_cone_count") 72 | """Number of light cones owned""" 73 | characters: int = Field(0, alias="avatar_count") 74 | """Number of characters owned""" 75 | achievements: int = Field(0, alias="achievement_count") 76 | """Number of achievements unlocked""" 77 | 78 | @root_validator(pre=True) 79 | def decompose_space_info(cls, data): 80 | if isinstance(data, dict): 81 | space_info = data.get("space_info") 82 | if isinstance(space_info, dict): 83 | data.update(space_info) 84 | return data 85 | 86 | @root_validator(pre=True) 87 | def transform_for_backward_compatibility(cls, data): 88 | if isinstance(data, dict): 89 | if "pass_area_progress" in data and "universe_level" not in data: 90 | data["universe_level"] = data["pass_area_progress"] 91 | if "challenge_data" in data and "memory_data" not in data: 92 | c: dict[str, int] = data["challenge_data"] 93 | data["memory_data"] = {} 94 | data["memory_data"]["level"] = c.get("pre_maze_group_index") 95 | data["memory_data"]["chaos_id"] = c.get("maze_group_id") 96 | data["memory_data"]["chaos_level"] = c.get("maze_group_index") 97 | return data 98 | -------------------------------------------------------------------------------- /mihomo/models/stat.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel, Field 2 | 3 | 4 | class Attribute(BaseModel): 5 | """ 6 | Represents an attribute. 7 | 8 | Attributes: 9 | - field (`str`): The field of the attribute. 10 | - name (`str`): The name of the attribute. 11 | - icon (`str`): The attribute icon image. 12 | - value (`float`): The value of the attribute. 13 | - displayed_value (`str`): The displayed value of the attribute. 14 | - is_percent (`bool`): Indicates if the value is in percentage. 15 | """ 16 | 17 | field: str 18 | """The field of the attribute""" 19 | name: str 20 | """The name of the attribute""" 21 | icon: str 22 | """The attribute icon image""" 23 | value: float 24 | """The value of the attribute""" 25 | displayed_value: str = Field(..., alias="display") 26 | """The displayed value of the attribute""" 27 | is_percent: bool = Field(..., alias="percent") 28 | """Indicates if the value is in percentage""" 29 | 30 | 31 | class Property(BaseModel): 32 | """ 33 | Represents a property. 34 | 35 | Attributes: 36 | - type (`str`): The type of the property. 37 | - field (`str`): The field of the property. 38 | - name (`str`): The name of the property. 39 | - icon (`str`): The property icon image. 40 | - value (`float`): The value of the property. 41 | - displayed_value (`str`): The displayed value of the property. 42 | - is_percent (`bool`): Indicates if the value is in percentage. 43 | """ 44 | 45 | type: str 46 | """The type of the property""" 47 | field: str 48 | """The field of the property""" 49 | name: str 50 | """The name of the property""" 51 | icon: str 52 | """The property icon image""" 53 | value: float 54 | """The value of the property""" 55 | displayed_value: str = Field(..., alias="display") 56 | """The displayed value of the property""" 57 | is_percent: bool = Field(..., alias="percent") 58 | """Indicates if the value is in percentage""" 59 | 60 | 61 | class MainAffix(Property): 62 | """ 63 | Represents a relic main affix. 64 | 65 | Attributes: 66 | - type (`str`): The type of the affix. 67 | - field (`str`): The field of the affix. 68 | - name (`str`): The name of the affix. 69 | - icon (`str`): The affix icon image. 70 | - value (`float`): The value of the affix. 71 | - displayed_value (`str`): The displayed value of the affix. 72 | - is_percent (`bool`): Indicates if the value is in percentage. 73 | """ 74 | 75 | ... 76 | 77 | 78 | class SubAffix(MainAffix): 79 | """ 80 | Represents a relic sub-affix. 81 | 82 | Attributes: 83 | - type (`str`): The type of the affix. 84 | - field (`str`): The field of the affix. 85 | - name (`str`): The name of the affix. 86 | - icon (`str`): The affix icon image. 87 | - value (`float`): The value of the affix. 88 | - displayed_value (`str`): The displayed value of the affix. 89 | - is_percent (`bool`): Indicates if the value is in percentage. 90 | - count (`int`): The upgrade times of the affix. 91 | - step (`int`): The additional value of the affix. 92 | """ 93 | 94 | count: int 95 | """The upgrade times of the affix""" 96 | step: int 97 | """The additional value of the affix""" 98 | -------------------------------------------------------------------------------- /mihomo/models/v1/__init__.py: -------------------------------------------------------------------------------- 1 | from .base import * 2 | from .character import * 3 | from .equipment import * 4 | from .player import * 5 | -------------------------------------------------------------------------------- /mihomo/models/v1/base.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel, Field 2 | 3 | from .character import Character 4 | from .player import Player, PlayerSpaceInfo 5 | 6 | 7 | class StarrailInfoParsedV1(BaseModel): 8 | """ 9 | Mihomo parsed data V1 10 | 11 | Attributes: 12 | - player (`Player`): The player's basic info. 13 | - player_details (`PlayerSpaceInfo`): The player's details. 14 | - characters (list[`Character`]): The list of characters. 15 | """ 16 | 17 | player: Player 18 | """Player's basic info""" 19 | player_details: PlayerSpaceInfo = Field(..., alias="PlayerSpaceInfo") 20 | """Player's details""" 21 | characters: list[Character] 22 | """The list of characters""" 23 | -------------------------------------------------------------------------------- /mihomo/models/v1/character.py: -------------------------------------------------------------------------------- 1 | from typing import Any 2 | 3 | from pydantic import BaseModel, Field, root_validator 4 | 5 | from .equipment import LightCone, Relic, RelicSet 6 | 7 | 8 | class EidolonIcon(BaseModel): 9 | """ 10 | Represents an Eidolon icon. 11 | 12 | Attributes: 13 | - icon (`str`): The eidolon icon. 14 | - unlock (`bool`): Indicates if the eidolon is unlocked. 15 | """ 16 | 17 | icon: str 18 | """The eidolon icon""" 19 | unlock: bool 20 | """Indicates if the eidolon is unlocked""" 21 | 22 | 23 | class Trace(BaseModel): 24 | """ 25 | Represents a character's skill trace. 26 | 27 | Attributes: 28 | - name (`str`): The name of the trace. 29 | - level (`int`): The level of the trace. 30 | - type (`str`): The type of the trace. 31 | - icon (`str`): The trace icon. 32 | """ 33 | 34 | name: str 35 | """The name of the trace""" 36 | level: int 37 | """The level of the trace""" 38 | type: str 39 | """The type of the trace""" 40 | icon: str 41 | """The trace icon""" 42 | 43 | 44 | class Stat(BaseModel): 45 | """ 46 | Represents a character's stat. 47 | 48 | Attributes: 49 | - name (`str`): The name of the stat. 50 | - base (`str`): The base value of the stat. 51 | - addition (`str` | `None`): The additional value of the stat, or None if not applicable. 52 | - icon (`str`): The stat icon. 53 | """ 54 | 55 | name: str 56 | """The name of the stat""" 57 | base: str 58 | """The base value of the stat""" 59 | addition: str | None = None 60 | """The additional value of the stat""" 61 | icon: str 62 | """The stat icon""" 63 | 64 | 65 | class Character(BaseModel): 66 | """ 67 | Represents a character. 68 | 69 | Attributes: 70 | - Basic info: 71 | - id (`str`): The character's ID. 72 | - name (`str`): The character's name. 73 | - rarity (`int`): The character's rarity. 74 | - level (`int`): The character's level. 75 | - Eidolon 76 | - eidolon (`int`): The character's eidolon rank. 77 | - eidolon_icons (list[`EidolonIcon`]): The list of eidolon icons. 78 | - Image 79 | - icon (`str`): The character avatar image 80 | - preview (`str`): The character's preview image. 81 | - portrait (`str`): The character's portrait image. 82 | - Combat type 83 | - path (`str`): The character's path. 84 | - path_icon (`str`): The character's path icon. 85 | - element (`str`): The character's element. 86 | - element_icon (`str`): The character's element icon. 87 | - color (`str`): The character's element color. 88 | - Equipment 89 | - traces (list[`Trace`]): The list of character's skill traces. 90 | - light_cone (`LightCone` | `None`): The character's light cone (weapon), or None if not applicable. 91 | - relics (list[`Relic`] | `None`): The list of character's relics, or None if not applicable. 92 | - relic_set (list[`RelicSet`] | `None`): The list of character's relic sets, or None if not applicable. 93 | - stats (list[`Stat`]): The list of character's stats. 94 | """ 95 | 96 | id: str 97 | """Character's ID""" 98 | name: str 99 | """Character's name""" 100 | rarity: int 101 | """Character's rarity""" 102 | level: int 103 | """Character's level""" 104 | 105 | eidolon: int = Field(..., alias="rank") 106 | """Character's eidolon rank""" 107 | eidolon_icons: list[EidolonIcon] = Field(..., alias="rank_icons") 108 | """The list of eidolon icons""" 109 | 110 | preview: str 111 | """Character preview image""" 112 | portrait: str 113 | """Character portrait image""" 114 | 115 | path: str 116 | """Character's path""" 117 | path_icon: str 118 | """Character's path icon""" 119 | 120 | element: str 121 | """Character's element""" 122 | element_icon: str 123 | """Character's element icon""" 124 | 125 | color: str 126 | """Character's element color""" 127 | 128 | traces: list[Trace] = Field(..., alias="skill") 129 | """The list of character's skill traces""" 130 | light_cone: LightCone | None = None 131 | """Character's light cone (weapon)""" 132 | relics: list[Relic] | None = Field(None, alias="relic") 133 | """The list of character's relics""" 134 | relic_set: list[RelicSet] | None = None 135 | """The list of character's relic sets""" 136 | stats: list[Stat] = Field(..., alias="property") 137 | """The list of character's stats""" 138 | 139 | @root_validator(pre=True) 140 | def dict_to_list(cls, data: dict[str, Any]): 141 | # The keys of the original dict is not necessary, so remove them here. 142 | if isinstance(data, dict) and data.get("relic") is not None: 143 | if isinstance(data["relic"], dict): 144 | data["relic"] = list(data["relic"].values()) 145 | return data 146 | 147 | @property 148 | def icon(self) -> str: 149 | """Character avatar image""" 150 | return f"icon/character/{self.id}.png" 151 | -------------------------------------------------------------------------------- /mihomo/models/v1/equipment.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel, Field 2 | 3 | 4 | class LightCone(BaseModel): 5 | """ 6 | Represents a light cone (weapon). 7 | 8 | Attributes: 9 | - name (`str`): The name of the light cone. 10 | - rarity (`int`): The rarity of the light cone. 11 | - superimpose (`int`): The superimpose rank of the light cone. 12 | - level (`int`): The level of the light cone. 13 | - icon (`str`): The light cone icon. 14 | """ 15 | 16 | name: str 17 | rarity: int 18 | superimpose: int = Field(..., alias="rank") 19 | level: int 20 | icon: str 21 | 22 | 23 | class RelicProperty(BaseModel): 24 | """ 25 | Represents a property of a relic. 26 | 27 | Attributes: 28 | - name (`str`): The name of the relic property. 29 | - value (`str`): The value of the relic property. 30 | - icon (`str`): The property icon. 31 | """ 32 | 33 | name: str 34 | value: str 35 | icon: str 36 | 37 | 38 | class Relic(BaseModel): 39 | """ 40 | Represents a relic. 41 | 42 | Attributes: 43 | - name (`str`): The name of the relic. 44 | - rarity (`int`): The rarity of the relic. 45 | - level (`int`): The level of the relic. 46 | - main_property (`RelicProperty`): The main property of the relic. 47 | - sub_property (list[`RelicProperty`]): The list of sub properties of the relic. 48 | - icon (`str`): The relic icon. 49 | """ 50 | 51 | name: str 52 | rarity: int 53 | level: int 54 | main_property: RelicProperty 55 | sub_property: list[RelicProperty] 56 | icon: str 57 | 58 | 59 | class RelicSet(BaseModel): 60 | """ 61 | Represents a set of relics. 62 | 63 | Attributes: 64 | - name (`str`): The name of the relic set. 65 | - icon (`str`): The relic set icon. 66 | - desc (`int`): The description of the relic set. 67 | """ 68 | 69 | name: str 70 | icon: str 71 | desc: int 72 | -------------------------------------------------------------------------------- /mihomo/models/v1/player.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel, Field 2 | 3 | 4 | class Player(BaseModel): 5 | """ 6 | Player basic info 7 | 8 | Attributes: 9 | - uid (`str`): The player's uid. 10 | - name (`str`): The player's nickname. 11 | - level (`int`): The player's Trailblaze level. 12 | - icon (`str`): The player's profile picture. 13 | - signature (`str`): The player's bio. 14 | """ 15 | 16 | uid: str 17 | """Player's uid""" 18 | name: str 19 | """Player's nickname""" 20 | level: int 21 | """Trailblaze level""" 22 | icon: str 23 | """Profile picture""" 24 | signature: str 25 | """Bio""" 26 | 27 | 28 | class ForgottenHall(BaseModel): 29 | """The progress of the Forgotten Hall 30 | 31 | Attributes: 32 | - memory (`int`): The progress of the memory. 33 | - memory_of_chaos_id (`int` | `None`): The ID of the memory of chaos, or None if not applicable. 34 | - memory_of_chaos (`int` | `None`): The progress of the memory of chaos, or None if not applicable. 35 | """ 36 | 37 | memory: int | None = Field(None, alias="PreMazeGroupIndex") 38 | """The progress of the memory""" 39 | memory_of_chaos_id: int | None = Field(None, alias="MazeGroupIndex") 40 | """The ID of the memory of chaos""" 41 | memory_of_chaos: int | None = Field(None, alias="MazeGroupID") 42 | """The progress of the memory of chaos""" 43 | 44 | 45 | class PlayerSpaceInfo(BaseModel): 46 | """Player details 47 | 48 | Attributes: 49 | - forgotten_hall (`ForgottenHall` | None): The progress of the Forgotten Hall, or None if not applicable. 50 | - simulated_universes (`int`): The number of simulated universes passed. 51 | - light_cones (`int`): The number of light cones owned. 52 | - characters (`int`): The number of characters owned. 53 | - achievements (`int`): The number of achievements unlocked. 54 | """ 55 | 56 | forgotten_hall: ForgottenHall | None = Field(None, alias="ChallengeData") 57 | """The progress of the Forgotten Hall""" 58 | simulated_universes: int = Field(0, alias="PassAreaProgress") 59 | """Number of simulated universes passed""" 60 | light_cones: int = Field(0, alias="LightConeCount") 61 | """Number of light cones owned""" 62 | characters: int = Field(0, alias="AvatarCount") 63 | """Number of characters owned""" 64 | achievements: int = Field(0, alias="AchievementCount") 65 | """Number of achievements unlocked""" 66 | -------------------------------------------------------------------------------- /mihomo/tools.py: -------------------------------------------------------------------------------- 1 | from typing import Final, TypeVar 2 | 3 | from .models import Character, StarrailInfoParsed 4 | from .models.v1 import Character, StarrailInfoParsedV1 5 | 6 | RawData = TypeVar("RawData") 7 | ParsedData = TypeVar("ParsedData", StarrailInfoParsed, StarrailInfoParsedV1) 8 | 9 | ASSET_URL: Final[str] = "https://raw.githubusercontent.com/Mar-7th/StarRailRes/master" 10 | 11 | 12 | def remove_empty_dict(data: RawData) -> RawData: 13 | """ 14 | Recursively removes empty dictionaries from the given raw data. 15 | 16 | Args: 17 | - data (`RawData`): The input raw data. 18 | 19 | Returns: 20 | - `RawData`: The data with empty dictionaries removed. 21 | """ 22 | if isinstance(data, dict): 23 | for key in data.keys(): 24 | data[key] = None if (data[key] == {}) else remove_empty_dict(data[key]) 25 | elif isinstance(data, list): 26 | for i in range(len(data)): 27 | data[i] = remove_empty_dict(data[i]) 28 | return data 29 | 30 | 31 | def replace_icon_name_with_url(data: RawData) -> RawData: 32 | """ 33 | Replaces icon file names with asset URLs in the given raw data. 34 | 35 | Example: Replace "/icon/avatar/1201.png" with 36 | "https://raw.githubusercontent.com/Mar-7th/StarRailRes/master/icon/avatar/1201.png" 37 | 38 | Args: 39 | - data (`RawData`): The input raw data. 40 | 41 | Returns: 42 | - `RawData`: The data with icon file names replaced by asset URLs. 43 | """ 44 | if isinstance(data, dict): 45 | for key in data.keys(): 46 | data[key] = replace_icon_name_with_url(data[key]) 47 | elif isinstance(data, list): 48 | for i in range(len(data)): 49 | data[i] = replace_icon_name_with_url(data[i]) 50 | elif isinstance(data, str): 51 | if ".png" in data: 52 | data = ASSET_URL + "/" + data 53 | return data 54 | 55 | 56 | def replace_trailblazer_name(data: StarrailInfoParsedV1) -> StarrailInfoParsedV1: 57 | """ 58 | Replaces the trailblazer name with the player's name. 59 | 60 | Args: 61 | - data (`StarrailInfoParsed`): The input StarrailInfoParsed data. 62 | 63 | Returns: 64 | - `StarrailInfoParsed`: The updated StarrailInfoParsed data. 65 | """ 66 | for i in range(len(data.characters)): 67 | if data.characters[i].name == r"{NICKNAME}": 68 | data.characters[i].name = data.player.name 69 | return data 70 | 71 | 72 | def remove_duplicate_character(data: ParsedData) -> ParsedData: 73 | """ 74 | Removes duplicate characters from the given StarrailInfoParsed data. 75 | 76 | Args: 77 | - data (`ParsedData`): The input StarrailInfoParsed data. 78 | 79 | Returns: 80 | - `ParsedData`: The updated StarrailInfoParsed data without duplicate characters. 81 | """ 82 | new_characters = [] 83 | characters_ids: set[str] = set() 84 | for character in data.characters: 85 | if character.id not in characters_ids: 86 | new_characters.append(character) 87 | characters_ids.add(character.id) 88 | data.characters = new_characters 89 | return data 90 | 91 | 92 | def merge_character_data(new_data: ParsedData, old_data: ParsedData) -> ParsedData: 93 | """ 94 | Append the old data characters to the list of new data characters. 95 | The player's info from the old data will be omitted/discarded. 96 | 97 | Args: 98 | - new_data (`ParsedData`): The new data to be merged. 99 | - old_data (`ParsedData`): The old data to merge into. 100 | 101 | Returns: 102 | - `ParsedData`: The merged new data. 103 | """ 104 | for character in old_data.characters: 105 | new_data.characters.append(character) 106 | new_data = remove_duplicate_character(new_data) 107 | return new_data 108 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools>=61.0"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [project] 6 | name = "mihomo" 7 | version = "1.1.7" 8 | authors = [ 9 | { name="KT", email="xns77477@gmail.com" }, 10 | ] 11 | description = "A simple Python Pydantic model for Honkai: Star Rail parsed data from the Mihomo API." 12 | readme = "README.md" 13 | requires-python = ">=3.10" 14 | classifiers = [ 15 | "Programming Language :: Python :: 3", 16 | "License :: OSI Approved :: MIT License", 17 | "Operating System :: OS Independent", 18 | ] 19 | dependencies = [ 20 | "aiohttp==3.*", 21 | "pydantic==1.*", 22 | ] --------------------------------------------------------------------------------