twitter-openapi-python 0.0.23__py3-none-any.whl → 0.0.25__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -31,6 +31,10 @@ class PostApiUtils:
31
31
  self,
32
32
  tweet_text: str,
33
33
  media_ids: Optional[list[str]] = None,
34
+ tagged_users: Optional[list[list[str]]] = None,
35
+ in_reply_to_tweet_id: Optional[str] = None,
36
+ attachment_url: Optional[str] = None,
37
+ conversation_control: Optional[str] = None,
34
38
  ) -> ResponseType[models.CreateTweetResponse]:
35
39
  variables = non_nullable(
36
40
  twitter.PostCreateTweetRequestVariables.from_dict(
@@ -43,13 +47,28 @@ class PostApiUtils:
43
47
  )
44
48
  )
45
49
  variables.tweet_text = tweet_text
46
- variables.media.media_entities = [
47
- twitter.PostCreateTweetRequestVariablesMediaMediaEntitiesInner(
48
- media_id=media_id,
49
- tagged_users=[],
50
+ if media_ids:
51
+ tagged_or = tagged_users or []
52
+ variables.media.media_entities = [
53
+ twitter.PostCreateTweetRequestVariablesMediaMediaEntitiesInner(
54
+ media_id=media_id,
55
+ tagged_users=tagged_or[idx] if len(tagged_or) > idx else [],
56
+ )
57
+ for idx, media_id in enumerate(media_ids)
58
+ ]
59
+ variables.attachment_url = attachment_url
60
+ if conversation_control:
61
+ variables.conversation_control = (
62
+ twitter.PostCreateTweetRequestVariablesConversationControl(
63
+ mode=conversation_control
64
+ )
65
+ )
66
+
67
+ if in_reply_to_tweet_id:
68
+ variables.reply = twitter.PostCreateTweetRequestVariablesReply(
69
+ exclude_reply_user_ids=[],
70
+ in_reply_to_tweet_id=in_reply_to_tweet_id,
50
71
  )
51
- for media_id in media_ids or []
52
- ]
53
72
 
54
73
  res = self.api.post_create_tweet_with_http_info(
55
74
  path_query_id=self.flag["CreateTweet"]["queryId"],
@@ -58,43 +58,54 @@ class TwitterOpenapiPythonClient:
58
58
 
59
59
 
60
60
  class TwitterOpenapiPython:
61
- hash: str = "a18a24e4fd96967314c452a6ec2fe6e54f112351"
61
+ hash: str = "0c64eebbfb93b3ed69c3aba923ec8d6894a39902"
62
62
  placeholder_url = "https://raw.githubusercontent.com/fa0311/twitter-openapi/{hash}/src/config/placeholder.json"
63
- placeholder: ParamType
64
- user_agent: str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36"
63
+ header = "https://raw.githubusercontent.com/fa0311/latest-user-agent/refs/heads/main/header.json"
65
64
  access_token: str = "AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA"
65
+ twitter_url: str = "https://x.com/home"
66
+ additional_browser_headers = {}
67
+ additional_api_headers = {}
68
+
69
+ def get_header(self) -> tuple[dict[str, str], dict[str, str]]:
70
+ http = urllib3.PoolManager()
71
+ res = http.request("GET", self.header)
72
+ data = json.loads(res.data)
73
+ ignore = ["host", "connection"]
66
74
 
67
- api_key = {
68
- "Accept": "*/*",
69
- # "AcceptEncoding": "gzip, deflate, br",
70
- # "AcceptEncoding": "deflate, br",
71
- "AcceptLanguage": "en-US,en;q=0.9",
72
- "CacheControl": "no-cache",
73
- "Pragma": "no-cache",
74
- "SecChUa": '"Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116"',
75
- "SecChUaMobile": "?0",
76
- "SecChUaPlatform": '"Windows"',
77
- "SecFetchDest": "empty",
78
- "SecFetchMode": "cors",
79
- "SecFetchSite": "same-origin",
80
- "ClientLanguage": "en",
81
- "ActiveUser": "yes",
82
- }
83
-
84
- browser_headers = {
85
- "accept": "text/plain, */*; q=0.01",
86
- "accept-encoding": "gzip, deflate, br",
87
- "accept-language": "en-US,en;q=0.9",
88
- "cache-control": "no-cache",
89
- "pragma": "no-cache",
90
- "sec-ch-ua": '"Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116"',
91
- "sec-ch-ua-mobile": "?0",
92
- "sec-ch-ua-platform": '"Windows"',
93
- "sec-fetch-dest": "empty",
94
- "sec-fetch-mode": "cors",
95
- "sec-fetch-site": "same-site",
96
- "user-agent": user_agent,
97
- }
75
+ def getHader(name: str) -> dict[str, str]:
76
+ return {
77
+ key: value for key, value in data[name].items() if key not in ignore
78
+ }
79
+
80
+ return (
81
+ {
82
+ **getHader("chrome-fetch"),
83
+ "accept-encoding": "identity",
84
+ "pragma": "no-cache",
85
+ "referer": self.twitter_url,
86
+ "priority": "u=1, i",
87
+ "x-twitter-client-language": "en",
88
+ "x-twitter-active-user": "yes",
89
+ # 'x-twitter-auth-type': 'xxxx'
90
+ # 'x-csrf-token': 'xxxx',
91
+ # 'x-guest-token': 'xxxx',
92
+ "authorization": f"Bearer {self.access_token}",
93
+ **self.additional_api_headers,
94
+ },
95
+ {
96
+ **getHader("chrome"),
97
+ **self.additional_browser_headers,
98
+ },
99
+ )
100
+
101
+ def kebab_to_upper_camel(self, text: dict[str, Any]) -> dict[str, Any]:
102
+ res = {}
103
+ for key, value in text.items():
104
+ new_key = "".join(
105
+ [x.capitalize() for x in key.replace("x-twitter-", "").split("-")]
106
+ )
107
+ res[new_key] = value
108
+ return res
98
109
 
99
110
  def cookie_normalize(self, cookie: list[str]) -> dict[str, str]:
100
111
  return {
@@ -117,7 +128,7 @@ class TwitterOpenapiPython:
117
128
  self,
118
129
  cookies: dict[str, str],
119
130
  ) -> TwitterOpenapiPythonClient:
120
- api_key = self.api_key.copy()
131
+ api_key = self.kebab_to_upper_camel(self.get_header()[0])
121
132
 
122
133
  if cookies.get("ct0"):
123
134
  api_key.update({"AuthType": "OAuth2Session"})
@@ -132,27 +143,28 @@ class TwitterOpenapiPython:
132
143
  configuration=api_conf,
133
144
  cookie=self.cookie_to_str(cookies),
134
145
  )
135
- api_client.user_agent = self.user_agent
146
+ api_client.user_agent = api_key["UserAgent"]
136
147
  return self.get_twitter_openapi_python_client(api_client)
137
148
 
138
149
  def get_guest_client(self) -> TwitterOpenapiPythonClient:
139
150
  http = urllib3.PoolManager()
140
151
  session = {}
141
152
 
153
+ header = self.get_header()
154
+
142
155
  res_1 = http.request(
143
156
  "GET",
144
- "https://x.com",
157
+ self.twitter_url,
145
158
  redirect=False,
146
- headers=self.browser_headers.copy(),
159
+ headers=header[1],
147
160
  )
148
161
  cookie = res_1.headers._container["set-cookie"][1:]
149
162
  session.update(self.cookie_normalize(cookie))
150
163
  res_2 = http.request(
151
164
  "GET",
152
- "https://x.com",
165
+ self.twitter_url,
153
166
  redirect=False,
154
- headers=self.browser_headers.copy()
155
- | {"Cookie": self.cookie_to_str(session)},
167
+ headers=header[1],
156
168
  )
157
169
 
158
170
  find = re.findall(r'document.cookie="(.*?)";', res_2.data.decode())
@@ -161,15 +173,13 @@ class TwitterOpenapiPython:
161
173
  session.pop("ct0")
162
174
 
163
175
  if not session.get("gt"):
164
- activate_header = self.browser_headers.copy() | {
165
- "authorization": "Bearer {}".format(self.access_token),
166
- "x-twitter-active-user": "yes",
167
- "x-twitter-client-language": "en",
176
+ activate_header = header[0] | {
177
+ "cookie": self.cookie_to_str(session),
168
178
  }
169
179
  res_3 = http.request(
170
180
  "POST",
171
181
  "https://api.x.com/1.1/guest/activate.json",
172
- headers=activate_header | {"Cookie": self.cookie_to_str(session)},
182
+ headers=activate_header,
173
183
  )
174
184
  gt = json.loads(res_3.data.decode())["guest_token"]
175
185
  session.update({"gt": gt})
@@ -0,0 +1,93 @@
1
+ Metadata-Version: 2.1
2
+ Name: twitter-openapi-python
3
+ Version: 0.0.25
4
+ Summary: Twitter OpenAPI
5
+ Home-page: https://github.com/fa0311/twitter_openapi_python
6
+ Author: fa0311
7
+ Author-email: yuki@yuki0311.com
8
+ License: proprietary or AGPL-3.0-or-later
9
+ Keywords: OpenAPI,OpenAPI-Generator,Twitter OpenAPI
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ License-File: LICENSE.AGPL
13
+ Requires-Dist: twitter-openapi-python-generated ==0.0.21
14
+ Requires-Dist: pydantic >=2.6
15
+
16
+ # twitter_openapi_python
17
+
18
+ Twitter scraping with data validation by pydantic.
19
+
20
+ ![1691572735537](https://raw.githubusercontent.com/fa0311/twitter_openapi_python/refs/heads/master/twitter_openapi_python/docs/image/README/1691572735537.png)
21
+
22
+ ## Setup
23
+
24
+ ```shell
25
+ pip install twitter-openapi-python
26
+ ```
27
+
28
+ ## Usage
29
+
30
+ ```python
31
+ import json
32
+ import datetime
33
+
34
+ from pathlib import Path
35
+ from tweepy_authlib import CookieSessionUserHandler
36
+ from twitter_openapi_python import TwitterOpenapiPython
37
+
38
+ # login by tweepy_authlib
39
+ if Path("cookie.json").exists():
40
+ with open("cookie.json", "r") as f:
41
+ cookies_dict = json.load(f)
42
+ if isinstance(cookies_dict, list):
43
+ cookies_dict = {k["name"]: k["value"] for k in cookies_dict}
44
+ else:
45
+ auth_handler = CookieSessionUserHandler(
46
+ screen_name=input("screen_name: "),
47
+ password=input("password: "),
48
+ )
49
+ cookies_dict = auth_handler.get_cookies().get_dict()
50
+
51
+ # get client from cookies
52
+ 撫 = TwitterOpenapiPython().get_client_from_cookies(cookies=cookies_dict)
53
+
54
+ # tweet "Hello World!!" with current time
55
+ time = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ")
56
+ 撫.get_post_api().post_create_tweet(tweet_text=f"Hello World!!{time}")
57
+
58
+ # get user info
59
+ response = 撫.get_user_api().get_user_by_screen_name("elonmusk")
60
+ ```
61
+
62
+ ### Login
63
+
64
+ ```python
65
+ from twitter_openapi_python import TwitterOpenapiPython
66
+
67
+ # guest client
68
+ 撫 = TwitterOpenapiPython().get_guest_client()
69
+ tweet = 撫.get_default_api().get_tweet_result_by_rest_id("1349129669258448897")
70
+ assert tweet.data is not None
71
+ assert tweet.data.tweet.legacy is not None
72
+ print(tweet.data.tweet.legacy.full_text)
73
+ ```
74
+
75
+ ### Multiple OS
76
+
77
+ The Token can only be used on the same OS that issued the Token
78
+ In other words, if the sec-ch-ua-platform does not match, the Token cannot be used.
79
+ This library uses the Linux Chrome header by default.
80
+ To use Token issued by Windows, do the following.
81
+
82
+ ```typescript
83
+ TwitterOpenapiPython.additional_api_headers = {
84
+ "sec-ch-ua-platform": '"Windows"',
85
+ };
86
+ ```
87
+
88
+ ## License
89
+
90
+ This project is dual licensed. You can choose one of the following licenses:
91
+
92
+ - [Custom License](./LICENSE)
93
+ - [GNU Affero General Public License v3.0](./LICENSE.AGPL)
@@ -1,10 +1,10 @@
1
1
  twitter_openapi_python/__init__.py,sha256=stqYIfWDqM0yC93SQNp4-b2hSz-ONWR3QxOG5g2oREg,339
2
- twitter_openapi_python/client.py,sha256=vLJsD49AzN4nvrLlNmRQgdN4Fn8VBoT9eyq-vOwZzwU,6482
2
+ twitter_openapi_python/client.py,sha256=i0ynE5orodZtPCLGUYmalBD7lL4HMBBItypdUmlJYJg,6673
3
3
  twitter_openapi_python/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
4
  twitter_openapi_python/api/__init__.py,sha256=-2hoS75Fp0KvCIWKYQFpvAl0pcbFyt7Be3ood08P7n8,643
5
5
  twitter_openapi_python/api/default_api.py,sha256=PeHYaAw6xaUB9ZE3An5SKcEvW71JLTFSgyte80BBvX4,2751
6
6
  twitter_openapi_python/api/initial_state_api.py,sha256=N4yA3oXDbke7bH-XOuKQ4WVUm5sKbC2C3Dd3AvFINLY,2355
7
- twitter_openapi_python/api/post_api.py,sha256=W85UFViBoElS8T2-E9teRcC-9ngcSapoymZWoIb3qno,5944
7
+ twitter_openapi_python/api/post_api.py,sha256=9xvA0LrtcxWOVBkkVwvMS-zBcJFh1ZVUF_dm1zzZq5o,6826
8
8
  twitter_openapi_python/api/tweet_api.py,sha256=iZC3PlFS9SD3olb4BRrMYfyoCUf1UuD2XToXd33S-UM,10184
9
9
  twitter_openapi_python/api/user_api.py,sha256=oH5JBNemBSCyUFAbDSDbjRUOZN3bZMa_tI8PQ4C1wYk,2619
10
10
  twitter_openapi_python/api/user_list_api.py,sha256=7o1dqRrXzk0F6ywQ-dhyMR0eCzsGJ6HeUHYswPDx3hI,5748
@@ -19,9 +19,9 @@ twitter_openapi_python/models/response.py,sha256=ZuaX36mKRsVx5aiJhNw3CjrvVGVaGjM
19
19
  twitter_openapi_python/models/timeline.py,sha256=AoWfrJsonYImlweciaUSjFzmeciaX0zshi7d-FkT4LM,1392
20
20
  twitter_openapi_python/utils/__init__.py,sha256=QVT1eCClP9EVfcZ4QU96TVegfAUDEtJ-PVp3zv6qy6w,449
21
21
  twitter_openapi_python/utils/api.py,sha256=JTSXE1Wh3AiuOb_APTDTQMrR4HTkI9AihzrXkJGV2d8,10026
22
- twitter_openapi_python-0.0.23.dist-info/LICENSE,sha256=xthyYzrtSmRlBu2gnfuIxzsZeHrqtIZgZPL9UPrYiQU,1524
23
- twitter_openapi_python-0.0.23.dist-info/LICENSE.AGPL,sha256=Nv6u1ubULm-E2y6q2-pQPK8s2BzkOltLaVlPKQ3tkcs,35182
24
- twitter_openapi_python-0.0.23.dist-info/METADATA,sha256=NqIdS2rue_6LZmO73CSxjpeNebHwrIdQkXrQOixJOio,551
25
- twitter_openapi_python-0.0.23.dist-info/WHEEL,sha256=Xo9-1PvkuimrydujYJAjF7pCkriuXBpUPEjma1nZyJ0,92
26
- twitter_openapi_python-0.0.23.dist-info/top_level.txt,sha256=wKFCnW_S6aWD3nFPmd65SxZIviiqQ30LqHOLLpcnTdE,23
27
- twitter_openapi_python-0.0.23.dist-info/RECORD,,
22
+ twitter_openapi_python-0.0.25.dist-info/LICENSE,sha256=xthyYzrtSmRlBu2gnfuIxzsZeHrqtIZgZPL9UPrYiQU,1524
23
+ twitter_openapi_python-0.0.25.dist-info/LICENSE.AGPL,sha256=Nv6u1ubULm-E2y6q2-pQPK8s2BzkOltLaVlPKQ3tkcs,35182
24
+ twitter_openapi_python-0.0.25.dist-info/METADATA,sha256=DBxA123_stiz681r3-Ttb4UfWg5cYuP0SKy-KLjnHmc,2769
25
+ twitter_openapi_python-0.0.25.dist-info/WHEEL,sha256=Xo9-1PvkuimrydujYJAjF7pCkriuXBpUPEjma1nZyJ0,92
26
+ twitter_openapi_python-0.0.25.dist-info/top_level.txt,sha256=wKFCnW_S6aWD3nFPmd65SxZIviiqQ30LqHOLLpcnTdE,23
27
+ twitter_openapi_python-0.0.25.dist-info/RECORD,,
@@ -1,17 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: twitter-openapi-python
3
- Version: 0.0.23
4
- Summary: Twitter OpenAPI
5
- Home-page: https://github.com/fa0311/twitter_openapi_python
6
- Author: fa0311
7
- Author-email: yuki@yuki0311.com
8
- License: proprietary or AGPL-3.0-or-later
9
- Keywords: OpenAPI,OpenAPI-Generator,Twitter OpenAPI
10
- Description-Content-Type: text/markdown
11
- License-File: LICENSE
12
- License-File: LICENSE.AGPL
13
- Requires-Dist: twitter-openapi-python-generated ==0.0.20
14
- Requires-Dist: pydantic >=2.6
15
-
16
- Twitter scraping with data validation by pydantic.
17
-