예제 #1
0
def send_email(subject: str, message: str) -> None:
    msg = EmailMessage()
    msg["Subject"] = subject
    msg["From"] = SENDER_EMAIL
    msg["To"] = RECEIVER_EMAIL
    msg.set_content(message)

    try:
        server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
        server.ehlo()
        authorization = server.login(SENDER_EMAIL, PASSWORD)
        send_message = server.send_message(msg)
        server.close()
        LOGGER.debug(
            f"Successfully sent email notification to {RECEIVER_EMAIL} from {SENDER_EMAIL}"
        )

    except smtplib.SMTPAuthenticationError as auth_error:
        LOGGER.exception(auth_error.smtp_error)
예제 #2
0
def grab_latest() -> List:
    """
    Grab the latest [LIMIT] posts from subreddits inside [SUBREDDITS]
    and filter them down to just a handful of relevant fields and remove
    posts that have already been parsed in the past.
    """
    # TODO: async requests, cuz fuggit
    posts = {}

    for sub in SUBREDDITS:
        url = _get_subreddit_url(sub)
        LOGGER.debug(f"Querying: {url}")
        response = get(url, headers={"User-Agent": USER_AGENT})

        try:
            new_posts = parse_json_response(response.json())

        except Exception as e:
            LOGGER.exception(
                f"Request to {url} failed with code {response.status_code}: {response.reason}"
            )

        # We got some posts we haven't seen before. Let's filter through them
        if new_posts:
            posts[sub] = filter_results(new_posts, sub)

    subject = format_subject(posts)
    message = format_response(posts)
    if not message:
        LOGGER_RESULTS.info("No new posts.")
        return

    LOGGER_RESULTS.info(f"\n{message}")

    if EMAIL_NOTIFICATIONS:
        send_email(subject, message)