Debian Codegraph @

gallery_dl/extractor/twitter.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2016-2026 Mike Fährmann
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License version 2 as
7 # published by the Free Software Foundation.
8
9 """Extractors for https://x.com/"""
10
11 from .common import Extractor, Message, Dispatch
12 from .. import text, util, dt
13 import itertools
14 import random
15
16 BASE_PATTERN = (r"(?:https?://)?(?:www\.|mobile\.)?"
17 r"(?:(?:[fv]x)?twitter|(?:fix(?:up|v))?x)\.com")
18 USER_PATTERN = BASE_PATTERN + r"/([^/?#]+)"
19
20
21 class TwitterExtractor(Extractor):
22 """Base class for twitter extractors"""
23 category = "twitter"
24 directory_fmt = ("{category}", "{user[name]}")
25 filename_fmt = "{tweet_id}_{num}.{extension}"
26 archive_fmt = "{tweet_id}_{retweet_id}_{num}"
27 cookies_domain = ".x.com"
28 cookies_names = ("auth_token",)
29 root = "https://x.com"
30 browser = "firefox"
31
32 def __init__(self, match):
33 Extractor.__init__(self, match)
34 self.user = match[1]
35
36 def _init(self):
37 self.showmore = self.config("showmore", True)
38 self.showreplies = self.config("showreplies", True)
39 self.unavailable = self.config("unavailable", False)
40 self.textonly = self.config("text-tweets", False)
41 self.retweets = self.config("retweets", False)
42 self.replies = self.config("replies", True)
43 self.twitpic = self.config("twitpic", False)
44 self.pinned = self.config("pinned", False)
45 self.quoted = self.config("quoted", False)
46 self.quoted_expand = self.quoted and self.config("quoted-expand", True)
47 self.ads = self.config("ads", False)
48 self.cards = self.config("cards", False)
49 self.cards_blacklist = self.config("cards-blacklist")
50 self.videos_files = self.config("videos", True)
51 self.videos_previews = self.config("previews", False)
52 self.videos_ytdl = (self.videos_files == "ytdl")
53 self.videos = (self.videos_files or self.videos_previews)
54
55 if not self.config("transform", True):
56 self._transform_community = \
57 self._transform_tweet = \
58 self._transform_user = util.identity
59
60 self.articles = articles = self.config("articles", True)
61 if articles:
62 if isinstance(articles, str):
63 articles = articles.split(",")
64 elif not isinstance(articles, (list, tuple)):
65 articles = {"meta", "cover", "media"}
66 self._article_doc = ("doc" in articles or "document" in articles)
67 self._article_html = ("html" in articles)
68 self._article_meta = ("meta" in articles or "metadata" in articles)
69 self._article_cover = ("cover" in articles)
70 self._article_media = ("media" in articles)
71
72 self.api = TwitterAPI(self)
73 self._cursor = None
74 self._user = None
75 self._user_obj = None
76 self._user_cache = {}
77 self._init_sizes()
78
79 def _init_sizes(self):
80 size = self.config("size")
81 if size is None:
82 self._size_image = "orig"
83 self._size_fallback = ("4096x4096", "large", "medium", "small")
84 else:
85 if isinstance(size, str):
86 size = size.split(",")
87 self._size_image = size[0]
88 self._size_fallback = size[1:]
89
90 def items(self):
91 self.login()
92 metadata = self.metadata()
93 seen_tweets = set() if self.config("unique", True) else None
94
95 if self.twitpic:
96 self._find_twitpic = text.re(
97 r"https?(://twitpic\.com/(?!photos/)\w+)").findall
98
99 tweets = self.tweets()
100 if self.config("expand"):
101 tweets = self._expand_tweets(tweets)
102 for tweet in tweets:
103
104 if "legacy" in tweet:
105 data = tweet["legacy"]
106 else:
107 data = tweet
108
109 if not self.retweets and "retweeted_status_id_str" in data:
110 self.log.debug("Skipping %s (retweet)", data["id_str"])
111 continue
112 if not self.quoted and "quoted_by_id_str" in data:
113 self.log.debug("Skipping %s (quoted tweet)", data["id_str"])
114 continue
115 if "in_reply_to_user_id_str" in data and (
116 not self.replies or (
117 self.replies == "self" and
118 data["user_id_str"] !=
119 (self._user_obj["rest_id"] if self._user else
120 data["in_reply_to_user_id_str"])
121 )
122 ):
123 self.log.debug("Skipping %s (reply)", data["id_str"])
124 continue
125
126 if seen_tweets is not None:
127 if data["id_str"] in seen_tweets:
128 self.log.debug(
129 "Skipping %s (previously seen)", data["id_str"])
130 continue
131 seen_tweets.add(data["id_str"])
132
133 if "withheld_scope" in data:
134 txt = data.get("full_text") or data.get("text") or ""
135 self.log.warning("'%s' (%s)", txt, data["id_str"])
136
137 files = self._extract_files(data, tweet)
138 if not files and not self.textonly:
139 continue
140
141 tdata = self._transform_tweet(tweet)
142 tdata.update(metadata)
143 tdata["count"] = len(files)
144 yield Message.Directory, "", tdata
145
146 tdata.pop("source_id", None)
147 tdata.pop("source_user", None)
148 tdata.pop("sensitive_flags", None)
149
150 for tdata["num"], file in enumerate(files, 1):
151 file.update(tdata)
152 url = file.pop("url")
153 if "extension" not in file:
154 text.nameext_from_url(url, file)
155 yield Message.Url, url, file
156
157 def _extract_files(self, data, tweet):
158 files = []
159
160 if "extended_entities" in data:
161 try:
162 self._extract_media(
163 data, data["extended_entities"]["media"], files)
164 except Exception as exc:
165 self.log.traceback(exc)
166 self.log.warning(
167 "%s: Error while extracting media files (%s: %s)",
168 data["id_str"], exc.__class__.__name__, exc)
169
170 if self.cards and "card" in tweet:
171 try:
172 tweet["id_str"] = data["id_str"]
173 self._extract_card(tweet, files)
174 except Exception as exc:
175 self.log.traceback(exc)
176 self.log.warning(
177 "%s: Error while extracting Card files (%s: %s)",
178 data["id_str"], exc.__class__.__name__, exc)
179
180 if self.articles and "article" in tweet:
181 try:
182 self._extract_article(tweet, files)
183 except Exception as exc:
184 self.log.traceback(exc)
185 self.log.warning(
186 "%s: Error while processing article data (%s: %s)",
187 data["id_str"], exc.__class__.__name__, exc)
188
189 if self.twitpic:
190 try:
191 self._extract_twitpic(data, files)
192 except Exception as exc:
193 self.log.traceback(exc)
194 self.log.warning(
195 "%s: Error while extracting TwitPic files (%s: %s)",
196 data["id_str"], exc.__class__.__name__, exc)
197
198 return files
199
200 def _extract_media(self, tweet, entities, files):
201 flags_tweet = None
202
203 for media in entities:
204
205 if "sensitive_media_warning" in media:
206 flags_media = media["sensitive_media_warning"]
207
208 flags = []
209 if "adult_content" in flags_media:
210 flags.append("Nudity")
211 if "other" in flags_media:
212 flags.append("Sensitive")
213 if "graphic_violence" in flags_media:
214 flags.append("Violence")
215
216 if flags_tweet is None:
217 flags_tweet = set(flags)
218 else:
219 flags_tweet.update(flags)
220 flags_media = flags
221 else:
222 flags_media = ()
223
224 if "ext_media_availability" in media:
225 ext = media["ext_media_availability"]
226 if ext.get("status") == "Unavailable":
227 self.log.warning("Media unavailable (%s - '%s')",
228 tweet["id_str"], ext.get("reason"))
229 if not self.unavailable:
230 continue
231
232 if "video_info" in media:
233 if self.videos_ytdl:
234 url = (f"ytdl:{self.root}/i/web/status/"
235 f"{tweet.get('id_str') or tweet['rest_id']}")
236 file = {"url": url, "extension": "mp4"}
237 elif self.videos_files:
238 video_info = media["video_info"]
239 variant = max(
240 video_info["variants"],
241 key=lambda v: v.get("bitrate", 0),
242 )
243 file = {
244 "url" : variant["url"],
245 "bitrate" : variant.get("bitrate", 0),
246 "duration": video_info.get(
247 "duration_millis", 0) / 1000,
248 }
249 else:
250 file = None
251
252 if file is not None:
253 file["type"] = media.get("type")
254 file["width"] = media["original_info"].get("width", 0)
255 file["height"] = media["original_info"].get("height", 0)
256 file["description"] = media.get("ext_alt_text")
257 file["sensitive_flags"] = flags_media
258 self._extract_media_source(file, media)
259 files.append(file)
260
261 if not self.videos_previews:
262 continue
263 media["type"] = "preview"
264
265 if "media_url_https" in media:
266 url = media["media_url_https"]
267 if url[-4] == ".":
268 base, _, fmt = url.rpartition(".")
269 base = f"{base}?format={fmt}&name="
270 else:
271 base = url.rpartition("=")[0] + "="
272 file = text.nameext_from_url(url, {
273 "url" : base + self._size_image,
274 "_fallback": self._image_fallback(base),
275 })
276 else:
277 files.append({"url": media["media_url"]})
278 continue
279
280 file["type"] = media.get("type")
281 file["width"] = media["original_info"].get("width", 0)
282 file["height"] = media["original_info"].get("height", 0)
283 file["description"] = media.get("ext_alt_text")
284 file["sensitive_flags"] = flags_media
285 self._extract_media_source(file, media)
286 files.append(file)
287
288 tweet["sensitive_flags"] = \
289 () if flags_tweet is None else sorted(flags_tweet)
290
291 def _extract_media_source(self, dest, media):
292 dest["source_id"] = 0
293
294 if "source_status_id_str" in media:
295 try:
296 dest["source_id"] = text.parse_int(
297 media["source_status_id_str"])
298 dest["source_user"] = self._transform_user(
299 media["additional_media_info"]["source_user"]
300 ["user_results"]["result"])
301 except Exception:
302 pass
303
304 def _image_fallback(self, base):
305 for fmt in self._size_fallback:
306 yield base + fmt
307
308 def _extract_components(self, tweet, data, files):
309 for component_id in data["components"]:
310 com = data["component_objects"][component_id]
311 for conv in com["data"].get("conversation_preview") or ():
312 for url in conv.get("mediaUrls") or ():
313 files.append({"url": url})
314
315 def _extract_card(self, tweet, files):
316 card = tweet["card"]
317 if "legacy" in card:
318 card = card["legacy"]
319
320 try:
321 name = card["name"].rpartition(":")[2]
322 bvals = card["binding_values"]
323 except Exception:
324 self.log.debug("%s: Ignoring external card (%s)",
325 tweet["id_str"], card.get("rest_id"))
326 return
327
328 if isinstance(bvals, list):
329 bvals = {bval["key"]: bval["value"]
330 for bval in card["binding_values"]}
331
332 if cbl := self.cards_blacklist:
333 if name in cbl:
334 return
335 if "vanity_url" in bvals:
336 domain = bvals["vanity_url"]["string_value"]
337 if domain in cbl or name + ":" + domain in cbl:
338 return
339
340 if name in {"summary", "summary_large_image"}:
341 for prefix in ("photo_image_full_size_",
342 "summary_photo_image_",
343 "thumbnail_image_"):
344 for size in ("original", "x_large", "large", "small"):
345 key = prefix + size
346 if key in bvals:
347 value = bvals[key].get("image_value")
348 if value and "url" in value:
349 base, sep, size = value["url"].rpartition("&name=")
350 if sep:
351 base += sep
352 value["url"] = base + self._size_image
353 value["_fallback"] = self._image_fallback(base)
354 files.append(value)
355 return
356 elif name == "unified_card":
357 data = util.json_loads(bvals["unified_card"]["string_value"])
358 if "media_entities" in data:
359 self._extract_media(
360 tweet, data["media_entities"].values(), files)
361 if "component_objects" in data:
362 self._extract_components(tweet, data, files)
363 return
364 elif name == "poll_choice_images":
365 for i in range(1, 100):
366 key = f"choice{i}_image_original"
367 if key not in bvals:
368 break
369 value = bvals[key].get("image_value")
370 if value and "url" in value:
371 base, sep, size = value["url"].rpartition("&name=")
372 if sep:
373 base += sep
374 value["url"] = base + self._size_image
375 value["_fallback"] = self._image_fallback(base)
376 files.append(value)
377 return
378
379 if self.cards == "ytdl":
380 tweet_id = tweet.get("rest_id") or tweet["id_str"]
381 url = f"ytdl:{self.root}/i/web/status/{tweet_id}"
382 files.append({"url": url})
383
384 def _extract_article(self, tweet, files):
385 article = tweet["article"]["article_results"]["result"]
386 if self._article_meta:
387 tweet["article"] = {
388 "id": article.get("rest_id"),
389 "title": article.get("title"),
390 "date": self.parse_timestamp(
391 (m := article.get("metadata")) and
392 m.get("first_published_at_secs")),
393 "date_updated": self.parse_timestamp(
394 (m := article.get("lifecycle_state")) and
395 m.get("modified_at_secs")),
396 }
397 if self._article_html:
398 html = self.utils("article").to_html(article)
399 if "article" not in tweet:
400 tweet["article"] = {}
401 tweet["article"]["html"] = "".join(html)
402 else:
403 html = None
404 if self._article_doc:
405 doc = self.utils("article").to_document(article, html)
406 files.append({
407 "url" : "text:" + "".join(doc),
408 "type" : "article:html",
409 "extension": "htm",
410 })
411 if self._article_cover:
412 if media := article.get("cover_media"):
413 files.append(self._extract_article_media(media, "cover"))
414 if self._article_media:
415 for media in article["media_entities"]:
416 files.append(self._extract_article_media(media, "image"))
417
418 def _extract_article_media(self, media, type):
419 info = media["media_info"]
420
421 if "duration_millis" in info:
422 preview = info["preview_image"]
423 variant = max(info["variants"],
424 key=lambda v: v.get("bit_rate", 0))
425 return {
426 "url" : variant["url"],
427 "bitrate" : variant.get("bit_rate"),
428 "duration" : info["duration_millis"] / 1000,
429 "width" : preview["original_img_width"],
430 "height" : preview["original_img_height"],
431 "media_id" : media["media_id"],
432 "media_key": media["media_key"],
433 "type" : "article:video",
434 }
435
436 url = info["original_img_url"]
437 if url[-4] == ".":
438 base, _, fmt = url.rpartition(".")
439 base = f"{base}?format={fmt}&name="
440 else:
441 base = url.rpartition("=")[0] + "="
442
443 return {
444 "url" : base + self._size_image,
445 "_fallback": self._image_fallback(base),
446 "width" : info["original_img_width"],
447 "height" : info["original_img_height"],
448 "media_id" : media["media_id"],
449 "media_key": media["media_key"],
450 "type" : "article:" + type,
451 }
452
453 def _extract_twitpic(self, tweet, files):
454 urls = {}
455
456 # collect URLs from entities
457 for url in tweet["entities"].get("urls") or ():
458 url = url.get("expanded_url") or url.get("url") or ""
459 if not url or "//twitpic.com/" not in url or "/photos/" in url:
460 continue
461 if url.startswith("http:"):
462 url = "https" + url[4:]
463 urls[url] = None
464
465 # collect URLs from text
466 for url in self._find_twitpic(
467 tweet.get("full_text") or tweet.get("text") or ""):
468 urls["https" + url] = None
469
470 # extract actual URLs
471 for url in urls:
472 response = self.request(url, fatal=False)
473 if response.status_code >= 400:
474 continue
475 if url := text.extr(
476 response.text, 'name="twitter:image" value="', '"'):
477 files.append({"url": url})
478
479 def _transform_tweet(self, tweet):
480 if "legacy" in tweet:
481 legacy = tweet["legacy"]
482 else:
483 legacy = tweet
484 tweet_id = int(legacy["id_str"])
485
486 if "author" in tweet:
487 author = tweet["author"]
488 elif "core" in tweet:
489 try:
490 author = tweet["core"]["user_results"]["result"]
491 except KeyError:
492 self.log.warning("%s: Missing 'author' data", tweet_id)
493 author = util.NONE
494 else:
495 author = tweet["user"]
496 author = self._transform_user(author)
497
498 if tweet_id >= 300_000_000_000_000:
499 date = self._tweetid_to_datetime(tweet_id)
500 else:
501 try:
502 date = dt.parse(
503 legacy["created_at"], "%a %b %d %H:%M:%S %z %Y")
504 except Exception:
505 date = dt.NONE
506 source = tweet.get("source")
507
508 tget = legacy.get
509 tdata = {
510 "tweet_id" : tweet_id,
511 "retweet_id" : text.parse_int(
512 tget("retweeted_status_id_str")),
513 "quote_id" : text.parse_int(
514 tget("quoted_by_id_str")),
515 "quoted_id" : text.parse_int(
516 tget("quoted_status_id_str")),
517 "reply_id" : text.parse_int(
518 tget("in_reply_to_status_id_str")),
519 "conversation_id": text.parse_int(
520 tget("conversation_id_str")),
521 "source_id" : 0,
522 "date" : date,
523 "author" : author,
524 "user" : self._user or author,
525 "lang" : legacy["lang"],
526 "source" : text.extr(source, ">", "<") if source else "",
527 "sensitive" : tget("possibly_sensitive"),
528 "sensitive_flags": tget("sensitive_flags"),
529 "favorite_count": tget("favorite_count"),
530 "quote_count" : tget("quote_count"),
531 "reply_count" : tget("reply_count"),
532 "retweet_count" : tget("retweet_count"),
533 "bookmark_count": tget("bookmark_count"),
534 }
535
536 if "views" in tweet:
537 try:
538 tdata["view_count"] = int(tweet["views"]["count"])
539 except Exception:
540 tdata["view_count"] = 0
541 else:
542 tdata["view_count"] = 0
543
544 if "note_tweet" in tweet:
545 note = tweet["note_tweet"]["note_tweet_results"]["result"]
546 content = note["text"]
547 entities = note["entity_set"]
548 else:
549 content = tget("full_text") or tget("text") or ""
550 entities = legacy["entities"]
551
552 if "author_community_relationship" in tweet:
553 tdata["community"] = self._transform_community(
554 tweet["author_community_relationship"]
555 ["community_results"]["result"])
556
557 if hashtags := entities.get("hashtags"):
558 tdata["hashtags"] = [t["text"] for t in hashtags]
559
560 if mentions := entities.get("user_mentions"):
561 tdata["mentions"] = [{
562 "id": text.parse_int(u["id_str"]),
563 "name": u["screen_name"],
564 "nick": u["name"],
565 } for u in mentions]
566
567 content = text.unescape(content)
568 if urls := entities.get("urls"):
569 for url in urls:
570 try:
571 content = content.replace(url["url"], url["expanded_url"])
572 except KeyError:
573 pass
574 txt, _, tco = content.rpartition(" ")
575 tdata["content"] = txt if tco.startswith("https://t.co/") else content
576
577 if "pinned" in tweet:
578 tdata["pinned"] = True
579 if "birdwatch_pivot" in tweet:
580 try:
581 tdata["birdwatch"] = \
582 tweet["birdwatch_pivot"]["subtitle"]["text"]
583 except KeyError:
584 self.log.debug("Unable to extract 'birdwatch' note from %s",
585 tweet["birdwatch_pivot"])
586 if "article" in tweet:
587 tdata["article"] = tweet["article"]
588 if "in_reply_to_screen_name" in legacy:
589 tdata["reply_to"] = legacy["in_reply_to_screen_name"]
590 if "quoted_by" in legacy:
591 tdata["quote_by"] = legacy["quoted_by"]
592 if "extended_entities" in legacy:
593 self._extract_media_source(
594 tdata, legacy["extended_entities"]["media"][0])
595 if tdata["retweet_id"]:
596 tdata["content"] = f"RT @{author['name']}: {tdata['content']}"
597 tdata["date_original"] = self._tweetid_to_datetime(
598 tdata["retweet_id"])
599
600 return tdata
601
602 def _transform_community(self, com):
603 try:
604 cid = com.get("id_str") or com["rest_id"]
605 except KeyError:
606 return {}
607
608 try:
609 return self._user_cache[f"C#{cid}"]
610 except KeyError:
611 pass
612
613 admin = creator = banner = None
614 try:
615 if results := com.get("admin_results"):
616 admin = results["result"]["core"]["screen_name"]
617 except Exception:
618 pass
619 try:
620 if results := com.get("creator_results"):
621 creator = results["result"]["core"]["screen_name"]
622 except Exception:
623 pass
624 try:
625 if results := com.get("custom_banner_media"):
626 banner = results["media_info"]["original_img_url"]
627 except Exception:
628 pass
629
630 self._user_cache[f"C#{cid}"] = cdata = {
631 "id": text.parse_int(cid),
632 "name": com.get("name"),
633 "description": com.get("description"),
634 "date": dt.parse_ts(com.get("created_at", 0) / 1000),
635 "nsfw": com.get("is_nsfw"),
636 "role": com.get("role"),
637 "member_count": com.get("member_count"),
638 "rules": [rule["name"] for rule in com.get("rules", ())],
639 "admin" : admin,
640 "creator": creator,
641 "banner" : banner,
642 }
643
644 return cdata
645
646 def _transform_user(self, user):
647 try:
648 uid = user.get("rest_id") or user["id_str"]
649 except KeyError:
650 # private/invalid user (#4349)
651 return {}
652
653 try:
654 return self._user_cache[uid]
655 except KeyError:
656 pass
657
658 if "core" in user:
659 core = user["core"]
660 legacy = user["legacy"]
661 else:
662 core = legacy = user
663
664 lget = legacy.get
665 if lget("withheld_scope"):
666 self.log.warning("u%s: '%s'", uid, lget("description"))
667
668 self._user_cache[uid] = udata = {
669 "id" : text.parse_int(uid),
670 "name" : core.get("screen_name"),
671 "nick" : core.get("name"),
672 "date" : dt.parse(
673 core["created_at"], "%a %b %d %H:%M:%S %z %Y"),
674 "profile_banner" : lget("profile_banner_url", ""),
675 "favourites_count": lget("favourites_count"),
676 "followers_count" : lget("followers_count"),
677 "friends_count" : lget("friends_count"),
678 "listed_count" : lget("listed_count"),
679 "media_count" : lget("media_count"),
680 "statuses_count" : lget("statuses_count"),
681 }
682
683 if "core" in user:
684 udata["location"] = user["location"].get("location")
685 udata["verified"] = user["verification"]["verified"]
686 udata["protected"] = user["privacy"]["protected"]
687 udata["profile_image"] = user["avatar"].get(
688 "image_url", "").replace("_normal.", ".")
689 else:
690 udata["location"] = user["location"]
691 udata["verified"] = user["verified"]
692 udata["protected"] = user["protected"]
693 udata["profile_image"] = user["profile_image_url_https"].replace(
694 "_normal.", ".")
695
696 descr = legacy["description"]
697 if entities := legacy.get("entities"):
698 if urls := entities["description"].get("urls"):
699 for url in urls:
700 try:
701 descr = descr.replace(url["url"], url["expanded_url"])
702 except KeyError:
703 pass
704 if "url" in entities:
705 url = entities["url"]["urls"][0]
706 udata["url"] = url.get("expanded_url") or url.get("url")
707 udata["description"] = descr
708
709 if self.config("metadata-user", False):
710 try:
711 if (about := self.cache(self.api.user_about_account,
712 udata["name"]).get("about_profile")):
713 udata["source"] = about.get("source")
714 udata["based_in"] = about.get("account_based_in")
715 udata["location_accurate"] = about.get("location_accurate")
716 udata["name_changes"] = (d := about.get(
717 "username_changes")) and d.get("count") or 0
718 udata["friends_mutual"] = self.api.friends_following_list(
719 uid).get("total_count")
720 except Exception as exc:
721 self.log.traceback(exc)
722 self.log.warning("u%s: Failed to extract extended user "
723 "metadata (%s: %s)",
724 uid, exc.__class__.__name__, exc)
725
726 return udata
727
728 def _assign_user(self, user):
729 self._user_obj = user
730 self._user = self._transform_user(user)
731
732 def _users_result(self, users):
733 userfmt = self.config("users")
734 if not userfmt or userfmt == "user":
735 cls = TwitterUserExtractor
736 fmt = (self.root + "/i/user/{rest_id}").format_map
737 elif userfmt == "timeline":
738 cls = TwitterTimelineExtractor
739 fmt = (self.root + "/id:{rest_id}/timeline").format_map
740 elif userfmt == "media":
741 cls = TwitterMediaExtractor
742 fmt = (self.root + "/id:{rest_id}/media").format_map
743 elif userfmt == "tweets":
744 cls = TwitterTweetsExtractor
745 fmt = (self.root + "/id:{rest_id}/tweets").format_map
746 else:
747 cls = None
748 fmt = userfmt.format_map
749
750 for user in users:
751 user["_extractor"] = cls
752 yield Message.Queue, fmt(user), user
753
754 def _expand_tweets(self, tweets):
755 seen = set()
756 for tweet in tweets:
757 obj = tweet["legacy"] if "legacy" in tweet else tweet
758 cid = obj.get("conversation_id_str")
759 if not cid:
760 if cid is False:
761 yield tweet
762 else:
763 tid = obj["id_str"]
764 self.log.warning(
765 "Unable to expand %s (no 'conversation_id')", tid)
766 continue
767 if cid in seen:
768 self.log.debug(
769 "Skipping expansion of %s (previously seen)", cid)
770 continue
771 seen.add(cid)
772 try:
773 yield from self.api.tweet_detail(cid)
774 except Exception:
775 yield tweet
776
777 def _make_tweet(self, user, url, id_str):
778 return {
779 "id_str": id_str,
780 "conversation_id_str": False,
781 "lang": None,
782 "user": user,
783 "source": "><",
784 "entities": {},
785 "extended_entities": {
786 "media": [
787 {
788 "original_info": {},
789 "media_url": url,
790 },
791 ],
792 },
793 }
794
795 def _init_cursor(self):
796 cursor = self.config("cursor", True)
797 if not cursor:
798 self._update_cursor = util.identity
799 elif isinstance(cursor, str):
800 return cursor
801
802 def _update_cursor(self, cursor):
803 self.log.debug("Cursor: %s", cursor)
804 self._cursor = cursor
805 return cursor
806
807 def _tweetid_to_datetime(self, tweet_id):
808 return dt.parse_ts(((tweet_id >> 22) + 1_288_834_974_657) / 1000)
809
810 def metadata(self):
811 """Return general metadata"""
812 return {}
813
814 def tweets(self):
815 """Yield all relevant tweet objects"""
816
817 def finalize(self, status):
818 if status and self._cursor:
819 self.log.info("Use '-o cursor=%s' to continue downloading "
820 "from the current position", self._cursor)
821
822 def login(self):
823 if self.cookies_check(self.cookies_names):
824 return
825
826 username, password = self._get_auth_info()
827 if username:
828 return self.cookies_update(self.cache(
829 self._login_impl, username, password, _mem=False))
830
831 def _login_impl(self, username, password):
832 self.log.error("Login with username & password is no longer "
833 "supported. Use browser cookies instead.")
834 return {}
835
836
837 class TwitterHomeExtractor(TwitterExtractor):
838 """Extractor for Twitter home timelines"""
839 subcategory = "home"
840 pattern = BASE_PATTERN + r"/home(?:/fo(?:llowing|r[-_ ]?you()))?/?$"
841 example = "https://x.com/home"
842
843 def tweets(self):
844 if self.groups[0] is None:
845 return self.api.home_latest_timeline()
846 return self.api.home_timeline()
847
848
849 class TwitterNotificationsExtractor(TwitterExtractor):
850 """Extractor for Twitter notifications timelines"""
851 subcategory = "notifications"
852 pattern = BASE_PATTERN + r"/(?:notifications|i/timeline())"
853 example = "https://x.com/notifications"
854
855 def tweets(self):
856 return self.api.notifications_devicefollow()
857
858
859 class TwitterSearchExtractor(TwitterExtractor):
860 """Extractor for Twitter search results"""
861 subcategory = "search"
862 pattern = BASE_PATTERN + r"/search/?\?(?:[^&#]+&)*q=([^&#]+)"
863 example = "https://x.com/search?q=QUERY"
864
865 def metadata(self):
866 return {"search": text.unquote(self.user)}
867
868 def tweets(self):
869 query = text.unquote(self.user.replace("+", " "))
870
871 user = None
872 for item in query.split():
873 item = item.strip("()")
874 if item.startswith("from:"):
875 if user:
876 user = None
877 break
878 else:
879 user = item[5:]
880
881 if user is not None:
882 try:
883 self._assign_user(self.api.user_by_screen_name(user))
884 except KeyError:
885 pass
886
887 return self.api.search_timeline(query)
888
889
890 class TwitterHashtagExtractor(TwitterExtractor):
891 """Extractor for Twitter hashtags"""
892 subcategory = "hashtag"
893 pattern = BASE_PATTERN + r"/hashtag/([^/?#]+)"
894 example = "https://x.com/hashtag/NAME"
895
896 def items(self):
897 url = f"{self.root}/search?q=%23{self.user}"
898 data = {"_extractor": TwitterSearchExtractor}
899 yield Message.Queue, url, data
900
901
902 class TwitterUserExtractor(Dispatch, TwitterExtractor):
903 """Extractor for a Twitter user"""
904 pattern = (BASE_PATTERN + r"/(?:"
905 r"([^/?#]+)/?(?:$|\?|#)"
906 r"|i(?:/user/|ntent/user\?user_id=)(\d+))")
907 example = "https://x.com/USER"
908
909 def items(self):
910 user, user_id = self.groups
911 if user_id is not None:
912 user = "id:" + user_id
913
914 base = f"{self.root}/{user}/"
915 return self._dispatch_extractors((
916 (TwitterInfoExtractor , base + "info"),
917 (TwitterAvatarExtractor , base + "photo"),
918 (TwitterBackgroundExtractor, base + "header_photo"),
919 (TwitterTimelineExtractor , base + "timeline"),
920 (TwitterTweetsExtractor , base + "tweets"),
921 (TwitterMediaExtractor , base + "media"),
922 (TwitterWithRepliesExtractor, base + "with_replies"),
923 (TwitterHighlightsExtractor, base + "highlights"),
924 (TwitterLikesExtractor , base + "likes"),
925 ), ("timeline",), (
926 ("with-replies", "replies", None),
927 ))
928
929
930 class TwitterTimelineExtractor(TwitterExtractor):
931 """Extractor for a Twitter user timeline"""
932 subcategory = "timeline"
933 pattern = USER_PATTERN + r"/timeline(?!\w)"
934 example = "https://x.com/USER/timeline"
935
936 def _init_cursor(self):
937 if self._cursor:
938 return self._cursor.partition("/")[2] or None
939 return None
940
941 def _update_cursor(self, cursor):
942 if cursor:
943 self._cursor = self._cursor_prefix + cursor
944 self.log.debug("Cursor: %s", self._cursor)
945 else:
946 self._cursor = None
947 return cursor
948
949 def tweets(self):
950 reset = False
951
952 cursor = self.config("cursor", True)
953 if not cursor:
954 self._update_cursor = util.identity
955 elif isinstance(cursor, str):
956 self._cursor = cursor
957 else:
958 cursor = None
959
960 if cursor:
961 state = cursor.partition("/")[0]
962 state, _, tweet_id = state.partition("_")
963 state = text.parse_int(state, 1)
964 else:
965 state = 1
966
967 if state <= 1:
968 self._cursor_prefix = "1/"
969
970 # yield initial batch of (media) tweets
971 tweet = None
972 for tweet in self._select_tweet_source()(self.user):
973 yield tweet
974 if tweet is None and not cursor:
975 return
976 tweet_id = tweet["rest_id"]
977
978 state = reset = 2
979 else:
980 self.api._user_id_by_screen_name(self.user)
981
982 # build search query
983 try:
984 name = self._user["name"]
985 except KeyError:
986 name = self._user["core"]["screen_name"]
987 query = f"from:{name} max_id:{tweet_id}"
988 if self.retweets:
989 query += " include:retweets include:nativeretweets"
990
991 if state <= 2:
992 self._cursor_prefix = f"2_{tweet_id}/"
993 if reset:
994 self._cursor = self._cursor_prefix
995
996 if not self.textonly:
997 # try to search for media-only tweets
998 tweet = None
999 for tweet in self.api.search_timeline(query + " filter:links"):
1000 yield tweet
1001 if tweet is not None:
1002 return self._update_cursor(None)
1003
1004 state = reset = 3
1005
1006 if state <= 3:
1007 # yield unfiltered search results
1008 self._cursor_prefix = f"3_{tweet_id}/"
1009 if reset:
1010 self._cursor = self._cursor_prefix
1011
1012 yield from self.api.search_timeline(query)
1013 return self._update_cursor(None)
1014
1015 def _select_tweet_source(self):
1016 strategy = self.config("strategy")
1017 if strategy is None or strategy == "auto":
1018 if self.retweets or self.textonly:
1019 return self.api.user_tweets
1020 else:
1021 return self.api.user_media
1022 if strategy == "tweets":
1023 return self.api.user_tweets
1024 if strategy == "media":
1025 return self.api.user_media
1026 if strategy == "with_replies":
1027 return self.api.user_tweets_and_replies
1028 raise self.exc.AbortExtraction(f"Invalid strategy '{strategy}'")
1029
1030
1031 class TwitterTweetsExtractor(TwitterExtractor):
1032 """Extractor for Tweets from a user's Posts timeline"""
1033 subcategory = "tweets"
1034 pattern = USER_PATTERN + r"/tweets(?!\w)"
1035 example = "https://x.com/USER/tweets"
1036
1037 def tweets(self):
1038 return self.api.user_tweets(self.user)
1039
1040
1041 class TwitterWithRepliesExtractor(TwitterExtractor):
1042 """Extractor for Tweets from a user's Replies timeline"""
1043 subcategory = "with-replies"
1044 pattern = USER_PATTERN + r"/with_replies(?!\w)"
1045 example = "https://x.com/USER/with_replies"
1046
1047 def tweets(self):
1048 return self.api.user_tweets_and_replies(self.user)
1049
1050
1051 class TwitterHighlightsExtractor(TwitterExtractor):
1052 """Extractor for Tweets from a user's Highlights timeline"""
1053 subcategory = "highlights"
1054 pattern = USER_PATTERN + r"/highlights(?!\w)"
1055 example = "https://x.com/USER/highlights"
1056
1057 def tweets(self):
1058 return self.api.user_highlights(self.user)
1059
1060
1061 class TwitterMediaExtractor(TwitterExtractor):
1062 """Extractor for Tweets from a user's Media timeline"""
1063 subcategory = "media"
1064 pattern = USER_PATTERN + r"/media(?!\w)"
1065 example = "https://x.com/USER/media"
1066
1067 def tweets(self):
1068 return self.api.user_media(self.user)
1069
1070
1071 class TwitterLikesExtractor(TwitterExtractor):
1072 """Extractor for liked tweets"""
1073 subcategory = "likes"
1074 pattern = USER_PATTERN + r"/likes(?!\w)"
1075 example = "https://x.com/USER/likes"
1076
1077 def metadata(self):
1078 return {"user_likes": self.user}
1079
1080 def tweets(self):
1081 return self.api.user_likes(self.user)
1082
1083
1084 class TwitterBookmarkExtractor(TwitterExtractor):
1085 """Extractor for bookmarked tweets"""
1086 subcategory = "bookmark"
1087 pattern = BASE_PATTERN + r"/i/(?:history|bookmarks)()"
1088 example = "https://x.com/i/history"
1089
1090 def tweets(self):
1091 return self.api.user_bookmarks()
1092
1093 def _transform_tweet(self, tweet):
1094 tdata = TwitterExtractor._transform_tweet(self, tweet)
1095 tdata["date_bookmarked"] = dt.parse_ts(
1096 (int(tweet["sortIndex"] or 0) >> 20) / 1000)
1097 return tdata
1098
1099
1100 class TwitterListExtractor(TwitterExtractor):
1101 """Extractor for Twitter lists"""
1102 subcategory = "list"
1103 pattern = BASE_PATTERN + r"/i/lists/(\d+)/?$"
1104 example = "https://x.com/i/lists/12345"
1105
1106 def tweets(self):
1107 return self.api.list_latest_tweets_timeline(self.user)
1108
1109
1110 class TwitterListMembersExtractor(TwitterExtractor):
1111 """Extractor for members of a Twitter list"""
1112 subcategory = "list-members"
1113 pattern = BASE_PATTERN + r"/i/lists/(\d+)/members"
1114 example = "https://x.com/i/lists/12345/members"
1115
1116 def items(self):
1117 self.login()
1118 return self._users_result(self.api.list_members(self.user))
1119
1120
1121 class TwitterFollowingExtractor(TwitterExtractor):
1122 """Extractor for followed users"""
1123 subcategory = "following"
1124 pattern = USER_PATTERN + r"/following(?!\w)"
1125 example = "https://x.com/USER/following"
1126
1127 def items(self):
1128 self.login()
1129 return self._users_result(self.api.user_following(self.user))
1130
1131
1132 class TwitterFollowersExtractor(TwitterExtractor):
1133 """Extractor for a user's followers"""
1134 subcategory = "followers"
1135 pattern = USER_PATTERN + r"/followers(?!\w)"
1136 example = "https://x.com/USER/followers"
1137
1138 def items(self):
1139 self.login()
1140 return self._users_result(self.api.user_followers(self.user))
1141
1142
1143 class TwitterCommunityExtractor(TwitterExtractor):
1144 """Extractor for a Twitter community"""
1145 subcategory = "community"
1146 directory_fmt = ("{category}", "Communities",
1147 "{community[name]} ({community[id]})")
1148 archive_fmt = "C_{community[id]}_{tweet_id}_{num}"
1149 pattern = BASE_PATTERN + r"/i/communities/(\d+)"
1150 example = "https://x.com/i/communities/12345"
1151
1152 def tweets(self):
1153 if self.textonly:
1154 return self.api.community_tweets_timeline(self.user)
1155 return self.api.community_media_timeline(self.user)
1156
1157
1158 class TwitterCommunitiesExtractor(TwitterExtractor):
1159 """Extractor for followed Twitter communities"""
1160 subcategory = "communities"
1161 directory_fmt = TwitterCommunityExtractor.directory_fmt
1162 archive_fmt = TwitterCommunityExtractor.archive_fmt
1163 pattern = BASE_PATTERN + r"/([^/?#]+)/communities/?$"
1164 example = "https://x.com/i/communities"
1165
1166 def tweets(self):
1167 return self.api.communities_main_page_timeline(self.user)
1168
1169
1170 class TwitterEventExtractor(TwitterExtractor):
1171 """Extractor for Tweets from a Twitter Event"""
1172 subcategory = "event"
1173 directory_fmt = ("{category}", "Events",
1174 "{event[id]} {event[short_title]}")
1175 pattern = BASE_PATTERN + r"/i/events/(\d+)"
1176 example = "https://x.com/i/events/12345"
1177
1178 def metadata(self):
1179 return {"event": self.api.live_event(self.user)}
1180
1181 def tweets(self):
1182 return self.api.live_event_timeline(self.user)
1183
1184
1185 class TwitterTweetExtractor(TwitterExtractor):
1186 """Extractor for individual tweets"""
1187 subcategory = "tweet"
1188 pattern = (BASE_PATTERN + r"/([^/?#]+|i/web)/status/(\d+)"
1189 r"/?(?:$|\?|#|photo/|video/)")
1190 example = "https://x.com/USER/status/12345"
1191
1192 def __init__(self, match):
1193 TwitterExtractor.__init__(self, match)
1194 self.tweet_id = match[2]
1195
1196 def tweets(self):
1197 if conversations := self.config("conversations"):
1198 self._accessible = (conversations == "accessible")
1199 return self._tweets_conversation(self.tweet_id)
1200
1201 endpoint = self.config("tweet-endpoint")
1202 if endpoint == "detail" or endpoint in {None, "auto"} and \
1203 self.api.headers["x-twitter-auth-type"]:
1204 return self._tweets_detail(self.tweet_id)
1205
1206 return self._tweets_single(self.tweet_id)
1207
1208 def _tweets_single(self, tweet_id):
1209 tweet = self.api.tweet_result_by_rest_id(tweet_id)
1210
1211 try:
1212 self._assign_user(tweet["core"]["user_results"]["result"])
1213 except KeyError:
1214 raise self.exc.AbortExtraction(
1215 f"'{tweet.get('reason') or 'Unavailable'}'")
1216
1217 yield tweet
1218
1219 if not self.quoted:
1220 return
1221
1222 while True:
1223 parent_id = tweet["rest_id"]
1224 tweet_id = tweet["legacy"].get("quoted_status_id_str")
1225 if not tweet_id:
1226 break
1227 tweet = self.api.tweet_result_by_rest_id(tweet_id)
1228 tweet["legacy"]["quoted_by_id_str"] = parent_id
1229 yield tweet
1230
1231 def _tweets_detail(self, tweet_id):
1232 tweets = []
1233
1234 for tweet in self.api.tweet_detail(tweet_id):
1235 if tweet["rest_id"] == tweet_id or \
1236 tweet.get("_retweet_id_str") == tweet_id:
1237 if self._user_obj is None:
1238 self._assign_user(tweet["core"]["user_results"]["result"])
1239 tweets.append(tweet)
1240
1241 tweet_id = tweet["legacy"].get("quoted_status_id_str")
1242 if not tweet_id:
1243 break
1244
1245 return tweets
1246
1247 def _tweets_conversation(self, tweet_id):
1248 tweets = self.api.tweet_detail(tweet_id)
1249 buffer = []
1250
1251 for tweet in tweets:
1252 buffer.append(tweet)
1253 if tweet["rest_id"] == tweet_id or \
1254 tweet.get("_retweet_id_str") == tweet_id:
1255 self._assign_user(tweet["core"]["user_results"]["result"])
1256 break
1257 else:
1258 # initial Tweet not accessible
1259 if self._accessible:
1260 return ()
1261 return buffer
1262
1263 return itertools.chain(buffer, tweets)
1264
1265
1266 class TwitterQuotesExtractor(TwitterExtractor):
1267 """Extractor for quotes of a Tweet"""
1268 subcategory = "quotes"
1269 pattern = BASE_PATTERN + r"/(?:[^/?#]+|i/web)/status/(\d+)/quotes"
1270 example = "https://x.com/USER/status/12345/quotes"
1271
1272 def items(self):
1273 url = f"{self.root}/search?q=quoted_tweet_id:{self.user}"
1274 data = {"_extractor": TwitterSearchExtractor}
1275 yield Message.Queue, url, data
1276
1277
1278 class TwitterInfoExtractor(TwitterExtractor):
1279 """Extractor for a user's profile data"""
1280 subcategory = "info"
1281 directory_fmt = ("{category}", "{name}")
1282 pattern = USER_PATTERN + r"/info"
1283 example = "https://x.com/USER/info"
1284
1285 def items(self):
1286 screen_name = self.user
1287 if screen_name.startswith("id:"):
1288 user = self.cache(self.api.user_by_rest_id, screen_name[3:])
1289 else:
1290 user = self.cache(self.api.user_by_screen_name, screen_name)
1291
1292 return iter(((Message.Directory, "",
1293 self._transform_user(user).copy()),))
1294
1295
1296 class TwitterAvatarExtractor(TwitterExtractor):
1297 subcategory = "avatar"
1298 filename_fmt = "avatar {date}.{extension}"
1299 archive_fmt = "AV_{user[id]}_{date}"
1300 pattern = USER_PATTERN + r"/photo"
1301 example = "https://x.com/USER/photo"
1302
1303 def tweets(self):
1304 self.api._user_id_by_screen_name(self.user)
1305 user = self._user_obj
1306 url = user["avatar"]["image_url"]
1307
1308 if url == ("https://abs.twimg.com/sticky"
1309 "/default_profile_images/default_profile_normal.png"):
1310 return ()
1311
1312 url = url.replace("_normal.", ".")
1313 id_str = url.rsplit("/", 2)[1]
1314
1315 return (self._make_tweet(user, url, id_str),)
1316
1317
1318 class TwitterBackgroundExtractor(TwitterExtractor):
1319 subcategory = "background"
1320 filename_fmt = "background {date}.{extension}"
1321 archive_fmt = "BG_{user[id]}_{date}"
1322 pattern = USER_PATTERN + r"/header_photo"
1323 example = "https://x.com/USER/header_photo"
1324
1325 def tweets(self):
1326 self.api._user_id_by_screen_name(self.user)
1327 user = self._user_obj
1328
1329 try:
1330 url = user["legacy"]["profile_banner_url"]
1331 _, timestamp = url.rsplit("/", 1)
1332 except (KeyError, ValueError):
1333 return ()
1334
1335 id_str = str((int(timestamp) * 1000 - 1288834974657) << 22)
1336 return (self._make_tweet(user, url, id_str),)
1337
1338
1339 class TwitterImageExtractor(Extractor):
1340 category = "twitter"
1341 subcategory = "image"
1342 pattern = r"https?://pbs\.twimg\.com/media/([\w-]+)(?:\?format=|\.)(\w+)"
1343 example = "https://pbs.twimg.com/media/ABCDE?format=jpg&name=orig"
1344
1345 def __init__(self, match):
1346 Extractor.__init__(self, match)
1347 self.id, self.fmt = match.groups()
1348 TwitterExtractor._init_sizes(self)
1349
1350 def items(self):
1351 base = f"https://pbs.twimg.com/media/{self.id}?format={self.fmt}&name="
1352
1353 data = {
1354 "filename": self.id,
1355 "extension": self.fmt,
1356 "_fallback": TwitterExtractor._image_fallback(self, base),
1357 }
1358
1359 yield Message.Directory, "", data
1360 yield Message.Url, base + self._size_image, data
1361
1362
1363 class TwitterAPI():
1364 client_transaction = None
1365
1366 def __init__(self, extractor):
1367 self.extractor = extractor
1368 self.log = extractor.log
1369 self.exc = extractor.exc
1370
1371 self.root = "https://x.com/i/api"
1372 self._nsfw_warning = True
1373 self._json_dumps = util.json_dumps
1374
1375 cookies = extractor.cookies
1376 cookies_domain = extractor.cookies_domain
1377
1378 csrf = extractor.config("csrf")
1379 if csrf is None or csrf == "cookies":
1380 csrf_token = cookies.get("ct0", domain=cookies_domain)
1381 else:
1382 csrf_token = None
1383 if not csrf_token:
1384 csrf_token = util.generate_token()
1385 cookies.set("ct0", csrf_token, domain=cookies_domain)
1386
1387 auth_token = cookies.get("auth_token", domain=cookies_domain)
1388
1389 self.headers = {
1390 "Accept": "*/*",
1391 "Referer": extractor.root + "/",
1392 "content-type": "application/json",
1393 "x-guest-token": None,
1394 "x-twitter-auth-type": "OAuth2Session" if auth_token else None,
1395 "x-csrf-token": csrf_token,
1396 "x-twitter-client-language": "en",
1397 "x-twitter-active-user": "yes",
1398 "x-client-transaction-id": None,
1399 "Sec-Fetch-Dest": "empty",
1400 "Sec-Fetch-Mode": "cors",
1401 "Sec-Fetch-Site": "same-origin",
1402 "authorization": "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejR"
1403 "COuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu"
1404 "4FA33AGWWjCpTnA",
1405 }
1406 self.params = {
1407 "include_profile_interstitial_type": "1",
1408 "include_blocking": "1",
1409 "include_blocked_by": "1",
1410 "include_followed_by": "1",
1411 "include_want_retweets": "1",
1412 "include_mute_edge": "1",
1413 "include_can_dm": "1",
1414 "include_can_media_tag": "1",
1415 "include_ext_is_blue_verified": "1",
1416 "include_ext_verified_type": "1",
1417 "include_ext_profile_image_shape": "1",
1418 "skip_status": "1",
1419 "cards_platform": "Web-12",
1420 "include_cards": "1",
1421 "include_ext_alt_text": "true",
1422 "include_ext_limited_action_results": "true",
1423 "include_quote_count": "true",
1424 "include_reply_count": "1",
1425 "tweet_mode": "extended",
1426 "include_ext_views": "true",
1427 "include_entities": "true",
1428 "include_user_entities": "true",
1429 "include_ext_media_color": "true",
1430 "include_ext_media_availability": "true",
1431 "include_ext_sensitive_media_warning": "true",
1432 "include_ext_trusted_friends_metadata": "true",
1433 "send_error_codes": "true",
1434 "simple_quoted_tweet": "true",
1435 "cursor": None,
1436 "count": "20",
1437 "ext": "mediaStats,highlightedLabel,parodyCommentaryFanLabel,"
1438 "voiceInfo,birdwatchPivot,superFollowMetadata,"
1439 "unmentionInfo,editControl,article",
1440 }
1441 self.features = {
1442 "hidden_profile_subscriptions_enabled": True,
1443 "payments_enabled": False,
1444 "rweb_xchat_enabled": False,
1445 "profile_label_improvements_pcf_label_in_post_enabled": True,
1446 "rweb_tipjar_consumption_enabled": True,
1447 "verified_phone_label_enabled": False,
1448 "highlights_tweets_tab_ui_enabled": True,
1449 "responsive_web_twitter_article_notes_tab_enabled": True,
1450 "subscriptions_feature_can_gift_premium": True,
1451 "creator_subscriptions_tweet_preview_api_enabled": True,
1452 "responsive_web_graphql_"
1453 "skip_user_profile_image_extensions_enabled": False,
1454 "responsive_web_graphql_timeline_navigation_enabled": True,
1455 }
1456 self.features_pagination = {
1457 "rweb_video_screen_enabled": False,
1458 "payments_enabled": False,
1459 "rweb_xchat_enabled": False,
1460 "profile_label_improvements_pcf_label_in_post_enabled": True,
1461 "rweb_tipjar_consumption_enabled": True,
1462 "verified_phone_label_enabled": False,
1463 "creator_subscriptions_tweet_preview_api_enabled": True,
1464 "responsive_web_graphql"
1465 "_timeline_navigation_enabled": True,
1466 "responsive_web_graphql"
1467 "_skip_user_profile_image_extensions_enabled": False,
1468 "premium_content_api_read_enabled": False,
1469 "communities_web_enable_tweet_community_results_fetch": True,
1470 "c9s_tweet_anatomy_moderator_badge_enabled": True,
1471 "responsive_web_grok_analyze_button_fetch_trends_enabled": False,
1472 "responsive_web_grok_analyze_post_followups_enabled": True,
1473 "responsive_web_jetfuel_frame": True,
1474 "responsive_web_grok_share_attachment_enabled": True,
1475 "articles_preview_enabled": True,
1476 "responsive_web_edit_tweet_api_enabled": True,
1477 "graphql_is_translatable_rweb_tweet_is_translatable_enabled": True,
1478 "view_counts_everywhere_api_enabled": True,
1479 "longform_notetweets_consumption_enabled": True,
1480 "responsive_web_twitter_article_tweet_consumption_enabled": True,
1481 "tweet_awards_web_tipping_enabled": False,
1482 "responsive_web_grok_show_grok_translated_post": False,
1483 "responsive_web_grok_analysis_button_from_backend": True,
1484 "creator_subscriptions_quote_tweet_preview_enabled": False,
1485 "freedom_of_speech_not_reach_fetch_enabled": True,
1486 "standardized_nudges_misinfo": True,
1487 "tweet_with_visibility_results"
1488 "_prefer_gql_limited_actions_policy_enabled": True,
1489 "longform_notetweets_rich_text_read_enabled": True,
1490 "longform_notetweets_inline_media_enabled": True,
1491 "responsive_web_grok_image_annotation_enabled": True,
1492 "responsive_web_grok_imagine_annotation_enabled": True,
1493 "responsive_web_grok"
1494 "_community_note_auto_translation_is_enabled": False,
1495 "responsive_web_enhance_cards_enabled": False,
1496 }
1497
1498 def tweet_result_by_rest_id(self, tweet_id):
1499 endpoint = "/graphql/qxWQxcMLiTPcavz9Qy5hwQ/TweetResultByRestId"
1500 variables = {
1501 "tweetId": tweet_id,
1502 "withCommunity": False,
1503 "includePromotedContent": False,
1504 "withVoice": False,
1505 }
1506 features = self.features_pagination.copy()
1507 del features["rweb_video_screen_enabled"]
1508 field_toggles = {
1509 "withArticleRichContentState": True,
1510 "withArticlePlainText": False,
1511 "withGrokAnalyze": False,
1512 "withDisallowedReplyControls": False,
1513 }
1514 params = {
1515 "variables" : self._json_dumps(variables),
1516 "features" : self._json_dumps(features),
1517 "fieldToggles": self._json_dumps(field_toggles),
1518 }
1519 tweet = self._call(endpoint, params)["data"]["tweetResult"]["result"]
1520 if "tweet" in tweet:
1521 tweet = tweet["tweet"]
1522
1523 if tweet.get("__typename") == "TweetUnavailable":
1524 reason = tweet.get("reason")
1525 if reason in {"NsfwViewerHasNoStatedAge", "NsfwLoggedOut"}:
1526 raise self.exc.AuthRequired(message="NSFW Tweet")
1527 if reason == "Protected":
1528 raise self.exc.AuthRequired(message="Protected Tweet")
1529 raise self.exc.AbortExtraction(f"Tweet unavailable ('{reason}')")
1530
1531 return tweet
1532
1533 def tweet_detail(self, tweet_id, cursor=None):
1534 endpoint = "/graphql/iFEr5AcP121Og4wx9Yqo3w/TweetDetail"
1535 variables = {
1536 "focalTweetId": tweet_id,
1537 "referrer": "profile",
1538 "with_rux_injections": False,
1539 # "rankingMode": "Relevance",
1540 "includePromotedContent": False,
1541 "withCommunity": True,
1542 "withQuickPromoteEligibilityTweetFields": False,
1543 "withBirdwatchNotes": True,
1544 "withVoice": True,
1545 }
1546 field_toggles = {
1547 "withArticleRichContentState": True,
1548 "withArticlePlainText": False,
1549 "withGrokAnalyze": False,
1550 "withDisallowedReplyControls": False,
1551 }
1552 return self._pagination_tweets(
1553 endpoint, variables,
1554 ("threaded_conversation_with_injections_v2",),
1555 field_toggles=field_toggles, cursor=cursor)
1556
1557 def user_tweets(self, screen_name):
1558 endpoint = "/graphql/E8Wq-_jFSaU7hxVcuOPR9g/UserTweets"
1559 variables = {
1560 "userId": self._user_id_by_screen_name(screen_name),
1561 "count": self.extractor.config("limit", 50),
1562 "includePromotedContent": False,
1563 "withQuickPromoteEligibilityTweetFields": False,
1564 "withVoice": True,
1565 }
1566 field_toggles = {
1567 "withArticlePlainText": False,
1568 }
1569 return self._pagination_tweets(
1570 endpoint, variables, field_toggles=field_toggles)
1571
1572 def user_tweets_and_replies(self, screen_name):
1573 endpoint = "/graphql/-O3QOHrVn1aOm_cF5wyTCQ/UserTweetsAndReplies"
1574 variables = {
1575 "userId": self._user_id_by_screen_name(screen_name),
1576 "count": self.extractor.config("limit", 50),
1577 "includePromotedContent": False,
1578 "withCommunity": True,
1579 "withVoice": True,
1580 }
1581 field_toggles = {
1582 "withArticlePlainText": False,
1583 }
1584 return self._pagination_tweets(
1585 endpoint, variables, field_toggles=field_toggles)
1586
1587 def user_highlights(self, screen_name):
1588 endpoint = "/graphql/gmHw9geMTncZ7jeLLUUNOw/UserHighlightsTweets"
1589 variables = {
1590 "userId": self._user_id_by_screen_name(screen_name),
1591 "count": self.extractor.config("limit", 50),
1592 "includePromotedContent": False,
1593 "withVoice": True,
1594 }
1595 field_toggles = {
1596 "withArticlePlainText": False,
1597 }
1598 return self._pagination_tweets(
1599 endpoint, variables, field_toggles=field_toggles)
1600
1601 def user_media(self, screen_name):
1602 endpoint = "/graphql/jCRhbOzdgOHp6u9H4g2tEg/UserMedia"
1603 variables = {
1604 "userId": self._user_id_by_screen_name(screen_name),
1605 "count": self.extractor.config("limit", 50),
1606 "includePromotedContent": False,
1607 "withClientEventToken": False,
1608 "withBirdwatchNotes": False,
1609 "withVoice": True,
1610 }
1611 field_toggles = {
1612 "withArticlePlainText": False,
1613 }
1614 return self._pagination_tweets(
1615 endpoint, variables, field_toggles=field_toggles)
1616
1617 def user_likes(self, screen_name):
1618 endpoint = "/graphql/TGEKkJG_meudeaFcqaxM-Q/Likes"
1619 variables = {
1620 "userId": self._user_id_by_screen_name(screen_name),
1621 "count": self.extractor.config("limit", 50),
1622 "includePromotedContent": False,
1623 "withClientEventToken": False,
1624 "withBirdwatchNotes": False,
1625 "withVoice": True,
1626 }
1627 field_toggles = {
1628 "withArticlePlainText": False,
1629 }
1630 return self._pagination_tweets(
1631 endpoint, variables, field_toggles=field_toggles)
1632
1633 def user_bookmarks(self):
1634 endpoint = "/graphql/pLtjrO4ubNh996M_Cubwsg/Bookmarks"
1635 variables = {
1636 "count": self.extractor.config("limit", 50),
1637 "includePromotedContent": False,
1638 }
1639 return self._pagination_tweets(
1640 endpoint, variables, ("bookmark_timeline_v2", "timeline"),
1641 stop_tweets=128)
1642
1643 def search_timeline(self, query, product=None):
1644 cfg = self.extractor.config
1645
1646 if product is None:
1647 if product := cfg("search-results"):
1648 product = {
1649 "top" : "Top",
1650 "live" : "Latest",
1651 "user" : "People",
1652 "media": "Media",
1653 "list" : "Lists",
1654 }.get(product.lower(), product).capitalize()
1655 else:
1656 product = "Latest"
1657
1658 endpoint = "/graphql/4fpceYZ6-YQCx_JSl_Cn_A/SearchTimeline"
1659 variables = {
1660 "rawQuery": query,
1661 "count": cfg("search-limit", 20),
1662 "querySource": "typed_query",
1663 "product": product,
1664 "withGrokTranslatedBio": False,
1665 }
1666
1667 pgn = cfg("search-pagination", "max_id")
1668 if pgn in {"max_id", "maxid", "id"}:
1669 update_variables = self._update_variables_search_maxid
1670 self._var_maxid_prev = None
1671 elif pgn in {"until", "date", "datetime", "dt"}:
1672 update_variables = self._update_variables_search_date
1673 self._var_date_prev = None
1674 else:
1675 update_variables = None
1676
1677 stop_tweets = cfg("search-stop")
1678 if stop_tweets is None or stop_tweets == "auto":
1679 stop_tweets = 3
1680
1681 return self._pagination_tweets(
1682 endpoint, variables,
1683 ("search_by_raw_query", "search_timeline", "timeline"),
1684 stop_tweets=stop_tweets, update_variables=update_variables)
1685
1686 def community_query(self, community_id):
1687 endpoint = "/graphql/2W09l7nD7ZbxGQHXvfB22w/CommunityQuery"
1688 params = {
1689 "variables": self._json_dumps({
1690 "communityId": community_id,
1691 }),
1692 "features": self._json_dumps({
1693 "c9s_list_members_action_api_enabled": False,
1694 "c9s_superc9s_indication_enabled": False,
1695 }),
1696 }
1697 return (self._call(endpoint, params)
1698 ["data"]["communityResults"]["result"])
1699
1700 def community_tweets_timeline(self, community_id):
1701 endpoint = "/graphql/Nyt-88UX4-pPCImZNUl9RQ/CommunityTweetsTimeline"
1702 variables = {
1703 "communityId": community_id,
1704 "count": self.extractor.config("limit", 50),
1705 "displayLocation": "Community",
1706 "rankingMode": "Recency",
1707 "withCommunity": True,
1708 }
1709 return self._pagination_tweets(
1710 endpoint, variables,
1711 ("communityResults", "result", "ranked_community_timeline",
1712 "timeline"))
1713
1714 def community_media_timeline(self, community_id):
1715 endpoint = "/graphql/ZniZ7AAK_VVu1xtSx1V-gQ/CommunityMediaTimeline"
1716 variables = {
1717 "communityId": community_id,
1718 "count": self.extractor.config("limit", 50),
1719 "withCommunity": True,
1720 }
1721 return self._pagination_tweets(
1722 endpoint, variables,
1723 ("communityResults", "result", "community_media_timeline",
1724 "timeline"))
1725
1726 def communities_main_page_timeline(self, screen_name):
1727 endpoint = ("/graphql/p048a9n3hTPppQyK7FQTFw"
1728 "/CommunitiesMainPageTimeline")
1729 variables = {
1730 "count": self.extractor.config("limit", 50),
1731 "withCommunity": True,
1732 }
1733 return self._pagination_tweets(
1734 endpoint, variables,
1735 ("viewer", "communities_timeline", "timeline"))
1736
1737 def home_timeline(self):
1738 endpoint = "/graphql/DXmgQYmIft1oLP6vMkJixw/HomeTimeline"
1739 variables = {
1740 "count": self.extractor.config("limit", 50),
1741 "includePromotedContent": False,
1742 "latestControlAvailable": True,
1743 "withCommunity": True,
1744 }
1745 return self._pagination_tweets(
1746 endpoint, variables, ("home", "home_timeline_urt"))
1747
1748 def home_latest_timeline(self):
1749 endpoint = "/graphql/SFxmNKWfN9ySJcXG_tjX8g/HomeLatestTimeline"
1750 variables = {
1751 "count": self.extractor.config("limit", 50),
1752 "includePromotedContent": False,
1753 "latestControlAvailable": True,
1754 }
1755 return self._pagination_tweets(
1756 endpoint, variables, ("home", "home_timeline_urt"))
1757
1758 def live_event_timeline(self, event_id):
1759 endpoint = f"/2/live_event/timeline/{event_id}.json"
1760 params = self.params.copy()
1761 params["timeline_id"] = "recap"
1762 params["urt"] = "true"
1763 params["get_annotations"] = "true"
1764 return self._pagination_rest(endpoint, params)
1765
1766 def live_event(self, event_id):
1767 endpoint = f"/1.1/live_event/1/{event_id}/timeline.json"
1768 params = self.params.copy()
1769 params["count"] = "0"
1770 params["urt"] = "true"
1771 return (self._call(endpoint, params)
1772 ["twitter_objects"]["live_events"][event_id])
1773
1774 def list_latest_tweets_timeline(self, list_id):
1775 endpoint = "/graphql/06JtmwM8k_1cthpFZITVVA/ListLatestTweetsTimeline"
1776 variables = {
1777 "listId": list_id,
1778 "count": self.extractor.config("limit", 50),
1779 }
1780 return self._pagination_tweets(
1781 endpoint, variables, ("list", "tweets_timeline", "timeline"))
1782
1783 def list_members(self, list_id):
1784 endpoint = "/graphql/naea_MSad4pOb-D6_oVv_g/ListMembers"
1785 variables = {
1786 "listId": list_id,
1787 "count": 100,
1788 }
1789 return self._pagination_users(
1790 endpoint, variables, ("list", "members_timeline", "timeline"))
1791
1792 def friends_following_list(self, user_id):
1793 endpoint = "/1.1/friends/following/list.json"
1794 params = {
1795 "include_profile_interstitial_type": "1",
1796 "include_blocking": "1",
1797 "include_blocked_by": "1",
1798 "include_followed_by": "1",
1799 "include_want_retweets": "1",
1800 "include_mute_edge": "1",
1801 "include_can_dm": "1",
1802 "include_can_media_tag": "1",
1803 "include_ext_is_blue_verified": "1",
1804 "include_ext_verified_type": "1",
1805 "include_ext_profile_image_shape": "1",
1806 "skip_status": "1",
1807 "cursor": "-1",
1808 "user_id": user_id,
1809 "count": "3",
1810 "with_total_count": "true",
1811 }
1812 return self._call(endpoint, params)
1813
1814 def notifications_devicefollow(self):
1815 endpoint = "/2/notifications/device_follow.json"
1816 params = self.params.copy()
1817 params["count"] = self.extractor.config("limit", 50)
1818 return self._pagination_rest(endpoint, params)
1819
1820 def user_followers(self, screen_name):
1821 endpoint = "/graphql/i6PPdIMm1MO7CpAqjau7sw/Followers"
1822 variables = {
1823 "userId": self._user_id_by_screen_name(screen_name),
1824 "count": 100,
1825 "includePromotedContent": False,
1826 "withGrokTranslatedBio": False,
1827 }
1828 return self._pagination_users(endpoint, variables)
1829
1830 def user_followers_verified(self, screen_name):
1831 endpoint = "/graphql/fxEl9kp1Tgolqkq8_Lo3sg/BlueVerifiedFollowers"
1832 variables = {
1833 "userId": self._user_id_by_screen_name(screen_name),
1834 "count": 100,
1835 "includePromotedContent": False,
1836 "withGrokTranslatedBio": False,
1837 }
1838 return self._pagination_users(endpoint, variables)
1839
1840 def user_following(self, screen_name):
1841 endpoint = "/graphql/SaWqzw0TFAWMx1nXWjXoaQ/Following"
1842 variables = {
1843 "userId": self._user_id_by_screen_name(screen_name),
1844 "count": 100,
1845 "includePromotedContent": False,
1846 "withGrokTranslatedBio": False,
1847 }
1848 return self._pagination_users(endpoint, variables)
1849
1850 def user_by_rest_id(self, rest_id):
1851 endpoint = "/graphql/8r5oa_2vD0WkhIAOkY4TTA/UserByRestId"
1852 features = self.features
1853 params = {
1854 "variables": self._json_dumps({
1855 "userId": rest_id,
1856 }),
1857 "features": self._json_dumps(features),
1858 }
1859 return self._call(endpoint, params)["data"]["user"]["result"]
1860
1861 def user_by_screen_name(self, screen_name):
1862 endpoint = "/graphql/ck5KkZ8t5cOmoLssopN99Q/UserByScreenName"
1863 features = self.features.copy()
1864 features["subscriptions_verification_info_"
1865 "is_identity_verified_enabled"] = True
1866 features["subscriptions_verification_info_"
1867 "verified_since_enabled"] = True
1868 params = {
1869 "variables": self._json_dumps({
1870 "screen_name": screen_name,
1871 "withGrokTranslatedBio": False,
1872 }),
1873 "features": self._json_dumps(features),
1874 "fieldToggles": self._json_dumps({
1875 "withAuxiliaryUserLabels": True,
1876 }),
1877 }
1878 return self._call(endpoint, params)["data"]["user"]["result"]
1879
1880 def user_about_account(self, screen_name):
1881 endpoint = "/graphql/zs_jFPFT78rBpXv9Z3U2YQ/AboutAccountQuery"
1882 params = {"variables": self._json_dumps({"screenName": screen_name})}
1883 return (self._call(endpoint, params)
1884 ["data"]["user_result_by_screen_name"]["result"])
1885
1886 def _user_id_by_screen_name(self, screen_name):
1887 user = ()
1888 extr = self.extractor
1889 try:
1890 if screen_name.startswith("id:"):
1891 user = extr.cache(self.user_by_rest_id, screen_name[3:])
1892 else:
1893 user = extr.cache(self.user_by_screen_name, screen_name)
1894 extr._assign_user(user)
1895 return user["rest_id"]
1896 except KeyError:
1897 if user and user.get("__typename") == "UserUnavailable":
1898 raise extr.exc.NotFoundError(user["message"], False)
1899 else:
1900 raise extr.exc.NotFoundError("user")
1901
1902 def _guest_token(self):
1903 endpoint = "/1.1/guest/activate.json"
1904 self.log.info("Requesting guest token")
1905 return str(self._call(
1906 endpoint, None, "POST", False, "https://api.x.com",
1907 )["guest_token"])
1908
1909 def _authenticate_guest(self):
1910 guest_token = self.extractor.cache(
1911 self._guest_token, _key=None, _exp=3600, _mem=False)
1912 if guest_token != self.headers["x-guest-token"]:
1913 self.headers["x-guest-token"] = guest_token
1914 self.extractor.cookies.set(
1915 "gt", guest_token, domain=self.extractor.cookies_domain)
1916
1917 def _client_transaction(self):
1918 self.log.info("Initializing client transaction keys")
1919
1920 ct = self.extractor.utils("transaction_id").ClientTransaction()
1921 ct.initialize(self.extractor)
1922
1923 # update 'x-csrf-token' header (#7467)
1924 csrf_token = self.extractor.cookies.get(
1925 "ct0", domain=self.extractor.cookies_domain)
1926 if csrf_token:
1927 self.headers["x-csrf-token"] = csrf_token
1928
1929 return ct
1930
1931 def _transaction_id(self, url, method="GET"):
1932 if self.client_transaction is None:
1933 TwitterAPI.client_transaction = self.extractor.cache(
1934 self._client_transaction, _key=None, _exp=10_800, _mem=False)
1935 path = url[url.find("/", 8):]
1936 self.headers["x-client-transaction-id"] = \
1937 self.client_transaction.generate_transaction_id(method, path)
1938
1939 def _call(self, endpoint, params, method="GET", auth=True, root=None):
1940 url = (self.root if root is None else root) + endpoint
1941
1942 while True:
1943 if auth:
1944 if self.headers["x-twitter-auth-type"]:
1945 self._transaction_id(url, method)
1946 else:
1947 self._authenticate_guest()
1948
1949 response = self.extractor.request(
1950 url, method=method, params=params,
1951 headers=self.headers, fatal=None)
1952
1953 # update 'x-csrf-token' header (#1170)
1954 if csrf_token := response.cookies.get("ct0"):
1955 self.headers["x-csrf-token"] = csrf_token
1956
1957 remaining = int(response.headers.get("x-rate-limit-remaining", 6))
1958 if remaining < 6 and remaining <= random.randrange(1, 6):
1959 self._handle_ratelimit(response)
1960 continue
1961
1962 try:
1963 data = response.json()
1964 except ValueError:
1965 data = {"errors": ({"message": response.text},)}
1966
1967 errors = data.get("errors")
1968 if not errors:
1969 return data
1970
1971 retry = False
1972 for error in errors:
1973 msg = error.get("message") or "Unspecified"
1974 self.log.debug("API error: '%s'", msg)
1975
1976 if "this account is temporarily locked" in msg:
1977 msg = "Account temporarily locked"
1978 if self.extractor.config("locked") != "wait":
1979 raise self.exc.AuthorizationError(msg)
1980 self.log.warning(msg)
1981 self.extractor.input("Press ENTER to retry.")
1982 retry = True
1983
1984 elif "Could not authenticate you" in msg:
1985 raise self.exc.AbortExtraction(f"'{msg}'")
1986
1987 elif msg.lower().startswith("timeout"):
1988 retry = True
1989
1990 if retry:
1991 if self.headers["x-twitter-auth-type"]:
1992 self.log.debug("Retrying API request")
1993 continue
1994 else:
1995 # fall through to "Login Required"
1996 response.status_code = 404
1997
1998 if response.status_code < 400:
1999 return data
2000 elif response.status_code in {403, 404} and \
2001 not self.headers["x-twitter-auth-type"]:
2002 raise self.exc.AuthRequired(
2003 "authenticated cookies", "timeline")
2004 elif response.status_code == 429:
2005 self._handle_ratelimit(response)
2006 continue
2007
2008 # error
2009 try:
2010 errors = ", ".join(e["message"] for e in errors)
2011 except Exception:
2012 pass
2013
2014 raise self.exc.AbortExtraction(
2015 f"{response.status_code} {response.reason} ({errors})")
2016
2017 def _pagination_rest(self, endpoint, params):
2018 extr = self.extractor
2019 if cursor := extr._init_cursor():
2020 params["cursor"] = cursor
2021 original_retweets = (extr.retweets == "original")
2022 bottom = ("cursor-bottom-", "sq-cursor-bottom")
2023
2024 while True:
2025 data = self._call(endpoint, params)
2026
2027 instructions = data["timeline"]["instructions"]
2028 if not instructions:
2029 return extr._update_cursor(None)
2030
2031 tweets = data["globalObjects"]["tweets"]
2032 users = data["globalObjects"]["users"]
2033 tweet_id = cursor = None
2034 tweet_ids = []
2035 entries = ()
2036
2037 # process instructions
2038 for instr in instructions:
2039 if "addEntries" in instr:
2040 entries = instr["addEntries"]["entries"]
2041 elif "replaceEntry" in instr:
2042 entry = instr["replaceEntry"]["entry"]
2043 if entry["entryId"].startswith(bottom):
2044 cursor = (entry["content"]["operation"]
2045 ["cursor"]["value"])
2046
2047 # collect tweet IDs and cursor value
2048 for entry in entries:
2049 entry_startswith = entry["entryId"].startswith
2050
2051 if entry_startswith(("tweet-", "sq-I-t-")):
2052 tweet_ids.append(
2053 entry["content"]["item"]["content"]["tweet"]["id"])
2054
2055 elif entry_startswith("homeConversation-"):
2056 tweet_ids.extend(
2057 entry["content"]["timelineModule"]["metadata"]
2058 ["conversationMetadata"]["allTweetIds"][::-1])
2059
2060 elif entry_startswith(bottom):
2061 cursor = entry["content"]["operation"]["cursor"]
2062 if not cursor.get("stopOnEmptyResponse", True):
2063 # keep going even if there are no tweets
2064 tweet_id = True
2065 cursor = cursor["value"]
2066
2067 elif entry_startswith("conversationThread-"):
2068 tweet_ids.extend(
2069 item["entryId"][6:]
2070 for item in entry["content"]["timelineModule"]["items"]
2071 if item["entryId"].startswith("tweet-")
2072 )
2073
2074 # process tweets
2075 for tweet_id in tweet_ids:
2076 try:
2077 tweet = tweets[tweet_id]
2078 except KeyError:
2079 self.log.debug("Skipping %s (deleted)", tweet_id)
2080 continue
2081
2082 if "retweeted_status_id_str" in tweet:
2083 retweet = tweets.get(tweet["retweeted_status_id_str"])
2084 if original_retweets:
2085 if not retweet:
2086 continue
2087 retweet["retweeted_status_id_str"] = retweet["id_str"]
2088 retweet["_retweet_id_str"] = tweet["id_str"]
2089 tweet = retweet
2090 elif retweet:
2091 tweet["author"] = users[retweet["user_id_str"]]
2092 if "extended_entities" in retweet and \
2093 "extended_entities" not in tweet:
2094 tweet["extended_entities"] = \
2095 retweet["extended_entities"]
2096 tweet["user"] = users[tweet["user_id_str"]]
2097 yield tweet
2098
2099 if "quoted_status_id_str" in tweet:
2100 if quoted := tweets.get(tweet["quoted_status_id_str"]):
2101 quoted = quoted.copy()
2102 quoted["author"] = users[quoted["user_id_str"]]
2103 quoted["quoted_by"] = tweet["user"]["screen_name"]
2104 quoted["quoted_by_id_str"] = tweet["id_str"]
2105 yield quoted
2106
2107 # stop on empty response
2108 if not cursor or (not tweets and not tweet_id):
2109 return extr._update_cursor(None)
2110 params["cursor"] = extr._update_cursor(cursor)
2111
2112 def _pagination_tweets(self, endpoint, variables,
2113 path=None, stop_tweets=0, update_variables=None,
2114 features=None, field_toggles=None, cursor=None):
2115 extr = self.extractor
2116 original_retweets = (extr.retweets == "original")
2117 pinned_tweet = True if extr.pinned else None
2118 stop_tweets_max = stop_tweets
2119 api_retries = None
2120
2121 if isinstance(count := variables.get("count"), list):
2122 count = count.copy()
2123 count.reverse()
2124 self.log.debug("Using 'count: %s'", count[-1])
2125 variables["count"] = count.pop()
2126 else:
2127 count = False
2128
2129 params = {"variables": None}
2130 if cursor is not None or (cursor := extr._init_cursor()):
2131 variables["cursor"] = cursor
2132 if features is None:
2133 features = self.features_pagination
2134 if features:
2135 params["features"] = self._json_dumps(features)
2136 if field_toggles:
2137 params["fieldToggles"] = self._json_dumps(field_toggles)
2138
2139 while True:
2140 params["variables"] = self._json_dumps(variables)
2141 data = self._call(endpoint, params)
2142
2143 try:
2144 if path is None:
2145 instructions = (data["data"]["user"]["result"]["timeline"]
2146 ["timeline"]["instructions"])
2147 else:
2148 instructions = data["data"]
2149 for key in path:
2150 instructions = instructions[key]
2151 instructions = instructions["instructions"]
2152
2153 cursor = None
2154 entries = None
2155 for instr in instructions:
2156 instr_type = instr.get("type")
2157 if instr_type == "TimelineAddEntries":
2158 if entries:
2159 entries.extend(instr["entries"])
2160 else:
2161 entries = instr["entries"]
2162 elif instr_type == "TimelineAddToModule":
2163 entries = instr["moduleItems"]
2164 elif instr_type == "TimelinePinEntry":
2165 if pinned_tweet is not None:
2166 pinned_tweet = instr["entry"]
2167 elif instr_type == "TimelineReplaceEntry":
2168 entry = instr["entry"]
2169 if entry["entryId"].startswith("cursor-bottom-"):
2170 cursor = entry["content"]["value"]
2171 if entries is None:
2172 if not cursor:
2173 return extr._update_cursor(None)
2174 entries = ()
2175
2176 except LookupError:
2177 extr.log.debug(data)
2178
2179 if errors := data.get("errors"):
2180 if api_retries is None:
2181 api_tries = 1
2182 api_retries = extr.config("retries-api", 9)
2183 if api_retries < 0:
2184 api_retries = float("inf")
2185
2186 err = []
2187 srv = False
2188 for e in errors:
2189 err.append(f"- '{e.get('message') or e.get('name')}'")
2190 if e.get("source") == "Server":
2191 srv = True
2192
2193 self.log.warning("API errors (%s/%s):\n%s",
2194 api_tries, api_retries+1, "\n".join(err))
2195 if srv and api_tries <= api_retries:
2196 api_tries += 1
2197 continue
2198
2199 if user := extr._user_obj:
2200 core = user.get("core") or user["legacy"]
2201 if (user.get("relationship_perspectives") or
2202 user["legacy"]).get("blocked_by"):
2203 if self.headers["x-twitter-auth-type"] and \
2204 extr.config("logout"):
2205 extr.cookies_file = None
2206 del extr.cookies["auth_token"]
2207 self.headers["x-twitter-auth-type"] = None
2208 extr.log.info("Retrying API request as guest")
2209 continue
2210 raise self.exc.AuthorizationError(
2211 core["screen_name"] + " blocked your account")
2212 if (user.get("privacy") or
2213 user["legacy"]).get("protected"):
2214 raise self.exc.AuthorizationError(
2215 core["screen_name"] + "'s Tweets are protected")
2216
2217 raise self.exc.AbortExtraction(
2218 "Unable to retrieve Tweets from this timeline")
2219
2220 tweets = []
2221 tweet = last_tweet = retry = None
2222 api_tries = 1
2223
2224 if pinned_tweet is not None and isinstance(pinned_tweet, dict):
2225 pinned_tweet["pinned"] = True
2226 tweets.append(pinned_tweet)
2227 pinned_tweet = None
2228
2229 for entry in entries:
2230 esw = entry["entryId"].startswith
2231
2232 if esw("tweet-"):
2233 tweets.append(entry)
2234 elif esw(("profile-grid-",
2235 "search-grid-",
2236 "communities-grid-")):
2237 if "content" in entry:
2238 tweets.extend(entry["content"]["items"])
2239 else:
2240 tweets.append(entry)
2241 elif esw(("homeConversation-",
2242 "profile-conversation-",
2243 "conversationthread-")):
2244 if "content" in entry:
2245 tweets.extend(entry["content"]["items"])
2246 else:
2247 tweets.append(entry)
2248 elif esw("tombstone-"):
2249 item = entry["content"]["itemContent"]
2250 item["tweet_results"] = \
2251 {"result": {"tombstone": item["tombstoneInfo"]}}
2252 tweets.append(entry)
2253 elif esw("cursor-bottom-"):
2254 cursor = entry["content"]
2255 if "itemContent" in cursor:
2256 cursor = cursor["itemContent"]
2257 if not cursor.get("stopOnEmptyResponse", True):
2258 # keep going even if there are no tweets
2259 tweet = True
2260 cursor = cursor.get("value")
2261 elif esw("cursor-showmorethreads-") and extr.showmore:
2262 cursor = entry["content"]
2263 if "displayTreatment" in cursor:
2264 item = cursor["displayTreatment"].get("actionText")
2265 extr.log.debug("Expanding '%s' stub",
2266 item or "Show More")
2267 cursor = cursor.get("value")
2268
2269 if pinned_tweet is not None:
2270 if extr._user_obj is None:
2271 pinned = None
2272 elif pinned := extr._user_obj["legacy"].get(
2273 "pinned_tweet_ids_str"):
2274 pinned = "-tweet-" + pinned[0]
2275 for idx, entry in enumerate(tweets):
2276 if entry["entryId"].endswith(pinned):
2277 # mark as pinned / set 'pinned = True'
2278 try:
2279 pinned_tweet = (
2280 (entry.get("content") or entry["item"])
2281 ["itemContent"]["tweet_results"]["result"])
2282 if "tweet" in pinned_tweet:
2283 pinned_tweet = pinned_tweet["tweet"]
2284 pinned_tweet["pinned"] = True
2285 # move to front of 'tweets'
2286 del tweets[idx]
2287 tweets.insert(0, entry)
2288 except Exception:
2289 pass
2290 break
2291 del pinned
2292 pinned_tweet = None
2293
2294 for entry in tweets:
2295 try:
2296 item = ((entry.get("content") or entry["item"])
2297 ["itemContent"])
2298 if "promotedMetadata" in item and not extr.ads:
2299 extr.log.debug(
2300 "Skipping %s (ad)",
2301 (entry.get("entryId") or "").rpartition("-")[2])
2302 continue
2303
2304 tweet = item["tweet_results"]["result"]
2305 if "tombstone" in tweet:
2306 tweet = self._process_tombstone(
2307 entry, tweet["tombstone"])
2308 if not tweet:
2309 continue
2310
2311 if "tweet" in tweet:
2312 tweet = tweet["tweet"]
2313 legacy = tweet["legacy"]
2314 tweet["sortIndex"] = entry.get("sortIndex")
2315 except KeyError as exc:
2316 tid = (entry.get("entryId") or "").rpartition("-")[2]
2317 if exc.args[0] == "tweet_results" and item.get(
2318 "cursorType") == "ShowMore":
2319 if extr.showreplies:
2320 extr.log.debug(
2321 "Expanding %s ('Show replies' stub)", tid)
2322 yield from self.tweet_detail(
2323 variables.get("focalTweetId") or tid,
2324 cursor=item["value"])
2325 else:
2326 extr.log.debug(
2327 "Skipping %s ('Show More' stub)", tid)
2328 else:
2329 extr.log.debug("Skipping %s (deleted)", tid)
2330 continue
2331
2332 if retry is None:
2333 try:
2334 tweet["core"]["user_results"]["result"]
2335 retry = False
2336 except KeyError:
2337 self.log.warning("Received Tweet results without "
2338 "'core' data ... Retrying")
2339 retry = True
2340 break
2341
2342 if "retweeted_status_result" in legacy:
2343 try:
2344 retweet = legacy["retweeted_status_result"]["result"]
2345 if "tweet" in retweet:
2346 retweet = retweet["tweet"]
2347 if original_retweets:
2348 retweet["legacy"]["retweeted_status_id_str"] = \
2349 retweet["rest_id"]
2350 retweet["_retweet_id_str"] = tweet["rest_id"]
2351 tweet = retweet
2352 else:
2353 legacy["retweeted_status_id_str"] = \
2354 retweet["rest_id"]
2355 tweet["author"] = \
2356 retweet["core"]["user_results"]["result"]
2357
2358 rtlegacy = retweet["legacy"]
2359
2360 if "note_tweet" in retweet:
2361 tweet["note_tweet"] = retweet["note_tweet"]
2362
2363 if "extended_entities" in rtlegacy and \
2364 "extended_entities" not in legacy:
2365 legacy["extended_entities"] = \
2366 rtlegacy["extended_entities"]
2367
2368 if "withheld_scope" in rtlegacy and \
2369 "withheld_scope" not in legacy:
2370 legacy["withheld_scope"] = \
2371 rtlegacy["withheld_scope"]
2372
2373 legacy["full_text"] = rtlegacy["full_text"]
2374 except Exception as exc:
2375 extr.log.debug(
2376 "%s: %s: %s",
2377 tweet.get("rest_id"), exc.__class__.__name__, exc)
2378 continue
2379
2380 yield tweet
2381
2382 if "quoted_status_result" in tweet:
2383 try:
2384 if quoted := tweet["quoted_status_result"]:
2385 quoted = quoted["result"]
2386 elif extr.quoted_expand:
2387 quoted_id = legacy["quoted_status_id_str"]
2388 extr.log.debug("Retrieving data for quote %s",
2389 quoted_id)
2390 for quoted in self.tweet_detail(quoted_id):
2391 if quoted["rest_id"] == quoted_id:
2392 break
2393 else:
2394 quoted = {}
2395 if "tweet" in quoted:
2396 # limitedActionResults
2397 quoted = quoted["tweet"]
2398 quoted["legacy"]["quoted_by"] = (
2399 tweet["core"]["user_results"]["result"]
2400 ["core"]["screen_name"])
2401 quoted["legacy"]["quoted_by_id_str"] = tweet["rest_id"]
2402 quoted["sortIndex"] = entry.get("sortIndex")
2403
2404 yield quoted
2405 except KeyError:
2406 extr.log.debug(
2407 "Skipping quote of %s (deleted)",
2408 tweet.get("rest_id"))
2409 continue
2410
2411 if retry:
2412 continue
2413 elif tweet:
2414 stop_tweets = stop_tweets_max
2415 last_tweet = tweet
2416 elif stop_tweets <= 0:
2417 if not count:
2418 return extr._update_cursor(None)
2419 self.log.debug("Switching to 'count: %s'", count[-1])
2420 variables["count"] = count.pop()
2421 continue
2422 else:
2423 self.log.debug(
2424 "No Tweet results (%s/%s)",
2425 stop_tweets_max - stop_tweets + 1, stop_tweets_max)
2426 stop_tweets -= 1
2427
2428 if not cursor or cursor == variables.get("cursor"):
2429 self.log.debug("No continuation cursor")
2430 return extr._update_cursor(None)
2431
2432 if update_variables is None:
2433 variables["cursor"] = extr._update_cursor(cursor)
2434 else:
2435 variables = update_variables(variables, cursor, last_tweet)
2436
2437 def _pagination_users(self, endpoint, variables, path=None):
2438 extr = self.extractor
2439 if cursor := extr._init_cursor():
2440 variables["cursor"] = cursor
2441 params = {
2442 "variables": None,
2443 "features" : self._json_dumps(self.features_pagination),
2444 }
2445
2446 while True:
2447 cursor = entry = None
2448 params["variables"] = self._json_dumps(variables)
2449 data = self._call(endpoint, params)["data"]
2450
2451 try:
2452 if path is None:
2453 instructions = (data["user"]["result"]["timeline"]
2454 ["timeline"]["instructions"])
2455 else:
2456 for key in path:
2457 data = data[key]
2458 instructions = data["instructions"]
2459 except KeyError:
2460 return extr._update_cursor(None)
2461
2462 for instr in instructions:
2463 if instr["type"] == "TimelineAddEntries":
2464 for entry in instr["entries"]:
2465 if entry["entryId"].startswith("user-"):
2466 try:
2467 user = (entry["content"]["itemContent"]
2468 ["user_results"]["result"])
2469 except KeyError:
2470 pass
2471 else:
2472 if "rest_id" in user:
2473 yield user
2474 elif entry["entryId"].startswith("cursor-bottom-"):
2475 cursor = entry["content"]["value"]
2476
2477 if not cursor or cursor.startswith(("-1|", "0|")) or not entry:
2478 return extr._update_cursor(None)
2479 variables["cursor"] = extr._update_cursor(cursor)
2480
2481 def _handle_ratelimit(self, response):
2482 rl = self.extractor.config("ratelimit")
2483 if rl == "abort":
2484 raise self.exc.AbortExtraction("Rate limit exceeded")
2485
2486 until = response.headers.get("x-rate-limit-reset")
2487 seconds = None if until else 60.0
2488
2489 if rl and isinstance(rl, str) and ":" in rl:
2490 rl, _, num = rl.partition(":")
2491 if rl == "abort":
2492 amt = getattr(self, "_ratelimit_amt", 1)
2493 num = text.parse_int(num)
2494 msg = f"Rate limit exceeded ({amt}/{num})"
2495 if amt >= num:
2496 raise self.exc.AbortExtraction(msg)
2497 self.log.warning(msg)
2498 self._ratelimit_amt = amt + 1
2499 elif rl == "wait":
2500 until = None
2501 seconds = text.parse_float(num) or 60.0
2502 else:
2503 self.log.warning("Unsupported 'ratelimit' setting '%s'", rl)
2504
2505 self.extractor.wait(until=until, seconds=seconds)
2506
2507 def _process_tombstone(self, entry, tombstone):
2508 text = (tombstone.get("richText") or tombstone["text"])["text"]
2509 tweet_id = entry["entryId"].rpartition("-")[2]
2510
2511 if text.startswith("Age-restricted"):
2512 if self._nsfw_warning:
2513 self._nsfw_warning = False
2514 self.log.warning('"%s"', text)
2515
2516 self.log.debug("Skipping %s ('%s')", tweet_id, text)
2517
2518 def _update_variables_search_maxid(self, variables, cursor, tweet):
2519 try:
2520 tweet_id = tweet.get("id_str") or tweet["legacy"]["id_str"]
2521 max_id = int(tweet_id)
2522
2523 user = self.extractor._user
2524 if user is not None or max_id == self._var_maxid_prev:
2525 if user is None:
2526 self.log.debug("Repeated 'max_id' value (%s)", max_id)
2527 # reduce 'max_id' timestamp milliseconds by 1
2528 # https://docs.x.com/fundamentals/x-ids
2529 max_id = (max_id - 0x400000) | 0x3fffff
2530 self.log.debug("Next 'max_id': %s", max_id)
2531 self._var_maxid_prev = max_id
2532 max_id = "max_id:" + str(max_id)
2533
2534 query, n = text.re(r"\bmax_id:\d+").subn(
2535 max_id, variables["rawQuery"])
2536 if n:
2537 variables["rawQuery"] = query
2538 else:
2539 variables["rawQuery"] = f"{query} {max_id}"
2540
2541 if prefix := getattr(self.extractor, "_cursor_prefix", None):
2542 self.extractor._cursor_prefix = \
2543 f"{prefix.partition('_')[0]}_{tweet_id}/"
2544 variables["cursor"] = None
2545 except Exception as exc:
2546 self.extractor.log.debug(
2547 "Failed to update 'max_id' search query (%s: %s). Falling "
2548 "back to 'cursor' pagination", exc.__class__.__name__, exc)
2549 variables["cursor"] = self.extractor._update_cursor(cursor)
2550
2551 return variables
2552
2553 def _update_variables_search_date(self, variables, cursor, tweet):
2554 try:
2555 tweet_id = tweet.get("id_str") or tweet["legacy"]["id_str"]
2556 date = self.extractor._tweetid_to_datetime(int(tweet_id))
2557
2558 if date == self._var_date_prev:
2559 variables["cursor"] = self.extractor._update_cursor(cursor)
2560 return variables
2561
2562 dstr = f"until:{date.year:>04}-{date.month:>02}-{date.day:>02}"
2563 query, n = text.re(r"\buntil:\d{4}-\d{2}-\d{2}").subn(
2564 dstr, variables["rawQuery"])
2565 if n:
2566 variables["rawQuery"] = query
2567 else:
2568 variables["rawQuery"] = f"{query} {dstr}"
2569
2570 if prefix := getattr(self.extractor, "_cursor_prefix", None):
2571 self.extractor._cursor_prefix = \
2572 f"{prefix.partition('_')[0]}_{tweet_id}/"
2573 variables["cursor"] = None
2574 self._var_date_prev = date
2575 except Exception as exc:
2576 self.extractor.log.debug(
2577 "Failed to update 'until' search query (%s: %s). Falling "
2578 "back to 'cursor' pagination", exc.__class__.__name__, exc)
2579 variables["cursor"] = self.extractor._update_cursor(cursor)
2580
2581 return variables