update_readme.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import feedparser
  2. from datetime import datetime
  3. # Fetch the RSS feed
  4. feed_url = "https://blog.joinmastodon.org/index.xml"
  5. feed = feedparser.parse(feed_url)
  6. # Function to format the publication date
  7. def format_date(published):
  8. try:
  9. # Parse the published date from the entry
  10. parsed_date = datetime(*published[:6])
  11. return parsed_date.strftime("%Y-%m-%d")
  12. except Exception as e:
  13. # Return an empty string if date parsing fails
  14. return ""
  15. # Extract the latest 3 posts
  16. max_posts = 3
  17. latest_posts = []
  18. for entry in feed.entries[:max_posts]:
  19. title = entry.title
  20. link = entry.link
  21. pub_date = format_date(entry.published_parsed) # Format the publication date
  22. # Add the post with the title, publication date, and optionally the summary
  23. latest_posts.append(f"- :newspaper: [{title}]({link}) - *{pub_date}*")
  24. with open("profile/README.md", "r") as readme_file:
  25. readme_content = readme_file.readlines()
  26. start_marker = "<!-- BLOG-POST-LIST:START -->\n"
  27. end_marker = "<!-- BLOG-POST-LIST:END -->\n"
  28. # Ensure the markers are present in the README.md
  29. if start_marker not in readme_content or end_marker not in readme_content:
  30. print("Markers not found in README.md. Please ensure you have the markers.")
  31. exit(1)
  32. # Get the content before and after the markers
  33. start_index = readme_content.index(start_marker) + 1
  34. end_index = readme_content.index(end_marker)
  35. # Create the new content between the markers
  36. new_readme_content = (
  37. readme_content[:start_index]
  38. + [f"{post}\n" for post in latest_posts]
  39. + readme_content[end_index:]
  40. )
  41. # Write the new content back to README.md
  42. with open("profile/README.md", "w") as readme_file:
  43. readme_file.writelines(new_readme_content)
  44. print("profile/README.md has been updated with the latest blog posts.")