-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtoot.py
60 lines (48 loc) · 1.7 KB
/
toot.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
from constants import *
from secrets import *
import logging
import os
from mastodon import Mastodon
def authenticate():
"""
Authenticate to Mastodon.
Returns:
Authenticated Mastodon client.
"""
api = Mastodon(client_id="mastodon.secret")
api.log_in(MASTODON_EMAIL, MASTODON_PASSWORD, to_file="mastodon_user.secret")
return api
def send_toot(post_text, num_screenshots, entry_details):
"""
Create and send the toot for this entry.
Args:
post_text: Text to post as the toot contents.
num_screenshots: Number of screenshots to be attached.
entry_details: Object containing title, url, date, and array of entry text
Returns:
String containing ID of the toot that was just posted, or None if the post fails.
"""
logger = logging.getLogger(__name__)
try:
api = authenticate()
# Upload screenshots
media_ids = []
for ind in range(num_screenshots):
logger.debug(f"Uploading Mastodon image {ind}")
# Get alt text for this image
alt_text = entry_details["entry_text"][ind]
if ind == 0:
alt_text = entry_details["title"] + "\n" + alt_text
resp = api.media_post(
os.path.join(OUTPUT_DIR, FILENAME_ROOT + str(ind) + ".png"),
description=alt_text[:MASTODON_ALT_TEXT_LIMIT],
focus=(0, -1), # Set focus to center top of post
)
media_ids.append(resp.id)
# Send tweet
logger.info("Sending toot.")
toot = api.status_post(post_text, media_ids=media_ids)
return str(toot["id"])
except Exception as e:
print(e)
return None