Last active
September 25, 2023 15:13
-
-
Save EllieTheYeen/5bce66df1d4de2a6ac36e956a0d676d9 to your computer and use it in GitHub Desktop.
BSKY preview thing with link title
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
text = """ | |
https://docs.unity3d.com/2017.3/Documentation/Manual/class-AnimationClip.html wrgtiujerpgerhg | |
e | |
hgerth https://github.com/psf 3r54t | |
rthrthrth | |
""" | |
facets = [] | |
firstlink = None | |
for match in re.finditer( | |
rb'https?://[^\t\n\ "\'<>\\\^\{\|\}]*', text.encode("utf-8") | |
): | |
link = match.group().decode("utf-8") | |
if not firstlink: | |
firstlink = link | |
span = match.span() | |
facets.append( | |
{ | |
"$type": "app.bsky.richtext.facet", | |
"features": [ | |
{ | |
"$type": "app.bsky.richtext.facet#link", | |
"uri": link, | |
} | |
], | |
"index": { | |
"$type": "app.bsky.richtext.facet#byteSlice", | |
"byteStart": span[0], | |
"byteEnd": span[1], | |
}, | |
} | |
) | |
embed = None | |
if firstlink: # Only if no pics | |
try: | |
resp = httpx.get('https://cardyb.bsky.app/v1/extract', params=dict(url=firstlink), timeout=15) | |
resp.raise_for_status() | |
jdat = resp.json() | |
if jdat.get('error'): raise ValueError(jdat.get('error')) | |
embe = {"$type": "app.bsky.embed.external#external"} | |
embe["uri"] = firstlink | |
embe["description"] = jdat.get('description', 'No description') | |
embe["title"] = jdat.get('title', 'No title') | |
if jdat.get('image'): | |
ires = httpx.get(jdat.get('image'), timeout=15) | |
ires.raise_for_status() | |
upload = client.com.atproto.repo.upload_blob(ires.content, timeout=15) | |
embe["thumb"] = upload.blob | |
print(upload) | |
embed = {"$type": "app.bsky.embed.external", "external": embe} | |
except Exception: | |
traceback.print_exc() | |
print('Failed to get stuff from cardy b') | |
pprint.pprint(dict(facets=facets, embed=embed)) | |
print(json.dumps(dict(facets=facets, embed=embed), indent=1, default=str)) | |
post = client.com.atproto.repo.create_record( | |
atproto.models.ComAtprotoRepoCreateRecord.Data( | |
repo=client.me.did, | |
collection=atproto.models.ids.AppBskyFeedPost, | |
record=atproto.models.AppBskyFeedPost.Main( | |
facets=facets, | |
createdAt=datetime.datetime.now().isoformat(), | |
text=text, | |
reply=None, | |
embed=embed, | |
langs=["en"], | |
), | |
), | |
timeout=60, | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment