#!/usr/bin/env python # -*- coding: utf-8 -*- # A bot that takes an RSS feed and posts to Mastodon # Parses the latest entry in the RSS feed and if it doesn't match the last toot, sends the latest entry from secrets import * from pathlib import Path import requests import feedparser import time RSS_FEED = feedparser.parse(FEED_URL) # Function to build the toot, send it and update the 'last_toot.txt' file def send_toot(): # Build the authorisation header auth = { "Authorization" : f"Bearer {MASTODON_TOKEN}" } # Build the text part of the toot from the chosen 'RSS_ENTRY' toot_str = '' toot_str += f"{RSS_ENTRY['title']}\n\n" toot_str += f"{RSS_ENTRY['description']}\n" toot_str += f"\n\n{RSS_ENTRY['link']}\n\n" toot_str += f"\n\nThis is an automated post from the #foo-bar RSS feed dated {RSS_ENTRY['published']}\n\n" toot_str += f"\n\n#foo #bar #foo-bar\n\n" # Build the payload payload = { "status": toot_str } # Send toot (to 'MASTODON_STATUS') requests.post(MASTODON_STATUS, headers=auth, data=payload) # Update the 'last_toot.txt' file with 'latest_entry' last_toot = open(Path(FILE_PATH) / "last_toot.txt","w") last_toot.write(latest_entry) last_toot.close() # Update the 'last_post.txt' file with 'published' date last_post = open(Path(FILE_PATH) / "last_post.txt","w") last_post.write(published) last_post.close() # How many RSS entries are there (-1 as the indexing starts at 0) count = len(feedparser.parse(FEED_URL)['entries'])-1 # Loop through all of the RSS entries (until it is less than 0, where the indexing started) print("There are ", count+1, " RSS entries to toot") while count != -1: latest_entry = RSS_FEED.entries[count].id # Find the published date published = RSS_FEED.entries[count].published RSS_ENTRY = RSS_FEED.entries[count] print("Tooting - " + RSS_FEED.entries[count].title + " ", count, " toots to go") send_toot() count = count -1 time.sleep(180) # Output a response print("All done!")