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
SiliconCompiler is an open source compiler framework that automates translation from source code to silicon.

SiliconCompiler is an open source compiler framework that aims to automate translation from source code to silicon.

siliconcompiler 539 Jan 04, 2023
This is a simple analogue clock made with turtle in python...

Analogue-Clock This is a simple analogue clock made with turtle in python... Requirements None, only you need to have windows 😉 ...Enjoy! Installatio

Abhyush 3 Jan 14, 2022
A script to add issues to a project in Github based on label or status.

Add Github Issues to Project (Beta) A python script to move Github issues to a next-gen (beta) Github Project Getting Started These instructions will

Kate Donaldson 3 Jan 16, 2022
PyMedPhys is an open-source Medical Physics python library

PyMedPhys is an open-source Medical Physics python library built by an open community that values and prioritises code sharing, review, improvement, and learning from each other. I

PyMedPhys 238 Dec 27, 2022
A short course on Julia and open-source software development

Advanced Scientific Computing: producing better code This course is taught as a 6-session "nanocourse" at Washington University in St. Louis. See the

Tim Holy 230 Jan 07, 2023
ESteg - A simple steganography program for python

ESteg A simple steganography program to embed the contents of a text file into a

Jithin Renji 1 Jan 02, 2022
Buffer overflow example for python

Buffer overflow example for python

Mehmet 1 Jan 04, 2022
NeurIPS'19: Meta-Weight-Net: Learning an Explicit Mapping For Sample Weighting (Pytorch implementation for noisy labels).

Meta-Weight-Net NeurIPS'19: Meta-Weight-Net: Learning an Explicit Mapping For Sample Weighting (Official Pytorch implementation for noisy labels). The

243 Jan 03, 2023
Repo created for the purpose of adding any kind of programs and projects

Programs and Project Repository A repository for adding programs and projects of any kind starting from beginners level to expert ones Contributing to

Unicorn Dev Community 3 Nov 02, 2022
A complete python calculator with 2 modes Float and Int numbers.

Python Calculator This program is made for learning purpose. Getting started This Program runs using python, install it via terminal or from thier ofi

Felix Sanchez 1 Jan 18, 2022
Companion Web site for Fluent Python, Second Edition

Fluent Python, the site Source code and content for fluentpython.com. The site complements Fluent Python, Second Edition with extra content that did n

Fluent Python 49 Dec 08, 2022
Read and write life sciences file formats

Python-bioformats is a Python wrapper for Bio-Formats, a standalone Java library for reading and writing life sciences image file formats. Bio-Formats

CellProfiler 106 Dec 19, 2022
Team collaborative evaluation tracker.

Team collaborative evaluation tracker.

2 Dec 19, 2021
An html wrapper for python

MessySoup What is it? MessySoup is a python wrapper for html elements. While still a ways away, the main goal is to be able to build a wesbite straigh

4 Jan 05, 2022
This module is for finding the execution time of a whole python program

exetime 3.8 This module is for finding the execution time of a whole program How to install $ pip install exetime Contents: General Information Instru

Saikat Das 4 Oct 18, 2021
Get the stats of a (or more) Hypixel player(s)

Hypixel_Stats Get the statistics of a (or more) Hypixel player(s) Who needs this? Everyone who plays a lot of Minecraft and often plays on mc.hypixel.

Finnomator 1 Feb 12, 2022
Strong Typing in Python with Decorators

typy Strong Typing in Python with Decorators Description This light-weight library provides decorators that can be used to implement strongly-typed be

Ekin 0 Feb 06, 2022
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

106 Dec 19, 2022
Python version of RocketLeague-Dropshot-Calculated-shot

Python version of RocketLeague-Dropshot-Calculated-shot. This is just to demo around and a tool I used to develop the actual plugin.

JareBear 1 Jan 14, 2022
ChieriBot,词云API版,用于统计群友说过的怪话

wordCloud_API 词云API版,用于统计群友说过的怪话,基于wordCloud 消息储存在mysql数据库中.数据表结构见table.sql 为啥要做成API:这玩意太吃性能了,如果和Bot放在同一个服务器,可能会影响到bot的正常运行 你服务器性能够用的话就当我在放屁 依赖包 pip i

chinosk 7 Mar 20, 2022