Code Monkey home page Code Monkey logo

arkprts's Introduction

ArkPRTS

Arknights python wrapper.

Interacts directly with the game servers, no delays.

支持中文和B站账户!


Source Code: https://github.com/thesadru/arkprts


Installation

pip install -U arkprts

There are some optional requirements, you can install them all with all.

pip install -U arkprts[all]

Usage

import arkprts

async def main() -> None:
    client = arkprts.Client(assets=False)

    # search users by nickname
    users = await client.search_players("Doctor", server="en")
    print("User level: ", users[0].level)


    # =======

    # login with email or token
    auth = arkprts.YostarAuth("en")
    await auth.login_with_email_code("[email protected]")
    # or auth.login_with_token("123456", "abcdefg")
    client = arkprts.Client(auth=auth, assets=False)

    # get logged-in user data
    data = await client.get_data()
    print("Level: ", data.status.level)

Returned data is in the form of pydantic models, however you can also request raw json with client.get_raw_player_info()/client.get_raw_data()/... to access even untyped data.

For convenience, static game data is automatically downloaded and updated on login. You can access the static data directly or through the models. This is useful for getting names and descriptions of objects.

users = await client.search_user("UserName")
operator = users[0].assist_char_list[0]  # type: arkprts.models.Character
print(f"Assist operator {operator.static.name} is level {operator.level}")

To disable downloading static data use arkprts.Client(assets=False). To choose the data download location set arkprts.Client(assets="/path/to/data") (/tmp/%TEMP% is chosen by default).

ArkPRTS supports en, jp, kr, cn and bili servers. However only global/yostar servers (en, jp and kr) can be used without logging in.

Frequent usage cases

Get all of my operators.

data = await client.get_data()
for char in data.troop.chars.values():
    print(char.char_id)

Get my inventory.

data = await client.get_data()
# normal inventory items
for item_id, count in user.inventory.items():
    if count > 0:
        print(item_id, count)
# basic items like originium or green certificates
for item_id, count in user.status.basic_item_inventory.items():
    if count > 0:
        print(item_id, count)
# consumable expirable items
for item_id, subitems in user.consumable.items():
    for item in subitems.values():
        if count > 0:
            print(item_id, item.ts, item.count)

Logging in with email and password to the cn server.

auth = arkprts.HypergryphAuth()
await auth.login("[email protected]", "wordpass12")
client = arkprts.Client(auth=auth)

await client.get_data()

Making a new client when a global guest client already exists; without excess overhead.

public_client = arkprts.Client()

# ----
auth = arkprts.YostarAuth("en", network=public_client.network)
await auth.login_with_token("123456", "abcdefg")
private_client = arkprts.Client(auth=auth, assets=public_client.assets)

Programmatically getting auth tokens from a user on your website.

@route("/code")
def code(request):
    auth = arkprts.YostarAuth(request.query["server"], network=...)
    await auth.send_email_code(request.query["email"])

    return "Code sent!"


@route("/login")
def login(request):
    auth = arkprts.YostarAuth(request.query["server"], network=...)
    channel_uid, yostar_token = await auth.get_token_from_email_code(request.query["email"], request.query["code"])

    return {"channel_uid": channel_uid, "yostar_token": yostar_token}

Contributing

Any kind of contribution is welcome. Please read CONTRIBUTING.md for more information.

arkprts's People

Contributors

sharp-eyes avatar thesadru avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

arkprts's Issues

Restart connections on an outdated version

Arkprts is not reliable when the server happens to have an update. If a "version outdated" error is encountered all sessions should be logged out and back in with new version info.

Maybe also trigger a gamedata update, depending on how reliable the repository can be.

building_sync fails

AutomationClient.building_sync() consistency fails

await a_client.building_sync()

IndexError                                Traceback (most recent call last)
Cell In[25], line 1
----> 1 await a_client.building_sync()

File $DIRPATH\arkprts\automation.py:228, in AutomationClient.building_sync(self)
    223 async def building_sync(self) -> typing.Any:
    224     """Sync base data.
    225 
    226     APP behavior: Called when entered the base.
    227     """
--> 228     return await self.request("building/sync")

File $DIRPATH\arkprts\automation.py:173, in AutomationClient.request(self, endpoint, json, **kwargs)
    171 """Send an authenticated request to the arknights game server."""
    172 data = await super().request(endpoint, json=json, method="POST", **kwargs)
--> 173 self.update_player_data_delta(data["playerDataDelta"])
    174 if data.get("ts"):
    175     self.time_offset = data["ts"] - time.time()

File $DIRPATH\arkprts\automation.py:168, in AutomationClient.update_player_data_delta(self, delta)
    163 """Take a player data delta and update the player data.
    164 
    165 Does not implement deleted as it is often overwritten with "modified".
    166 """
    167 recursively_delete_dict(self.data, delta["deleted"])
--> 168 recursively_update_dict(self.data, delta["modified"])

File $DIRPATH\arkprts\automation.py:34, in recursively_update_dict(target, source)
     32 for key, value in source.items():
     33     if isinstance(value, dict):
---> 34         recursively_update_dict(target[key], typing.cast("dict[object, object]", value))
     35     elif isinstance(value, list):
     36         for i, v in enumerate(typing.cast("list[object]", value)):

File $DIRPATH\arkprts\automation.py:34, in recursively_update_dict(target, source)
     32 for key, value in source.items():
     33     if isinstance(value, dict):
---> 34         recursively_update_dict(target[key], typing.cast("dict[object, object]", value))
     35     elif isinstance(value, list):
     36         for i, v in enumerate(typing.cast("list[object]", value)):

    [... skipping similar frames: recursively_update_dict at line 34 (1 times)]

File $DIRPATH\arkprts\automation.py:34, in recursively_update_dict(target, source)
     32 for key, value in source.items():
     33     if isinstance(value, dict):
---> 34         recursively_update_dict(target[key], typing.cast("dict[object, object]", value))
     35     elif isinstance(value, list):
     36         for i, v in enumerate(typing.cast("list[object]", value)):

File $DIRPATH\arkprts\automation.py:38, in recursively_update_dict(target, source)
     36     for i, v in enumerate(typing.cast("list[object]", value)):
     37         if isinstance(v, dict):
---> 38             recursively_update_dict(target[key][i], typing.cast("dict[object, object]", v))
     39 else:
     40     target[key] = value

IndexError: list index out of range

Other functions seem to work, but if I can't get the status of the base then I don't understand how you're supposed to be able to practically use them.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.