welldungeon 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- welldungeon-0.1.0/.gitignore +18 -0
- welldungeon-0.1.0/LICENSE +21 -0
- welldungeon-0.1.0/PKG-INFO +152 -0
- welldungeon-0.1.0/README.md +124 -0
- welldungeon-0.1.0/pyproject.toml +61 -0
- welldungeon-0.1.0/src/welldungeon/__init__.py +65 -0
- welldungeon-0.1.0/src/welldungeon/_transport.py +76 -0
- welldungeon-0.1.0/src/welldungeon/async_client.py +102 -0
- welldungeon-0.1.0/src/welldungeon/client.py +102 -0
- welldungeon-0.1.0/src/welldungeon/enums.py +52 -0
- welldungeon-0.1.0/src/welldungeon/exceptions.py +100 -0
- welldungeon-0.1.0/src/welldungeon/items.py +105 -0
- welldungeon-0.1.0/src/welldungeon/models.py +149 -0
- welldungeon-0.1.0/tests/conftest.py +84 -0
- welldungeon-0.1.0/tests/test_client.py +149 -0
- welldungeon-0.1.0/tests/test_integration.py +84 -0
- welldungeon-0.1.0/tests/test_items.py +48 -0
- welldungeon-0.1.0/tests/test_transport.py +77 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Racoonchik
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: welldungeon
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python SDK для API игры «Подземелья Колодца» (sync + async)
|
|
5
|
+
Project-URL: Homepage, https://gitlab.com/Racoonchik/wd-api
|
|
6
|
+
Project-URL: Documentation, https://welldungeon.online/gtdoc/api
|
|
7
|
+
Project-URL: Repository, https://gitlab.com/Racoonchik/wd-api
|
|
8
|
+
Author: Racoonchik
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: api,game,sdk,vk,welldungeon
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.11
|
|
21
|
+
Requires-Dist: httpx>=0.27
|
|
22
|
+
Provides-Extra: dev
|
|
23
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
|
|
24
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
25
|
+
Requires-Dist: respx>=0.21; extra == 'dev'
|
|
26
|
+
Requires-Dist: ruff>=0.8; extra == 'dev'
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# wd-api
|
|
30
|
+
|
|
31
|
+
Python SDK для API игры [«Подземелья Колодца»](https://welldungeon.online/) с поддержкой **синхронного** и **асинхронного** режимов.
|
|
32
|
+
|
|
33
|
+
Документация API: https://welldungeon.online/gtdoc/api
|
|
34
|
+
|
|
35
|
+
## Установка
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install welldungeon
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Из GitLab (если нужна версия из репозитория):
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
pip install git+https://gitlab.com/Racoonchik/wd-api.git
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Для разработки:
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
pip install -e ".[dev]"
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Быстрый старт
|
|
54
|
+
|
|
55
|
+
Токен можно получить на странице https://welldungeon.online/?act=tokens
|
|
56
|
+
|
|
57
|
+
### Синхронный клиент
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
from welldungeon import Client
|
|
61
|
+
|
|
62
|
+
with Client(token="wd1_live_...") as client:
|
|
63
|
+
info = client.get_character_info()
|
|
64
|
+
print(f"{info.race}, уровень {info.level}")
|
|
65
|
+
|
|
66
|
+
inventory = client.get_inventory()
|
|
67
|
+
print(inventory.items)
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
### Асинхронный клиент
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
import asyncio
|
|
74
|
+
|
|
75
|
+
from welldungeon import AsyncClient
|
|
76
|
+
|
|
77
|
+
async def main():
|
|
78
|
+
async with AsyncClient(token="wd1_live_...") as client:
|
|
79
|
+
token_info = await client.token_info()
|
|
80
|
+
items = await client.lib_items()
|
|
81
|
+
print(token_info.rights, len(items))
|
|
82
|
+
|
|
83
|
+
asyncio.run(main())
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### Переменная окружения
|
|
87
|
+
|
|
88
|
+
```bash
|
|
89
|
+
export WELL_DUNGEON_TOKEN=wd1_live_...
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
from welldungeon import Client
|
|
94
|
+
|
|
95
|
+
client = Client() # токен из WELL_DUNGEON_TOKEN
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## Методы
|
|
99
|
+
|
|
100
|
+
| Метод Python | API | Право токена |
|
|
101
|
+
|---|---|---|
|
|
102
|
+
| `get_character_info()` | `GetCharacterInfo` | `character_info` |
|
|
103
|
+
| `get_inventory()` | `GetInventory` | `inventory_read` |
|
|
104
|
+
| `transfer_item_to_player(player_id, item_id, count=1)` | `TransferItemToPlayer` | `transfer_player_to_player` |
|
|
105
|
+
| `apply_social_effect_to_player(player_id, effect_type)` | `ApplySocialEffectToPlayer` | `social_effects_player_to_player` |
|
|
106
|
+
| `lib_items()` | `LibItems` | — |
|
|
107
|
+
| `token_info()` | `TokenInfo` | — |
|
|
108
|
+
| `get_log(start=0, limit=100)` | `Log` | — |
|
|
109
|
+
|
|
110
|
+
## Кэш справочника предметов
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
from welldungeon import Client, ItemsCache
|
|
114
|
+
|
|
115
|
+
with Client(token="...") as client:
|
|
116
|
+
cache = ItemsCache.fetch_and_save(client, "items_cache.json")
|
|
117
|
+
print(cache.get_title(13322)) # Золото
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
## Обработка ошибок
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
from welldungeon import Client, InvalidTokenError, ConditionsNotMetError
|
|
124
|
+
|
|
125
|
+
try:
|
|
126
|
+
client.token_info()
|
|
127
|
+
except InvalidTokenError as e:
|
|
128
|
+
print(e.code, e.message)
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
## Ограничения API
|
|
132
|
+
|
|
133
|
+
- Не более **3 запросов в секунду** с одного IP (в клиенте есть встроенный rate limiter).
|
|
134
|
+
- Токен можно привязать к белому списку IP-адресов.
|
|
135
|
+
- Храните токен в секрете.
|
|
136
|
+
|
|
137
|
+
## Разработка
|
|
138
|
+
|
|
139
|
+
```bash
|
|
140
|
+
ruff check src tests
|
|
141
|
+
pytest -m "not integration"
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
Интеграционные тесты (нужен реальный токен):
|
|
145
|
+
|
|
146
|
+
```bash
|
|
147
|
+
WELL_DUNGEON_TOKEN=wd1_live_... pytest -m integration
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
## Лицензия
|
|
151
|
+
|
|
152
|
+
MIT
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
# wd-api
|
|
2
|
+
|
|
3
|
+
Python SDK для API игры [«Подземелья Колодца»](https://welldungeon.online/) с поддержкой **синхронного** и **асинхронного** режимов.
|
|
4
|
+
|
|
5
|
+
Документация API: https://welldungeon.online/gtdoc/api
|
|
6
|
+
|
|
7
|
+
## Установка
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install welldungeon
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Из GitLab (если нужна версия из репозитория):
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pip install git+https://gitlab.com/Racoonchik/wd-api.git
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Для разработки:
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
pip install -e ".[dev]"
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Быстрый старт
|
|
26
|
+
|
|
27
|
+
Токен можно получить на странице https://welldungeon.online/?act=tokens
|
|
28
|
+
|
|
29
|
+
### Синхронный клиент
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from welldungeon import Client
|
|
33
|
+
|
|
34
|
+
with Client(token="wd1_live_...") as client:
|
|
35
|
+
info = client.get_character_info()
|
|
36
|
+
print(f"{info.race}, уровень {info.level}")
|
|
37
|
+
|
|
38
|
+
inventory = client.get_inventory()
|
|
39
|
+
print(inventory.items)
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
### Асинхронный клиент
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
import asyncio
|
|
46
|
+
|
|
47
|
+
from welldungeon import AsyncClient
|
|
48
|
+
|
|
49
|
+
async def main():
|
|
50
|
+
async with AsyncClient(token="wd1_live_...") as client:
|
|
51
|
+
token_info = await client.token_info()
|
|
52
|
+
items = await client.lib_items()
|
|
53
|
+
print(token_info.rights, len(items))
|
|
54
|
+
|
|
55
|
+
asyncio.run(main())
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
### Переменная окружения
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
export WELL_DUNGEON_TOKEN=wd1_live_...
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
from welldungeon import Client
|
|
66
|
+
|
|
67
|
+
client = Client() # токен из WELL_DUNGEON_TOKEN
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Методы
|
|
71
|
+
|
|
72
|
+
| Метод Python | API | Право токена |
|
|
73
|
+
|---|---|---|
|
|
74
|
+
| `get_character_info()` | `GetCharacterInfo` | `character_info` |
|
|
75
|
+
| `get_inventory()` | `GetInventory` | `inventory_read` |
|
|
76
|
+
| `transfer_item_to_player(player_id, item_id, count=1)` | `TransferItemToPlayer` | `transfer_player_to_player` |
|
|
77
|
+
| `apply_social_effect_to_player(player_id, effect_type)` | `ApplySocialEffectToPlayer` | `social_effects_player_to_player` |
|
|
78
|
+
| `lib_items()` | `LibItems` | — |
|
|
79
|
+
| `token_info()` | `TokenInfo` | — |
|
|
80
|
+
| `get_log(start=0, limit=100)` | `Log` | — |
|
|
81
|
+
|
|
82
|
+
## Кэш справочника предметов
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
from welldungeon import Client, ItemsCache
|
|
86
|
+
|
|
87
|
+
with Client(token="...") as client:
|
|
88
|
+
cache = ItemsCache.fetch_and_save(client, "items_cache.json")
|
|
89
|
+
print(cache.get_title(13322)) # Золото
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Обработка ошибок
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
from welldungeon import Client, InvalidTokenError, ConditionsNotMetError
|
|
96
|
+
|
|
97
|
+
try:
|
|
98
|
+
client.token_info()
|
|
99
|
+
except InvalidTokenError as e:
|
|
100
|
+
print(e.code, e.message)
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## Ограничения API
|
|
104
|
+
|
|
105
|
+
- Не более **3 запросов в секунду** с одного IP (в клиенте есть встроенный rate limiter).
|
|
106
|
+
- Токен можно привязать к белому списку IP-адресов.
|
|
107
|
+
- Храните токен в секрете.
|
|
108
|
+
|
|
109
|
+
## Разработка
|
|
110
|
+
|
|
111
|
+
```bash
|
|
112
|
+
ruff check src tests
|
|
113
|
+
pytest -m "not integration"
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Интеграционные тесты (нужен реальный токен):
|
|
117
|
+
|
|
118
|
+
```bash
|
|
119
|
+
WELL_DUNGEON_TOKEN=wd1_live_... pytest -m integration
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
## Лицензия
|
|
123
|
+
|
|
124
|
+
MIT
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "welldungeon"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Python SDK для API игры «Подземелья Колодца» (sync + async)"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.11"
|
|
12
|
+
authors = [{ name = "Racoonchik" }]
|
|
13
|
+
keywords = ["welldungeon", "api", "sdk", "vk", "game"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 3 - Alpha",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"License :: OSI Approved :: MIT License",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Programming Language :: Python :: 3.11",
|
|
20
|
+
"Programming Language :: Python :: 3.12",
|
|
21
|
+
"Programming Language :: Python :: 3.13",
|
|
22
|
+
"Typing :: Typed",
|
|
23
|
+
]
|
|
24
|
+
dependencies = [
|
|
25
|
+
"httpx>=0.27",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
[project.optional-dependencies]
|
|
29
|
+
dev = [
|
|
30
|
+
"pytest>=8.0",
|
|
31
|
+
"pytest-asyncio>=0.24",
|
|
32
|
+
"respx>=0.21",
|
|
33
|
+
"ruff>=0.8",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
[project.urls]
|
|
37
|
+
Homepage = "https://gitlab.com/Racoonchik/wd-api"
|
|
38
|
+
Documentation = "https://welldungeon.online/gtdoc/api"
|
|
39
|
+
Repository = "https://gitlab.com/Racoonchik/wd-api"
|
|
40
|
+
|
|
41
|
+
[tool.hatch.build.targets.wheel]
|
|
42
|
+
packages = ["src/welldungeon"]
|
|
43
|
+
|
|
44
|
+
[tool.hatch.build.targets.sdist]
|
|
45
|
+
only-include = ["src/welldungeon", "tests", "README.md", "LICENSE", "pyproject.toml"]
|
|
46
|
+
|
|
47
|
+
[tool.pytest.ini_options]
|
|
48
|
+
testpaths = ["tests"]
|
|
49
|
+
asyncio_mode = "auto"
|
|
50
|
+
asyncio_default_fixture_loop_scope = "session"
|
|
51
|
+
markers = [
|
|
52
|
+
"integration: интеграционные тесты (требуют WELL_DUNGEON_TOKEN)",
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
[tool.ruff]
|
|
56
|
+
target-version = "py311"
|
|
57
|
+
line-length = 100
|
|
58
|
+
src = ["src", "tests"]
|
|
59
|
+
|
|
60
|
+
[tool.ruff.lint]
|
|
61
|
+
select = ["E", "F", "I", "UP", "B", "SIM"]
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Python SDK для API игры «Подземелья Колодца»."""
|
|
2
|
+
|
|
3
|
+
from welldungeon.async_client import AsyncClient
|
|
4
|
+
from welldungeon.client import Client
|
|
5
|
+
from welldungeon.enums import ErrorCode, SocialEffectType, TokenScope
|
|
6
|
+
from welldungeon.exceptions import (
|
|
7
|
+
ConditionsNotMetError,
|
|
8
|
+
ForbiddenScopeError,
|
|
9
|
+
GuildPermissionDeniedError,
|
|
10
|
+
InsufficientVoicesError,
|
|
11
|
+
InternalError,
|
|
12
|
+
InvalidTokenError,
|
|
13
|
+
InventoryError,
|
|
14
|
+
OnCooldownError,
|
|
15
|
+
TargetNotFoundError,
|
|
16
|
+
TooManyRequestsError,
|
|
17
|
+
UnderConstructionError,
|
|
18
|
+
UnknownMethodError,
|
|
19
|
+
ValidationError,
|
|
20
|
+
WellDungeonError,
|
|
21
|
+
WrongIpError,
|
|
22
|
+
raise_for_error,
|
|
23
|
+
)
|
|
24
|
+
from welldungeon.items import ItemsCache
|
|
25
|
+
from welldungeon.models import (
|
|
26
|
+
CharacterInfo,
|
|
27
|
+
GuildInfo,
|
|
28
|
+
Inventory,
|
|
29
|
+
ItemInfo,
|
|
30
|
+
LogEntry,
|
|
31
|
+
TokenInfo,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
__all__ = [
|
|
35
|
+
"AsyncClient",
|
|
36
|
+
"CharacterInfo",
|
|
37
|
+
"Client",
|
|
38
|
+
"ConditionsNotMetError",
|
|
39
|
+
"ErrorCode",
|
|
40
|
+
"ForbiddenScopeError",
|
|
41
|
+
"GuildInfo",
|
|
42
|
+
"GuildPermissionDeniedError",
|
|
43
|
+
"InsufficientVoicesError",
|
|
44
|
+
"InternalError",
|
|
45
|
+
"InventoryError",
|
|
46
|
+
"InvalidTokenError",
|
|
47
|
+
"ItemInfo",
|
|
48
|
+
"ItemsCache",
|
|
49
|
+
"LogEntry",
|
|
50
|
+
"OnCooldownError",
|
|
51
|
+
"SocialEffectType",
|
|
52
|
+
"TargetNotFoundError",
|
|
53
|
+
"TokenInfo",
|
|
54
|
+
"TokenScope",
|
|
55
|
+
"TooManyRequestsError",
|
|
56
|
+
"UnderConstructionError",
|
|
57
|
+
"UnknownMethodError",
|
|
58
|
+
"ValidationError",
|
|
59
|
+
"WellDungeonError",
|
|
60
|
+
"WrongIpError",
|
|
61
|
+
"Inventory",
|
|
62
|
+
"raise_for_error",
|
|
63
|
+
]
|
|
64
|
+
|
|
65
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Общая логика HTTP-транспорта и rate limiting."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import os
|
|
7
|
+
import time
|
|
8
|
+
from collections import deque
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from welldungeon.exceptions import raise_for_error
|
|
12
|
+
|
|
13
|
+
DEFAULT_BASE_URL = "https://welldungeon.online/api/v1"
|
|
14
|
+
DEFAULT_RATE_LIMIT = 3.0 # запросов в секунду
|
|
15
|
+
TOKEN_ENV_VAR = "WELL_DUNGEON_TOKEN"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class RateLimiter:
|
|
19
|
+
"""Ограничитель частоты запросов (sliding window)."""
|
|
20
|
+
|
|
21
|
+
def __init__(self, rate: float = DEFAULT_RATE_LIMIT, per: float = 1.0) -> None:
|
|
22
|
+
self.rate = rate
|
|
23
|
+
self.per = per
|
|
24
|
+
self._timestamps: deque[float] = deque()
|
|
25
|
+
self._lock = asyncio.Lock()
|
|
26
|
+
|
|
27
|
+
def _prune(self, now: float) -> None:
|
|
28
|
+
while self._timestamps and now - self._timestamps[0] >= self.per:
|
|
29
|
+
self._timestamps.popleft()
|
|
30
|
+
|
|
31
|
+
def acquire_sync(self) -> None:
|
|
32
|
+
while True:
|
|
33
|
+
now = time.monotonic()
|
|
34
|
+
self._prune(now)
|
|
35
|
+
if len(self._timestamps) < self.rate:
|
|
36
|
+
self._timestamps.append(now)
|
|
37
|
+
return
|
|
38
|
+
sleep_for = self.per - (now - self._timestamps[0])
|
|
39
|
+
if sleep_for > 0:
|
|
40
|
+
time.sleep(sleep_for)
|
|
41
|
+
|
|
42
|
+
async def acquire_async(self) -> None:
|
|
43
|
+
while True:
|
|
44
|
+
async with self._lock:
|
|
45
|
+
now = time.monotonic()
|
|
46
|
+
self._prune(now)
|
|
47
|
+
if len(self._timestamps) < self.rate:
|
|
48
|
+
self._timestamps.append(now)
|
|
49
|
+
return
|
|
50
|
+
sleep_for = self.per - (now - self._timestamps[0])
|
|
51
|
+
if sleep_for > 0:
|
|
52
|
+
await asyncio.sleep(sleep_for)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def resolve_token(token: str | None) -> str:
|
|
56
|
+
resolved = token or os.environ.get(TOKEN_ENV_VAR)
|
|
57
|
+
if not resolved:
|
|
58
|
+
msg = (
|
|
59
|
+
"Токен не указан. Передайте token= в конструктор клиента "
|
|
60
|
+
f"или установите переменную окружения {TOKEN_ENV_VAR}."
|
|
61
|
+
)
|
|
62
|
+
raise ValueError(msg)
|
|
63
|
+
return resolved
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def parse_response(payload: dict[str, Any]) -> dict[str, Any]:
|
|
67
|
+
if payload.get("result") != 1:
|
|
68
|
+
raise_for_error(payload)
|
|
69
|
+
return payload
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def build_params(token: str, extra: dict[str, Any] | None = None) -> dict[str, Any]:
|
|
73
|
+
params: dict[str, Any] = {"token": token}
|
|
74
|
+
if extra:
|
|
75
|
+
params.update(extra)
|
|
76
|
+
return params
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Асинхронный клиент API «Подземелья Колодца»."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
from welldungeon._transport import (
|
|
10
|
+
DEFAULT_BASE_URL,
|
|
11
|
+
DEFAULT_RATE_LIMIT,
|
|
12
|
+
RateLimiter,
|
|
13
|
+
build_params,
|
|
14
|
+
parse_response,
|
|
15
|
+
resolve_token,
|
|
16
|
+
)
|
|
17
|
+
from welldungeon.enums import SocialEffectType
|
|
18
|
+
from welldungeon.models import CharacterInfo, Inventory, ItemInfo, LogEntry, TokenInfo
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class AsyncClient:
|
|
22
|
+
"""Асинхронный клиент Well Dungeon API."""
|
|
23
|
+
|
|
24
|
+
def __init__(
|
|
25
|
+
self,
|
|
26
|
+
token: str | None = None,
|
|
27
|
+
*,
|
|
28
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
29
|
+
rate_limit: float = DEFAULT_RATE_LIMIT,
|
|
30
|
+
timeout: float = 30.0,
|
|
31
|
+
http_client: httpx.AsyncClient | None = None,
|
|
32
|
+
) -> None:
|
|
33
|
+
self._token = resolve_token(token)
|
|
34
|
+
self._base_url = base_url.rstrip("/")
|
|
35
|
+
self._rate_limiter = RateLimiter(rate=rate_limit)
|
|
36
|
+
self._owns_client = http_client is None
|
|
37
|
+
self._http = http_client or httpx.AsyncClient(timeout=timeout)
|
|
38
|
+
|
|
39
|
+
async def aclose(self) -> None:
|
|
40
|
+
if self._owns_client:
|
|
41
|
+
await self._http.aclose()
|
|
42
|
+
|
|
43
|
+
async def __aenter__(self) -> AsyncClient:
|
|
44
|
+
return self
|
|
45
|
+
|
|
46
|
+
async def __aexit__(self, *args: object) -> None:
|
|
47
|
+
await self.aclose()
|
|
48
|
+
|
|
49
|
+
async def _request(self, method: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
|
|
50
|
+
await self._rate_limiter.acquire_async()
|
|
51
|
+
response = await self._http.get(
|
|
52
|
+
f"{self._base_url}/{method}",
|
|
53
|
+
params=build_params(self._token, params),
|
|
54
|
+
)
|
|
55
|
+
response.raise_for_status()
|
|
56
|
+
return parse_response(response.json())
|
|
57
|
+
|
|
58
|
+
async def get_character_info(self) -> CharacterInfo:
|
|
59
|
+
payload = await self._request("GetCharacterInfo")
|
|
60
|
+
return CharacterInfo.from_dict(payload["info"])
|
|
61
|
+
|
|
62
|
+
async def get_inventory(self) -> Inventory:
|
|
63
|
+
payload = await self._request("GetInventory")
|
|
64
|
+
return Inventory.from_dict(payload)
|
|
65
|
+
|
|
66
|
+
async def transfer_item_to_player(
|
|
67
|
+
self,
|
|
68
|
+
player_id: int,
|
|
69
|
+
item_id: int,
|
|
70
|
+
count: int = 1,
|
|
71
|
+
) -> dict[str, Any]:
|
|
72
|
+
if not 1 <= count <= 9999:
|
|
73
|
+
raise ValueError("count должен быть в диапазоне 1–9999")
|
|
74
|
+
return await self._request(
|
|
75
|
+
"TransferItemToPlayer",
|
|
76
|
+
{"player_id": player_id, "item_id": item_id, "count": count},
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
async def apply_social_effect_to_player(
|
|
80
|
+
self,
|
|
81
|
+
player_id: int,
|
|
82
|
+
effect_type: SocialEffectType | str,
|
|
83
|
+
) -> dict[str, Any]:
|
|
84
|
+
effect = effect_type.value if isinstance(effect_type, SocialEffectType) else effect_type
|
|
85
|
+
return await self._request(
|
|
86
|
+
"ApplySocialEffectToPlayer",
|
|
87
|
+
{"player_id": player_id, "type": effect},
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
async def lib_items(self) -> dict[int, ItemInfo]:
|
|
91
|
+
payload = await self._request("LibItems")
|
|
92
|
+
raw_items = payload.get("items") or {}
|
|
93
|
+
return {int(item_id): ItemInfo.from_dict(info) for item_id, info in raw_items.items()}
|
|
94
|
+
|
|
95
|
+
async def token_info(self) -> TokenInfo:
|
|
96
|
+
payload = await self._request("TokenInfo")
|
|
97
|
+
return TokenInfo.from_dict(payload)
|
|
98
|
+
|
|
99
|
+
async def get_log(self, start: int = 0, limit: int = 100) -> list[LogEntry]:
|
|
100
|
+
payload = await self._request("Log", {"start": start, "limit": limit})
|
|
101
|
+
logs = payload.get("logs") or []
|
|
102
|
+
return [LogEntry.from_dict(entry) for entry in logs]
|