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
A Puzzle A Day Keep the Work Away

A Puzzle A Day Keep the Work Away No moyu again!

P4SSER8Y 5 Feb 12, 2022
Python Repository for Bachelor Ski Sign.

BachelorSkiSign Python Repository for Bachelor Ski Sign. This application reads data from https://bachelorapi.azurewebsites.net/ It is written in Ciru

Winston 1 Jan 04, 2022
Simple Kahoot Botter.

Kahoot A simple Botter made in Python 3 for Kahoot.com. Also sorry for the shitty code lol. How to Run You need Python 3 installed on your device. Aft

7 Jun 29, 2022
Scripts to convert the Ted-MDB corpora into the formats for DISRPT shared task and the converted corpora

Scripts to convert the Ted-MDB corpora into the formats for DISRPT shared task and the converted corpora.

1 Feb 08, 2022
A simple 3D rigid body simulation written in python

pyRigidBody3d A simple 3D rigid body simulation written in python

30 Oct 07, 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
The Begin button and menu for the Meadows operating system. The start button for UNIX/Linux.

By: Seanpm2001, Meadows Et; Al. Top README.md Read this article in a different language Sorted by: A-Z Sorting options unavailable ( af Afrikaans Afri

Sean P. Myrick V19.1.7.2 4 Aug 28, 2022
Never miss a deadline again

Hack the Opportunities Never miss a deadline again! Link to the excel sheet Contribution This list is not complete and I alone cannot make it whole. T

Vibali Joshi 391 Dec 28, 2022
Powerful virtual assistant in python

Virtual assistant in python Powerful virtual assistant in python Set up Step 1: download repo and unzip Step 2: pip install requirements.txt (if py au

Arkal 3 Jan 23, 2022
Paxos in Python, tested with Jepsen

Python implementation of Multi-Paxos with a stable leader and reconfiguration, roughly following "Paxos Made Moderately Complex". Run python3 paxos/st

A. Jesse Jiryu Davis 25 Dec 15, 2022
A synchronous, single-threaded interface for starting processes on Linux

A synchronous, single-threaded interface for starting processes on Linux

Spencer Baugh 27 Jan 28, 2022
AIST++ API This repo contains starter code for using the AIST++ dataset.

Explainability for Vision Transformers (in PyTorch) This repository implements methods for explainability in Vision Transformers

Google 260 Dec 30, 2022
Release for Improved Denoising Diffusion Probabilistic Models

improved-diffusion This is the codebase for Improved Denoising Diffusion Probabilistic Models. Usage This section of the README walks through how to t

OpenAI 1.2k Dec 30, 2022
use Notepad++ for real-time sync after python appending new log text

FTP远程log同步工具 使用Notepad++配合来获取实时更新的log文档效果 适用于FTP协议的log远程同步工具,配合MT管理器开启FTP服务器使用,通过Notepad++监听文本变化,更便捷的使用电脑查看方法注入打印后的信息 功能 过滤器 对每行要打印的文本使用回调函数筛选,支持链式调用

Liuhaixv 1 Oct 17, 2021
An Insurance firm providing tour insurance is facing higher claim frequency

An Insurance firm providing tour insurance is facing higher claim frequency. Data is collected from the past few years. Made a model which predicts the claim status using CART, RF & ANN and compare t

1 Jan 27, 2022
Python script for converting obsidian md-file to html (recursively adds all link/images)

ObsidianToHtmlConverter I made a small python script for converting obsidian md-file to static (local) html (recursively adds all link/images) I made

47 Jan 03, 2023
Files for QMC Workshop 2021

QMC Workshop 2021 This repository contains the presented slides and example files for the Quantum Monte Carlo (QMC) Workshop 5 October - 23 November,

QMCPACK 39 Nov 04, 2022
A totally unrealistic cell growth/reproduction simulation.

A totally unrealistic cell growth/reproduction simulation.

Andrien Wiandyano 1 Oct 24, 2021
A tool to allow New World players to calculate the best place to put their Attribute Points for their build and level

New World Damage Simulator A tool designed to take a characters base stats including armor and weapons, level, and base damage of their items (slash d

Joseph P Langford 31 Nov 01, 2022
A small Blender addon for changing an object's local orientation while in edit mode

A small Blender addon for changing an object's local orientation while in edit mode.

Jonathan Lampel 50 Jan 06, 2023