Skip to content

Commit 859dd2a

Browse files
committed
initial commit
0 parents  commit 859dd2a

15 files changed

+691
-0
lines changed

.gitignore

+209
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,209 @@
1+
# Created by https://www.toptal.com/developers/gitignore/api/python,macos
2+
# Edit at https://www.toptal.com/developers/gitignore?templates=python,macos
3+
4+
### macOS ###
5+
# General
6+
.DS_Store
7+
.AppleDouble
8+
.LSOverride
9+
10+
# Icon must end with two \r
11+
Icon
12+
13+
14+
# Thumbnails
15+
._*
16+
17+
# Files that might appear in the root of a volume
18+
.DocumentRevisions-V100
19+
.fseventsd
20+
.Spotlight-V100
21+
.TemporaryItems
22+
.Trashes
23+
.VolumeIcon.icns
24+
.com.apple.timemachine.donotpresent
25+
26+
# Directories potentially created on remote AFP share
27+
.AppleDB
28+
.AppleDesktop
29+
Network Trash Folder
30+
Temporary Items
31+
.apdisk
32+
33+
### macOS Patch ###
34+
# iCloud generated files
35+
*.icloud
36+
37+
### Python ###
38+
# Byte-compiled / optimized / DLL files
39+
__pycache__/
40+
*.py[cod]
41+
*$py.class
42+
43+
# C extensions
44+
*.so
45+
46+
# Distribution / packaging
47+
.Python
48+
build/
49+
develop-eggs/
50+
dist/
51+
downloads/
52+
eggs/
53+
.eggs/
54+
lib/
55+
lib64/
56+
parts/
57+
sdist/
58+
var/
59+
wheels/
60+
share/python-wheels/
61+
*.egg-info/
62+
.installed.cfg
63+
*.egg
64+
MANIFEST
65+
66+
# PyInstaller
67+
# Usually these files are written by a python script from a template
68+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
69+
*.manifest
70+
*.spec
71+
72+
# Installer logs
73+
pip-log.txt
74+
pip-delete-this-directory.txt
75+
76+
# Unit test / coverage reports
77+
htmlcov/
78+
.tox/
79+
.nox/
80+
.coverage
81+
.coverage.*
82+
.cache
83+
nosetests.xml
84+
coverage.xml
85+
*.cover
86+
*.py,cover
87+
.hypothesis/
88+
.pytest_cache/
89+
cover/
90+
91+
# Translations
92+
*.mo
93+
*.pot
94+
95+
# Django stuff:
96+
*.log
97+
local_settings.py
98+
db.sqlite3
99+
db.sqlite3-journal
100+
101+
# Flask stuff:
102+
instance/
103+
.webassets-cache
104+
105+
# Scrapy stuff:
106+
.scrapy
107+
108+
# Sphinx documentation
109+
docs/_build/
110+
111+
# PyBuilder
112+
.pybuilder/
113+
target/
114+
115+
# Jupyter Notebook
116+
.ipynb_checkpoints
117+
118+
# IPython
119+
profile_default/
120+
ipython_config.py
121+
122+
# pyenv
123+
# For a library or package, you might want to ignore these files since the code is
124+
# intended to run in multiple environments; otherwise, check them in:
125+
# .python-version
126+
127+
# pipenv
128+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
129+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
130+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
131+
# install all needed dependencies.
132+
#Pipfile.lock
133+
134+
# poetry
135+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
136+
# This is especially recommended for binary packages to ensure reproducibility, and is more
137+
# commonly ignored for libraries.
138+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
139+
#poetry.lock
140+
141+
# pdm
142+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
143+
#pdm.lock
144+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
145+
# in version control.
146+
# https://pdm.fming.dev/#use-with-ide
147+
.pdm.toml
148+
149+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
150+
__pypackages__/
151+
152+
# Celery stuff
153+
celerybeat-schedule
154+
celerybeat.pid
155+
156+
# SageMath parsed files
157+
*.sage.py
158+
159+
# Environments
160+
.env
161+
.venv
162+
env/
163+
venv/
164+
ENV/
165+
env.bak/
166+
venv.bak/
167+
168+
# Spyder project settings
169+
.spyderproject
170+
.spyproject
171+
172+
# Rope project settings
173+
.ropeproject
174+
175+
# mkdocs documentation
176+
/site
177+
178+
# mypy
179+
.mypy_cache/
180+
.dmypy.json
181+
dmypy.json
182+
183+
# Pyre type checker
184+
.pyre/
185+
186+
# pytype static type analyzer
187+
.pytype/
188+
189+
# Cython debug symbols
190+
cython_debug/
191+
192+
# PyCharm
193+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
194+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
195+
# and can be added to the global gitignore or merged into this file. For a more nuclear
196+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
197+
#.idea/
198+
199+
### Python Patch ###
200+
# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
201+
poetry.toml
202+
203+
# ruff
204+
.ruff_cache/
205+
206+
# LSP config files
207+
pyrightconfig.json
208+
209+
# End of https://www.toptal.com/developers/gitignore/api/python,macos

LICENSE

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2023 Jonghwan Hyeon
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.

