Created
October 9, 2016 15:51
-
-
Save bsquidwrd/6a396715aeb20fa93c7723e8f6f66892 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3.4 | |
# Project: reddit_notifier | |
# File Name: reddit_notifier | |
# Created by: bsquidwrd | |
# Created on: 9/6/2015 | |
import json | |
import sys | |
import time | |
import traceback | |
from datetime import datetime | |
import os | |
import praw | |
import requests | |
from requests import exceptions as req_exc | |
# Global functions and variables | |
settings = __import__('settings') | |
pushover = settings.PushoverInformation() | |
notificationURL = pushover.get_url() | |
def send_notification(message=None, title=None, url=None, url_title=None, priority=0, urgent=False, urgent_retry=60, urgent_expire=86400): | |
# Priorities | |
# -2 Lowest Priority = no sound whatsoever but badge number increases | |
# -1 Lower Priority = no sound but shows popup | |
# 0 Normal = sound and popup | |
# 1 High Priority = Bypasses quiet hours and shows red notification | |
# 2 Urgent = Same as High but repeated until acknowledged by the user | |
# If urgent, default is to retry every 60 seconds until acknowledged | |
# Also sets expiration time 24 hours from when sent | |
my_data = { | |
'token': pushover.get_token(), | |
'user': pushover.get_user(), | |
'title': title, | |
'message': message, | |
'priority': priority, | |
} | |
if url: | |
my_data['url'] = url | |
if url_title: | |
my_data['url_title'] = url_title | |
else: | |
my_data['url_title'] = url | |
if urgent: | |
my_data['retry'] = urgent_retry | |
my_data['expire'] = urgent_expire | |
response = requests.post(notificationURL, data=my_data) | |
json_data = json.loads(response.text) | |
if json_data['status'] == 1: | |
return { | |
'status': True, | |
'data': json_data, | |
} | |
else: | |
return { | |
'status': False, | |
'data': json_data, | |
} | |
wait_time = settings.wait_time | |
redditCredentials = settings.RedditCredentials() | |
user_agent = "TurdNotifier 1.0 by /u/turdzip" | |
reddit = praw.Reddit(user_agent = user_agent) | |
if ((pushover.get_token() is False) or (pushover.get_user() is False)): | |
print('Pushover information is not set correctly') | |
sys.exit() | |
if ((redditCredentials.username is False) or (redditCredentials.password is False)): | |
print('reddit information is not set correctly') | |
error_title = "reddit info not set" | |
error_msg = "Please correct this issue before continuing" | |
error_notification = send_notification(title=error_title, message=error_msg, priority=1) | |
while error_notification['status'] is False: | |
error_notification = send_notification(title=error_title, message=error_msg, priority=1) | |
time.sleep(5) | |
sys.exit() | |
reddit.login(username=redditCredentials.username, password=redditCredentials.password, disable_warning=True) | |
# Blank list to store id's in for testing right now | |
# Hopefully this will move to some sort of database | |
read_messages = [] | |
def read_pm(): | |
try: | |
for message in reddit.get_unread(unset_has_mail=False, update_user=False): | |
prawobject = isinstance(message, praw.objects.Message) | |
if prawobject and (message.id not in read_messages): | |
message_content = ('From: %s\nTitle: %s\nMessage: %s\n' % (message.author, message.subject, message.body)) | |
message_url = "https://www.reddit.com/message/messages/%s" % (message.id) | |
url_title = "View message from %s" % (message.author) | |
notification = send_notification(title='New message on reddit', message=message_content, url=message_url, url_title=url_title) | |
if notification['status']: | |
read_messages.append(message.id) | |
print('Got message %s, sent notification' % (message.id)) | |
else: | |
print(notification['data']) | |
print('Got error for message') | |
timeString = datetime.now().strftime('%Y-%m-%d %H-%M-%S') | |
print("Finished getting messages for %s" % (timeString)) | |
except praw.errors.HTTPException as err: | |
print("Received error from reddit...") | |
print(traceback.format_exc()) | |
except req_exc.RequestException as err: | |
print("Could not contact reddit, are the servers down?") | |
except Exception as err: | |
error_title = ("Error while running %s" % (os.path.basename(__file__))) | |
error_msg = ('Error:\n%s' % (traceback.format_exc())) | |
error_notification = send_notification(title=error_title, message=error_msg) | |
print(traceback.format_exc()) | |
if error_notification['status'] is False: | |
sys.exit() | |
if __name__ == "__main__": | |
# Unless this is being run on a remote server, | |
# I don't need confirmation that it started | |
send_notification(title=("%s has started" % os.path.basename(__file__)), message=("Start time is %s" % (datetime.now()))) | |
while True: | |
timeString = datetime.now().strftime('%Y-%m-%d %H-%M-%S') | |
print('Fetching messages at %s' % (timeString)) | |
try: | |
read_pm() | |
except: | |
print('Error connecting to reddit, is it down? %s', (timeString)) | |
print('-----') | |
time.sleep(float(wait_time)) | |
send_notification(title=("%s has ended" % os.path.basename(__file__)), message=("End time is %s" % (datetime.now()))) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Project: reddit_notifier | |
# File Name: settings.py | |
# Created by: bsquidwrd | |
# Created on: 9/6/2015 | |
import os | |
wait_time = "300" # In seconds, ex. 300 seconds is 5 minutes | |
class RedditCredentials(): | |
# Used to store login information for reddit | |
def __init__(self): | |
self.username = os.environ.get('REDDIT_USER', False) | |
self.password = os.environ.get('REDDIT_PASS', False) | |
def get_username(self): | |
return self.username | |
def get_password(self): | |
return self.password | |
class PushoverInformation(): | |
# Used to store connection information for Pushover.net | |
def __init__(self): | |
self.url = 'https://api.pushover.net/1/messages.json' | |
self.token = os.environ.get('PUSHOVER_TOKEN', False) | |
self.user = os.environ.get('PUSHOVER_USER', False) | |
def get_url(self): | |
return self.url | |
def get_token(self): | |
return self.token | |
def get_user(self): | |
return self.user |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment