<file_sep>import argparse
import logging
import sqlite3
from collections import Counter

from argParseLog import addLoggingArgs, handleLoggingArgs

log = logging.getLogger(__name__)

if __name__ == '__main__':
    ap = argparse.ArgumentParser()
    ap.add_argument('-d', '--database', help='The database to read.', default='boardgames.db')
    ap.add_argument('-u', '--unit', help='List post count by time ago given.',
                    choices=['second', 'minute', 'hour', 'day', 'week', 'month', 'year'])
    ap.add_argument('-v', '--value', help='How many of the unit to have. i.e. -v 1 -u \'day\''
                    ' is one day ago.', type=int)
    ap.add_argument('-c', '--count', help='Number of results to return.', type=int)
    addLoggingArgs(ap)
    args = ap.parse_args()
    handleLoggingArgs(args)

    db = sqlite3.connect(args.database)

    # select count(*) from comments where datetime(timestamp, 'unixepoch') > datetime('now', '-1 hour');
    then = db.execute("SELECT datetime('now', '-{} {}')".format(args.value, args.unit)).fetchone()[0]
    rows = db.execute("SELECT cid,username,datetime(timestamp, 'unixepoch') FROM comments WHERE "
                      "datetime(timestamp, 'unixepoch') > datetime('now', '-{} {}')".format(
                          args.value, args.unit)).fetchall()

    ess = 's' if args.value > 1 else ''
    print('Found {} comments from the last {} {}{}. Comments newer than {}'.format(
        len(rows), args.value, args.unit, ess, then))
    print('Oldest comment: {}'.format(rows[0][2]))

    # there is probably an SQL way to do this much much better.
    c = Counter()
    for row in rows:
        c[row[1]] += 1

    result_count = len(rows) if not args.count else args.count
    rank = 1
    print('    Rank Count Username')
    for user, count in c.most_common(result_count):
        print('    {:3}. {:5} {}'.format(rank, str(count).center(5), user))
        rank = rank + 1
<file_sep>import argparse
import praw
import logging
import sqlite3
from praw.helpers import comment_stream

from argParseLog import addLoggingArgs, handleLoggingArgs

log = logging.getLogger(__name__)

if __name__ == '__main__':
    def_sub = 'boardgames'
    ap = argparse.ArgumentParser()
    ap.add_argument('-s', '--subreddit', help='The subreddit to read.', default=def_sub)
    addLoggingArgs(ap)
    args = ap.parse_args()
    handleLoggingArgs(args)

    log.info('Connecting to reddit.')
    reddit = praw.Reddit('{} bot that counts user posts in a subreddit. v.0.1'
                         ' by /u/phil_s_stein.')
    reddit.login()
    log.info('Logged in.')

    db = sqlite3.connect('{}.db'.format(args.subreddit))
    log.info('Bot database opened/created.')

    stmt = 'SELECT name FROM sqlite_master WHERE type="table" AND name="comments"'
    q = db.execute(stmt).fetchall()
    if not q:
        log.info('Creating DB tables.')
        db.execute('CREATE table comments (cid text, username text, timestamp date)')
        db.execute('CREATE table error (count integer)')

    log.info('Reading new comments from /r/{}.'.format(args.subreddit))
    subreddit = reddit.get_subreddit(args.subreddit)
    while True:
        try:
            for comment in comment_stream(reddit, subreddit):
                log.debug('read comment {} by {}'.format(comment.id, comment.author))
                # log.debug('comment {}'.format(comment.__dict__))
                # log.debug('author {}'.format(comment.author.__dict__))
                count = db.execute('SELECT COUNT(*) FROM comments WHERE cid=?', (comment.id, )).fetchall()[0][0]
                if not count or count == 0:
                    log.info('logging comment {} by {}'.format(comment.id, comment.author.name))
                    db.execute('INSERT into comments VALUES (?, ?, ?)',
                               (comment.id, comment.author.name, comment.created_utc))
                    db.commit()
        except Exception as e:
            log.error('Caught exception: {}'.format(e))
            db.execute('UPDATE error set count = count + 1')
<file_sep>import logging

log = logging.getLogger(__name__)


def handleLoggingArgs(args):
    logLevels = {
       u'none': 100,
       u'all': 0,
       u'debug': logging.DEBUG,
       u'info': logging.INFO,
       u'warning': logging.WARNING,
       u'error': logging.ERROR,
       u'critical': logging.CRITICAL
    }
    log_format = u'%(asctime)s %(name)-12s %(levelname)-8s %(message)s'
    log_datefmt = u'%m-%d %H:%M:%S'
    logging.basicConfig(format=log_format, datefmt=log_datefmt,
                        level=logLevels[args.loglevel])


def addLoggingArgs(ap):
    ap.add_argument("-l", "--loglevel", dest="loglevel",
                    help="The level at which to log. Must be one of "
                    "none, debug, info, warning, error, or critical. Default is none. ("
                    "This is mostly used for debugging.)",
                    default='none', choices=['none', u'all', u'debug', u'info', u'warning',
                                             u'error', u'critical'])
