# Start

import sys

import io

import praw

from praw. models import MoreComments

import sqlite3

import time

from datetime import datetime

from dateutil. relativedelta import relativedelta

from dateutil import tz

def get_time_difference ( dt ) :

to_zone = tz. gettz ( 'US/Pacific' )

start = datetime . now ( to_zone )

ends = datetime . fromtimestamp ( dt ) . replace ( tzinfo = to_zone )

diff = relativedelta ( start , ends )

return "%d days %d hours %d minutes" % ( diff. days , diff. hours , diff. minutes )

def local_time_as_text ( dt ) :

to_zone = tz. gettz ( 'US/Pacific' )

return datetime . fromtimestamp ( dt ) . replace ( tzinfo = to_zone ) . strftime ( "%m/%d/%Y %I:%M:%S %p" )

subreddits = [ ]

subreddits. append ( [ "politics" , "hot" , 50 ] )

# Subreddit name, post sorting and minimum score for the submission within the subreddit before it appears.

#

sq = "c: \\ code \\ python \\ sq_red.sqlite"

# SQLITE database only contains a 'posts' table - CREATE TABLE posts (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, subreddit text, post_id text, added_on integer)

conn = sqlite3. connect ( sq )

c = conn. cursor ( )

#

reddit = praw. Reddit ( client_id = '' , client_secret = '' , user_agent = 'testscript by /u/blessedarethegeek' , username = '' , password = '' )

file = open ( "c: \\ temp \\ " + datetime . today ( ) . strftime ( '%Y-%m-%d %H %M %S' ) + " red.html" , "w" , encoding = "utf-8" )

