Modern API wrapper for Genshin Impact built on asyncio and pydantic.

Overview

genshin.py

Modern API wrapper for Genshin Impact built on asyncio and pydantic.


Documentation: https://thesadru.github.io/genshin.py

Source Code: https://github.com/thesadru/genshin.py


The primary focus of genshin.py is convenience. The entire project is fully type-hinted and abstracts a large amount of the api to be easier to use.

Key features:

  • All data is in the form of Pydantic Models which means full autocompletion and linter support.
  • Requests are significantly faster thanks to proper usage of asyncio.
  • Chinese and Engrish names returned by the API are renamed to simpler English fields.
  • Supports the majority of the popular endpoints.
  • Cleanly integrates with frameworks like FastAPI out of the box.

Note: This library is a successor to genshinstats - an unofficial wrapper for the Genshin Impact api.

Requirements

  • Python 3.8+
  • aiohttp
  • Pydantic
pip install genshin

Example

A very simple example of how genshin.py would be used:

import asyncio
import genshin

async def main():
    cookies = {"ltuid": 119480035, "ltoken": "cnF7TiZqHAAvYqgCBoSPx5EjwezOh1ZHoqSHf7dT"}
    client = genshin.GenshinClient(cookies)

    data = await client.get_user(710785423)
    print(f"User has a total of {len(data.characters)} characters")

    await client.close()

asyncio.run(main())

Contributing

Any kind of contribution is welcome.

Before making a pull request remember to test your changes using pytest. Remember to set your LTUID and LTOKEN environment variables.

pip install genshin[test]
python -m pytest

Please also edit the documentation accordingly. You may see how the final documentation would look like by starting an mkdocs server.

pip install genshin[doc]
mkdocs serve

I am currently looking for any chinese mainland players who could share their account_id and cookie_token cookies to allow for testing of chinese endpoints.