README.md

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# python-chzzk
2+
An unofficial Python library for CHZZK. **Caution**: APIs are currently experimental.
3+
4+
## Requirements
5+
- Python 3.8+
6+
7+
## Installation
8+
```python
9+
pip install chzzk
10+
```
11+
12+
## Usage
13+
```python
14+
import asyncio
15+
16+
from chzzk import Chzzk, Credential
17+
18+
19+
async def main():
20+
credential = Credential(
21+
nid_auth="Your NID_AUT",
22+
nid_session="Your NID_SES",
23+
)
24+
chzzk = Chzzk(credential)
25+
26+
print(await chzzk.channel("bdc57cc4217173f0e89f63fba2f1c6e5"))
27+
print(await chzzk.video(1794))
28+
29+
30+
if __name__ == "__main__":
31+
asyncio.run(main())
32+
```
33+
34+
## Acknowledgement
35+
- Thanks [kimcore/chzzk](https://github.com/kimcore/chzzk) for sharing API urls and explaining how it works.

chzzk/__init__.py

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
from chzzk.chzzk import Chzzk
2+
from chzzk.client import Credential
3+
4+
__version__ = "0.0.2"

chzzk/chzzk.py

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
from typing import Optional
2+
3+
from chzzk.client import ChzzkClient, Credential, GameClient
4+
from chzzk.models import Channel, User, Video
5+
from chzzk.models import raw as r
6+
7+
8+
class Chzzk:
9+
def __init__(self, credential: Optional[Credential] = None):
10+
self._client = ChzzkClient(credential)
11+
self._game = Game(credential)
12+
13+
async def me(self) -> User:
14+
return await self._game.me()
15+
16+
async def channel(self, id: str) -> Channel:
17+
response = await self._client.get(f"service/v1/channels/{id}")
18+
return r.Channel(**response).wrap()
19+
20+
async def video(self, no: int) -> Video:
21+
response = await self._client.get(f"service/v1/videos/{no}")
22+
return r.Video(**response).wrap()
23+
24+
25+
class Game:
26+
def __init__(self, credential: Optional[Credential] = None):
27+
self._client = GameClient(credential)
28+
29+
async def me(self) -> User:
30+
response = await self._client.get("v1/user/getUserStatus")
31+
return r.User(**response).wrap()

chzzk/client.py

+92
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
from dataclasses import dataclass
2+
from typing import Any, ClassVar, Mapping, Optional
3+
from urllib.parse import urljoin
4+
5+
import httpx
6+
7+
from chzzk.errors import ChzzkHTTPError
8+
9+
10+
@dataclass
11+
class Credential:
12+
nid_auth: str
13+
nid_session: str
14+
15+
def as_cookie(self) -> dict[str, str]:
16+
return {
17+
"NID_AUT": self.nid_auth,
18+
"NID_SES": self.nid_session,
19+
}
20+
21+
22+
class HTTPClient:
23+
BASE_URL: ClassVar[str]
24+
25+
def __init__(self, credential: Optional[Credential] = None):
26+
assert self.BASE_URL.endswith("/")
27+
28+
self._credential = credential
29+
self._client = httpx.AsyncClient()
30+
31+
if self._credential is not None:
32+
self._client.cookies.update(self._credential.as_cookie())
33+
34+
async def request(
35+
self,
36+
method: str,
37+
url: str,
38+
*,
39+
params: Optional[Mapping[str, Any]] = None,
40+
data: Optional[Mapping[str, Any]] = None,
41+
**kwargs,
42+
) -> Any:
43+
raw_response = await self._client.request(
44+
method=method,
45+
url=urljoin(self.BASE_URL, url),
46+
params=params,
47+
data=data,
48+
**kwargs,
49+
)
50+
51+
if raw_response.status_code != 200:
52+
raise ChzzkHTTPError(message="Server did not return a successful response", code=raw_response.status_code)
53+
54+
response = raw_response.json()
55+
if response["code"] != 200:
56+
raise ChzzkHTTPError(message=response["message"], code=response["code"])
57+
58+
return response["content"]
59+
60+
async def get(
61+
self,
62+
url: str,
63+
*,
64+
params: Optional[Mapping[str, Any]] = None,
65+
data: Optional[Mapping[str, Any]] = None,
66+
**kwargs,
67+
) -> Any:
68+
return await self.request("GET", url, params=params, data=data, **kwargs)
69+
70+
async def post(
71+
self,
72+
url: str,
73+
*,
74+
params: Optional[Mapping[str, Any]] = None,
75+
data: Optional[Mapping[str, Any]] = None,
76+
**kwargs,
77+
) -> Any:
78+
return await self.request("POST", url, params=params, data=data, **kwargs)
79+
80+
81+
class GameClient(HTTPClient):
82+
BASE_URL = "https://comm-api.game.naver.com/nng_main/"
83+
84+
def __init__(self, credential: Optional[Credential] = None):
85+
super().__init__(credential)
86+
87+
88+
class ChzzkClient(HTTPClient):
89+
BASE_URL = "https://api.chzzk.naver.com/"
90+
91+
def __init__(self, credential: Optional[Credential] = None):
92+
super().__init__(credential)

0 commit comments

Comments
 (0)