file . write ( "<html>

" )

file . write ( " <head>" )

file . write ( '<meta charset="utf-8"/>' )

file . write ( '<title>Summary</title>' )

file . write ( '<style type="text/css">.post_header p {margin-top:-20px;} .subreddit {border:1px solid black;background-color:#fdc4c4;} .sub_cell {text-align:center;border:1px solid black;width:auto;} .post_header {text-align:center; border:1px solid black;width:auto;background-color:#d4d4d4;} .post_image {border:1px solid black;white-space:nowrap;width:150px;text-align:center;} .post {text-align:center; border:1px solid black;width:auto;} .post_info {text-align:center; border:1px solid black;width:auto;} .post_body {text-align:left; border:1px solid black;word-break:break-all;width:auto;} .comment_info {border:1px solid black;white-space:nowrap;width:150px;text-align:center;} .comment_body {border:1px solid black;white-space:normal;word-break:break-all;width:auto;padding-left:10px;} .comment_reply {border:1px solid black;white-space:normal;word-break:break-all;width:auto;padding-left:30px;} </style>' )

# Horrible CSS here

file . write ( '<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>' )

file . write ( '<script src="https://cdnjs.cloudflare.com/ajax/libs/mousetrap/1.4.6/mousetrap.min.js"></script>' )

file . write ( '<script language="javascript">' )

file . write ( "function nextElement(inputClass) {$(inputClass).each(function(index) {if ($(this).position().top > $(document).scrollTop() + 5) {$(this).get(0).scrollIntoView(); return false;}});}" ) ;

file . write ( "function prevElement(inputClass) {$(inputClass).each(function(index) {if (parseInt($(this).position().top) >= parseInt($(document).scrollTop())) {holdElement.get(0).scrollIntoView(); return false;} else {holdElement = $(this);}});}" ) ;

file . write ( "Mousetrap.bind('p', function() { nextElement('.subreddit'); });" ) ;

file . write ( "Mousetrap.bind('o', function() { prevElement('.subreddit'); });" ) ;

file . write ( "Mousetrap.bind('m', function() { nextElement('.post'); });" ) ;

file . write ( "Mousetrap.bind('n', function() { prevElement('.post'); });" ) ;

# Mousetrap for handling forward/previous subreddit/post keyboard shortcuts

file . write ( '</script>' )

file . write ( " </head>

" )

file . write ( " <body>

" )

file . write ( " <table style='border-collapse: collapse;table-layout:fixed;'>

" )

for sub_detail in subreddits:

totalSubmissions = 50

subs = sub_detail [ 0 ]

sub_sort = sub_detail [ 1 ]

sub_minimum = sub_detail [ 2 ]

file . write ( " <tr class='subreddit'><td colspan=2 class='sub_cell'><h2>" +subs+ "</h2></td></tr>

" )

if sub_sort == "hot" :

checkSort = reddit. subreddit ( subs ) . hot ( limit = totalSubmissions )

elif sub_sort == "new" :

checkSort = reddit. subreddit ( subs ) . new ( limit = totalSubmissions )

else :

checkSort = reddit. subreddit ( subs ) . rising ( limit = totalSubmissions )

for submission in checkSort:

#

cursor = c. execute ( "SELECT id, subreddit, post_id, added_on FROM posts WHERE post_id = '" +submission. id + "';" )

rows = cursor. fetchall ( )

if len ( rows ) != 0 :

print ( "In Database" )

continue

if submission. score < sub_minimum:

continue

if submission. over_18 == True :

continue

if submission. thumbnail == None or submission. thumbnail == "self" :

adder = " "

else :

adder = "<img src='" +submission. thumbnail + "'/>"

file . write ( " <tr class='post'><td class='post_image'>" +adder+ "</td><td class='post_header' colspan=2><h3><p>[ " + str ( submission. score ) + " ] " +submission. title + "</p></h3><p>" +local_time_as_text ( submission. created_utc ) + " ( " +get_time_difference ( submission. created_utc ) + " )</p><hr>Posted By: <a href='https://www.reddit.com/u/" +submission. author . name + "'>" +submission. author . name + "</a> || <a href='https://www.reddit.com/r/" +submission. subreddit . display_name + "'>[/r/" +submission. subreddit . display_name + "]</a> || " + str ( submission. score ) + " Score || " + str ( submission. num_comments ) + " Comments || <a href='https://www.reddit.com" +submission. permalink + "'>[Main Post URL]</a> || <a href='" +submission. url + "'>[Article URL]</a></td></tr>

" )

if submission. selftext_html == None :

adder = submission. selftext

else :

adder = submission. selftext_html

if adder. strip ( ) != "" :

file . write ( " <tr><td class='post_body' colspan=2>" +adder+ "</td></tr>

" )

#

c. execute ( "INSERT INTO posts (subreddit, post_id, added_on) VALUES ('" +submission. subreddit . display_name + "', '" +submission. id + "', " + str ( time . time ( ) ) + ");" )

conn. commit ( )

#

submission. comment_sort = 'best'

submission. comment_limit = 10

for top_level_comment in submission. comments :

if isinstance ( top_level_comment , MoreComments ) :

continue

if "As a reminder, this subreddit [is for civil" in top_level_comment. body :

continue

if top_level_comment. is_submitter == True :

adder = " <b>[Author]</b> "

else :

adder = ""

if top_level_comment. author is None :

authorName = "no-author"

else :

authorName = top_level_comment. author . name

file . write ( " <tr><td class='comment_info'><a href='https://www.reddit.com" +top_level_comment. permalink + "'>[comment permalink]</a><br/><a href='https://www.reddit.com/u/" +authorName+ "'>" +authorName+ "</a>" +adder+ " (" + str ( top_level_comment. score ) + ")<br/>" +local_time_as_text ( top_level_comment. created_utc ) + "<br/>" +get_time_difference ( top_level_comment. created_utc ) + "</td><td class='comment_body'>" +top_level_comment. body_html + "</td></tr>

" )

top_level_comment. reply_sort = 'best'

top_level_comment. reply_limit = 3

top_level_comment. refresh ( )

sub_comments = top_level_comment. replies

for sub_comment in sub_comments:

if isinstance ( sub_comment , MoreComments ) :

continue

if sub_comment. is_submitter == True :

adder = " <b>[Author]</b> "

else :

adder = ""

if sub_comment. score == 0 :

check_score = "0"

elif sub_comment. score > 1 :

check_score = "+" + str ( sub_comment. score )

else :

check_score = "-" + str ( sub_comment. score )

if sub_comment. author is None :

authorName = "no-author"

else :

authorName = sub_comment. author . name

file . write ( " <tr><td> </td><td class='comment_reply'><a href='https://www.reddit.com" +sub_comment. permalink + "'>[comment permalink]</a> <a href='https://www.reddit.com/u/" +authorName+ "'>" +authorName+ "</a>" +adder+ " (" +check_score+ ") " +local_time_as_text ( sub_comment. created_utc ) + " " +get_time_difference ( sub_comment. created_utc ) + "<hr>" +sub_comment. body_html + "</td></tr>

" )

#

file . write ( " </table>

" )

file . write ( " </body>

" )

file . write ( "</html>

" )

file . close ( )

#

conn. commit ( )

conn. close ( )