import os import shutil from pathlib import Path import jinja2 import requests from mastodon import Mastodon instance = "https://social.lumbung.space" email = "" password = "" hashtags = [ "documentafifteen", "harvestedbyputra", "jalansesama", "lumbungdotspace", "majelisakakbar", "majelisakbar", "warungkopi", ] def login_mastodon_bot(): mastodon = Mastodon( access_token=os.environ.get("MASTODON_AUTH_TOKEN"), api_base_url = instance ) return mastodon def create_frontmatter(post_metadata): """ Parse post metadata and return it as HUGO frontmatter """ frontmatter = "" return frontmatter def download_media(post_directory, media_attachments): """ Download media attached to posts. N.b. currently only images See: https://mastodonpy.readthedocs.io/en/stable/#media-dicts """ for item in media_attachments: if item["type"] == "image": image = localize_media_url(item["url"]) # TODO check whether this needs to handle delete & redraft with different images if not os.path.exists(os.path.join(post_directory, image)): # download image response = requests.get(item["url"], stream=True) with open(os.path.join(post_directory, image), "wb") as img_file: shutil.copyfileobj(response.raw, img_file) print("Downloaded cover image", image) def create_post(post_directory, post_metadata): """ Create Hugo posts based on Toots/posts retuned in timeline. See: https://mastodonpy.readthedocs.io/en/stable/#toot-dicts """ if not os.path.exists(post_directory): os.mkdir(post_directory) template_dir = os.path.join(Path(__file__).parent.resolve(), "templates") env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir)) env.filters["localize_media_url"] = localize_media_url env.filters["filter_mastodon_urls"] = filter_mastodon_urls template = env.get_template("hashtag.md") with open(os.path.join(post_directory, "index.html"), "w") as f: post = template.render(post_metadata=post_metadata) f.write(post) download_media(post_directory, post_metadata["media_attachments"]) def localize_media_url(url): """ Returns the filename, used also as custom jinja filter """ return url.split("/")[-1] def filter_mastodon_urls(content): """ Filters out Mastodon generated URLS for tags e.g.