1322-python 0.1.0__py3-none-any.whl
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.
- 1322_python-0.1.0.dist-info/METADATA +273 -0
- 1322_python-0.1.0.dist-info/RECORD +18 -0
- 1322_python-0.1.0.dist-info/WHEEL +4 -0
- 1322_python-0.1.0.dist-info/licenses/LICENSE +21 -0
- client1322/__init__.py +48 -0
- client1322/_backoff.py +76 -0
- client1322/_merge.py +199 -0
- client1322/client.py +114 -0
- client1322/exceptions.py +40 -0
- client1322/platforms/__init__.py +1 -0
- client1322/platforms/_base.py +191 -0
- client1322/platforms/binance.py +219 -0
- client1322/platforms/instagram.py +146 -0
- client1322/platforms/news.py +150 -0
- client1322/platforms/truth.py +189 -0
- client1322/platforms/x.py +577 -0
- client1322/platforms/youtube.py +155 -0
- client1322/py.typed +0 -0
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: 1322-python
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Unified async Python client for the 1322 real-time social monitoring API (X, Instagram, Truth Social, YouTube, Binance Square, News).
|
|
5
|
+
Project-URL: Homepage, https://1322.io
|
|
6
|
+
Project-URL: Documentation, https://1322.io/docs
|
|
7
|
+
Project-URL: Repository, https://github.com/SisoSol/1322-python
|
|
8
|
+
Project-URL: Issues, https://github.com/SisoSol/1322-python/issues
|
|
9
|
+
Author: SisoSol
|
|
10
|
+
License: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: 1322,async,binance,instagram,realtime,social-media-monitoring,truth-social,twitter,websocket,x,youtube
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Framework :: AsyncIO
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
24
|
+
Classifier: Topic :: Communications :: Chat
|
|
25
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: Indexing/Search
|
|
26
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
27
|
+
Classifier: Typing :: Typed
|
|
28
|
+
Requires-Python: >=3.10
|
|
29
|
+
Requires-Dist: aiohttp>=3.9
|
|
30
|
+
Provides-Extra: dev
|
|
31
|
+
Requires-Dist: build>=1.0; extra == 'dev'
|
|
32
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
33
|
+
Description-Content-Type: text/markdown
|
|
34
|
+
|
|
35
|
+
# 1322-python
|
|
36
|
+
|
|
37
|
+
A unified async Python client for the [1322](https://1322.io) real-time social
|
|
38
|
+
monitoring API. 1322 tracks accounts on X (Twitter), Truth Social, Instagram,
|
|
39
|
+
YouTube, Binance Square, and 15+ news outlets, and delivers new posts,
|
|
40
|
+
updates, and deletions over WebSocket.
|
|
41
|
+
|
|
42
|
+
1322 already publishes several single-platform example repos (see
|
|
43
|
+
[social-monitor-examples](https://github.com/SisoSol/social-monitor-examples)
|
|
44
|
+
and [binance-square-realtime](https://github.com/SisoSol/binance-square-realtime)).
|
|
45
|
+
This package is different: it's one installable, typed client covering all
|
|
46
|
+
six platforms behind a single consistent async shape, instead of copying a
|
|
47
|
+
connection script per platform.
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from client1322 import Client
|
|
51
|
+
|
|
52
|
+
async with Client(platform="x", api_key="YOUR_API_KEY_HERE") as client:
|
|
53
|
+
async for event in client.stream():
|
|
54
|
+
print(event)
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Distribution name vs. import name
|
|
58
|
+
|
|
59
|
+
The PyPI distribution name is **`1322-python`** (Python package names on
|
|
60
|
+
PyPI may start with a digit; Python *module* names cannot). The importable
|
|
61
|
+
module is **`client1322`**. So you `pip install 1322-python` but
|
|
62
|
+
`import client1322` in code. Every example in this repo uses the real
|
|
63
|
+
import name.
|
|
64
|
+
|
|
65
|
+
## Install
|
|
66
|
+
|
|
67
|
+
From GitHub (works today, no PyPI account needed):
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
pip install git+https://github.com/SisoSol/1322-python
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
From PyPI (once published -- see [Publishing](#publishing) below):
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
pip install 1322-python
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Requires Python 3.10+.
|
|
80
|
+
|
|
81
|
+
## Why one client instead of six scripts
|
|
82
|
+
|
|
83
|
+
1322 documents six platforms, each with its own REST base URL, WebSocket
|
|
84
|
+
connection scheme, auth header, and event payload shape (see
|
|
85
|
+
[1322.io/docs](https://1322.io/docs) for the authoritative contract). This
|
|
86
|
+
package keeps that per-platform reality -- it does not invent a fake common
|
|
87
|
+
REST API that doesn't exist -- but gives you the same connection lifecycle,
|
|
88
|
+
reconnect behavior, and streaming interface everywhere:
|
|
89
|
+
|
|
90
|
+
- **One shape**: `async with Client(platform=..., api_key=...) as client:`
|
|
91
|
+
then `async for event in client.stream():`, for all six platforms.
|
|
92
|
+
- **Typed events**: every event is a `dataclass` with real field types
|
|
93
|
+
(`TypedDict`-typed nested payloads), not a loosely-typed `dict`. Full
|
|
94
|
+
`py.typed` support for IDEs and type checkers.
|
|
95
|
+
- **Auto-reconnect**: exponential backoff (1s, 2s, 4s, 8s, ... capped at
|
|
96
|
+
30s), matching 1322's documented reconnection policy, implemented once
|
|
97
|
+
and shared by every platform adapter.
|
|
98
|
+
- **Additive tweet merge**: X tweets arrive across up to four progressive
|
|
99
|
+
stages (`tweet.mini.update` -> `tweet.update` -> `tweet.update.expanded`
|
|
100
|
+
-> `tweet.full`); `TweetMerger` implements 1322's documented merge rules
|
|
101
|
+
(longest text, unioned media, deepest reply/quote chain, highest metrics,
|
|
102
|
+
never overwrite a populated field with null) so you don't have to.
|
|
103
|
+
- **Thin REST helpers**: `track()` / `untrack()` / `list_tracked()` /
|
|
104
|
+
`health()` and friends, matching each platform's documented management
|
|
105
|
+
API exactly.
|
|
106
|
+
|
|
107
|
+
## Platform coverage
|
|
108
|
+
|
|
109
|
+
| Platform | `platform=` | REST base | Connection details |
|
|
110
|
+
|---|---|---|---|
|
|
111
|
+
| X / Twitter | `"x"` (or `"twitter"`) | `api.1322.io` | fixed WS URL per tier (`normal`/`ultimate`) |
|
|
112
|
+
| Truth Social | `"truth"` | `truth.1322.io` | needs `ws_path`+`ws_key` from your dashboard |
|
|
113
|
+
| Instagram | `"instagram"` | `1322.io` | fixed WS URL, same key as REST |
|
|
114
|
+
| News | `"news"` | `newsfeed.1322.io` | `ws_path`/`ws_key` auto-fetched from `/v1/dashboard` |
|
|
115
|
+
| Binance Square | `"binance"` | `binance.1322.io` | `ws_path`/`ws_key` auto-fetched from `/v1/dashboard` |
|
|
116
|
+
| YouTube | `"youtube"` | -- | requires an explicit `ws_url` (see below) |
|
|
117
|
+
|
|
118
|
+
**About YouTube:** 1322's public docs describe the YouTube event payload
|
|
119
|
+
contract in full (upload / thumbnail upgrade / deletion) but, as of this
|
|
120
|
+
writing, do not publish a fixed WebSocket URL pattern or a customer-facing
|
|
121
|
+
REST tracked-account API for YouTube the way they do for the other five
|
|
122
|
+
platforms. Rather than guess at an undocumented endpoint, `YouTubeAdapter`
|
|
123
|
+
requires you to pass the exact WebSocket URL from your dashboard
|
|
124
|
+
configuration as `ws_url=`, and only implements event parsing -- no
|
|
125
|
+
`track()`/`untrack()`/`list_tracked()`, because 1322's docs don't define
|
|
126
|
+
them for this platform. Check [1322.io/docs](https://1322.io/docs) directly
|
|
127
|
+
if that changes.
|
|
128
|
+
|
|
129
|
+
## Usage per platform
|
|
130
|
+
|
|
131
|
+
Runnable examples for all six platforms live in [`examples/`](examples/).
|
|
132
|
+
Each one reads its API key from an environment variable and does something
|
|
133
|
+
useful with the REST helpers plus the event stream. Quick summaries:
|
|
134
|
+
|
|
135
|
+
### X / Twitter
|
|
136
|
+
|
|
137
|
+
```python
|
|
138
|
+
from client1322 import Client, TweetMerger
|
|
139
|
+
from client1322.platforms.x import MiniTweetUpdate, TweetUpdate, TweetFull
|
|
140
|
+
|
|
141
|
+
merger = TweetMerger()
|
|
142
|
+
|
|
143
|
+
async with Client(platform="x", api_key="YOUR_API_KEY_HERE", tier="normal") as client:
|
|
144
|
+
async for event in client.stream():
|
|
145
|
+
if isinstance(event, (MiniTweetUpdate, TweetUpdate, TweetFull)):
|
|
146
|
+
merged = merger.merge(event.tweet) # dedup + additive merge by tweet id
|
|
147
|
+
print(merged["author"]["handle"], merged["body"]["text"])
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
Also available: `client.list_tracked()`, `client.add_tracked("elonmusk")`,
|
|
151
|
+
`client.remove_tracked("elonmusk")`, `client.list_keys()`,
|
|
152
|
+
`client.get_tweet(tweet_id, full=True)`, `client.resolve_username("elonmusk")`.
|
|
153
|
+
|
|
154
|
+
### Truth Social
|
|
155
|
+
|
|
156
|
+
```python
|
|
157
|
+
async with Client(
|
|
158
|
+
platform="truth", api_key="YOUR_API_KEY_HERE",
|
|
159
|
+
ws_path="YOUR_WS_PATH_HERE", ws_key="YOUR_WS_KEY_HERE",
|
|
160
|
+
) as client:
|
|
161
|
+
async for post in client.stream():
|
|
162
|
+
print(post.username, post.text)
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
Also available: `client.track("realDonaldTrump")`, `client.untrack(...)`,
|
|
166
|
+
`client.list_tracked()`, `client.limits()`, `client.status()`, `client.health()`.
|
|
167
|
+
|
|
168
|
+
### Instagram
|
|
169
|
+
|
|
170
|
+
```python
|
|
171
|
+
async with Client(platform="instagram", api_key="YOUR_API_KEY_HERE") as client:
|
|
172
|
+
async for post in client.stream():
|
|
173
|
+
print(post.post_type, post.username, post.text)
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
Also available: `client.track("username")`, `client.untrack(...)`,
|
|
177
|
+
`client.list_tracked()`, `client.limits()`, `client.health()`.
|
|
178
|
+
|
|
179
|
+
### News
|
|
180
|
+
|
|
181
|
+
```python
|
|
182
|
+
async with Client(platform="news", api_key="YOUR_API_KEY_HERE") as client:
|
|
183
|
+
async for article in client.stream():
|
|
184
|
+
print(article.feed, article.title, article.url)
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
Also available: `client.dashboard()`, `client.subscribe("BBC News")`,
|
|
188
|
+
`client.unsubscribe(...)`.
|
|
189
|
+
|
|
190
|
+
### Binance Square
|
|
191
|
+
|
|
192
|
+
```python
|
|
193
|
+
from client1322.platforms.binance import BinancePinUpdateEvent, BinancePostEvent
|
|
194
|
+
|
|
195
|
+
async with Client(platform="binance", api_key="YOUR_API_KEY_HERE") as client:
|
|
196
|
+
async for event in client.stream():
|
|
197
|
+
if isinstance(event, BinancePostEvent):
|
|
198
|
+
print(event.post["username"], event.post.get("tendency"), event.post.get("text"))
|
|
199
|
+
elif isinstance(event, BinancePinUpdateEvent):
|
|
200
|
+
print("pin change:", event.pin["username"])
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
Also available: `client.track("CZ_Binance")`, `client.untrack(...)`, `client.dashboard()`.
|
|
204
|
+
|
|
205
|
+
### YouTube
|
|
206
|
+
|
|
207
|
+
```python
|
|
208
|
+
from client1322.platforms.youtube import DeletionMessage, UploadMessage, UpgradeMessage
|
|
209
|
+
|
|
210
|
+
async with Client(
|
|
211
|
+
platform="youtube", api_key="YOUR_API_KEY_HERE", ws_url="YOUR_WS_URL_HERE"
|
|
212
|
+
) as client:
|
|
213
|
+
async for event in client.stream():
|
|
214
|
+
if isinstance(event, UploadMessage):
|
|
215
|
+
print(event.channel["name"], event.video["title"])
|
|
216
|
+
elif isinstance(event, UpgradeMessage):
|
|
217
|
+
print("thumbnail upgraded:", event.upgrade["video_id"])
|
|
218
|
+
elif isinstance(event, DeletionMessage):
|
|
219
|
+
print("deleted:", event.video["id"])
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
## Auth and secrets
|
|
223
|
+
|
|
224
|
+
Each platform key comes from your [1322 dashboard](https://1322.io). Never
|
|
225
|
+
hardcode a key in source; read it from the environment instead. See
|
|
226
|
+
[`.env.example`](.env.example) for the full list of variables each platform
|
|
227
|
+
example expects.
|
|
228
|
+
|
|
229
|
+
## Reconnection
|
|
230
|
+
|
|
231
|
+
`stream()` reconnects automatically on disconnect using 1322's documented
|
|
232
|
+
policy: exponential backoff starting at 1 second, doubling each attempt, and
|
|
233
|
+
capped at 30 seconds. No events are queued while disconnected -- this
|
|
234
|
+
matches 1322's documented server behavior, so a client that's offline will
|
|
235
|
+
simply miss whatever happened during that window, the same as any other
|
|
236
|
+
1322 WebSocket client. Server-sent WebSocket pings are answered
|
|
237
|
+
automatically by the underlying `aiohttp` transport; you don't need to
|
|
238
|
+
handle that yourself. Pass `auto_reconnect=False` to `Client(...)` to
|
|
239
|
+
disable reconnection (`stream()` then returns after the first disconnect),
|
|
240
|
+
and `backoff_base=`/`backoff_cap=` to tune the delay curve.
|
|
241
|
+
|
|
242
|
+
## Development
|
|
243
|
+
|
|
244
|
+
```bash
|
|
245
|
+
git clone https://github.com/SisoSol/1322-python
|
|
246
|
+
cd 1322-python
|
|
247
|
+
python -m venv .venv && source .venv/bin/activate # or .venv\Scripts\activate on Windows
|
|
248
|
+
pip install -e ".[dev]"
|
|
249
|
+
pytest
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
The test suite (`tests/`) covers backoff math, additive tweet merging, and
|
|
253
|
+
event parsing for all six platforms against payload shapes taken from
|
|
254
|
+
[1322.io/docs](https://1322.io/docs), plus an end-to-end `Client.stream()`
|
|
255
|
+
reconnect test driven against a fake `aiohttp` session (no real socket, no
|
|
256
|
+
API key needed). Every event-parsing fixture uses illustrative example
|
|
257
|
+
data, not measured production traffic.
|
|
258
|
+
|
|
259
|
+
## Publishing
|
|
260
|
+
|
|
261
|
+
This repository is not published to PyPI yet. To publish it yourself:
|
|
262
|
+
|
|
263
|
+
```bash
|
|
264
|
+
pip install build twine
|
|
265
|
+
python -m build
|
|
266
|
+
twine upload dist/*
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
`twine upload` prompts for your PyPI credentials/API token interactively.
|
|
270
|
+
|
|
271
|
+
## License
|
|
272
|
+
|
|
273
|
+
MIT, see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
client1322/__init__.py,sha256=Zo2ihSnqbmluVuJiq7JyjxB3BYQ-pIRDrZMCBxdQXJ0,1266
|
|
2
|
+
client1322/_backoff.py,sha256=tr7jSxSOrll359UZJwjVq0ViV_pjqzdmNycXuMVeZ-o,2054
|
|
3
|
+
client1322/_merge.py,sha256=jmSNsmTgj0xCLEVIojCHekaqTmioJ7PJdipUBxEjItU,7452
|
|
4
|
+
client1322/client.py,sha256=mVay9UTFq7oz_CCg_x3hQ3grmST0a29k4Gmk5HWt_9M,4651
|
|
5
|
+
client1322/exceptions.py,sha256=F3BR_M7KXd2BKxXLMIdADy2iolNnPWa4hrYKPOnEfS4,1219
|
|
6
|
+
client1322/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
client1322/platforms/__init__.py,sha256=05_QgIOcXJvtKyd4sCr04pL0w6IAPHujl7G7MPoxfBg,53
|
|
8
|
+
client1322/platforms/_base.py,sha256=3YXHmXu7BSXbU87D8NZpTGuzeOp8RyEx4XUVici5uLw,7257
|
|
9
|
+
client1322/platforms/binance.py,sha256=V3xz3K_YC12HSPnnZtUSUdzaQufWnbAu9HEDi1QZ5ts,6024
|
|
10
|
+
client1322/platforms/instagram.py,sha256=XMPltAqUXUPcOvihWCRQJCppYL8U3Cmb99FuOMsSeL4,4457
|
|
11
|
+
client1322/platforms/news.py,sha256=_XjEkeRf_qWFiMCCCnY5Ppsny-41jgJmF2dhiCTmRJ4,4726
|
|
12
|
+
client1322/platforms/truth.py,sha256=9YZ4OJRxfQ-0-dw3dX8wUcpJ7SnHPgrbs1sTvVw0lU0,5924
|
|
13
|
+
client1322/platforms/x.py,sha256=kQ6Ue-ktfSxuJJCRAn7MIUwOqiYVB2Fg5e6CSv4Z_1M,15224
|
|
14
|
+
client1322/platforms/youtube.py,sha256=nNm3YX5k9eHttJ8p12EwwyaF71Hu7sEVDERfDfOfcbk,4675
|
|
15
|
+
1322_python-0.1.0.dist-info/METADATA,sha256=pihIUfO1m9FhNpc8zOYe-eTz6GwOsPE7yDtzCGe3ZVw,10891
|
|
16
|
+
1322_python-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
|
|
17
|
+
1322_python-0.1.0.dist-info/licenses/LICENSE,sha256=G4pIQS2HGymqxoSh_hF_395DtCefxhS7W2LyfEACq1Q,1085
|
|
18
|
+
1322_python-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 SisoSol
|
|
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.
|
client1322/__init__.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""client1322 -- unified async Python client for the 1322 real-time social
|
|
2
|
+
monitoring API.
|
|
3
|
+
|
|
4
|
+
Distributed on PyPI as ``1322-python``; imported as ``client1322`` because
|
|
5
|
+
Python module names cannot start with a digit. See the README for details.
|
|
6
|
+
|
|
7
|
+
Covers all six 1322 platforms (X/Twitter, Truth Social, Instagram, News,
|
|
8
|
+
YouTube, Binance Square) behind one consistent async shape:
|
|
9
|
+
|
|
10
|
+
.. code-block:: python
|
|
11
|
+
|
|
12
|
+
from client1322 import Client
|
|
13
|
+
|
|
14
|
+
async with Client(platform="x", api_key="...") as client:
|
|
15
|
+
async for event in client.stream():
|
|
16
|
+
print(event)
|
|
17
|
+
|
|
18
|
+
Ground truth for every endpoint, payload shape, and reconnect policy this
|
|
19
|
+
library implements: https://1322.io/docs
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
from ._backoff import BackoffPolicy, next_delay
|
|
25
|
+
from ._merge import TweetMerger, merge_tweet
|
|
26
|
+
from .client import Client, Platform
|
|
27
|
+
from .exceptions import (
|
|
28
|
+
APIError,
|
|
29
|
+
Client1322Error,
|
|
30
|
+
ConfigurationError,
|
|
31
|
+
UnknownEventError,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
__version__ = "0.1.0"
|
|
35
|
+
|
|
36
|
+
__all__ = [
|
|
37
|
+
"Client",
|
|
38
|
+
"Platform",
|
|
39
|
+
"Client1322Error",
|
|
40
|
+
"APIError",
|
|
41
|
+
"ConfigurationError",
|
|
42
|
+
"UnknownEventError",
|
|
43
|
+
"BackoffPolicy",
|
|
44
|
+
"next_delay",
|
|
45
|
+
"TweetMerger",
|
|
46
|
+
"merge_tweet",
|
|
47
|
+
"__version__",
|
|
48
|
+
]
|
client1322/_backoff.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Reconnect backoff math.
|
|
2
|
+
|
|
3
|
+
1322's documented WebSocket reconnection policy (see https://1322.io/docs,
|
|
4
|
+
"Reconnection" section): on disconnect, reconnect with exponential backoff
|
|
5
|
+
starting at 1s and doubling up to a 30s cap (1s, 2s, 4s, 8s, 16s, 30s, 30s, ...).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
DEFAULT_BASE_DELAY = 1.0
|
|
11
|
+
DEFAULT_MAX_DELAY = 30.0
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def next_delay(
|
|
15
|
+
attempt: int,
|
|
16
|
+
*,
|
|
17
|
+
base: float = DEFAULT_BASE_DELAY,
|
|
18
|
+
cap: float = DEFAULT_MAX_DELAY,
|
|
19
|
+
) -> float:
|
|
20
|
+
"""Return the delay, in seconds, before reconnect attempt ``attempt``.
|
|
21
|
+
|
|
22
|
+
``attempt`` is 0-indexed: the delay before the *first* reconnect attempt
|
|
23
|
+
(i.e. after the first disconnect) is ``next_delay(0)``.
|
|
24
|
+
|
|
25
|
+
>>> next_delay(0)
|
|
26
|
+
1.0
|
|
27
|
+
>>> next_delay(1)
|
|
28
|
+
2.0
|
|
29
|
+
>>> next_delay(4)
|
|
30
|
+
16.0
|
|
31
|
+
>>> next_delay(5)
|
|
32
|
+
30.0
|
|
33
|
+
>>> next_delay(100)
|
|
34
|
+
30.0
|
|
35
|
+
"""
|
|
36
|
+
if attempt < 0:
|
|
37
|
+
raise ValueError("attempt must be >= 0")
|
|
38
|
+
if base < 0:
|
|
39
|
+
raise ValueError("base must be >= 0")
|
|
40
|
+
if cap < 0:
|
|
41
|
+
raise ValueError("cap must be >= 0")
|
|
42
|
+
delay = base * (2**attempt)
|
|
43
|
+
return min(delay, cap)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class BackoffPolicy:
|
|
47
|
+
"""Stateful reconnect-delay counter used by each platform adapter.
|
|
48
|
+
|
|
49
|
+
Call :meth:`next` to get the delay before the next reconnect attempt and
|
|
50
|
+
advance the internal counter. Call :meth:`reset` after a connection is
|
|
51
|
+
established successfully so the next disconnect starts from 1s again.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
__slots__ = ("base", "cap", "_attempt")
|
|
55
|
+
|
|
56
|
+
def __init__(
|
|
57
|
+
self,
|
|
58
|
+
*,
|
|
59
|
+
base: float = DEFAULT_BASE_DELAY,
|
|
60
|
+
cap: float = DEFAULT_MAX_DELAY,
|
|
61
|
+
) -> None:
|
|
62
|
+
self.base = base
|
|
63
|
+
self.cap = cap
|
|
64
|
+
self._attempt = 0
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def attempt(self) -> int:
|
|
68
|
+
return self._attempt
|
|
69
|
+
|
|
70
|
+
def next(self) -> float:
|
|
71
|
+
delay = next_delay(self._attempt, base=self.base, cap=self.cap)
|
|
72
|
+
self._attempt += 1
|
|
73
|
+
return delay
|
|
74
|
+
|
|
75
|
+
def reset(self) -> None:
|
|
76
|
+
self._attempt = 0
|
client1322/_merge.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""Additive merge + dedup for progressive X/Twitter tweet events.
|
|
2
|
+
|
|
3
|
+
Per https://1322.io/docs ("Additive Merge (Recommended)"), X tweets arrive
|
|
4
|
+
across up to four progressive stages (``tweet.mini.update`` ->
|
|
5
|
+
``tweet.update`` -> ``tweet.update.expanded`` -> ``tweet.full``), each one
|
|
6
|
+
enriching the previous. The documented merge rules, by ``tweet.id``:
|
|
7
|
+
|
|
8
|
+
- use the **longest** ``body.text``
|
|
9
|
+
- **union** all media arrays
|
|
10
|
+
- keep the **deepest** ``subtweet`` chain
|
|
11
|
+
- take the **highest** metric values
|
|
12
|
+
- **never overwrite** a populated field with null/empty; a later stage may
|
|
13
|
+
lack data an earlier stage had
|
|
14
|
+
|
|
15
|
+
Everything below operates on plain ``dict`` payloads (the raw
|
|
16
|
+
``TwitterMiniTweet`` / ``TwitterTweet`` JSON shape) so it has no dependency
|
|
17
|
+
on the dataclass wrappers in :mod:`client1322.platforms.x` and is trivial to
|
|
18
|
+
unit test.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import copy
|
|
24
|
+
from collections import OrderedDict
|
|
25
|
+
from typing import Any
|
|
26
|
+
|
|
27
|
+
_MEDIA_ARRAY_KEYS = ("images", "videos", "thumbnails")
|
|
28
|
+
_PROXIED_ARRAY_KEYS = ("images", "thumbnails")
|
|
29
|
+
_METRIC_KEYS = ("likes", "quotes", "replies", "retweets")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _union_preserve_order(a: list[Any], b: list[Any]) -> list[Any]:
|
|
33
|
+
seen: set[Any] = set()
|
|
34
|
+
out: list[Any] = []
|
|
35
|
+
for item in (*a, *b):
|
|
36
|
+
key = item if isinstance(item, (str, int, float, bool, type(None))) else repr(item)
|
|
37
|
+
if key in seen:
|
|
38
|
+
continue
|
|
39
|
+
seen.add(key)
|
|
40
|
+
out.append(item)
|
|
41
|
+
return out
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _merge_body(dst: dict[str, Any], src: dict[str, Any]) -> None:
|
|
45
|
+
src_text = src.get("text")
|
|
46
|
+
dst_text = dst.get("text")
|
|
47
|
+
if isinstance(src_text, str) and (
|
|
48
|
+
not isinstance(dst_text, str) or len(src_text) > len(dst_text)
|
|
49
|
+
):
|
|
50
|
+
dst["text"] = src_text
|
|
51
|
+
# Other body fields (urls, mentions, components) are not called out with
|
|
52
|
+
# a specific merge rule in the docs; apply the general "later stage
|
|
53
|
+
# enriches, never overwrite with null" rule.
|
|
54
|
+
for key, val in src.items():
|
|
55
|
+
if key == "text" or val is None:
|
|
56
|
+
continue
|
|
57
|
+
dst[key] = val
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _merge_media(dst: dict[str, Any], src: dict[str, Any]) -> None:
|
|
61
|
+
for key in _MEDIA_ARRAY_KEYS:
|
|
62
|
+
if key in dst or key in src:
|
|
63
|
+
dst[key] = _union_preserve_order(dst.get(key) or [], src.get(key) or [])
|
|
64
|
+
|
|
65
|
+
src_proxied = src.get("proxied")
|
|
66
|
+
if src_proxied is None:
|
|
67
|
+
return
|
|
68
|
+
dst_proxied = dst.get("proxied")
|
|
69
|
+
if dst_proxied is None:
|
|
70
|
+
dst["proxied"] = copy.deepcopy(src_proxied)
|
|
71
|
+
return
|
|
72
|
+
for key in _PROXIED_ARRAY_KEYS:
|
|
73
|
+
if key in dst_proxied or key in src_proxied:
|
|
74
|
+
dst_proxied[key] = _union_preserve_order(
|
|
75
|
+
dst_proxied.get(key) or [], src_proxied.get(key) or []
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _merge_metrics(dst: dict[str, Any], src: dict[str, Any]) -> None:
|
|
80
|
+
for key in _METRIC_KEYS:
|
|
81
|
+
src_val = src.get(key)
|
|
82
|
+
if src_val is None:
|
|
83
|
+
continue
|
|
84
|
+
dst_val = dst.get(key)
|
|
85
|
+
if dst_val is None or src_val > dst_val:
|
|
86
|
+
dst[key] = src_val
|
|
87
|
+
|
|
88
|
+
src_adv = src.get("advanced")
|
|
89
|
+
if src_adv is None:
|
|
90
|
+
return # never overwrite a populated 'advanced' block with null
|
|
91
|
+
dst_adv = dst.get("advanced")
|
|
92
|
+
if dst_adv is None:
|
|
93
|
+
dst["advanced"] = copy.deepcopy(src_adv)
|
|
94
|
+
return
|
|
95
|
+
src_views = src_adv.get("views")
|
|
96
|
+
if src_views is not None and (
|
|
97
|
+
dst_adv.get("views") is None or src_views > dst_adv["views"]
|
|
98
|
+
):
|
|
99
|
+
dst_adv["views"] = src_views
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _chain_depth(node: dict[str, Any] | None) -> int:
|
|
103
|
+
depth = 0
|
|
104
|
+
while node is not None:
|
|
105
|
+
depth += 1
|
|
106
|
+
node = node.get("subtweet")
|
|
107
|
+
return depth
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _merge_subtweet(
|
|
111
|
+
dst_val: dict[str, Any] | None, src_val: dict[str, Any] | None
|
|
112
|
+
) -> dict[str, Any] | None:
|
|
113
|
+
if src_val is None:
|
|
114
|
+
return dst_val
|
|
115
|
+
if dst_val is None:
|
|
116
|
+
return copy.deepcopy(src_val)
|
|
117
|
+
if dst_val.get("id") == src_val.get("id"):
|
|
118
|
+
merged = copy.deepcopy(dst_val)
|
|
119
|
+
_merge_tweet_dicts(merged, src_val)
|
|
120
|
+
return merged
|
|
121
|
+
# Different referenced tweets (shouldn't normally happen across stages of
|
|
122
|
+
# the same root tweet) -- keep whichever chain resolves deeper.
|
|
123
|
+
return dst_val if _chain_depth(dst_val) >= _chain_depth(src_val) else copy.deepcopy(src_val)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _merge_tweet_dicts(dst: dict[str, Any], src: dict[str, Any]) -> None:
|
|
127
|
+
"""Merge ``src`` (a later/enriching stage) into ``dst`` in place."""
|
|
128
|
+
for key, src_val in src.items():
|
|
129
|
+
if key == "body" and isinstance(src_val, dict):
|
|
130
|
+
dst["body"] = dst.get("body") or {}
|
|
131
|
+
_merge_body(dst["body"], src_val)
|
|
132
|
+
elif key == "media" and isinstance(src_val, dict):
|
|
133
|
+
dst["media"] = dst.get("media") or {}
|
|
134
|
+
_merge_media(dst["media"], src_val)
|
|
135
|
+
elif key == "metrics" and isinstance(src_val, dict):
|
|
136
|
+
dst["metrics"] = dst.get("metrics") or {}
|
|
137
|
+
_merge_metrics(dst["metrics"], src_val)
|
|
138
|
+
elif key == "subtweet":
|
|
139
|
+
dst["subtweet"] = _merge_subtweet(dst.get("subtweet"), src_val)
|
|
140
|
+
elif src_val is not None:
|
|
141
|
+
dst[key] = src_val
|
|
142
|
+
# src_val is None and key already absent/None in dst: nothing to do.
|
|
143
|
+
# src_val is None and dst has a populated value: never overwrite.
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def merge_tweet(base: dict[str, Any] | None, incoming: dict[str, Any]) -> dict[str, Any]:
|
|
147
|
+
"""Merge ``incoming`` (a raw tweet dict) on top of ``base``.
|
|
148
|
+
|
|
149
|
+
``base`` may be ``None`` (first time this tweet id is seen). Returns a
|
|
150
|
+
new merged dict; neither input is mutated.
|
|
151
|
+
"""
|
|
152
|
+
if base is None:
|
|
153
|
+
return copy.deepcopy(incoming)
|
|
154
|
+
merged = copy.deepcopy(base)
|
|
155
|
+
_merge_tweet_dicts(merged, incoming)
|
|
156
|
+
return merged
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
class TweetMerger:
|
|
160
|
+
"""Bounded, in-memory cache that applies :func:`merge_tweet` by tweet id.
|
|
161
|
+
|
|
162
|
+
This is purely a client-side convenience for consumers who want a single
|
|
163
|
+
up-to-date view of each tweet across its progressive stages, matching
|
|
164
|
+
the docs' recommended merge behavior. It has no bearing on 1322's own
|
|
165
|
+
infrastructure -- it just deduplicates and enriches events on your side.
|
|
166
|
+
|
|
167
|
+
``max_entries`` bounds memory use: once exceeded, the least-recently-
|
|
168
|
+
merged tweet is evicted (simple LRU), independent of stream volume.
|
|
169
|
+
"""
|
|
170
|
+
|
|
171
|
+
def __init__(self, max_entries: int = 500) -> None:
|
|
172
|
+
if max_entries <= 0:
|
|
173
|
+
raise ValueError("max_entries must be > 0")
|
|
174
|
+
self.max_entries = max_entries
|
|
175
|
+
self._cache: "OrderedDict[str, dict[str, Any]]" = OrderedDict()
|
|
176
|
+
|
|
177
|
+
def __len__(self) -> int:
|
|
178
|
+
return len(self._cache)
|
|
179
|
+
|
|
180
|
+
def get(self, tweet_id: str) -> dict[str, Any] | None:
|
|
181
|
+
return self._cache.get(tweet_id)
|
|
182
|
+
|
|
183
|
+
def merge(self, tweet: dict[str, Any]) -> dict[str, Any]:
|
|
184
|
+
"""Merge ``tweet`` into the cache and return the merged result."""
|
|
185
|
+
tweet_id = tweet.get("id")
|
|
186
|
+
if not tweet_id:
|
|
187
|
+
raise ValueError("tweet dict has no 'id' field")
|
|
188
|
+
merged = merge_tweet(self._cache.get(tweet_id), tweet)
|
|
189
|
+
self._cache[tweet_id] = merged
|
|
190
|
+
self._cache.move_to_end(tweet_id)
|
|
191
|
+
while len(self._cache) > self.max_entries:
|
|
192
|
+
self._cache.popitem(last=False)
|
|
193
|
+
return merged
|
|
194
|
+
|
|
195
|
+
def clear(self) -> None:
|
|
196
|
+
self._cache.clear()
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
__all__ = ["merge_tweet", "TweetMerger"]
|