1
Create Bluesky Post
One script reply has been approved by the moderators Verified

Posts to Bluesky.

If shorten_urls is set to true, the script shortens and adds a hyperlink faucet to all urls.

Created by gabrielius.m896 2 days ago Viewed 104 times
0
Submitted by gabrielius.m896 Python3
Verified 2 days ago
1
# import wmill
2
from typing import TypedDict
3
from atproto import Client, client_utils
4

5
class bluesky(TypedDict):
6
    username: str
7
    password: str
8

9
def main(creds: bluesky, text: str, shorten_urls: bool = True):
10
    client = Client()
11
    client.login(creds["username"], creds["password"])
12

13
    if shorten_urls:
14
        builder = builder_shorten_urls(text)
15
        response = client.send_post(builder)
16
    else:
17
        response = client.send_post(text=text)
18

19
    return response
20

21
def builder_shorten_urls(buffer):
22
    import re
23

24
    builder = client_utils.TextBuilder()
25

26
    while True:
27
        match = re.search(r"(?P<url>https?://[^\s]+)", buffer)
28
        if not match:
29
            break
30
        
31
        builder.text(buffer[:match.start()])
32
        buffer = buffer[match.end():]
33

34
        url = match.group("url")
35
        builder.link(shorten_url(url, 9), url)
36
    
37
    builder.text(buffer)
38

39
    return builder
40

41
def shorten_url(string_url, max_path_query_length):
42
    from urllib.parse import urlparse
43

44
    url = urlparse(string_url)
45
    netloc = url.netloc
46
    path_query = url.path
47
    if url.query:
48
        path_query += "?" + url.query
49

50
    # Keep the first "/" before the "...".
51
    if len(path_query) > 0:
52
        netloc += path_query[0]
53
        path_query = path_query[1:]
54

55
    # path_query is short enough.
56
    if len(path_query) <= max_path_query_length:
57
        return f"{netloc}{path_query}"
58

59
    # Shorten the path_query with a "...".
60
    path_query_length = max_path_query_length - 3
61
    if path_query_length > 0:
62
        return f"{netloc}...{path_query[-path_query_length:]}"
63

64
    # path_query too small to be added after the "...".
65
    return f"{netloc}..."
66