#!/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 RSS_FEED = feedparser.parse(FEED_URL) RSS_ENTRY = RSS_FEED.entries[0] # Function to build the toot, send it and update the 'last_toot.txt' and 'last_post.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() # Output a response print("New toot sent from the foo-bar RSS feed!") # Find the latest RSS entry latest_entry = RSS_ENTRY.id # Find the latest published date published = RSS_ENTRY.published # Find the 'last_toot' sent with open(Path(FILE_PATH) / "last_toot.txt") as last_toot: last_toot = last_toot.read() # If 'latest_entry' does not equal 'last_toot' then send a new toot based on 'latest_entry' if latest_entry != last_toot: send_toot() elif latest_entry == last_toot: # Output a response print("Nothing new to add from the foo-bar RSS feed!")