neuroinfoapi-client 2.10.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.
@@ -0,0 +1,19 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ .eggs/
6
+ build/
7
+ dist/
8
+ .venv/
9
+ venv/
10
+ .pytest_cache/
11
+ .mypy_cache/
12
+ .ruff_cache/
13
+ .coverage
14
+ htmlcov/
15
+
16
+ # Environment files
17
+ .env
18
+ .env.*
19
+ !.env.example
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Appstun
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,322 @@
1
+ Metadata-Version: 2.5
2
+ Name: neuroinfoapi-client
3
+ Version: 2.10.0
4
+ Summary: Python client for NeuroInfoAPI: typed HTTP client (sync and async) and a WebSocket client with auto reconnect
5
+ Project-URL: Homepage, https://neuroinfoapi.dev/api/docs
6
+ Project-URL: Documentation, https://neuroinfoapi.dev/api/docs
7
+ Project-URL: Repository, https://github.com/NeuroInfoAPI/Python-Package
8
+ Project-URL: Issues, https://github.com/NeuroInfoAPI/Python-Package/issues
9
+ Author: Appstun
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: api,client,neuro-sama,neuroinfoapi,twitch,websocket
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Framework :: AsyncIO
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Typing :: Typed
20
+ Requires-Python: >=3.10
21
+ Requires-Dist: httpx>=0.27
22
+ Requires-Dist: typing-extensions>=4.10
23
+ Requires-Dist: websockets>=14.1
24
+ Provides-Extra: dev
25
+ Requires-Dist: build; extra == 'dev'
26
+ Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
27
+ Requires-Dist: pytest>=8; extra == 'dev'
28
+ Description-Content-Type: text/markdown
29
+
30
+ # neuroinfoapi-client (Python)
31
+
32
+ Python client for the [NeuroInfoAPI](https://neuroinfoapi.dev/api/docs).
33
+
34
+ ## Features
35
+
36
+ - HTTP access to streams, VODs, schedules, subathons, shop products, blog and X feeds
37
+ - Synchronous **and** `asyncio` HTTP client with the same methods
38
+ - Methods return the data directly; errors are raised as `NeuroApiError`
39
+ - Typed responses (`TypedDict`) for editor autocompletion
40
+ - Configurable API base URL and request timeout (10 seconds by default)
41
+ - WebSocket client for real-time events: just call `ws.run()` (no `asyncio` needed) or use it
42
+ from async code; header or ticket auth, automatic reconnect, subscription recovery and heartbeat
43
+
44
+ ## Installation
45
+ Requires Python 3.10 or newer.
46
+
47
+ ```bash
48
+ pip install neuroinfoapi-client
49
+ ```
50
+
51
+ ## Quick Start
52
+
53
+ ```python
54
+ from neuroinfoapi_client import NeuroInfoApiClient, utils
55
+
56
+ client = NeuroInfoApiClient() # no token needed for public endpoints
57
+ # client = NeuroInfoApiClient("YOUR_API_TOKEN") # token required for some endpoints, see below
58
+
59
+ stream = client.get_current_stream() # raises NeuroApiError if something goes wrong
60
+ if utils.is_live(stream):
61
+ print("Live:", stream["title"], stream["viewerCount"])
62
+ else:
63
+ print("Stream is offline")
64
+ ```
65
+
66
+ Real-time events via WebSocket:
67
+
68
+ ```python
69
+ from neuroinfoapi_client import NeuroInfoApiWebsocketClient
70
+
71
+ ws = NeuroInfoApiWebsocketClient("YOUR_API_TOKEN")
72
+
73
+ @ws.on("streamOnline")
74
+ def on_online(data, timestamp):
75
+ print("Neuro is live:", data["title"])
76
+
77
+ ws.run() # blocks until Ctrl+C
78
+ ```
79
+
80
+ ### Async
81
+
82
+ ```python
83
+ import asyncio
84
+ from neuroinfoapi_client import AsyncNeuroInfoApiClient
85
+
86
+
87
+ async def main():
88
+ async with AsyncNeuroInfoApiClient() as client:
89
+ schedule = await client.get_latest_schedule()
90
+ for entry in schedule["schedule"]:
91
+ print(entry["day"], entry["message"])
92
+
93
+
94
+ asyncio.run(main())
95
+ ```
96
+
97
+ ## Client Configuration
98
+
99
+ ```python
100
+ NeuroInfoApiClient(token=None, *, api_base_url=None, use_tls=None, timeout=None)
101
+ ```
102
+
103
+ | Option | Default | Description |
104
+ | -------------- | ------------------------- | ---------------------------------------- |
105
+ | `api_base_url` | `neuroinfoapi.dev/api/v2` | API host and path without a protocol |
106
+ | `use_tls` | `True` | Use HTTPS when `True`, HTTP when `False` |
107
+ | `timeout` | `10` | HTTP request timeout in **seconds** |
108
+
109
+ ```python
110
+ # Token later
111
+ client = NeuroInfoApiClient()
112
+ client.set_api_token("YOUR_API_TOKEN")
113
+
114
+ # Local Mock-TestServer (https://github.com/NeuroInfoAPI/Mock-TestServer)
115
+ client = NeuroInfoApiClient(api_base_url="localhost:8787/api/v2", use_tls=False, timeout=15)
116
+ ```
117
+
118
+ Both clients keep a connection pool open. Use them with `with` / `async with`, or call
119
+ `client.close()` / `await client.aclose()` when you are done.
120
+
121
+ ## Error Handling
122
+
123
+ All errors are raised as `NeuroApiError` with `code`, `message` and the optional `status`,
124
+ `timestamp` and `path`:
125
+
126
+ ```python
127
+ from neuroinfoapi_client import NeuroApiError, NeuroInfoApiClient
128
+
129
+ client = NeuroInfoApiClient()
130
+
131
+ try:
132
+ subathons = client.get_current_subathons()
133
+ except NeuroApiError as error:
134
+ if error.code == "SB1":
135
+ print("No subathon right now")
136
+ else:
137
+ print(error.code, error.message)
138
+ else:
139
+ for subathon in subathons: # editor knows this is list[SubathonData]
140
+ print(subathon["name"], subathon["subcount"])
141
+ ```
142
+
143
+ Client error codes: `NETWORK` (connection problem or timeout), `HTTP_ERROR` (non-2xx without an
144
+ API error body), `INVALID_JSON`. All other codes come from the API.
145
+
146
+ > **Typing tip:** use `utils.is_live(stream)` (or `stream["isLive"] is True`, not just
147
+ > `if stream["isLive"]:`) so the editor knows live-only keys like `viewerCount` exist.
148
+
149
+ ## HTTP API Methods
150
+
151
+ | Python | Endpoint |
152
+ | ---------------------------------------------------------------- | ------------------------------------------------------------------------- |
153
+ | `get_current_stream()` | Current Twitch stream state |
154
+ | `get_schedule_linked_streams()` | Channels watched because of a schedule entry |
155
+ | `get_all_vods()` | All Twitch VODs (**token required**) |
156
+ | `get_vod(id)` | A VOD by stream ID (**token required**) |
157
+ | `get_schedule(week, year=None)` | Schedule for a specific week (**token required**) |
158
+ | `get_latest_schedule()` | Latest schedule |
159
+ | `get_schedule_weeks()` | Available schedule weeks grouped by year |
160
+ | `get_devstream_times()` | Devstream timestamps |
161
+ | `get_schedule_search(query, *, limit, year, sort, type, cursor)` | Search schedules (cursor pagination) (**token required**) |
162
+ | `get_current_subathons()` | Currently active subathons |
163
+ | `get_subathon(year)` | Subathon of a specific year (**token required**) |
164
+ | `get_subathon_years()` | Years with subathon data |
165
+ | `get_blog_feed(raw=False)` | Neuro-sama blog feed (**token required**) |
166
+ | `get_x_feed(user)` | X feed of `NeurosamaAI`, `EvilNeuroAI` or `Vedal987` (**token required**) |
167
+ | `get_shop_products(currency=None)` | Shop catalog (**token required**) |
168
+ | `get_shop_product(id, currency=None)` | A shop product (**token required**) |
169
+ | `request(path, params=None)` | Raw GET request to an API path such as `/twitch/stream` |
170
+
171
+ The response data is plain `dict`/`list` from JSON; keys are the same as in the API (camelCase).
172
+ Timestamps are Unix timestamps in milliseconds.
173
+
174
+ Search with pagination (needs a client with a token):
175
+
176
+ ```python
177
+ cursor = None
178
+ while True:
179
+ page = client.get_schedule_search("minecraft", limit=10, cursor=cursor)
180
+ for result in page["results"]:
181
+ print(result["data"]["year"], result["data"]["week"], result["foundDays"])
182
+ cursor = page["nextCursor"]
183
+ if cursor is None:
184
+ break
185
+ ```
186
+
187
+ ## WebSocket Client
188
+
189
+ The WebSocket client needs an API token.
190
+
191
+ ```python
192
+ from neuroinfoapi_client import NeuroInfoApiWebsocketClient
193
+
194
+ ws = NeuroInfoApiWebsocketClient("YOUR_API_TOKEN")
195
+
196
+ @ws.on("streamOnline")
197
+ def on_online(data, timestamp):
198
+ print("Neuro is live:", data["title"])
199
+
200
+ @ws.on("streamOffline")
201
+ def on_offline(data, timestamp):
202
+ print("Stream ended")
203
+ # ws.stop() # would end ws.run()
204
+
205
+ ws.on("_connected", lambda session_id: print("Connected:", session_id))
206
+ ws.on("_error", lambda error: print("Error:", error))
207
+
208
+ ws.run() # blocks; raises NeuroApiError if the first connection fails
209
+ ```
210
+
211
+ `ws.run()` returns after Ctrl+C, after `ws.stop()` (works from callbacks and other threads) or
212
+ when reconnecting gave up. Long-running work inside a callback pauses the client, so keep
213
+ callbacks short or start a thread for heavy work.
214
+
215
+ ### In async code
216
+
217
+ ```python
218
+ import asyncio
219
+ from neuroinfoapi_client import NeuroInfoApiWebsocketClient
220
+
221
+
222
+ async def main():
223
+ ws = NeuroInfoApiWebsocketClient("YOUR_API_TOKEN")
224
+
225
+ @ws.on("streamOnline")
226
+ async def on_online(data, timestamp): # async callbacks work too
227
+ print("Neuro is live:", data["title"])
228
+
229
+ await ws.connect() # raises NeuroApiError if the first connection fails
230
+ await ws.wait_closed() # runs until disconnect() or reconnecting gave up
231
+
232
+
233
+ asyncio.run(main())
234
+ ```
235
+
236
+ ### Events
237
+
238
+ `ws.on(event, callback)` returns an unsubscribe function; `ws.on(event)` without a callback
239
+ works as a decorator. Data events are subscribed on the server automatically and re-subscribed
240
+ after every reconnect.
241
+
242
+ Data events (callback gets `data, timestamp`):
243
+ `streamOnline`, `streamOffline`, `streamUpdate`, `secretneuroaccountOnline`,
244
+ `scheduleLinkedStreamOnline`, `scheduleLinkedStreamUpdate`, `scheduleLinkedStreamOffline`,
245
+ `streamRaidIncoming`, `streamRaidOutgoing`, `scheduleUpdate`, `subathonUpdate`,
246
+ `subathonGoalUpdate`, `blogFeedUpdate`, `xFeedNewEntries`, `shopProductsUpdate`
247
+ (`xFeedUpdate` is deprecated).
248
+
249
+ System events:
250
+
251
+ | Event | Callback arguments |
252
+ | ------------------ | ------------------------------------- |
253
+ | `_connected` | `session_id` |
254
+ | `_disconnected` | `code, reason` |
255
+ | `_reconnecting` | `attempt, delay_seconds` |
256
+ | `_reconnectFailed` | - |
257
+ | `_error` | `error` |
258
+ | `_message` | `message` (every raw message as dict) |
259
+ | `_pong` | - |
260
+ | `_eventAdded` | `event_type` |
261
+ | `_eventRemoved` | `event_type` |
262
+
263
+ Options (all durations in **seconds**):
264
+
265
+ | Option | Default | Description |
266
+ | ------------------------- | ---------- | ----------------------------------------------------------------- |
267
+ | `api_base_url`, `use_tls` | - | Same as the HTTP client |
268
+ | `websocket_url` | derived | Full WebSocket URL override |
269
+ | `auth_method` | `"header"` | `"header"` (Authorization header) or `"ticket"` (one-time ticket) |
270
+ | `auto_reconnect` | `True` | Reconnect after a lost connection |
271
+ | `max_reconnect_attempts` | `10` | `0` = unlimited |
272
+ | `reconnect_base_delay` | `1.0` | Exponential backoff base, capped at 30 seconds |
273
+ | `heartbeat_monitoring` | `True` | Send JSON pings and reconnect when no pong arrives |
274
+ | `heartbeat_interval` | `30` | Ping interval (min. 5) |
275
+ | `heartbeat_timeout` | `10` | Pong timeout (min. 1) |
276
+ | `connect_timeout` | `15` | Ticket + handshake + welcome timeout (min. 1) |
277
+
278
+ Other methods: `run()`, `stop()`, `disconnect()`, `destroy()` (also removes all listeners), `set_token(token)`,
279
+ `off(event, callback)`, `request_event_list()`, `get_subscribed_events()`, and the properties
280
+ `is_connected` and `session_id`. `async with NeuroInfoApiWebsocketClient(...) as ws:` connects
281
+ and disconnects automatically.
282
+
283
+ ## Utils
284
+
285
+ Small helpers for checking API data:
286
+
287
+ ```python
288
+ from neuroinfoapi_client import utils
289
+
290
+ utils.is_live(stream) # stream is live (editor then knows viewerCount etc.)
291
+ utils.is_schedule_final(schedule["status"])
292
+ utils.has_schedule_image(schedule)
293
+ utils.is_schedule_entry_online(entry) # also: is_schedule_entry_offline / _unknown
294
+ ```
295
+
296
+ For `scheduleLinkedStream*` WebSocket events: `is_link_type_on`, `is_link_type_collab`,
297
+ `is_trigger_stream_start`, `is_trigger_fetch`, `is_trigger_schedule_time`, `is_reason_stream_end`,
298
+ `is_reason_no_show`, `is_reason_schedule_removed`, `is_reason_timeout`, `did_linked_stream_happen`,
299
+ `is_linked_stream_live`.
300
+
301
+ ## Logging
302
+
303
+ The client logs through the `neuroinfoapi_client` logger (for example a warning when the
304
+ API version used by the client is outdated, or errors raised inside your WebSocket callbacks).
305
+ Set `NEUROINFOAPI_DISABLE_BOOT_CHECK=1` to skip the one-time API version check.
306
+
307
+ ## Development
308
+
309
+ ```bash
310
+ python -m venv .venv
311
+ .venv/Scripts/activate # Windows (Linux/macOS: source .venv/bin/activate)
312
+ pip install -e ".[dev]"
313
+ pytest
314
+ python -m build # creates dist/*.whl and dist/*.tar.gz
315
+ ```
316
+
317
+ Releases are published to PyPI by the GitHub Actions workflow `.github/workflows/publish.yml`
318
+ (see the comments there for the one-time PyPI setup).
319
+
320
+ ## License
321
+
322
+ MIT
@@ -0,0 +1,293 @@
1
+ # neuroinfoapi-client (Python)
2
+
3
+ Python client for the [NeuroInfoAPI](https://neuroinfoapi.dev/api/docs).
4
+
5
+ ## Features
6
+
7
+ - HTTP access to streams, VODs, schedules, subathons, shop products, blog and X feeds
8
+ - Synchronous **and** `asyncio` HTTP client with the same methods
9
+ - Methods return the data directly; errors are raised as `NeuroApiError`
10
+ - Typed responses (`TypedDict`) for editor autocompletion
11
+ - Configurable API base URL and request timeout (10 seconds by default)
12
+ - WebSocket client for real-time events: just call `ws.run()` (no `asyncio` needed) or use it
13
+ from async code; header or ticket auth, automatic reconnect, subscription recovery and heartbeat
14
+
15
+ ## Installation
16
+ Requires Python 3.10 or newer.
17
+
18
+ ```bash
19
+ pip install neuroinfoapi-client
20
+ ```
21
+
22
+ ## Quick Start
23
+
24
+ ```python
25
+ from neuroinfoapi_client import NeuroInfoApiClient, utils
26
+
27
+ client = NeuroInfoApiClient() # no token needed for public endpoints
28
+ # client = NeuroInfoApiClient("YOUR_API_TOKEN") # token required for some endpoints, see below
29
+
30
+ stream = client.get_current_stream() # raises NeuroApiError if something goes wrong
31
+ if utils.is_live(stream):
32
+ print("Live:", stream["title"], stream["viewerCount"])
33
+ else:
34
+ print("Stream is offline")
35
+ ```
36
+
37
+ Real-time events via WebSocket:
38
+
39
+ ```python
40
+ from neuroinfoapi_client import NeuroInfoApiWebsocketClient
41
+
42
+ ws = NeuroInfoApiWebsocketClient("YOUR_API_TOKEN")
43
+
44
+ @ws.on("streamOnline")
45
+ def on_online(data, timestamp):
46
+ print("Neuro is live:", data["title"])
47
+
48
+ ws.run() # blocks until Ctrl+C
49
+ ```
50
+
51
+ ### Async
52
+
53
+ ```python
54
+ import asyncio
55
+ from neuroinfoapi_client import AsyncNeuroInfoApiClient
56
+
57
+
58
+ async def main():
59
+ async with AsyncNeuroInfoApiClient() as client:
60
+ schedule = await client.get_latest_schedule()
61
+ for entry in schedule["schedule"]:
62
+ print(entry["day"], entry["message"])
63
+
64
+
65
+ asyncio.run(main())
66
+ ```
67
+
68
+ ## Client Configuration
69
+
70
+ ```python
71
+ NeuroInfoApiClient(token=None, *, api_base_url=None, use_tls=None, timeout=None)
72
+ ```
73
+
74
+ | Option | Default | Description |
75
+ | -------------- | ------------------------- | ---------------------------------------- |
76
+ | `api_base_url` | `neuroinfoapi.dev/api/v2` | API host and path without a protocol |
77
+ | `use_tls` | `True` | Use HTTPS when `True`, HTTP when `False` |
78
+ | `timeout` | `10` | HTTP request timeout in **seconds** |
79
+
80
+ ```python
81
+ # Token later
82
+ client = NeuroInfoApiClient()
83
+ client.set_api_token("YOUR_API_TOKEN")
84
+
85
+ # Local Mock-TestServer (https://github.com/NeuroInfoAPI/Mock-TestServer)
86
+ client = NeuroInfoApiClient(api_base_url="localhost:8787/api/v2", use_tls=False, timeout=15)
87
+ ```
88
+
89
+ Both clients keep a connection pool open. Use them with `with` / `async with`, or call
90
+ `client.close()` / `await client.aclose()` when you are done.
91
+
92
+ ## Error Handling
93
+
94
+ All errors are raised as `NeuroApiError` with `code`, `message` and the optional `status`,
95
+ `timestamp` and `path`:
96
+
97
+ ```python
98
+ from neuroinfoapi_client import NeuroApiError, NeuroInfoApiClient
99
+
100
+ client = NeuroInfoApiClient()
101
+
102
+ try:
103
+ subathons = client.get_current_subathons()
104
+ except NeuroApiError as error:
105
+ if error.code == "SB1":
106
+ print("No subathon right now")
107
+ else:
108
+ print(error.code, error.message)
109
+ else:
110
+ for subathon in subathons: # editor knows this is list[SubathonData]
111
+ print(subathon["name"], subathon["subcount"])
112
+ ```
113
+
114
+ Client error codes: `NETWORK` (connection problem or timeout), `HTTP_ERROR` (non-2xx without an
115
+ API error body), `INVALID_JSON`. All other codes come from the API.
116
+
117
+ > **Typing tip:** use `utils.is_live(stream)` (or `stream["isLive"] is True`, not just
118
+ > `if stream["isLive"]:`) so the editor knows live-only keys like `viewerCount` exist.
119
+
120
+ ## HTTP API Methods
121
+
122
+ | Python | Endpoint |
123
+ | ---------------------------------------------------------------- | ------------------------------------------------------------------------- |
124
+ | `get_current_stream()` | Current Twitch stream state |
125
+ | `get_schedule_linked_streams()` | Channels watched because of a schedule entry |
126
+ | `get_all_vods()` | All Twitch VODs (**token required**) |
127
+ | `get_vod(id)` | A VOD by stream ID (**token required**) |
128
+ | `get_schedule(week, year=None)` | Schedule for a specific week (**token required**) |
129
+ | `get_latest_schedule()` | Latest schedule |
130
+ | `get_schedule_weeks()` | Available schedule weeks grouped by year |
131
+ | `get_devstream_times()` | Devstream timestamps |
132
+ | `get_schedule_search(query, *, limit, year, sort, type, cursor)` | Search schedules (cursor pagination) (**token required**) |
133
+ | `get_current_subathons()` | Currently active subathons |
134
+ | `get_subathon(year)` | Subathon of a specific year (**token required**) |
135
+ | `get_subathon_years()` | Years with subathon data |
136
+ | `get_blog_feed(raw=False)` | Neuro-sama blog feed (**token required**) |
137
+ | `get_x_feed(user)` | X feed of `NeurosamaAI`, `EvilNeuroAI` or `Vedal987` (**token required**) |
138
+ | `get_shop_products(currency=None)` | Shop catalog (**token required**) |
139
+ | `get_shop_product(id, currency=None)` | A shop product (**token required**) |
140
+ | `request(path, params=None)` | Raw GET request to an API path such as `/twitch/stream` |
141
+
142
+ The response data is plain `dict`/`list` from JSON; keys are the same as in the API (camelCase).
143
+ Timestamps are Unix timestamps in milliseconds.
144
+
145
+ Search with pagination (needs a client with a token):
146
+
147
+ ```python
148
+ cursor = None
149
+ while True:
150
+ page = client.get_schedule_search("minecraft", limit=10, cursor=cursor)
151
+ for result in page["results"]:
152
+ print(result["data"]["year"], result["data"]["week"], result["foundDays"])
153
+ cursor = page["nextCursor"]
154
+ if cursor is None:
155
+ break
156
+ ```
157
+
158
+ ## WebSocket Client
159
+
160
+ The WebSocket client needs an API token.
161
+
162
+ ```python
163
+ from neuroinfoapi_client import NeuroInfoApiWebsocketClient
164
+
165
+ ws = NeuroInfoApiWebsocketClient("YOUR_API_TOKEN")
166
+
167
+ @ws.on("streamOnline")
168
+ def on_online(data, timestamp):
169
+ print("Neuro is live:", data["title"])
170
+
171
+ @ws.on("streamOffline")
172
+ def on_offline(data, timestamp):
173
+ print("Stream ended")
174
+ # ws.stop() # would end ws.run()
175
+
176
+ ws.on("_connected", lambda session_id: print("Connected:", session_id))
177
+ ws.on("_error", lambda error: print("Error:", error))
178
+
179
+ ws.run() # blocks; raises NeuroApiError if the first connection fails
180
+ ```
181
+
182
+ `ws.run()` returns after Ctrl+C, after `ws.stop()` (works from callbacks and other threads) or
183
+ when reconnecting gave up. Long-running work inside a callback pauses the client, so keep
184
+ callbacks short or start a thread for heavy work.
185
+
186
+ ### In async code
187
+
188
+ ```python
189
+ import asyncio
190
+ from neuroinfoapi_client import NeuroInfoApiWebsocketClient
191
+
192
+
193
+ async def main():
194
+ ws = NeuroInfoApiWebsocketClient("YOUR_API_TOKEN")
195
+
196
+ @ws.on("streamOnline")
197
+ async def on_online(data, timestamp): # async callbacks work too
198
+ print("Neuro is live:", data["title"])
199
+
200
+ await ws.connect() # raises NeuroApiError if the first connection fails
201
+ await ws.wait_closed() # runs until disconnect() or reconnecting gave up
202
+
203
+
204
+ asyncio.run(main())
205
+ ```
206
+
207
+ ### Events
208
+
209
+ `ws.on(event, callback)` returns an unsubscribe function; `ws.on(event)` without a callback
210
+ works as a decorator. Data events are subscribed on the server automatically and re-subscribed
211
+ after every reconnect.
212
+
213
+ Data events (callback gets `data, timestamp`):
214
+ `streamOnline`, `streamOffline`, `streamUpdate`, `secretneuroaccountOnline`,
215
+ `scheduleLinkedStreamOnline`, `scheduleLinkedStreamUpdate`, `scheduleLinkedStreamOffline`,
216
+ `streamRaidIncoming`, `streamRaidOutgoing`, `scheduleUpdate`, `subathonUpdate`,
217
+ `subathonGoalUpdate`, `blogFeedUpdate`, `xFeedNewEntries`, `shopProductsUpdate`
218
+ (`xFeedUpdate` is deprecated).
219
+
220
+ System events:
221
+
222
+ | Event | Callback arguments |
223
+ | ------------------ | ------------------------------------- |
224
+ | `_connected` | `session_id` |
225
+ | `_disconnected` | `code, reason` |
226
+ | `_reconnecting` | `attempt, delay_seconds` |
227
+ | `_reconnectFailed` | - |
228
+ | `_error` | `error` |
229
+ | `_message` | `message` (every raw message as dict) |
230
+ | `_pong` | - |
231
+ | `_eventAdded` | `event_type` |
232
+ | `_eventRemoved` | `event_type` |
233
+
234
+ Options (all durations in **seconds**):
235
+
236
+ | Option | Default | Description |
237
+ | ------------------------- | ---------- | ----------------------------------------------------------------- |
238
+ | `api_base_url`, `use_tls` | - | Same as the HTTP client |
239
+ | `websocket_url` | derived | Full WebSocket URL override |
240
+ | `auth_method` | `"header"` | `"header"` (Authorization header) or `"ticket"` (one-time ticket) |
241
+ | `auto_reconnect` | `True` | Reconnect after a lost connection |
242
+ | `max_reconnect_attempts` | `10` | `0` = unlimited |
243
+ | `reconnect_base_delay` | `1.0` | Exponential backoff base, capped at 30 seconds |
244
+ | `heartbeat_monitoring` | `True` | Send JSON pings and reconnect when no pong arrives |
245
+ | `heartbeat_interval` | `30` | Ping interval (min. 5) |
246
+ | `heartbeat_timeout` | `10` | Pong timeout (min. 1) |
247
+ | `connect_timeout` | `15` | Ticket + handshake + welcome timeout (min. 1) |
248
+
249
+ Other methods: `run()`, `stop()`, `disconnect()`, `destroy()` (also removes all listeners), `set_token(token)`,
250
+ `off(event, callback)`, `request_event_list()`, `get_subscribed_events()`, and the properties
251
+ `is_connected` and `session_id`. `async with NeuroInfoApiWebsocketClient(...) as ws:` connects
252
+ and disconnects automatically.
253
+
254
+ ## Utils
255
+
256
+ Small helpers for checking API data:
257
+
258
+ ```python
259
+ from neuroinfoapi_client import utils
260
+
261
+ utils.is_live(stream) # stream is live (editor then knows viewerCount etc.)
262
+ utils.is_schedule_final(schedule["status"])
263
+ utils.has_schedule_image(schedule)
264
+ utils.is_schedule_entry_online(entry) # also: is_schedule_entry_offline / _unknown
265
+ ```
266
+
267
+ For `scheduleLinkedStream*` WebSocket events: `is_link_type_on`, `is_link_type_collab`,
268
+ `is_trigger_stream_start`, `is_trigger_fetch`, `is_trigger_schedule_time`, `is_reason_stream_end`,
269
+ `is_reason_no_show`, `is_reason_schedule_removed`, `is_reason_timeout`, `did_linked_stream_happen`,
270
+ `is_linked_stream_live`.
271
+
272
+ ## Logging
273
+
274
+ The client logs through the `neuroinfoapi_client` logger (for example a warning when the
275
+ API version used by the client is outdated, or errors raised inside your WebSocket callbacks).
276
+ Set `NEUROINFOAPI_DISABLE_BOOT_CHECK=1` to skip the one-time API version check.
277
+
278
+ ## Development
279
+
280
+ ```bash
281
+ python -m venv .venv
282
+ .venv/Scripts/activate # Windows (Linux/macOS: source .venv/bin/activate)
283
+ pip install -e ".[dev]"
284
+ pytest
285
+ python -m build # creates dist/*.whl and dist/*.tar.gz
286
+ ```
287
+
288
+ Releases are published to PyPI by the GitHub Actions workflow `.github/workflows/publish.yml`
289
+ (see the comments there for the one-time PyPI setup).
290
+
291
+ ## License
292
+
293
+ MIT
@@ -0,0 +1,31 @@
1
+ from datetime import datetime
2
+
3
+ from neuroinfoapi_client import NeuroApiError, NeuroInfoApiClient, utils
4
+
5
+ DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
6
+
7
+ client = NeuroInfoApiClient() # no token needed for public endpoints
8
+ # client = NeuroInfoApiClient("YOUR_API_TOKEN") # token required for some endpoints (see README)
9
+
10
+ stream = client.get_current_stream()
11
+ if utils.is_live(stream):
12
+ print(f"LIVE: {stream['title']} ({stream['viewerCount']} viewers)")
13
+ else:
14
+ print("Offline. Last title:", stream["title"])
15
+
16
+ schedule = client.get_latest_schedule()
17
+ final = "confirmed" if utils.is_schedule_final(schedule["status"]) else "not final yet"
18
+ print(f"\nSchedule {schedule['year']} week {schedule['week']} ({final}):")
19
+ for entry in schedule["schedule"]:
20
+ when = datetime.fromtimestamp(entry["time"] / 1000).strftime("%d.%m. %H:%M")
21
+ print(f" {DAYS[entry['day']]} {when} {entry['message']}")
22
+
23
+ # Errors are raised as NeuroApiError
24
+ try:
25
+ subathons = client.get_current_subathons()
26
+ print("\nActive subathons:", [s["name"] for s in subathons])
27
+ except NeuroApiError as error:
28
+ if error.code == "SB1":
29
+ print("\nNo subathon right now")
30
+ else:
31
+ print("Error:", error.code, error.message)