-
Notifications
You must be signed in to change notification settings - Fork 23
/
client.py
1943 lines (1751 loc) · 72.3 KB
/
client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from typing import Any, Literal, Iterable
from time import time
import asyncio
import base64
import json
import re
from loguru import logger
from curl_cffi import requests
from yarl import URL
from ._capsolver.fun_captcha import FunCaptcha, FunCaptchaTypeEnm
from .errors import (
TwitterException,
FailedToFindDuplicatePost,
HTTPException,
BadRequest,
Unauthorized,
Forbidden,
NotFound,
RateLimited,
ServerError,
BadAccount,
BadToken,
Locked,
ConsentLocked,
Suspended,
)
from .utils import to_json
from .base import BaseHTTPClient
from .account import Account, AccountStatus
from .models import User, Tweet, Media, Subtask
from .utils import (
parse_oauth_html,
parse_unlock_html,
tweets_data_from_instructions,
)
class Client(BaseHTTPClient):
_BEARER_TOKEN = "AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA"
_DEFAULT_HEADERS = {
"authority": "twitter.com",
"origin": "https://twitter.com",
"x-twitter-active-user": "yes",
"x-twitter-client-language": "en",
}
_GRAPHQL_URL = "https://twitter.com/i/api/graphql"
_ACTION_TO_QUERY_ID = {
"CreateRetweet": "ojPdsZsimiJrUGLR1sjUtA",
"FavoriteTweet": "lI07N6Otwv1PhnEgXILM7A",
"UnfavoriteTweet": "ZYKSe-w7KEslx3JhSIk5LA",
"CreateTweet": "v0en1yVV-Ybeek8ClmXwYw",
"TweetResultByRestId": "V3vfsYzNEyD9tsf4xoFRgw",
"ModerateTweet": "p'jF:GVqCjTcZol0xcBJjw",
"DeleteTweet": "VaenaVgh5q5ih7kvyVjgtg",
"UserTweets": "V1ze5q3ijDS1VeLwLY0m7g",
"TweetDetail": "VWFGPVAGkZMGRKGe3GFFnA",
"ProfileSpotlightsQuery": "9zwVLJ48lmVUk8u_Gh9DmA",
"Following": "t-BPOrMIduGUJWO_LxcvNQ",
"Followers": "3yX7xr2hKjcZYnXt6cU6lQ",
"UserByScreenName": "G3KGOASz96M-Qu0nwmGXNg",
"UsersByRestIds": "itEhGywpgX9b3GJCzOtSrA",
"Viewer": "W62NnYgkgziw9bwyoVht0g",
}
_CAPTCHA_URL = "https://twitter.com/account/access"
_CAPTCHA_SITE_KEY = "0152B4EB-D2DC-460A-89A1-629838B529C9"
@classmethod
def _action_to_url(cls, action: str) -> tuple[str, str]:
"""
:return: URL and Query ID
"""
query_id = cls._ACTION_TO_QUERY_ID[action]
url = f"{cls._GRAPHQL_URL}/{query_id}/{action}"
return url, query_id
def __init__(
self,
account: Account,
*,
wait_on_rate_limit: bool = True,
capsolver_api_key: str = None,
max_unlock_attempts: int = 5,
auto_relogin: bool = True,
update_account_info_on_startup: bool = True,
**session_kwargs,
):
super().__init__(**session_kwargs)
self.account = account
self.wait_on_rate_limit = wait_on_rate_limit
self.capsolver_api_key = capsolver_api_key
self.max_unlock_attempts = max_unlock_attempts
self.auto_relogin = auto_relogin
self._update_account_info_on_startup = update_account_info_on_startup
async def __aenter__(self):
await self.on_startup()
return await super().__aenter__()
async def _request(
self,
method,
url,
*,
auth: bool = True,
bearer: bool = True,
wait_on_rate_limit: bool = None,
**kwargs,
) -> tuple[requests.Response, Any]:
cookies = kwargs["cookies"] = kwargs.get("cookies") or {}
headers = kwargs["headers"] = kwargs.get("headers") or {}
if bearer:
headers["authorization"] = f"Bearer {self._BEARER_TOKEN}"
# headers["x-twitter-auth-type"] = "OAuth2Session"
if auth:
if not self.account.auth_token:
raise ValueError("No auth_token. Login before")
cookies["auth_token"] = self.account.auth_token
if self.account.ct0:
cookies["ct0"] = self.account.ct0
headers["x-csrf-token"] = self.account.ct0
# fmt: off
log_message = (f"(auth_token={self.account.hidden_auth_token}, id={self.account.id}, username={self.account.username})"
f" ==> Request {method} {url}")
if kwargs.get('data'): log_message += f"\nRequest data: {kwargs.get('data')}"
if kwargs.get('json'): log_message += f"\nRequest data: {kwargs.get('json')}"
logger.debug(log_message)
# fmt: on
try:
response = await self._session.request(method, url, **kwargs)
except requests.errors.RequestsError as exc:
if exc.code == 35:
msg = (
"The IP address may have been blocked by Twitter. Blocked countries: Russia. "
+ str(exc)
)
raise requests.errors.RequestsError(msg, 35, exc.response)
raise
data = response.text
# fmt: off
logger.debug(f"(auth_token={self.account.hidden_auth_token}, id={self.account.id}, username={self.account.username})"
f" <== Response {method} {url}"
f"\nStatus code: {response.status_code}"
f"\nResponse data: {data}")
# fmt: on
if ct0 := self._session.cookies.get("ct0", domain=".twitter.com"):
self.account.ct0 = ct0
auth_token = self._session.cookies.get("auth_token")
if auth_token and auth_token != self.account.auth_token:
self.account.auth_token = auth_token
logger.warning(
f"(auth_token={self.account.hidden_auth_token}, id={self.account.id}, username={self.account.username})"
f" Requested new auth_token!"
)
try:
data = response.json()
except json.decoder.JSONDecodeError:
pass
if 300 > response.status_code >= 200:
if isinstance(data, dict) and "errors" in data:
exc = HTTPException(response, data)
if 141 in exc.api_codes:
self.account.status = AccountStatus.SUSPENDED
raise Suspended(exc, self.account)
if 326 in exc.api_codes:
for error_data in exc.api_errors:
if (
error_data.get("code") == 326
and error_data.get("bounce_location")
== "/i/flow/consent_flow"
):
self.account.status = AccountStatus.CONSENT_LOCKED
raise ConsentLocked(exc, self.account)
self.account.status = AccountStatus.LOCKED
raise Locked(exc, self.account)
raise exc
return response, data
if response.status_code == 400:
raise BadRequest(response, data)
if response.status_code == 401:
exc = Unauthorized(response, data)
if 32 in exc.api_codes:
self.account.status = AccountStatus.BAD_TOKEN
raise BadToken(exc, self.account)
raise exc
if response.status_code == 403:
exc = Forbidden(response, data)
if 64 in exc.api_codes:
self.account.status = AccountStatus.SUSPENDED
raise Suspended(exc, self.account)
if 326 in exc.api_codes:
for error_data in exc.api_errors:
if (
error_data.get("code") == 326
and error_data.get("bounce_location") == "/i/flow/consent_flow"
):
self.account.status = AccountStatus.CONSENT_LOCKED
raise ConsentLocked(exc, self.account)
self.account.status = AccountStatus.LOCKED
raise Locked(exc, self.account)
raise exc
if response.status_code == 404:
raise NotFound(response, data)
if response.status_code == 429:
if wait_on_rate_limit is None:
wait_on_rate_limit = self.wait_on_rate_limit
if not wait_on_rate_limit:
raise RateLimited(response, data)
reset_time = int(response.headers["x-rate-limit-reset"])
sleep_time = reset_time - int(time()) + 1
if sleep_time > 0:
logger.warning(
f"(auth_token={self.account.hidden_auth_token}, id={self.account.id}, username={self.account.username})"
f"Rate limited! Sleep time: {sleep_time} sec."
)
await asyncio.sleep(sleep_time)
return await self._request(
method,
url,
auth=auth,
bearer=bearer,
wait_on_rate_limit=wait_on_rate_limit,
**kwargs,
)
if response.status_code >= 500:
raise ServerError(response, data)
async def request(
self,
method,
url,
*,
auto_unlock: bool = True,
auto_relogin: bool = None,
rerequest_on_bad_ct0: bool = True,
**kwargs,
) -> tuple[requests.Response, Any]:
try:
return await self._request(method, url, **kwargs)
except Locked:
if not self.capsolver_api_key or not auto_unlock:
raise
await self.unlock()
return await self._request(method, url, **kwargs)
except BadToken:
if auto_relogin is None:
auto_relogin = self.auto_relogin
if (
not auto_relogin
or not self.account.password
or not (self.account.email or self.account.username)
):
raise
await self.relogin()
return await self._request(method, url, **kwargs)
except Forbidden as exc:
if (
rerequest_on_bad_ct0
and 353 in exc.api_codes
and "ct0" in exc.response.cookies
):
return await self.request(
method, url, rerequest_on_bad_ct0=False, **kwargs
)
else:
raise
async def on_startup(self):
if self._update_account_info_on_startup:
await self.update_account_info()
await self.establish_status()
async def _request_oauth2_auth_code(
self,
client_id: str,
code_challenge: str,
state: str,
redirect_uri: str,
code_challenge_method: str,
scope: str,
response_type: str,
) -> str:
url = "https://twitter.com/i/api/2/oauth2/authorize"
querystring = {
"client_id": client_id,
"code_challenge": code_challenge,
"code_challenge_method": code_challenge_method,
"state": state,
"scope": scope,
"response_type": response_type,
"redirect_uri": redirect_uri,
}
response, response_json = await self.request("GET", url, params=querystring)
auth_code = response_json["auth_code"]
return auth_code
async def _confirm_oauth2(self, auth_code: str):
data = {
"approval": "true",
"code": auth_code,
}
headers = {"content-type": "application/x-www-form-urlencoded"}
await self.request(
"POST",
"https://twitter.com/i/api/2/oauth2/authorize",
headers=headers,
data=data,
)
async def oauth2(
self,
client_id: str,
code_challenge: str,
state: str,
redirect_uri: str,
code_challenge_method: str,
scope: str,
response_type: str,
):
"""
Запрашивает код авторизации для OAuth 2.0 авторизации.
Привязка (бинд, линк) приложения.
:param client_id: Идентификатор клиента, используемый для OAuth.
:param state: Уникальная строка состояния для предотвращения CSRF-атак.
:param redirect_uri: URI перенаправления, на который будет отправлен ответ.
:param scope: Строка областей доступа, запрашиваемых у пользователя.
:param response_type: Тип ответа, который ожидается от сервера авторизации.
:return: Код авторизации (привязки).
"""
auth_code = await self._request_oauth2_auth_code(
client_id,
code_challenge,
state,
redirect_uri,
code_challenge_method,
scope,
response_type,
)
await self._confirm_oauth2(auth_code)
return auth_code
async def _oauth(self, oauth_token: str, **oauth_params) -> requests.Response:
"""
:return: Response: html страница привязки приложения (аутентификации) старого типа.
"""
url = "https://api.twitter.com/oauth/authenticate"
oauth_params["oauth_token"] = oauth_token
response, _ = await self.request("GET", url, params=oauth_params)
if response.status_code == 403:
raise ValueError(
"The request token (oauth_token) for this page is invalid."
" It may have already been used, or expired because it is too old."
)
return response
async def _confirm_oauth(
self,
oauth_token: str,
authenticity_token: str,
redirect_after_login_url: str,
) -> requests.Response:
url = "https://api.twitter.com/oauth/authorize"
params = {
"redirect_after_login": redirect_after_login_url,
"authenticity_token": authenticity_token,
"oauth_token": oauth_token,
}
response, _ = await self.request("POST", url, data=params)
return response
async def oauth(self, oauth_token: str, **oauth_params) -> tuple[str, str]:
"""
:return: authenticity_token, redirect_url
"""
response = await self._oauth(oauth_token, **oauth_params)
authenticity_token, redirect_url, redirect_after_login_url = parse_oauth_html(
response.text
)
# Первая привязка требует подтверждения
if redirect_after_login_url:
response = await self._confirm_oauth(
oauth_token, authenticity_token, redirect_after_login_url
)
authenticity_token, redirect_url, redirect_after_login_url = (
parse_oauth_html(response.text)
)
return authenticity_token, redirect_url
async def _update_account_username(self):
url = "https://twitter.com/i/api/1.1/account/settings.json"
response, response_json = await self.request("POST", url)
self.account.username = response_json["screen_name"]
async def _request_user_by_username(self, username: str) -> User | None:
url, query_id = self._action_to_url("UserByScreenName")
variables = {
"screen_name": username,
"withSafetyModeUserFields": True,
}
features = {
"hidden_profile_likes_enabled": True,
"hidden_profile_subscriptions_enabled": True,
"responsive_web_graphql_exclude_directive_enabled": True,
"verified_phone_label_enabled": False,
"subscriptions_verification_info_is_identity_verified_enabled": True,
"subscriptions_verification_info_verified_since_enabled": True,
"highlights_tweets_tab_ui_enabled": True,
"creator_subscriptions_tweet_preview_api_enabled": True,
"responsive_web_graphql_skip_user_profile_image_extensions_enabled": False,
"responsive_web_graphql_timeline_navigation_enabled": True,
}
field_toggles = {
"withAuxiliaryUserLabels": False,
}
params = {
"variables": to_json(variables),
"features": to_json(features),
"fieldToggles": to_json(field_toggles),
}
response, data = await self.request("GET", url, params=params)
if not data["data"]:
return None
return User.from_raw_data(data["data"]["user"]["result"])
async def request_user_by_username(self, username: str) -> User | Account | None:
"""
:param username: Имя пользователя без знака `@`
:return: Пользователь, если существует, иначе None. Или собственный аккаунт, если совпадает имя пользователя.
"""
if not self.account.username:
await self.update_account_info()
user = await self._request_user_by_username(username)
if user and user.username == self.account.username:
self.account.update(**user.model_dump())
return self.account
return user
async def _request_users_by_ids(
self, user_ids: Iterable[str | int]
) -> dict[int : User | Account]:
url, query_id = self._action_to_url("UsersByRestIds")
variables = {"userIds": list({str(user_id) for user_id in user_ids})}
features = {
"responsive_web_graphql_exclude_directive_enabled": True,
"responsive_web_graphql_skip_user_profile_image_extensions_enabled": False,
"responsive_web_graphql_timeline_navigation_enabled": True,
"verified_phone_label_enabled": False,
}
query = {"variables": variables, "features": features}
response, data = await self.request("GET", url, params=query)
users = {}
for user_data in data["data"]["users"]:
user_data = user_data["result"]
user = User.from_raw_data(user_data)
users[user.id] = user
if user.id == self.account.id:
users[self.account.id] = self.account
return users
async def request_user_by_id(self, user_id: int | str) -> User | Account | None:
"""
:param user_id: ID пользователя
:return: Пользователь, если существует, иначе None. Или собственный аккаунт, если совпадает ID.
"""
if not self.account.id:
await self.update_account_info()
users = await self._request_users_by_ids((user_id,))
user = users[user_id]
return user
async def request_users_by_ids(
self, user_ids: Iterable[str | int]
) -> dict[int : User | Account]:
"""
:param user_ids: ID пользователей
:return: Пользователи, если существует, иначе None. Или собственный аккаунт, если совпадает ID.
"""
return await self._request_users_by_ids(user_ids)
async def update_account_info(self):
if not self.account.username:
await self._update_account_username()
await self.request_user_by_username(self.account.username)
async def upload_image(
self,
image: bytes,
attempts: int = 3,
timeout: float | tuple[float, float] = 10,
) -> Media:
"""
Upload image as bytes.
Иногда при первой попытке загрузки изображения возвращает 408,
после чего повторная попытка загрузки изображения проходит успешно
:return: Media
"""
url = "https://upload.twitter.com/1.1/media/upload.json"
payload = {"media_data": base64.b64encode(image)}
for attempt in range(attempts):
try:
response, data = await self.request(
"POST", url, data=payload, timeout=timeout
)
return Media(**data)
except (HTTPException, requests.errors.RequestsError) as exc:
if (
attempt < attempts - 1
and (
isinstance(exc, requests.errors.RequestsError)
and exc.code == 28
)
or (
isinstance(exc, HTTPException)
and exc.response.status_code == 408
)
):
continue
else:
raise
async def _follow_action(self, action: str, user_id: int | str) -> bool:
url = f"https://twitter.com/i/api/1.1/friendships/{action}.json"
params = {
"include_profile_interstitial_type": "1",
"include_blocking": "1",
"include_blocked_by": "1",
"include_followed_by": "1",
"include_want_retweets": "1",
"include_mute_edge": "1",
"include_can_dm": "1",
"include_can_media_tag": "1",
"include_ext_has_nft_avatar": "1",
"include_ext_is_blue_verified": "1",
"include_ext_verified_type": "1",
"include_ext_profile_image_shape": "1",
"skip_status": "1",
"user_id": user_id,
}
headers = {
"content-type": "application/x-www-form-urlencoded",
}
response, response_json = await self.request(
"POST", url, params=params, headers=headers
)
return bool(response_json)
async def follow(self, user_id: str | int) -> bool:
return await self._follow_action("create", user_id)
async def unfollow(self, user_id: str | int) -> bool:
return await self._follow_action("destroy", user_id)
async def _interact_with_tweet(self, action: str, tweet_id: int) -> dict:
url, query_id = self._action_to_url(action)
json_payload = {
"variables": {"tweet_id": tweet_id, "dark_request": False},
"queryId": query_id,
}
response, data = await self.request("POST", url, json=json_payload)
return data
async def _repost(self, tweet_id: int | str) -> Tweet:
data = await self._interact_with_tweet("CreateRetweet", tweet_id)
tweet_id = data["data"]["create_retweet"]["retweet_results"]["result"]["rest_id"] # type: ignore
return await self.request_tweet(tweet_id)
async def _repost_or_search_duplicate(
self,
tweet_id: int,
*,
search_duplicate: bool = True,
) -> Tweet:
try:
tweet = await self._repost(tweet_id)
except HTTPException as exc:
if (
search_duplicate
and 327
in exc.api_codes # duplicate retweet (You have already retweeted this Tweet)
):
tweets = await self.request_tweets(self.account.id)
duplicate_tweet = None
for tweet_ in tweets: # type: Tweet
if tweet_.retweeted_tweet and tweet_.retweeted_tweet.id == tweet_id:
duplicate_tweet = tweet_
if not duplicate_tweet:
raise FailedToFindDuplicatePost(
f"Couldn't find a post duplicate in the next 20 posts"
)
tweet = duplicate_tweet
else:
raise
return tweet
async def repost(
self,
tweet_id: int,
*,
search_duplicate: bool = True,
) -> Tweet:
"""
Repost (retweet)
Иногда может вернуть ошибку 404 (Not Found), если плохой прокси или по другим неизвестным причинам
:return: Tweet
"""
return await self._repost_or_search_duplicate(
tweet_id, search_duplicate=search_duplicate
)
async def like(self, tweet_id: int) -> bool:
"""
:return: Liked or not
"""
try:
response_json = await self._interact_with_tweet("FavoriteTweet", tweet_id)
except HTTPException as exc:
if 139 in exc.api_codes:
# Already liked
return True
else:
raise
return response_json["data"]["favorite_tweet"] == "Done"
async def unlike(self, tweet_id: int) -> dict:
response_json = await self._interact_with_tweet("UnfavoriteTweet", tweet_id)
is_unliked = (
"data" in response_json
and response_json["data"]["unfavorite_tweet"] == "Done"
)
return is_unliked
async def delete_tweet(self, tweet_id: int | str) -> bool:
url, query_id = self._action_to_url("DeleteTweet")
json_payload = {
"variables": {
"tweet_id": tweet_id,
"dark_request": False,
},
"queryId": query_id,
}
response, response_json = await self.request("POST", url, json=json_payload)
is_deleted = "data" in response_json and "delete_tweet" in response_json["data"]
return is_deleted
async def pin_tweet(self, tweet_id: str | int) -> bool:
url = "https://api.twitter.com/1.1/account/pin_tweet.json"
data = {
"tweet_mode": "extended",
"id": str(tweet_id),
}
headers = {
"content-type": "application/x-www-form-urlencoded",
}
response, response_json = await self.request(
"POST", url, headers=headers, data=data
)
is_pinned = bool(response_json["pinned_tweets"])
return is_pinned
async def _tweet(
self,
text: str = None,
*,
media_id: int | str = None,
tweet_id_to_reply: str | int = None,
attachment_url: str = None,
) -> Tweet:
url, query_id = self._action_to_url("CreateTweet")
variables = {
"tweet_text": text if text is not None else "",
"dark_request": False,
"media": {"media_entities": [], "possibly_sensitive": False},
"semantic_annotation_ids": [],
}
if attachment_url:
variables["attachment_url"] = attachment_url
if tweet_id_to_reply:
variables["reply"] = {
"in_reply_to_tweet_id": str(tweet_id_to_reply),
"exclude_reply_user_ids": [],
}
if media_id:
variables["media"]["media_entities"].append(
{"media_id": str(media_id), "tagged_users": []}
)
features = {
"communities_web_enable_tweet_community_results_fetch": True,
"c9s_tweet_anatomy_moderator_badge_enabled": True,
"tweetypie_unmention_optimization_enabled": True,
"responsive_web_edit_tweet_api_enabled": True,
"graphql_is_translatable_rweb_tweet_is_translatable_enabled": True,
"view_counts_everywhere_api_enabled": True,
"longform_notetweets_consumption_enabled": True,
"responsive_web_twitter_article_tweet_consumption_enabled": True,
"tweet_awards_web_tipping_enabled": False,
"longform_notetweets_rich_text_read_enabled": True,
"longform_notetweets_inline_media_enabled": True,
"rweb_video_timestamps_enabled": True,
"responsive_web_graphql_exclude_directive_enabled": True,
"verified_phone_label_enabled": False,
"freedom_of_speech_not_reach_fetch_enabled": True,
"standardized_nudges_misinfo": True,
"tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled": True,
"responsive_web_graphql_skip_user_profile_image_extensions_enabled": False,
"responsive_web_graphql_timeline_navigation_enabled": True,
"responsive_web_enhance_cards_enabled": False,
}
payload = {
"variables": variables,
"features": features,
"queryId": query_id,
}
response, response_json = await self.request("POST", url, json=payload)
tweet = Tweet.from_raw_data(
response_json["data"]["create_tweet"]["tweet_results"]["result"]
)
return tweet
async def _tweet_or_search_duplicate(
self,
text: str = None,
*,
media_id: int | str = None,
tweet_id_to_reply: str | int = None,
attachment_url: str = None,
search_duplicate: bool = True,
) -> Tweet:
try:
tweet = await self._tweet(
text,
media_id=media_id,
tweet_id_to_reply=tweet_id_to_reply,
attachment_url=attachment_url,
)
except HTTPException as exc:
if (
search_duplicate
and 187 in exc.api_codes # duplicate tweet (Status is a duplicate)
):
tweets = await self.request_tweets()
duplicate_tweet = None
for tweet_ in tweets:
if tweet_.text.startswith(text.strip()):
duplicate_tweet = tweet_
if not duplicate_tweet:
raise FailedToFindDuplicatePost(
f"Couldn't find a post duplicate in the next 20 posts"
)
tweet = duplicate_tweet
else:
raise
return tweet
async def tweet(
self,
text: str,
*,
media_id: int | str = None,
search_duplicate: bool = True,
) -> Tweet:
"""
Иногда может вернуть ошибку 404 (Not Found), если плохой прокси или по другим неизвестным причинам
:return: Tweet
"""
return await self._tweet_or_search_duplicate(
text,
media_id=media_id,
search_duplicate=search_duplicate,
)
async def reply(
self,
tweet_id: str | int,
text: str,
*,
media_id: int | str = None,
search_duplicate: bool = True,
) -> Tweet:
"""
Иногда может вернуть ошибку 404 (Not Found), если плохой прокси или по другим неизвестным причинам
:return: Tweet
"""
return await self._tweet_or_search_duplicate(
text,
media_id=media_id,
tweet_id_to_reply=tweet_id,
search_duplicate=search_duplicate,
)
async def quote(
self,
tweet_url: str,
text: str,
*,
media_id: int | str = None,
search_duplicate: bool = True,
) -> Tweet:
"""
Иногда может вернуть ошибку 404 (Not Found), если плохой прокси или по другим неизвестным причинам
:return: Tweet
"""
return await self._tweet_or_search_duplicate(
text,
media_id=media_id,
attachment_url=tweet_url,
search_duplicate=search_duplicate,
)
async def vote(
self, tweet_id: int | str, card_id: int | str, choice_number: int
) -> dict:
"""
:return: Raw vote information
"""
url = "https://caps.twitter.com/v2/capi/passthrough/1"
params = {
"twitter:string:card_uri": f"card://{card_id}",
"twitter:long:original_tweet_id": str(tweet_id),
"twitter:string:response_card_name": "poll2choice_text_only",
"twitter:string:cards_platform": "Web-12",
"twitter:string:selected_choice": str(choice_number),
}
response, response_json = await self.request("POST", url, params=params)
return response_json
async def _request_users_by_action(
self,
action: str,
user_id: int | str,
count: int,
cursor: str = None,
) -> list[User]:
url, query_id = self._action_to_url(action)
variables = {
"userId": str(user_id),
"count": count,
"includePromotedContent": False,
}
if cursor:
variables["cursor"] = cursor
features = {
"rweb_lists_timeline_redesign_enabled": True,
"responsive_web_graphql_exclude_directive_enabled": True,
"verified_phone_label_enabled": False,
"creator_subscriptions_tweet_preview_api_enabled": True,
"responsive_web_graphql_timeline_navigation_enabled": True,
"responsive_web_graphql_skip_user_profile_image_extensions_enabled": False,
"tweetypie_unmention_optimization_enabled": True,
"responsive_web_edit_tweet_api_enabled": True,
"graphql_is_translatable_rweb_tweet_is_translatable_enabled": True,
"view_counts_everywhere_api_enabled": True,
"longform_notetweets_consumption_enabled": True,
"responsive_web_twitter_article_tweet_consumption_enabled": False,
"tweet_awards_web_tipping_enabled": False,
"freedom_of_speech_not_reach_fetch_enabled": True,
"standardized_nudges_misinfo": True,
"tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled": True,
"longform_notetweets_rich_text_read_enabled": True,
"longform_notetweets_inline_media_enabled": True,
"responsive_web_media_download_video_enabled": False,
"responsive_web_enhance_cards_enabled": False,
}
params = {
"variables": to_json(variables),
"features": to_json(features),
}
response, response_json = await self.request("GET", url, params=params)
users = []
if "result" in response_json["data"]["user"]:
entries = response_json["data"]["user"]["result"]["timeline"]["timeline"][
"instructions"
][-1]["entries"]
for entry in entries:
if entry["entryId"].startswith("user"):
user_data_dict = entry["content"]["itemContent"]["user_results"][
"result"
]
users.append(User.from_raw_data(user_data_dict))
return users
async def request_followers(
self,
user_id: int | str = None,
count: int = 20,
cursor: str = None,
) -> list[User]:
"""
:param user_id: Текущий пользователь, если не передан ID иного пользователя.
:param count: Количество подписчиков.
"""
if user_id:
return await self._request_users_by_action(
"Followers", user_id, count, cursor
)
else:
if not self.account.id:
await self.update_account_info()
return await self._request_users_by_action(
"Followers", self.account.id, count, cursor
)
async def request_followings(
self,
user_id: int | str = None,
count: int = 20,
cursor: str = None,
) -> list[User]:
"""
:param user_id: Текущий пользователь, если не передан ID иного пользователя.
:param count: Количество подписчиков.
"""
if user_id:
return await self._request_users_by_action(
"Following", user_id, count, cursor
)
else:
if not self.account.id:
await self.update_account_info()
return await self._request_users_by_action(
"Following", self.account.id, count, cursor
)
async def _request_tweet(self, tweet_id: int | str) -> Tweet:
url, query_id = self._action_to_url("TweetDetail")
variables = {
"focalTweetId": str(tweet_id),
"with_rux_injections": False,
"includePromotedContent": True,
"withCommunity": True,
"withQuickPromoteEligibilityTweetFields": True,
"withBirdwatchNotes": True,
"withVoice": True,
"withV2Timeline": True,
}
features = {
"rweb_lists_timeline_redesign_enabled": True,
"responsive_web_graphql_exclude_directive_enabled": True,
"verified_phone_label_enabled": False,