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 Python script to parse Fortinet products serial numbers, and detect the associated model and version.

ParseFortinetSerialNumber A Python script to parse Fortinet products serial numbers, and detect the associated model and version. Example $ ./ParseFor

Podalirius 10 Oct 28, 2022
Wisdom Tree is a concentration app i am working on.

Wisdom Tree Wisdom Tree is a tui concentration app I am working on. Inspired by the wisdom tree in Plants vs. Zombies which gives in-game tips when it

NO ONE 241 Jan 01, 2023
Mines all the moneys and stuff and things.

NFT Miner NFT Miner - Version 1.1.0 - Quick Fix Since the whole NFT thing started booming on Twitter it's been hard not to see one of those ugly ass m

8w8 1 Dec 13, 2021
This is a simple SV calling package for diploid assemblies.

dipdiff This is a simple SV calling package for diploid assemblies. It uses a modified version of svim-asm. The package includes its own version minim

Mikhail Kolmogorov 11 Jan 05, 2023
Auto check in via GitHub Actions

因为本人毕业离校,本项目交由在校的@hfut-xyc同学接手,请访问hfut-xyc/hfut_auto_check-in获得最新的脚本 本项目遵从GPLv2协定,Copyright (C) 2021, Fw[a]rd 免责声明 根据GPL协定,我、本项目的作者,不会对您使用这个脚本带来的任何后果

Fw[a]rd 3 Jun 27, 2021
Create N Share is a No Code solution which gives users the ability to create any type of feature rich survey forms with ease.

create n share Note : The Project Scaffold will be pushed soon. Create N Share is a No Code solution which gives users the ability to create any type

Chiraag Kakar 11 Dec 03, 2022
Tools for dos (denial-of-service) website / web server

DoS Attack Tools Tools for dos (denial-of-service) website / web server di buat olah NurvySec How to install on debian / ubuntu $ apt update $ apt ins

nurvy 1 Feb 10, 2022
Awesome open-source alternatives to SaaS

Awesome-oss-alternatives - Awesome list of open-source startup alternatives to well-known SaaS products

Runa Capital 12.7k Jan 03, 2023
RecurrentArchitectures - See the accompanying blog post

Why this? What is the goal? The goal of this repository is to write all the recurrent architectures from scratch in tensorflow for learning purposes.

Debajyoti Datta 9 Feb 06, 2022
A quick experiment to demonstrate Metamath formula parsing, where the grammar is embedded in a few additional 'syntax axioms'.

Warning: Hacked-up code ahead. (But it seems to work...) What it does This demonstrates an idea which I posted about several times on the Metamath mai

Marnix Klooster 1 Oct 21, 2021
Iss-tracker - ISS tracking script in python using NASA's API

ISS Tracker Tracking International Space Station using NASA's API and plotting i

Partho 9 Nov 29, 2022
1000+ ready code templates to kickstart your next AI experiment

AI Seed Projects Start with ready code for your next AI experiment. Choose from 1000+ code templates, across a wide variety of use cases. All examples

BlobCity, Inc 98 Jan 03, 2023
The update manager for the ERA App (era.sh)

ERA Update Manager This is the official update manager used in the ERA app (see era.sh) How it works Once a new version of ERA is available, the app l

Kian Shahriyari 1 Dec 29, 2021
ALSPAC data analysis studying links between screen-usage and mental health issues in children. Provided data has been synthesised.

ADSMH - Mental Health and Screen Time Group coursework for Applied Data Science at the University of Bristol. Overview The data set that you have was

Kai 1 Jan 13, 2022
Runtime inspection utilities for Python typing module

Typing Inspect The typing_inspect module defines experimental API for runtime inspection of types defined in the Python standard typing module. Works

Ivan Levkivskyi 284 Dec 29, 2022
A one place destination to check whatever is trending on the top social and news websites at present.

UpTrend A one place destination to check whatever is trending on the top social and news websites at present. Explore the docs » View Demo · Report Bu

Google Developer Student Clubs - JGEC 10 Oct 03, 2021
Markov Chain Composer

Markov Chain Composer Using Markov Chain to represent relationships between words in song lyrics and then generating new lyrics.. ahem interpretive po

Kylie 85 Dec 09, 2022
Easy way to build a SaaS application using Python and Dash

EasySaaS This project will be attempt to make a great starting point for your next big business as easy and efficent as possible. This project will cr

xianhu 3 Nov 17, 2022
Placeholders is a single-unit storage solution for your Frontend.

Placeholder Placeholders is a single-unit file storage solution for your Frontend. Why Placeholder? Generally, when a website/service requests for fil

Tanmoy Sen Gupta 1 Nov 09, 2021
A variant caller for the GBA gene using WGS data

Gauchian: WGS-based GBA variant caller Gauchian is a targeted variant caller for the GBA gene based on a whole-genome sequencing (WGS) BAM file. Gauch

Illumina 16 Oct 13, 2022