mihomo Python Library

repository·main·Indexed 12 days ago

https://github.com/metacubex/mihomo

A Python library providing Pydantic models and an API client for parsed Honkai: Star Rail user data from the Mihomo API. Version 1.1.7 includes the MihomoAPI client for fetching data in V1 and V2 formats, tools for character data manipulation, and support for persisting data via JSON or pickle.

Tokens
3.3K
Snippets
17
Records
18
Agent score
97%

What's inside mihomo

  1. Persist and load StarrailInfoParsed data

    main

    Since the models are Pydantic-based, you can persist data using standard Python methods like pickle or json.

    JSON Persistence

    • Save: Use data.json(by_alias=True, ensure_ascii=False) to generate a JSON string.
    • Load: Use StarrailInfoParsed.parse_raw(json_string) to reconstruct the model.

    Pickle Persistence

    • Save: Use pickle.dumps(data). It is recommended to use zlib.compress() to reduce size.
    • Load: Use pickle.loads(zlib.decompress(compressed_data)) to reconstruct the object.
    import pickle
    import zlib
    from mihomo import MihomoAPI, Language, StarrailInfoParsed
    
    client = MihomoAPI(language=Language.EN)
    data = await client.fetch_user(800333171)
    
    # --- Save ---
    # Pickle with compression
    pickle_data = zlib.compress(pickle.dumps(data))
    # JSON
    json_data = data.json(by_alias=True, ensure_ascii=False)
    
    # --- Load ---
    # From Pickle
    data_from_pickle = pickle.loads(zlib.decompress(pickle_data))
    # From JSON
    data_from_json = StarrailInfoParsed.parse_raw(json_data)
  2. Use mihomo tools for character data manipulation

    main

    The mihomo.tools module provides utilities for processing character data.

    • remove_duplicate_character(data): Removes duplicate character entries from the provided data object.
    • merge_character_data(new_data, old_data): Merges character information from a new data fetch into an old data object. This is useful for tracking changes after a user updates their characters in-game.
    from mihomo import tools
    
    # Remove duplicates
    data = await client.fetch_user(800333171)
    data = tools.remove_duplicate_character(data)
    
    # Merge data (e.g., after character changes in-game)
    old_data = await client.fetch_user(800333171)
    # ... wait for API refresh ...
    new_data = await client.fetch_user(800333171)
    data = tools.merge_character_data(new_data, old_data)
  3. Fetch Honkai: Star Rail data using V1 or V2 formats

    main

    The MihomoAPI client supports two data formats for fetching parsed user information.

    V1 Format

    • Method: client.fetch_user_v1(uid)
    • Model: mihomo.models.v1.StarrailInfoParsedV1
    • Note: Icons are returned as names; use client.get_icon_url(icon_name) to resolve them to full URLs.

    V2 Format

    • Method: client.fetch_user(uid)
    • Model: mihomo.models.StarrailInfoParsed
    • Asset URLs: To avoid calling get_icon_url repeatedly, pass replace_icon_name_with_url=True to fetch_user to receive full asset URLs directly in the model.
    from mihomo import MihomoAPI, Language
    
    client = MihomoAPI(language=Language.EN)
    
    # Fetch V1
    data_v1 = await client.fetch_user_v1(800333171)
    
    # Fetch V2 with direct asset URLs
    data_v2 = await client.fetch_user(800333171, replace_icon_name_with_url=True)
  4. Handle UserNotFound and InvalidParams exceptions

    main

    The library uses specific exception classes for common error scenarios:

    • UserNotFound: Raised when a requested user does not exist. The default message is "User not found.".
    • InvalidParams: Raised when the provided parameters for an API call are incorrect or invalid. The default message is "Invalid parameters".
    try:
        # Operation that might fail due to user or params
        pass
    except UserNotFound:
        print("The user does not exist.")
    except InvalidParams as e:
        print(f"Parameter error: {e.message}")
  5. Get asset URLs with MihomoAPI.get_icon_url()

    main

    The get_icon_url(icon) method constructs a full URL for a specific asset/icon by appending the provided icon name to the base ASSET_URL (https://raw.githubusercontent.com/Mar-7th/StarRailRes/master).

    from mihomo import MihomoAPI
    
    client = MihomoAPI()
    icon_url = client.get_icon_url("some_icon_name.png")
    # Returns: https://raw.githubusercontent.com/Mar-7th/StarRailRes/master/some_icon_name.png
  6. Merge character data with `merge_character_data`

    main

    Use merge_character_data(new_data, old_data) to combine two ParsedData objects.

    • It appends all characters from old_data to the new_data.characters list.
    • It discards the player information from the old_data.
    • It automatically calls remove_duplicate_character on the resulting set to ensure no duplicate IDs exist in the merged list.
    from mihomo.tools import merge_character_data
    
    # Merges characters from old_data into new_data and removes duplicates
    merged_data = merge_character_data(new_data, old_data)
  7. Use BaseException for catching all mihomo errors

    main

    All exceptions in this library inherit from BaseException. You can use this class to catch any error specifically raised by the mihomo package.

    try:
        # Any mihomo-related operation
        pass
    except BaseException as e:
        print(f"A library error occurred: {e.message}")
  8. Replace the Trailblazer placeholder name with `replace_trailblazer_name`

    main

    Use replace_trailblazer_name(data) on a StarrailInfoParsedV1 object. It iterates through the characters list and, if a character's name is exactly the literal string "{NICKNAME}", it replaces it with the name found in data.player.name.

    # Assuming data is an instance of StarrailInfoParsedV1
    updated_data = replace_trailblazer_name(data)
  9. Initialize the MihomoAPI client

    main

    To interact with the Mihomo API, instantiate the MihomoAPI class. You can optionally specify a language using the Language enum to determine the language of the API responses. If no language is provided, it defaults to Language.CHT (Traditional Chinese).

    from mihomo import MihomoAPI, Language
    
    # Initialize with English language
    client = MihomoAPI(language=Language.EN)
  10. Replace icon file names with asset URLs with `replace_icon_name_with_url`

    main

    Use replace_icon_name_with_url(data) to transform local icon file paths into full URLs using the ASSET_URL (https://raw.githubusercontent.com/Mar-7th/StarRailRes/master). It identifies strings containing .png and prepends the base URL.

    from mihomo.tools import replace_icon_name_with_url
    
    data = {"avatar": "/icon/avatar/1201.png"}
    updated_data = replace_icon_name_with_url(data)
    # Result: {'avatar': 'https://raw.githubusercontent.com/Mar-7th/StarRailRes/master/icon/avatar/1201.png'}
  11. Handle HTTP request errors with HttpRequestError

    main

    When an API request fails due to an HTTP error, HttpRequestError is raised. This exception provides access to the HTTP status code and the reason for the failure. If no custom message is provided during initialization, the message defaults to the format [{status}] {reason}.

    try:
        # Perform an API call that might fail
        pass
    except HttpRequestError as e:
        print(f"Error Status: {e.status}")
        print(f"Error Reason: {e.reason}")
        print(f"Message: {e.message}")