-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathatproto_client.py
343 lines (279 loc) · 10.3 KB
/
atproto_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
import datetime
import requests
import json
from .models.embed.external.view import View
from .models.feed.feed_view_post import FeedViewPost
from .models.feed.post_view import PostView
from .models.feed.recored import Record
from .models.feed.reply_ref import ReplyRef
from .models.richtext.facet.byte_slice import ByteSlice
from .models.richtext.facet.facet import Facet
from .models.richtext.facet.link import Link
class AtprotoClient:
def __init__(self, identifier, password):
self.identifier = identifier
self.password = password
self.base_url = "https://bsky.social/xrpc"
self.access_jwt, self.did = self.create_session()
self.headers = {"Authorization": f"Bearer {self.access_jwt}"}
def _request(
self,
endpoint,
method,
headers: dict | None = None,
params=None,
data=None,
) -> requests.Response:
url = f"{self.base_url}/{endpoint}"
print(f"url: {url}")
print(f"method: {method}")
print(f"params: {params}")
if headers is None:
headers = self.headers
response = requests.request(
method=method, url=url, params=params, data=data, headers=headers
)
if response.status_code >= 400:
print("【AtprotoClient】投稿に失敗しました。")
print(f"status_code: {response.status_code}")
raise Exception(f"atproto_api: {response.text}\n{data}")
return response
def create_session(self) -> list[str]:
endpoint = "com.atproto.server.createSession"
method = "POST"
data = {"identifier": self.identifier, "password": self.password}
headers = {"Content-Type": "application/json; charset=UTF-8"}
response = self._request(
endpoint=endpoint, method=method, data=json.dumps(data), headers=headers
)
print(response.text)
access_jwt = response.json()["accessJwt"]
did = response.json()["did"]
return [access_jwt, did]
def get_author_feed(self) -> list[FeedViewPost]:
endpoint = "app.bsky.feed.getAuthorFeed"
method = "GET"
params = {"actor": self.identifier}
headers = {"Authorization": f"Bearer {self.access_jwt}"}
response = self._request(
endpoint=endpoint, method=method, params=params, headers=headers
)
response_json = response.json()
print(response_json)
feed_list = []
for feed in response_json["feed"]:
text = feed["post"]["record"]["text"]
created_at = feed["post"]["record"]["createdAt"]
cid = feed["post"]["cid"]
parent_cid = (
feed["post"]["record"]["reply"]["parent"]["cid"]
if "reply" in feed["post"]["record"]
else ""
)
"""
feedを構築
"""
# facetsを構築
facets = []
facet_dict_list = (
feed["post"]["record"]["facets"]
if "facets" in feed["post"]["record"]
else []
)
for facet_dict in facet_dict_list:
# indexを構築
index = ByteSlice(
byteStart=facet_dict["index"]["byteStart"],
byteEnd=facet_dict["index"]["byteEnd"],
)
# featuresを構築
features = []
for feature_dict in facet_dict["features"]:
feature = None
print(f'type: {feature_dict["$type"]}')
if feature_dict["$type"] == "app.bsky.richtext.facet#link":
feature = Link(
uri=feature_dict["uri"],
)
if feature is not None:
features.append(feature)
facet = Facet(index=index, features=features)
facets.append(facet)
# recordを構築
record = Record(text=text, created_at=created_at, facets=facets)
# embedを構築
embed = None
post_embed_type = (
feed["post"]["embed"]["$type"] if "embed" in feed["post"] else None
)
if post_embed_type is not None:
post_embed_type_key = post_embed_type.split(".")[-1].split("#")[0]
embed_dict = feed["post"]["embed"][post_embed_type_key]
if post_embed_type == "app.bsky.embed.external#view":
embed = View(
uri=embed_dict["uri"],
title=embed_dict["title"],
description=embed_dict["description"],
thumb=embed_dict["thumb"],
)
# postを構築
post = PostView(cid=cid, record=record, embed=embed)
feed_list.append(
FeedViewPost(
post=post,
reply=ReplyRef(
parent=PostView(
cid=parent_cid,
),
),
)
)
# if "embed" in feed["post"]:
# print(feed["post"]["embed"]["images"][0]["fullsize"])
return feed_list
def generate_post_from_text(
self, text: str, self_labels: list[str] | None = None
) -> dict:
"""_summary_
Args:
text (str): _description_
self_labels (ex. "porn")
Returns:
dict: _description_
"""
post = {
"$type": "app.bsky.feed.post",
"text": text,
}
# labelsを構築
if self_labels is not None:
label_values = []
for label in self_labels:
label_values.append({"val": label})
labels = {
"$type": "com.atproto.label.defs#selfLabels",
"values": label_values,
}
post["labels"] = labels
# URLを元の状態に戻す
origin_text = text
# origin_textからURLを抽出
url_list = []
for word in origin_text.split("\n"):
if word.startswith("http"):
url_list.append(word)
# textをbyte文字列に変換
byte_text = origin_text.encode("utf-8")
# facetsを構築
facets = []
for url in url_list:
# indexを構築
index = {
"byteStart": byte_text.find(url.encode("utf-8")),
"byteEnd": byte_text.find(url.encode("utf-8")) + len(url),
}
# featuresを構築
features = []
feature = {
"$type": "app.bsky.richtext.facet#link",
"uri": url,
}
features.append(feature)
facet = {
"index": index,
"features": features,
}
facets.append(facet)
post["facets"] = facets
created_at = (
datetime.datetime.now(tz=datetime.timezone.utc)
.replace(tzinfo=None)
.isoformat(timespec="milliseconds")
+ "Z"
)
post["createdAt"] = created_at
return post
def upload_image(self, image_url: str) -> dict:
IMAGE_MIMETYPE = "image/png"
# url to media binary data
response = requests.get(image_url)
img_bytes = response.content
# this size limit is specified in the app.bsky.embed.images lexicon
if len(img_bytes) > 1000000:
raise Exception(
f"image file size too large. 1000000 bytes maximum, got: {len(img_bytes)}"
)
resp = requests.post(
"https://bsky.social/xrpc/com.atproto.repo.uploadBlob",
headers={
"Content-Type": IMAGE_MIMETYPE,
"Authorization": "Bearer " + self.access_jwt,
},
data=img_bytes,
)
resp.raise_for_status()
blob = resp.json()["blob"]
return blob
def create_record(
self,
text: str,
image_url: str | None = None,
self_labels: list[str] | None = None,
):
endpoint = "com.atproto.repo.createRecord"
method = "POST"
post = self.generate_post_from_text(text=text, self_labels=self_labels)
if image_url is not None:
blob = self.upload_image(image_url=image_url)
post["embed"] = {
"$type": "app.bsky.embed.images",
"images": [
{
"alt": "image",
"image": blob,
}
],
}
data = {
"repo": self.did,
"collection": "app.bsky.feed.post",
"record": post,
}
headers = {
"Authorization": f"Bearer {self.access_jwt}",
"Content-Type": "application/json; charset=UTF-8",
}
response = self._request(
endpoint=endpoint, method=method, data=json.dumps(data), headers=headers
)
print(response.text)
return response.json()
def get_profile(self, actor: str) -> dict:
"""
Ref: https://www.docs.bsky.app/docs/api/app-bsky-actor-get-profile
"""
endpoint = "app.bsky.actor.getProfile"
method = "GET"
params = {"actor": actor}
headers = {"Authorization": f"Bearer {self.access_jwt}"}
response = self._request(
endpoint=endpoint, method=method, params=params, headers=headers
)
return response.json()
def search_posts(self, q: str, limit: int = 25) -> dict:
"""
Args:
q (str): Search query string; syntax, phrase, boolean, and faceting is unspecified, but Lucene query syntax is recommended.
limit (int): 1 to 100
Returns:
_type_: _description_
Ref: https://www.docs.bsky.app/docs/api/app-bsky-feed-search-posts
"""
endpoint = "app.bsky.feed.searchPosts"
method = "GET"
params = {
"q": q,
"limit": limit,
}
response = self._request(endpoint=endpoint, method=method, params=params)
return response.json()