Comments
  • Change retcode for redeem code

    Change retcode for redeem code

    Redeem code has change retcode form -2003 to -2004 and add -2016 is Redemption in cooldown

    [-2004] Invalid redemption code. image [-2016] Redemption in cooldown. image

    enhancement 
    opened by mrwan200 18
  • Can't set authkey on GenshinClient due to size mismatch

    Can't set authkey on GenshinClient due to size mismatch

    Trying to create a new GenshinClient instance with an authkey fails with the error authkey must have precisely 1024 characters. Trying to set the authkey on an existing instance results in the same error. The auth key I'm providing is longer than 1024 characters. The base64 decoded auth key, however, is exactly 1024 characters long. Providing that instead of the base64 encoded one results in a different error: authkey is not a valid base64 encoded string

    bug 
    opened by Ennea 11
  • Support v2 cookies

    Support v2 cookies

    The ch server fully uses the v2 version of the cookies

    ltoken_v2=xxxx
    ltmid_v2=xxx
    cookie_token_v2=xxxx
    account_mid_v2=xxxxx
    

    It is not possible to get the user id from account_mid_v2 because it is a random string character generated by the ch server. https://github.com/thesadru/genshin.py/blob/dbebc29f485f01e352e75c6e389e754369101a9c/genshin/client/manager/managers.py#L238-L248

    bug API support 
    opened by luoshuijs 10
  • add proxy setting

    add proxy setting

    Some endpoint block some IP address, add a aiohttp proxy setting to client.

    https://docs.aiohttp.org/en/stable/client_advanced.html

    Hoyolab(oversea) block Chinese IP, a http proxy can help😀

    enhancement 
    opened by LuckyTain 6
  • Hoyolab check in?

    Hoyolab check in?

    Does Hoyoverse remove the Hoyolab check in API? I still use genshinstats but when I use Hoyolab check in it throw an error genshinstats.errors.GenshinStatsException: Internal database error, see original message, did they remove it now?

    enhancement API support 
    opened by rushkii 6
  • Support Honkai Impact daily sign-in

    Support Honkai Impact daily sign-in

    Since honkai has its own daily sign-in rewards it'd be nice to support it in genshin.py.

    The logic is the exact same, only the base url and act id differ. The biggest problem is figuring out how to properly implement it without much repetition.

    Currently, users can use:

    class HonkaiClient(GenshinClient):
        ACT_ID = "e202110291205111"
        REWARD_URL = "https://api-os-takumi.mihoyo.com/event/mani/"
    
    client = HonkaiClient(...)
    client.claim_daily_reward()
    
    enhancement 
    opened by thesadru 6
  • genshin.error.InvalidCookies

    genshin.error.InvalidCookies

    How to reproduce ? Using CLI to login after that invoke python -m genshin accounts --cookies "ltoken=...; ltuid=..."

    Current behavior It's just display error which state:

    genshin.errors.InvalidCookies: [-100] Cookies are not valid.
    
    opened by AFOEK 5
  • genshin.errors.GenshinException: [10104] Upon attempting to get the notes for another user.

    genshin.errors.GenshinException: [10104] Upon attempting to get the notes for another user.

    As the title suggests, attempting to use client.get_notes({uidOfSomeoneElse}) on another user that has a publicly open battle chronicle returns this exception. Is this because Hoyolab doesn't allow you to get notes for other users? If that's the case, the description "Tried to use a beta feature in an invalid context." doesn't sound correct (unless this is a beta feature that's actually being worked on, in that case go you!).

    bug 
    opened by emredesu 5
  • Set which region to fetch for Traveler's diary?

    Set which region to fetch for Traveler's diary?

    I'm not too familiar with the actual API endpoint myself, but it seems the current implementation defaults to 1 region only? (I'm guessing at the mercy of the default returned values from the API endpoint)

    enhancement 
    opened by BobbyWibowo 5
  • InternalDatabaseError when trying to get genshin characters (Nilou's id doesn't exist)

    InternalDatabaseError when trying to get genshin characters (Nilou's id doesn't exist)

    Obtaining this exception when trying to retrieve the genshin characters from the API. It's due to Nilou's ID not being in the internal database.

    Traceback (most recent call last):
      File "C:\Users\ElRey\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\tasks\__init__.py", line 239, in _loop
        await self.coro(*args, **kwargs)
      File "c:\Users\ElRey\Documents\Scripts\Python\ReyBot\discord_tools\tasks.py", line 10, in updateGenshinChars    
        chars = await client.get_genshin_characters(cfg.genshin_data["uuid"])
      File "C:\Users\ElRey\AppData\Local\Programs\Python\Python310\lib\site-packages\genshin\client\components\chronicle\genshin.py", line 78, in get_genshin_characters
        data = await self._request_genshin_record("character", uid, lang=lang, method="POST")
      File "C:\Users\ElRey\AppData\Local\Programs\Python\Python310\lib\site-packages\genshin\client\components\chronicle\genshin.py", line 51, in _request_genshin_record
        return await self.request_game_record(
      File "C:\Users\ElRey\AppData\Local\Programs\Python\Python310\lib\site-packages\genshin\client\components\chronicle\base.py", line 63, in request_game_record
        data = await self.request_hoyolab(url, lang=lang, region=region, **kwargs)
      File "C:\Users\ElRey\AppData\Local\Programs\Python\Python310\lib\site-packages\genshin\client\components\base.py", line 380, in request_hoyolab
        data = await self.request(url, method=method, params=params, data=data, headers=headers, **kwargs)
      File "C:\Users\ElRey\AppData\Local\Programs\Python\Python310\lib\site-packages\genshin\client\components\base.py", line 294, in request
        response = await self.cookie_manager.request(
      File "C:\Users\ElRey\AppData\Local\Programs\Python\Python310\lib\site-packages\genshin\client\manager.py", line 243, in request
        return await self._request(method, url, cookies=self.cookies, **kwargs)
      File "C:\Users\ElRey\AppData\Local\Programs\Python\Python310\lib\site-packages\genshin\client\ratelimit.py", line 24, in inner
        x = await func(*args, **kwargs)
      File "C:\Users\ElRey\AppData\Local\Programs\Python\Python310\lib\site-packages\genshin\client\manager.py", line 137, in _request
        errors.raise_for_retcode(data)
      File "C:\Users\ElRey\AppData\Local\Programs\Python\Python310\lib\site-packages\genshin\errors.py", line 224, in raise_for_retcode
        raise exctype(data, msg)
    genshin.errors.InternalDatabaseError: [-1] character id:10000070 is not exists
    
    opened by ElReyZero 4
  • TypeError: 'MergedPaginator' object is not iterable

    TypeError: 'MergedPaginator' object is not iterable

    i want to try wish history but i got this error TypeError: 'MergedPaginator' object is not iterable

    this is my code

    import asyncio
    import genshin
    cookies = {"ltuid": xxxxxxxx, "ltoken": "xxxxxxxxxxxxxx"}
    client = genshin.Client(cookies)
    
    async def main():
        for wish in client.wish_history():
            print(f"{wish.time} - {wish.name} ({wish.rarity}* {wish.type})")
    
    asyncio.run(main())
    

    if my coding is wrong I'm sorry, I'm just learning to use python

    opened by QueenLaurie 4
  • Use a more reliable source for character icon names

    Use a more reliable source for character icon names

    It would be ideal if there was an alternative source that reliably had the newest information. This is currently ambr but it would be better if we could have some alternative on hand like GenshinData. The current forks seem a bit unviable.

    enhancement help wanted 
    opened by thesadru 0
  • DS algorithm and salt value upgrade

    DS algorithm and salt value upgrade

    Currently we're using version 2.11.1, way lower behind the live production ds version 2.40.

    Some related code:

    https://github.com/y1ndan/genshinhelper2/blob/5402ffbe76885432d387e3cf04bb9d1dcefb9075/genshinhelper/utils.py#L163-L202 https://github.com/Le-niao/Yunzai-Bot/blob/07f39c89bd2603b447ba924aea43e55c2b6d6549/plugins/genshin/model/mys/mysApi.js#L230-L307

    Looks like we also need to send full headers to daily reward endpoint, but there's some problem:

    1. x-rpc-device_id value only obtainable in daily reward requests made by official client, kinda hard to get it unless everyone know how to use mitm proxy.
    2. Also x-rpc-device_model/x-rpc-device_name, I don't expect that many user know their correct device modal/name string.
    3. It isn't really user-friendly if some value aren't obtainable unless u install a mitm proxy.
    4. Does the daily reward requires separate ds salt value?
    API support help wanted 
    opened by BachelorForever 3
  • Use something better than pydantic

    Use something better than pydantic

    Pydantic is great and all but it's incredibly limiting for validation. (see the custom model that has to be used).

    This should either be decoupled into a separate library or at least cleaned up. Considering dropping re-serialization for optimization.

    enhancement 
    opened by thesadru 1
  • Add API documentation

    Add API documentation

    Possibilities:

    • mkdocs material for guide and pdoc for API (ugly)
    • mkdocs material for guide and sphinx for API (confusing)
    • sphinx for guide and API (limiting)
    documentation enhancement 
    opened by thesadru 0
Releases(1.5.0)
  • 1.5.0(Dec 21, 2022)

    What's new

    • Added genshin chronicle TCG endpoints.
    • Added teapot replica endpoints.
    • Aded an official source for banner IDs.
    • Made the hoyolab ID optional.

    Fixes

    • Fixed false positives when using multiple cookies.
    • Added turkish and italian to the list of languages.
    Source code(tar.gz)
    Source code(zip)
  • 1.4.0(Nov 16, 2022)

    What's new

    • Added geshin lineup.
    • Added cn calculator endpoints.
    • Added new icon types for genshin characters.

    Fixes

    • Invalid cookies are no longer kept.
    • Cookie tokens are now automatically refreshed.
    Source code(tar.gz)
    Source code(zip)
  • 1.3.0(Oct 15, 2022)

    What's new

    • Character data may be updated using 3rd party databases.

    Fixes

    • Character names are no longer in a different language.
    • Authkeys can be grabbed from local files again.
    Source code(tar.gz)
    Source code(zip)
  • 1.2.4(Sep 12, 2022)

  • 1.2.3(Aug 5, 2022)

    What's new

    • Added the golden apple archipelago activity.

    Fixes

    • Updated ds salt for cn daily rewards.
    • Exclude partial and empty characters from responses.
    Source code(tar.gz)
    Source code(zip)
  • 1.2.2(Jul 5, 2022)

    What's new

    • Added user info to genshin stats.

    Fixes

    • Fixed enabling of real-time notes and calculator sync.
    • Do not require cookies for authkey endpoints.
    Source code(tar.gz)
    Source code(zip)
  • 1.2.1(May 28, 2022)

  • 1.2.0(May 19, 2022)

    What's new

    • Added client.uid as a simpler alias for client.uids.
    • Allowed explicit UIDs in diary and calculator endpoints.
    • Implemented an international cookie manager.
    • Added client.proxy.
    • Implemented very basic wiki endpoints.
    • Implemented hoyolab community check-in.

    Changes

    • The password is now hidden in python -m genshin login
    • Stored timedeltas instead of datetimes in real-time notes.

    Fixes

    • Fixed honkai stats for users without any unlocked abyss.
    Source code(tar.gz)
    Source code(zip)
  • 1.1.0(Apr 22, 2022)

    What's new

    • Added the Parametric Transformer to notes.
    • Provided a direct Client.uid property for easier use with default_game.
    • Added missing activities.

    Changes

    • Improved the structure of Exploration models.
    • Removed is_chinese with recognize_region which now requires a genshin.Game.

    Fixes

    • Character model validation now works for foreign languages.
    Source code(tar.gz)
    Source code(zip)
  • 1.0.1(Apr 15, 2022)

  • 1.0.0(Apr 13, 2022)

    What's new

    • Added honkai endpoints.
    • Added login with username and password (Client.login_with_password)
    • Made the entire project be mypy and pyright strict compliant.

    Changes

    • Caching is now handled through Client.cache
    • Moved MultiCookieClient functionality to Client.cookie_manager

    Fixes

    • Reduced the amount of unexpected ratelimit exceptions
    • Made every single model be re-serializable.

    Deprecation

    • GenshinClient.cookies were removed in favor of cookie_manager
    • GenshinClient and subclasses were merged into Client
    • genshin_accounts -> get_game_accounts
    • get_record_card -> get_record_cards
    • get_[partial|full]_user -> get_[partial|full]_genshin_user
    Source code(tar.gz)
    Source code(zip)
  • 0.4(Feb 3, 2022)

    What's new

    • Added Serenitea Pot's Jar of Riches to Real-Time Notes
    • Implemented set_top_characters
    • Added models for A Study in Potions

    Changes

    • Made the Enhancement Progression Calculator use the builder pattern
    Source code(tar.gz)
    Source code(zip)
  • 0.3.1(Jan 10, 2022)

    Deprecation

    • Removed all_characters since the API no longer supports this feature

    Fixes

    • Images are now accounted for during character data completion
    • Diary log no longer repeatedly returns the first page in some cases
    Source code(tar.gz)
    Source code(zip)
  • 0.3.0(Dec 25, 2021)

    What's new

    • Added full support for the Genshin Impact Enhancement Progression Calculator
    • Improved debug mode to be slightly more descriptive

    Fixes

    • Fixed minor API inconsistencies including domain mismatches
    • Ensured some specific models no longer break when being revalidated
    Source code(tar.gz)
    Source code(zip)
  • 0.2.0(Dec 3, 2021)

    What's new

    • Added partial support for i18n
    • Added a way to specify the characters you want to get with get_user
    • Improved rate limit handling for certain endpoints
    • Made paginators awaitable

    Fixes

    • Fixed breaking API changes caused by the second banner
    • Deprecated authkeys in support pages
    • Fixed pydantic bug with ClassVar not being recognized properly
    Source code(tar.gz)
    Source code(zip)
  • 0.1.0(Nov 5, 2021)

    What's new

    • Implemented the Traveler's Diary
    • Cache uids for daily rewards and similar endpoints.
    • Support artifact levels
    • Add an enabled field for artifact set effects

    Fixes

    • Migrate server domains in accordance with the recent HoYoLAB server migration
    • Remove invalid authkey validation
    • Make permanent caches persist
    • No longer attempt to close non-existent sessions in MultiCookieClient
    • Fix minor problems with model validation
    Source code(tar.gz)
    Source code(zip)
  • 0.0.2(Oct 25, 2021)

    What's new

    • Implemented Real-Time notes
    • Added Labyrinth Warriors to activities
    • Made all datetime objects timezone aware.
    • Added public privacy settings to record cards.
    • Added basic support for Redis caches
    • Added new CLI commands
    • Added pdoc-generated API documentation
      • Started using ReST-style docstrings
      • Added module docstrings
    • Made debug a property instead of an __init__ param

    Fixes

    • Chinese daily reward claiming will no longer consistently raise errors due to invalid headers.
    • get_banner_details no longer requires gacha ids. They will be fetched from a user-maintained database from now on.
    • genshin.models.base.BaseCharacter is now a string instead of CharacterIcon
    • genshin.models.base.GenshinModel.dict() now also includes properties as it is immutable.

    Documentation

    • Documented a large part of the library with at least simple examples
    • Added credits to some people who considerably influenced the development of this library
    Source code(tar.gz)
    Source code(zip)
Owner
sadru
A python programmer who makes wrappers and downloaders for weeb shit. Creator of genshinstats; maintainer of disnake.
sadru
🪄 Auto-generate Streamlit UI from Pydantic Models and Dataclasses.

Streamlit Pydantic Auto-generate Streamlit UI elements from Pydantic models. Getting Started • Documentation • Support • Report a Bug • Contribution •

Lukas Masuch 103 Dec 25, 2022
A curated list of awesome things related to Pydantic! 🌪️

Awesome Pydantic A curated list of awesome things related to Pydantic. These packages have not been vetted or approved by the pydantic team. Feel free

Marcelo Trylesinski 186 Jan 5, 2023
Comprehensive OpenAPI schema generator for Django based on pydantic

??️ Djagger Automated OpenAPI documentation generator for Django. Djagger helps you generate a complete and comprehensive API documentation of your Dj

null 13 Nov 26, 2022
A python program with an Objective-C GUI for building and booting OpenCore on both legacy and modern Macs

A python program with an Objective-C GUI for building and booting OpenCore on both legacy and modern Macs, see our in-depth Guide for more information.

dortania 4.7k Jan 2, 2023
Lightweight and Modern kernel for VK Bots

This is the kernel for creating VK Bots written in Python 3.9

Yrvijo 4 Nov 21, 2021
Convert Roman numerals to modern numerals and vice-versa

Roman Numeral Conversion Utilities This is a utility module for converting from and to Roman numerals. It supports numbers upto 3,999,999, using the v

Fictive Kin 1 Dec 17, 2021
This Program Automates The Procces Of Adding Camos On Guns And Saving Them On Modern Warfare Guns

This Program Automates The Procces Of Adding Camos On Guns And Saving Them On Modern Warfare Guns

Flex Tools 6 May 26, 2022
A collection of modern themes for Tkinter TTK

ttkbootstrap A collection of modern flat themes inspired by Bootstrap. Also includes TTK Creator which allows you to easily create and use your own th

Israel Dryer 827 Jan 4, 2023
A modern Python build backend

trampolim A modern Python build backend. Features Task system, allowing to run arbitrary Python code during the build process (Planned) Easy to use CL

Filipe Laíns 39 Nov 8, 2022
A Modern Fetch Tool for Linux!

Ufetch A Modern Fetch Tool for Linux! Programming Language: Python IDE: Visual Studio Code Developed by Avishek Dutta If you get any kind of problem,

Avishek Dutta 7 Dec 12, 2021
A modern python module including many useful features that make discord bot programming extremely easy.

discord-super-utils Documentation Secondary Documentation A modern python module including many useful features that make discord bot programming extr

null 106 Dec 19, 2022
Open-source data observability for modern data teams

Use cases Monitor your data warehouse in minutes: Data anomalies monitoring as dbt tests Data lineage made simple, reliable, and automated dbt operati

null 889 Jan 1, 2023
Driving lessons made simpler. Custom scheduling API built with Python.

NOTE This is a mirror of a GitLab repository. Dryvo Dryvo is a unique solution for the driving lessons industry. Our aim is to save the teacher’s time

Adam Goldschmidt 595 Dec 5, 2022
A Python wrapper API for operating and working with the Neo4j Graph Data Science (GDS) library

gdsclient NOTE: This is a work in progress and many GDS features are known to be missing or not working properly. This repo hosts the sources for gdsc

Neo4j 100 Dec 20, 2022
Wrapper for the undocumented CodinGame API. Can be used both synchronously and asynchronlously.

codingame API wrapper Pythonic wrapper for the undocumented CodinGame API. Installation Python 3.6 or higher is required. Install codingame with pip:

Takos 19 Jun 20, 2022
A Python wrapper for Matrix Synapse admin API

Synapse-admin-api-python A Python wrapper for Matrix Synapse admin API. Versioning This library now supports up to Synapse 1.45.0, any Admin API intro

Knugi 9 Sep 28, 2022
An async API wrapper for Dress To Impress written in Python.

dti.py An async API wrapper for Dress To Impress written in Python. Some notes: For the time being, there are no front-facing docs for this beyond doc

Steve C 1 Dec 14, 2022
API wrapper for VCS hosting system.

PythonVCS API wrapper for VCS hosting system. Supported platforms Gitea Github, Gitlab, Bitbucket support will not, until that packages is not updated

MisileLaboratory 1 Apr 2, 2022
Built with Python programming language and QT library and Guess the number in three easy, medium and hard rolls

guess-the-numbers Built with Python programming language and QT library and Guess the number in three easy, medium and hard rolls Number guessing game

Amir Hussein Sharifnezhad 5 Oct 9, 2021