Add Mastodon API functionality

This commit is contained in:
pancakes 2024-11-25 00:50:43 +10:00
parent 556ad7a468
commit 1c72557230
No known key found for this signature in database
GPG key ID: ED53D426432B861B

27
main.py
View file

@ -1,6 +1,7 @@
import feedparser import feedparser
import json import json
from markdownify import markdownify from markdownify import markdownify
from mastodon import Mastodon
import re import re
import sys import sys
import time import time
@ -28,6 +29,20 @@ def split_notes(text: str, limit: int) -> list[str]:
return notes return notes
def post_note(client: Mastodon, content: str, in_reply_to_id: str | None) -> str:
note = client.status_post(content, in_reply_to_id, visibility="unlisted")
print("Posted:", note["url"])
return note["id"]
def post_notes(client: Mastodon, notes: list[str]):
ids = []
for note in notes:
in_reply_to_id = ids[-1] if len(ids) != 0 else None
posted_note = post_note(client, note, in_reply_to_id)
ids.append(posted_note)
if __name__ == "__main__": if __name__ == "__main__":
if len(sys.argv) < 3: if len(sys.argv) < 3:
print("Usage:", sys.argv[0], "<account> <config>") print("Usage:", sys.argv[0], "<account> <config>")
@ -36,6 +51,12 @@ if __name__ == "__main__":
account = sys.argv[1] account = sys.argv[1]
config_path = sys.argv[2] config_path = sys.argv[2]
client = Mastodon(access_token=f"accounts/{account}.secret")
creds = client.account_verify_credentials()
print(f"Logged in: {creds["display_name"]} (@{creds["fqn"]})")
instance = client.instance()
char_limit = instance["configuration"]["statuses"]["max_characters"]
config_file = open(config_path, "r") config_file = open(config_path, "r")
config = json.load(config_file) config = json.load(config_file)
config_file.close() config_file.close()
@ -56,9 +77,9 @@ if __name__ == "__main__":
continue continue
notes = split_notes("[" + entry.title + "](" + entry.link + ")\n" + process_html( notes = split_notes("[" + entry.title + "](" + entry.link + ")\n" + process_html(
entry.content[0].value) + "\n\n" + entry.link, 500) entry.content[0].value) + "\n\n" + entry.link, char_limit)
[print(note) for note in notes]
print() post_notes(client, notes)
config[url] = time.mktime(rss.entries[-1].published_parsed) config[url] = time.mktime(rss.entries[-1].published_parsed)