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
Inspect the resources of your android projects and understand which ones are not being used and could potentially be removed.

Android Resources Checker What This program will inspect the resources of your app and help you understand which ones are not being used and could pot

Fábio Carballo 39 Feb 08, 2022
Never see escaped bytes in output.

Uniout It makes Python print the object representation in readable chars instead of the escaped string. Example from pprint import pprint lang

Mosky Liu 156 Oct 21, 2022
AHP Calculator - A method for organizing and evaluating complicated decisions, using Maths and Psychology

AHP Calculator - A method for organizing and evaluating complicated decisions, using Maths and Psychology

16 Aug 08, 2022
A common, beautiful interface to tabular data, no matter the format

rows No matter in which format your tabular data is: rows will import it, automatically detect types and give you high-level Python objects so you can

Álvaro Justen 834 Jan 03, 2023
A web application which you can search, buy or sell shares with current prices which provided by IEX.

CS50 - Stock Exchange A web application which you can search, buy or sell shares with current prices which provided by IEX. Table of Contents Setup St

1 May 28, 2022
Python script which synchronizes the replica-directoty with the original-one.

directories_synchronizer Python script which synchronizes the replica-directoty with the original-one. Automatically detects all changes when script i

0 Feb 13, 2022
A system for assigning and grading notebooks

nbgrader Linux: Windows: Forum: Coverage: Cite: A system for assigning and grading Jupyter notebooks. Documentation can be found on Read the Docs. Hig

Project Jupyter 1.2k Dec 26, 2022
Performance monitoring and testing of OpenStack

Browbeat Browbeat is a performance tuning and analysis tool for OpenStack. Browbeat is free, Open Source software. Analyze and tune your Cloud for opt

cloud-bulldozer 83 Dec 14, 2022
Python framework to build apps with the GASP metaphor

Gaspium Python framework to build apps with the GASP metaphor This project is part of the Pyrustic Open Ecosystem. Installation | Documentation | Late

5 Jan 01, 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
Addon to give a keybind to automatically enable contact shadows on all lights in a scene

3-2-1 Contact(Shadow) An easy way to let you enable contact shadows on all your lights, because Blender doesn't enable it by default, and doesn't give

TDV Alinsa 3 Feb 02, 2022
Convert a .vcf file to 'aa_table.tsv', including depth & alt frequency info

Produce an 'amino acid table' file from a vcf, including depth and alt frequency info.

Dan Fornika 1 Oct 16, 2021
用于导出墨墨背单词的词库,并生成适用于 List 背单词,不背单词,欧陆词典等的自定义词库

maimemo-export 用于导出墨墨背单词的词库,并生成适用于 List 背单词,欧陆词典,不背单词等的自定义词库。 仓库内已经导出墨墨背单词所有自带词库(暂不包括云词库),多达 900 种词库,可以在仓库中选择需要的词库下载(下载单个文件的方法),也可以去 蓝奏云(密码:666) 下载打包好

ourongxing 293 Dec 29, 2022
A PG3D API Made with Python

PG3D Python API A Pixel Gun 3D Python API (Public Ver) Features Count: 29 How To Use? import api as pbn Examples pbn.isBanned(192819483) - True pbn.f

Karim 2 Mar 24, 2022
The purpose of this script is to bypass disablefund, provide some useful information, and dig the hook function of PHP extension.

The purpose of this script is to bypass disablefund, provide some useful information, and dig the hook function of PHP extension.

Firebasky 14 Aug 02, 2021
A student information management system in Python

Student-information-management-system 本项目是一个学生信息管理系统,这个项目是用Python语言实现的,也实现了图形化界面的显示,同时也实现了管理员端,学生端两个登陆入口,同时底层使用的是Redis做的数据持久化。 This project is a stude

liuyunfei 7 Nov 15, 2022
A python tool for synchronizing the messages from different threads, processes, or hosts.

Sync-stream This project is designed for providing the synchoronization of the stdout / stderr among different threads, processes, devices or hosts.

Yuchen Jin 0 Aug 11, 2021
p5 is a Python package based on the core ideas of Processing.

p5 p5 is a Python library that provides high level drawing functionality to help you quickly create simulations and interactive art using Python. It c

p5py 645 Jan 04, 2023
Enjoy Discords Unlimited Storage

Discord Storage V.3.5 (Beta) Made by BoKa Enjoy Discords free and unlimited storage... Prepare: Clone this from Github, make sure there either a folde

0 Dec 16, 2021
Reproduction repository for the MDX 2021 Hybrid Demucs model

Submission This is the submission for MDX 2021 Track A, for Track B go to the track_b branch. Submission Summary Submission ID: 151378 Submitter: defo

Alexandre Défossez 62 Dec 18, 2022