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.
@@ -0,0 +1,577 @@
1
+ """X / Twitter: REST management API + WebSocket event types.
2
+
3
+ Ground truth: https://1322.io/docs ("X / Twitter" reference).
4
+
5
+ - REST base: https://api.1322.io
6
+ - WebSocket: wss://ws.normal.1322.io/ws/normal (Normal tier) or
7
+ wss://ws.ultimate.1322.io/ws/ultimate (Ultimate tier)
8
+ - Auth: header X-API-Key, or Authorization: Bearer <key>, or query key=<key>
9
+ (REST); WebSocket: same headers, or query token=<key>.
10
+ - Rate limits: reads 1200/min (20/s), writes 600/min (10/s). Bulk add/remove
11
+ accept up to 200 identifiers per request.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from dataclasses import dataclass
17
+ from typing import Any, Literal, TypedDict, Union
18
+
19
+ from ..exceptions import ConfigurationError, UnknownEventError
20
+ from ._base import BaseAdapter
21
+
22
+ NORMAL_WS_URL = "wss://ws.normal.1322.io/ws/normal"
23
+ ULTIMATE_WS_URL = "wss://ws.ultimate.1322.io/ws/ultimate"
24
+ REST_BASE = "https://api.1322.io"
25
+
26
+ Tier = Literal["normal", "ultimate"]
27
+ TweetType = Literal["TWEET", "RETWEET", "QUOTE", "REPLY"]
28
+
29
+ # --------------------------------------------------------------------------
30
+ # Raw JSON shapes (TypedDicts), mirroring the TS interfaces in the docs.
31
+ # --------------------------------------------------------------------------
32
+
33
+
34
+ class TwitterUrlEntity(TypedDict):
35
+ name: str
36
+ url: str
37
+ tco: str
38
+
39
+
40
+ class TwitterMentionEntity(TypedDict):
41
+ id: str
42
+ name: str
43
+ handle: str
44
+
45
+
46
+ class VerificationLabel(TypedDict, total=False):
47
+ description: str
48
+ badge: str | None
49
+ url: str | None
50
+
51
+
52
+ class VerificationBadge(TypedDict):
53
+ type: Literal["none", "blue", "gold"]
54
+ label: VerificationLabel | None
55
+
56
+
57
+ VerifiedField = Union[bool, VerificationBadge]
58
+
59
+
60
+ class TwitterMiniUser(TypedDict, total=False):
61
+ id: str
62
+ handle: str
63
+ name: str
64
+ avatar: str | None
65
+ verified: VerifiedField
66
+ profile: dict[str, Any]
67
+ metrics: dict[str, Any]
68
+
69
+
70
+ class TwitterUserProfileUrl(TypedDict):
71
+ name: str
72
+ url: str
73
+ tco: str
74
+
75
+
76
+ class TwitterUserProfileDescription(TypedDict):
77
+ text: str
78
+ urls: list[TwitterUrlEntity]
79
+
80
+
81
+ class TwitterUserProfile(TypedDict):
82
+ name: str
83
+ location: str | None
84
+ avatar: str | None
85
+ banner: str | None
86
+ pinned: list[str]
87
+ url: TwitterUserProfileUrl | None
88
+ description: TwitterUserProfileDescription
89
+
90
+
91
+ class TwitterUserMetrics(TypedDict):
92
+ likes: int
93
+ media: int
94
+ tweets: int
95
+ friends: int
96
+ followers: int
97
+ following: int
98
+
99
+
100
+ class TwitterUser(TypedDict):
101
+ id: str
102
+ handle: str
103
+ private: bool
104
+ verified: VerifiedField
105
+ sensitive: bool
106
+ restricted: bool
107
+ joined_at: int
108
+ profile: TwitterUserProfile
109
+ metrics: TwitterUserMetrics
110
+
111
+
112
+ class TwitterMiniTweetBody(TypedDict):
113
+ text: str
114
+ urls: list[TwitterUrlEntity]
115
+ mentions: list[TwitterMentionEntity]
116
+
117
+
118
+ class TwitterMiniTweetMediaProxied(TypedDict):
119
+ images: list[str]
120
+
121
+
122
+ class TwitterMiniTweetMedia(TypedDict):
123
+ images: list[str]
124
+ videos: list[str]
125
+ thumbnails: list[str]
126
+ proxied: TwitterMiniTweetMediaProxied | None
127
+
128
+
129
+ class TwitterRef(TypedDict):
130
+ id: str
131
+ handle: str
132
+
133
+
134
+ class TwitterMiniTweet(TypedDict):
135
+ id: str
136
+ type: TweetType
137
+ created_at: int
138
+ author: TwitterMiniUser
139
+ subtweet: "TwitterMiniTweet | None"
140
+ reply: TwitterRef | None
141
+ quoted: TwitterRef | None
142
+ body: TwitterMiniTweetBody
143
+ media: TwitterMiniTweetMedia
144
+
145
+
146
+ class TwitterTextComponent(TypedDict):
147
+ type: Literal["text"]
148
+ text: str
149
+ bold: bool
150
+ italics: bool
151
+
152
+
153
+ class TwitterImageComponent(TypedDict):
154
+ type: Literal["image"]
155
+ url: str
156
+
157
+
158
+ class TwitterVideoComponent(TypedDict):
159
+ type: Literal["video"]
160
+ url: str
161
+
162
+
163
+ TweetBodyComponent = Union[TwitterTextComponent, TwitterImageComponent, TwitterVideoComponent]
164
+
165
+
166
+ class TwitterTweetBody(TypedDict):
167
+ text: str
168
+ urls: list[TwitterUrlEntity]
169
+ mentions: list[TwitterMentionEntity]
170
+ components: list[TweetBodyComponent]
171
+
172
+
173
+ class TwitterTweetMediaProxied(TypedDict):
174
+ images: list[str]
175
+ thumbnails: list[str]
176
+
177
+
178
+ class TwitterTweetMedia(TypedDict):
179
+ images: list[str]
180
+ videos: list[str]
181
+ thumbnails: list[str]
182
+ proxied: TwitterTweetMediaProxied | None
183
+
184
+
185
+ # "from" is a Python keyword, so this TypedDict must use the functional
186
+ # (dict-literal) form rather than the class-body form.
187
+ TwitterGrokMessage = TypedDict(
188
+ "TwitterGrokMessage",
189
+ {"from": Literal["USER", "AGENT"], "message": str, "images": list[str]},
190
+ )
191
+
192
+
193
+ class TwitterGrok(TypedDict):
194
+ id: str
195
+ conversation: list[TwitterGrokMessage]
196
+
197
+
198
+ class TwitterCard(TypedDict):
199
+ url: str
200
+ image: str
201
+ title: str
202
+ description: str
203
+
204
+
205
+ class TwitterPollChoice(TypedDict):
206
+ label: str
207
+ count: int
208
+
209
+
210
+ class TwitterPoll(TypedDict):
211
+ ends_at: int
212
+ updated_at: int
213
+ choices: list[TwitterPollChoice]
214
+
215
+
216
+ TwitterArticleTextStyle = TypedDict(
217
+ "TwitterArticleTextStyle",
218
+ {"from": int, "to": int, "text": Literal["bold", "italics", "strikethrough"]},
219
+ )
220
+
221
+ TwitterArticleTextUrl = TypedDict(
222
+ "TwitterArticleTextUrl", {"from": int, "to": int, "url": str}
223
+ )
224
+
225
+
226
+ class TwitterArticleTextLine(TypedDict):
227
+ text: str
228
+ styles: list[TwitterArticleTextStyle]
229
+ urls: list[TwitterArticleTextUrl]
230
+
231
+
232
+ class TwitterArticleDividerComponent(TypedDict):
233
+ type: Literal["divider"]
234
+
235
+
236
+ class TwitterArticleTextComponent(TypedDict):
237
+ type: Literal["text"]
238
+ variant: Literal[
239
+ "header-one",
240
+ "header-two",
241
+ "paragraph",
242
+ "blockquote",
243
+ "ordered-list",
244
+ "unordered-list",
245
+ "latex-box",
246
+ "markdown-box",
247
+ ]
248
+ lines: list[TwitterArticleTextLine]
249
+
250
+
251
+ class TwitterArticleMediaComponent(TypedDict):
252
+ type: Literal["media"]
253
+ variant: Literal["image", "gif", "video"]
254
+ url: str
255
+ thumbnail: str
256
+ caption: str | None
257
+
258
+
259
+ class TwitterArticleEmbeddedTweet(TypedDict):
260
+ id: str
261
+ url: str
262
+ object: "TwitterTweet | None"
263
+
264
+
265
+ class TwitterArticleTweetComponent(TypedDict):
266
+ type: Literal["tweet"]
267
+ tweet: TwitterArticleEmbeddedTweet
268
+
269
+
270
+ ArticleComponent = Union[
271
+ TwitterArticleDividerComponent,
272
+ TwitterArticleTextComponent,
273
+ TwitterArticleMediaComponent,
274
+ TwitterArticleTweetComponent,
275
+ ]
276
+
277
+
278
+ class TwitterArticleBody(TypedDict):
279
+ text: str
280
+ components: list[ArticleComponent]
281
+
282
+
283
+ class TwitterArticle(TypedDict):
284
+ id: str
285
+ title: str
286
+ thumbnail: str | None
287
+ created_at: int
288
+ updated_at: int
289
+ body: TwitterArticleBody
290
+
291
+
292
+ class TwitterAdvancedMetrics(TypedDict):
293
+ views: int
294
+
295
+
296
+ class TwitterTweetMetrics(TypedDict):
297
+ likes: int
298
+ quotes: int
299
+ replies: int
300
+ retweets: int
301
+ advanced: TwitterAdvancedMetrics | None
302
+
303
+
304
+ class TwitterCommunity(TypedDict):
305
+ id: str
306
+ name: str
307
+ url: str
308
+
309
+
310
+ class TwitterTweet(TypedDict, total=False):
311
+ id: str
312
+ type: TweetType
313
+ created_at: int
314
+ author: TwitterUser
315
+ subtweet: "TwitterTweet | None"
316
+ reply: TwitterRef | None
317
+ quoted: TwitterRef | None
318
+ body: TwitterTweetBody
319
+ media: TwitterTweetMedia
320
+ grok: TwitterGrok | None
321
+ card: TwitterCard | None
322
+ poll: TwitterPoll | None
323
+ article: TwitterArticle | None
324
+ metrics: TwitterTweetMetrics
325
+ community: TwitterCommunity
326
+
327
+
328
+ # --------------------------------------------------------------------------
329
+ # Event envelopes
330
+ # --------------------------------------------------------------------------
331
+
332
+
333
+ @dataclass(slots=True)
334
+ class MiniTweetUpdate:
335
+ type: Literal["tweet.mini.update"]
336
+ tweet: TwitterMiniTweet
337
+ raw: dict[str, Any]
338
+
339
+
340
+ @dataclass(slots=True)
341
+ class TweetUpdate:
342
+ type: Literal["tweet.update"]
343
+ tweet: TwitterTweet
344
+ raw: dict[str, Any]
345
+
346
+
347
+ @dataclass(slots=True)
348
+ class TweetUpdateExpanded:
349
+ type: Literal["tweet.update.expanded"]
350
+ tweet: TwitterTweet
351
+ raw: dict[str, Any]
352
+
353
+
354
+ @dataclass(slots=True)
355
+ class TweetFull:
356
+ type: Literal["tweet.full"]
357
+ tweet: TwitterTweet
358
+ raw: dict[str, Any]
359
+
360
+
361
+ @dataclass(slots=True)
362
+ class DeletedTweet:
363
+ type: Literal["tweet.deleted"]
364
+ tweet: TwitterTweet
365
+ deleted_at: int
366
+ raw: dict[str, Any]
367
+
368
+
369
+ @dataclass(slots=True)
370
+ class ProfileUpdate:
371
+ type: Literal["profile.update"]
372
+ user: TwitterUser
373
+ before: TwitterUser
374
+ raw: dict[str, Any]
375
+
376
+
377
+ @dataclass(slots=True)
378
+ class FollowingUpdate:
379
+ type: Literal["following.update"]
380
+ change: Literal["followed", "unfollowed"]
381
+ following: TwitterUser
382
+ user: TwitterUser
383
+ raw: dict[str, Any]
384
+
385
+
386
+ @dataclass(slots=True)
387
+ class ProfilePinnedUpdate:
388
+ type: Literal["profile.pinned.update"]
389
+ user: TwitterUser
390
+ pinned: list[TwitterTweet]
391
+ raw: dict[str, Any]
392
+
393
+
394
+ @dataclass(slots=True)
395
+ class ProfileUnpinnedUpdate:
396
+ type: Literal["profile.unpinned.update"]
397
+ user: TwitterUser
398
+ pinned: list[TwitterTweet]
399
+ raw: dict[str, Any]
400
+
401
+
402
+ XEvent = Union[
403
+ MiniTweetUpdate,
404
+ TweetUpdate,
405
+ TweetUpdateExpanded,
406
+ TweetFull,
407
+ DeletedTweet,
408
+ ProfileUpdate,
409
+ FollowingUpdate,
410
+ ProfilePinnedUpdate,
411
+ ProfileUnpinnedUpdate,
412
+ ]
413
+
414
+ _EVENT_TYPES = {
415
+ "tweet.mini.update",
416
+ "tweet.update",
417
+ "tweet.update.expanded",
418
+ "tweet.full",
419
+ "tweet.deleted",
420
+ "profile.update",
421
+ "following.update",
422
+ "profile.pinned.update",
423
+ "profile.unpinned.update",
424
+ }
425
+
426
+
427
+ def parse_x_event(raw: dict[str, Any]) -> XEvent:
428
+ """Parse one decoded X WebSocket frame into a typed event.
429
+
430
+ Every frame has ``{id, type, source: "1322"}`` plus type-specific fields
431
+ (see https://1322.io/docs, "WS Data Types & Events").
432
+ """
433
+ event_type = raw.get("type")
434
+ if event_type == "tweet.mini.update":
435
+ return MiniTweetUpdate(type=event_type, tweet=raw["tweet"], raw=raw)
436
+ if event_type == "tweet.update":
437
+ return TweetUpdate(type=event_type, tweet=raw["tweet"], raw=raw)
438
+ if event_type == "tweet.update.expanded":
439
+ return TweetUpdateExpanded(type=event_type, tweet=raw["tweet"], raw=raw)
440
+ if event_type == "tweet.full":
441
+ return TweetFull(type=event_type, tweet=raw["tweet"], raw=raw)
442
+ if event_type == "tweet.deleted":
443
+ return DeletedTweet(
444
+ type=event_type,
445
+ tweet=raw["tweet"],
446
+ deleted_at=raw.get("deleted_at", 0),
447
+ raw=raw,
448
+ )
449
+ if event_type == "profile.update":
450
+ return ProfileUpdate(type=event_type, user=raw["user"], before=raw["before"], raw=raw)
451
+ if event_type == "following.update":
452
+ return FollowingUpdate(
453
+ type=event_type,
454
+ change=raw["change"],
455
+ following=raw["following"],
456
+ user=raw["user"],
457
+ raw=raw,
458
+ )
459
+ if event_type == "profile.pinned.update":
460
+ return ProfilePinnedUpdate(
461
+ type=event_type, user=raw["user"], pinned=raw.get("pinned", []), raw=raw
462
+ )
463
+ if event_type == "profile.unpinned.update":
464
+ return ProfileUnpinnedUpdate(
465
+ type=event_type, user=raw["user"], pinned=raw.get("pinned", []), raw=raw
466
+ )
467
+ raise UnknownEventError(f"Unrecognized X event type: {event_type!r}")
468
+
469
+
470
+ def tweet_of(event: XEvent) -> TwitterTweet | TwitterMiniTweet | None:
471
+ """Return the tweet payload carried by ``event``, if any."""
472
+ if isinstance(event, (MiniTweetUpdate, TweetUpdate, TweetUpdateExpanded, TweetFull, DeletedTweet)):
473
+ return event.tweet
474
+ return None
475
+
476
+
477
+ # --------------------------------------------------------------------------
478
+ # Adapter
479
+ # --------------------------------------------------------------------------
480
+
481
+
482
+ class XAdapter(BaseAdapter):
483
+ """X / Twitter connection + REST management API."""
484
+
485
+ rest_base = REST_BASE
486
+
487
+ def __init__(self, api_key: str, *, tier: Tier = "normal", **kwargs: Any) -> None:
488
+ if tier not in ("normal", "ultimate"):
489
+ raise ConfigurationError(f"tier must be 'normal' or 'ultimate', got {tier!r}")
490
+ super().__init__(api_key, **kwargs)
491
+ self.tier: Tier = tier
492
+
493
+ def _ws_url(self) -> str:
494
+ return NORMAL_WS_URL if self.tier == "normal" else ULTIMATE_WS_URL
495
+
496
+ def _ws_headers(self) -> dict[str, str]:
497
+ return {"X-API-Key": self.api_key}
498
+
499
+ def _rest_headers(self) -> dict[str, str]:
500
+ return {"X-API-Key": self.api_key}
501
+
502
+ def _parse(self, raw: dict[str, Any]) -> XEvent:
503
+ return parse_x_event(raw)
504
+
505
+ # -- REST: GET /v1/tracked, GET /v1/keys, POST/DELETE /v1/tracked,
506
+ # GET /v1/data/tweet/:id, GET /v1/resolve/username/:username, GET /v1/health
507
+
508
+ async def list_tracked(self) -> dict[str, Any]:
509
+ return await self._request("GET", "/v1/tracked")
510
+
511
+ async def list_keys(self) -> dict[str, Any]:
512
+ """GET /v1/keys -- all keys (normal + ultimate) for hybrid accounts."""
513
+ return await self._request("GET", "/v1/keys")
514
+
515
+ @staticmethod
516
+ def _identifiers_param(identifiers: str | list[str]) -> str:
517
+ if isinstance(identifiers, str):
518
+ return identifiers
519
+ return ",".join(identifiers)
520
+
521
+ async def add_tracked(
522
+ self,
523
+ identifiers: str | list[str],
524
+ id_type: Literal["username", "id"] = "username",
525
+ ) -> dict[str, Any]:
526
+ """POST /v1/tracked. Accepts up to 200 identifiers per call."""
527
+ body = {"identifiers": self._identifiers_param(identifiers), "type": id_type}
528
+ return await self._request("POST", "/v1/tracked", json=body)
529
+
530
+ async def remove_tracked(
531
+ self,
532
+ identifiers: str | list[str],
533
+ id_type: Literal["username", "id"] = "username",
534
+ ) -> dict[str, Any]:
535
+ """DELETE /v1/tracked. Accepts up to 200 identifiers per call."""
536
+ body = {"identifiers": self._identifiers_param(identifiers), "type": id_type}
537
+ return await self._request("DELETE", "/v1/tracked", json=body)
538
+
539
+ async def get_tweet(
540
+ self, tweet_id: str, *, full: bool = False, expanded: bool = False
541
+ ) -> dict[str, Any]:
542
+ """GET /v1/data/tweet/:id."""
543
+ params: dict[str, str] = {}
544
+ if full:
545
+ params["full"] = "true"
546
+ if expanded:
547
+ params["expanded"] = "true"
548
+ return await self._request("GET", f"/v1/data/tweet/{tweet_id}", params=params)
549
+
550
+ async def resolve_username(self, username: str) -> dict[str, Any]:
551
+ """GET /v1/resolve/username/:username."""
552
+ return await self._request("GET", f"/v1/resolve/username/{username}")
553
+
554
+ async def health(self) -> dict[str, Any]:
555
+ return await self._request("GET", "/v1/health")
556
+
557
+
558
+ __all__ = [
559
+ "XAdapter",
560
+ "XEvent",
561
+ "MiniTweetUpdate",
562
+ "TweetUpdate",
563
+ "TweetUpdateExpanded",
564
+ "TweetFull",
565
+ "DeletedTweet",
566
+ "ProfileUpdate",
567
+ "FollowingUpdate",
568
+ "ProfilePinnedUpdate",
569
+ "ProfileUnpinnedUpdate",
570
+ "parse_x_event",
571
+ "tweet_of",
572
+ "TwitterTweet",
573
+ "TwitterMiniTweet",
574
+ "TwitterUser",
575
+ "TwitterMiniUser",
576
+ "VerificationBadge",
577
+ ]