reddit-mastodon-crossposter/script.py

71 lines
2.7 KiB
Python
Raw Normal View History

2022-12-09 00:04:01 +01:00
"""Main script to toot a new post"""
import praw, wget
from dotenv import load_dotenv
from mastodon import Mastodon
from os import getenv, remove
from os.path import getsize
# load .env
load_dotenv()
# initialize reddit
reddit = praw.Reddit(
client_id = getenv("REDDIT_CLIENT_ID"),
client_secret = getenv("REDDIT_CLIENT_SECRET"),
redirect_uri = "http://localhost:8080", # does not matter what is here
user_agent = getenv("REDDIT_USER_AGENT")
)
# initialize mastodon
mastodon = Mastodon(
access_token = getenv("MASTODON_USER_SECRET"),
api_base_url = getenv("MASTODON_URL")
)
# get recent posts to check for duplicates
last_posts = mastodon.account_statuses(getenv("MASTODON_USER_ID"), limit=15)
for submission in reddit.subreddit(str(getenv("REDDIT_SUBREDDIT"))).top(time_filter="day", limit=10):
2022-12-09 00:04:01 +01:00
# skip post if it is a stickied post
if (submission.stickied):
continue
# check if the post has been posted before
already_posted = False
for posted_submission in last_posts:
if submission.permalink in posted_submission["content"]:
already_posted = True
break
if already_posted:
continue
# check if text only
if submission.is_self:
status_text = submission.title + "\n\ngeposted von u/" + submission.author.name + "\n" + submission.permalink + "\n\n" + submission.selftext
mastodon.status_post(status_text, visibility="unlisted")
# check if reddit video
elif "v.redd.it" in submission.url:
url = submission.media["reddit_video"]["fallback_url"]
url = url.split("?")[0]
filename = wget.download(url)
print()
# check if video file is small enough for the server (10MB)
if getsize(filename) < 10*1000000:
media = mastodon.media_post(filename)
status_text = submission.title + "\n\ngeposted von u/" + submission.author.name + "\nhttps://reddit.com" + submission.permalink
mastodon.status_post(status_text, media_ids=media["id"], visibility="unlisted")
else:
status_text = submission.title + "\n\nGeposteter Videolink: " + url + "\n\ngeposted von u/" + submission.author.name + "\n" + submission.permalink + "\n\n" + submission.selftext
mastodon.status_post(status_text, visibility="unlisted")
remove(filename)
else:
filename = wget.download(submission.url)
print()
media = mastodon.media_post(filename)
status_text = submission.title + "\n\ngeposted von u/" + submission.author.name + "\nhttps://reddit.com" + submission.permalink
mastodon.status_post(status_text, media_ids=media["id"], visibility="unlisted")
remove(filename)
break