예제 #1
0
def reddit_oauth():
    """
    Get a new refresh token to ensure that access will be granted.
    No need to append the access key to the requests, PRAW handles that.
    """
    #Set Variables
    user_agent = 'Custom user_agent'
    reddit = praw.Reddit(user_agent=user_agent)
    app_key = "See https://github.com/reddit/reddit/wiki/OAuth2"
    app_secret = "See https://github.com/reddit/reddit/wiki/OAuth2"
    access_token = "From OAUTH API"
    refresh_token = "From OAUTH API"

    #Refresh OAuth access
    oauth_helper = PrawOAuth2Mini(reddit,
                                  app_key=app_key,
                                  app_secret=app_secret,
                                  access_token=access_token,
                                  refresh_token=refresh_token,
                                  scopes=[
                                      'identity', 'edit', 'read', 'history',
                                      'modconfig', 'modflair', 'modlog',
                                      'modposts', 'modwiki', 'mysubredits',
                                      'privatemessages', 'read', 'report',
                                      'save', 'submit', 'subscribe', 'vote',
                                      'wikiedit', 'wikiread'
                                  ])
    oauth_helper.refresh()
    return reddit
예제 #2
0
def refresh_oauth():
    logger.info("Attempting to refresh refresh token.")
    oauth_helper.refresh()
    logger.info("Token refreshed.")
    oauth_helper = PrawOAuth2Mini(r,
                                  app_key=APPKEY,
                                  app_secret=APPSECRET,
                                  access_token=ACCESSTOKEN,
                                  scopes=SCOPES,
                                  refresh_token=REFRESHTOKEN)
예제 #3
0
def test_oauth_mini():
    reddit_client = praw.Reddit(user_agent=user_agent)
    oauth_helper = PrawOAuth2Mini(
        reddit_client, app_key=app_key, app_secret=app_secret,
        access_token=access_token, refresh_token=refresh_token, scopes=scopes)
    try:
        subreddit = reddit_client.get_subreddit(test_subreddit)
        comment = list(subreddit.get_comments(limit=1)).pop()
    except praw.errors.OAuthInvalidToken:
        oauth_helper.refresh()
    assert comment
    assert comment.reply('reply from a bot, please ignore')
예제 #4
0
def runs(db,cursor):
    r = praw.Reddit(user_agent = USER_AGENT)
    oauth_helper = PrawOAuth2Mini(r,app_key = APP_KEY,app_secret = APP_SECRET,
                                    access_token = ACCESS_TOKEN,scopes = SCOPES,
                                    refresh_token = REFRESH_TOKEN)
    oauth_helper.refresh()
    subreddit = r.get_subreddit('all')

    author = "none"
    created = int(time())
    over_18 = 0
    permalink = "none"
    subred = "none"
    thumbnail = "none"
    title = "none"
    url = "none"
    name = "none"
    media = "none"

    lookup = {}

    sql_fetch = "SELECT name from post_info"
    try:
        cursor.execute(sql_fetch)
        result = cursor.fetchall()
        db.commit()
        for row in result:
            lookup[row[0]] = None
    except:
        pass
    for post in reversed(list(subreddit.get_new(limit=1000))):
        author = str(vars(post)['author'])
        created = time()
        over_18 = int(vars(post)['over_18'])
        permalink = str(vars(post)['permalink'])
        permalinkfix = fixurl(permalink)
        subred = str(vars(post)['subreddit'])
        thumbnail = str(vars(post)['thumbnail'])
        title = str(vars(post)['title'])
        titleformat = db.escape(re.sub('[^a-zA-Z0-9 \n\.]','',title))
        url = str(vars(post)['url'])
        name = str(vars(post)['name'])
        if thumbnail == "self":
            url = fixurl(url)
        if name not in lookup:
            sql_insert = "INSERT INTO `post_info` (`author`, `title`, `subreddit`, `url`, `permalink`,`created`, `thumbnail`, `over_18`, `name`)  VALUES ('%s', %s, '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % (author, titleformat, subred, url, permalinkfix, created, thumbnail, over_18, name)
            try:
                cursor.execute(sql_insert)
            except:
                db.rollback()
        db.commit()
예제 #5
0
def init():
    r = praw.Reddit(user_agent="Samachar Bot for /r/india by /u/sallurocks")
    scopes = {
        u'edit', u'submit', u'read', u'privatemessages', u'identity',
        u'history'
    }
    oauth_helper = PrawOAuth2Mini(r,
                                  app_key=os.environ['app_key'],
                                  app_secret=os.environ['app_secret'],
                                  access_token=os.environ['access_token'],
                                  refresh_token=os.environ['refresh_token'],
                                  scopes=scopes)
    subreddit = r.get_subreddit("+".join(subreddits.subreddits))
    return r, oauth_helper, subreddit
예제 #6
0
def bot_main():
    """
    Main function of the bot. Contains logic loop and oauth
    """
    oauth_helper = PrawOAuth2Mini(REDDIT_CLIENT,
                                  app_key=settings.reddit_app_key,
                                  app_secret=settings.reddit_app_secret,
                                  access_token=settings.reddit_access_token,
                                  scopes=settings.scopes,
                                  refresh_token=settings.reddit_refresh_token)
    print 'UsernameBot Online!'
    while True:
        try:
            bot_logic(oauth_helper)
        except praw.errors.OAuthInvalidToken:
            oauth_helper.refresh()
        time.sleep(30)
예제 #7
0
import praw
import humanize
from datetime import datetime
from flask import Flask
from flask import request, render_template
from prawoauth2 import PrawOAuth2Mini

from settings import (app_key, app_secret, access_token, refresh_token,
                      user_agent, scopes)

reddit_client = praw.Reddit(user_agent=user_agent)
oauth_helper = PrawOAuth2Mini(reddit_client,
                              app_key=app_key,
                              app_secret=app_secret,
                              access_token=access_token,
                              refresh_token=refresh_token,
                              scopes=scopes)

app = Flask(__name__)


def get_cake_day(username):
    redditor = reddit_client.get_redditor(username)
    try:
        created_on = datetime.utcfromtimestamp(redditor.created_utc)
    except praw.errors.NotFound:
        return False
    return humanize.naturalday(
        created_on), redditor.comment_karma, redditor.link_karma

예제 #8
0
REFRESH_TOKEN = config.get('Reddit', 'refresh_token')
SCOPES = ['identity', 'submit']

imgur_client_id = config.get('Imgur', 'client_id')
imgur_client_secret = config.get('Imgur', 'client_secret')
imgur_access_token = config.get('Imgur', 'access_token')
imgur_refresh_token = config.get('Imgur', 'refresh_token')

imgur_client = ImgurClient(imgur_client_id, imgur_client_secret,
                           imgur_access_token, imgur_refresh_token)

already_done = set()

oauth_helper = PrawOAuth2Mini(r,
                              app_key=CLIENT_ID,
                              app_secret=CLIENT_SECRET,
                              access_token=TOKEN,
                              refresh_token=REFRESH_TOKEN,
                              scopes=SCOPES)

# =============================================================================
# FUNCTIONS
# =============================================================================


def getTopSubmissions():
    print("Ready for images")
    subreddit = r.get_subreddit('test')
    for comment in praw.helpers.comment_stream(r,
                                               'test',
                                               limit=10,
                                               verbosity=0):
예제 #9
0
import time
import gfycat.gfycat
import traceback
import time
from datetime import datetime
from prawoauth2 import PrawOAuth2Mini
import settings as s

nothing_to_do = True
debug = s.debug

#Set up global reddit auth
reddit = praw.Reddit(user_agent=s.user_agent)
oauth_helper = PrawOAuth2Mini(reddit,
                              app_key=s.app_key,
                              app_secret=s.app_secret,
                              access_token=s.access_token,
                              refresh_token=s.refresh_token,
                              scopes=s.scopes)


def process_sub(reddit, subreddit_name):
    global nothing_to_do
    if debug:
        print(("Now running on: " + subreddit_name))
    #number_of_posts needs to be adjusted for subreddits with more postings per minute. Do so in settings.py
    submission_generator = reddit.get_subreddit(subreddit_name).get_new(
        limit=s.number_of_posts)
    for submission in submission_generator:
        post_id = vars(submission)['id']
        #file for keeping track of already processed links. Set in settings.py
        processed_file = open(s.processed_file)
예제 #10
0
import praw
from prawoauth2 import PrawOAuth2Mini
from tokens import app_key, app_secret, access_token, refresh_token, scopes

user_agent = "Drunken PRAWL"
reddit_client = praw.Reddit(user_agent=user_agent)
oauth_helper = PrawOAuth2Mini(reddit_client,
                              app_key='MY_KEY',
                              app_secret='MY_SECRET_KEY',
                              access_token='ACCESS_TOKEN',
                              scopes=scopes,
                              refresh_token='REFRESH_TOKEN')
already_done = set()


def loop():
    oauth_helper.refresh()
    for comment in reddit_client.get_comments('DrunkenPrawl'):
        if 'im drunk' in comment.body.lower(
        ) and comment.id not in already_done:
            print('Time to shitpost')
            comment.reply(
                'Give me your height, weight, and sex (like this: **5\'8", 150 lb, Male**). I\'ll tell you how much you *probably* had!'
            )
            already_done.add(comment.id)


while True:
    try:
        loop()
    except praw.errors.OAuthInvalidToken:
예제 #11
0
import praw
import instagram_converter
from prawoauth2 import PrawOAuth2Mini
key = "dFh4UjkvhdQIGw"
secret = "0FS1_D2242Y-cdC2EiEZdTjZ6u4"
token = "54589065-hluT2YOUajr1nTPdDokqFOGL_1g"
refresh = "54589065-hvu78d_mz4VDyGMLRTNIveSoP2k"
user_agent = ('instareposter 1.0')
r = praw.Reddit(user_agent=user_agent)
scopes = ['identity', 'read', 'submit']
oauth_helper = PrawOAuth2Mini(r,
                              app_key=key,
                              app_secret=secret,
                              access_token=token,
                              refresh_token=refresh,
                              scopes=scopes)
oauth_helper.refresh()
subreddit = r.get_subreddit("InstaRepostBot")
already_done = []


def bot_response(submission, new_url):
    head = "Hi! I'm InstaRepostBot. I take instagram links and re-upload them to streamable or imgur. Your new link is below \n\n"
    mid = new_url
    tail = "\n\nI'm only running for a short trial period, pm me feedback if you like the bot and want it to keep running!"
    submission.add_comment(head + mid + tail)


for submission in subreddit.get_new(limit=20):
    post_id = submission.id
    url = submission.url
예제 #12
0
    return counter


def handleComment(comment):
    result, counter = generateResponseText(comment.body)
    if result:
        comment.reply(result)

    return counter


r = praw.Reddit(user_agent=settings['user-agent'])

oauth_helper = PrawOAuth2Mini(r,
                              app_key=settings['app_key'],
                              app_secret=settings['app_secret'],
                              access_token=settings['access_token'],
                              refresh_token=settings['refresh_token'],
                              scopes=settings['scopes'])

readComments = CommentLog('readComments-%s.txt' % settings['subreddit'])

running = True

while running:
    try:
        sub = r.get_subreddit(settings['subreddit'])
        counter = 0
        handledComments = 0

        for submission in sub.get_hot(limit=10):
            if not readComments.contains(submission.id):
예제 #13
0
__author__ = 'salmaan'
import praw
from prawoauth2 import PrawOAuth2Mini
import os
from ignore import config
import blacklist
import smrzr
import find_other_news_sources

blockedid = []

reddit_client = praw.Reddit(
    user_agent="Samachar Bot for /r/india by /u/sallurocks")
oauth_helper = PrawOAuth2Mini(reddit_client,
                              app_key=config.app_key,
                              app_secret=config.app_secret,
                              access_token=config.access_token,
                              refresh_token=config.refresh_token,
                              scopes=config.scopes)


def get_latest_posts(subreddit):

    subreddit = reddit_client.get_subreddit(subreddit)
    return subreddit.get_new(limit=25)


def prepare(submission):
    link = submission.url
    summ_article = smrzr.Summarizer(link)
    keypoints = summ_article.keypoints
    summ = summ_article.summary
예제 #14
0
import time
import sys
import os

from difflib import SequenceMatcher
from prawoauth2 import PrawOAuth2Mini
from common import Utility
from settings import ARKENTHERA_BOT_TOKEN, ARKENTHERA_BOT_ID
from slackclient import SlackClient

from settings import SYACR_CLIENT_ID, SYACR_CLIENT_SECRET, SYACR_ACCESS_TOKEN, SYACR_REFRESH_TOKEN, UA, SCOPES

reddit_client = praw.Reddit(user_agent=UA)
oauth_helper = PrawOAuth2Mini(reddit_client,
                              app_key=SYACR_CLIENT_ID,
                              app_secret=SYACR_CLIENT_SECRET,
                              access_token=SYACR_ACCESS_TOKEN,
                              refresh_token=SYACR_REFRESH_TOKEN,
                              scopes=SCOPES)

DO_NOTHING = 0
DO_REPORT = 1
DO_REMOVE = 2
DO_IGNORE = 3

START_WITH_POST_COUNT = 1
ALLOW_REPOSTS_THREE_MONTH = 1

# Shared variables must exist in all threads
REPORT_THRESHOLD = 0.60
REMOVE_THRESHOLD = 0.95
예제 #15
0
if not os.path.isfile("steampowered_config.py"):
    logger.error("Config file not found in current directory.")
    exit(1)

db = SqliteDatabase('steampowered.db')
comments_replied_to = []

# Create Reddit object
r = praw.Reddit(user_agent=USER_AGENT)

# Login with credentials from config file
#r.login(REDDIT_USERNAME, REDDIT_PASS)
try:
    oauth_helper = PrawOAuth2Mini(r,
                                  app_key=APPKEY,
                                  app_secret=APPSECRET,
                                  access_token=ACCESSTOKEN,
                                  scopes=SCOPES,
                                  refresh_token=REFRESHTOKEN)
except praw.errors.OAuthInvalidToken:
    logger.warn("Invalid OAuth Token.")
    refresh_oauth()

subreddit = r.get_subreddit(SUBREDDIT)


def refresh_oauth():
    logger.info("Attempting to refresh refresh token.")
    oauth_helper.refresh()
    logger.info("Token refreshed.")
    oauth_helper = PrawOAuth2Mini(r,
                                  app_key=APPKEY,
예제 #16
0
파일: bot2.0.py 프로젝트: seanjhulse/Python
import pylab
from matplotlib.patches import Ellipse
import praw
from prawoauth2 import PrawOAuth2Mini
from tokens import app_key, app_secret, access_token, refresh_token, scopes
import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt

tracktime = time.time() #datetime when it was initialized so it doesn't post on old content 

user_agent = "Drunken PRAWL"
user_name = "DrunkWhenSober"
reddit_client = praw.Reddit(user_agent=user_agent)
oauth_helper = PrawOAuth2Mini(reddit_client, app_key='cnCoU2zAAb6IEA',
                              app_secret='-8F3XR-_-In7LENvBj7YKnmTG9s', access_token='isCMLVCkYF2RaTBm5mgBEYRoQ50',
                              scopes=scopes, refresh_token='44644420-0vrXSISDaSu3ThXYEhwldIj80gg')
already_done = set()
comment_count = []
plt.ion()
fig = plt.figure(figsize=(12, 8), dpi=80, facecolor='w', edgecolor='k')
ax = fig.add_subplot(111, autoscale_on=False, xlim=(0,50), ylim=(0,5000))

plt.xlabel("Time")
plt.ylabel("Number of Comments")

def loop():
    oauth_helper.refresh()
    
    submissions = reddit_client.get_subreddit('all').get_hot(limit=100)
    
예제 #17
0
# Config Stuff

r = praw.Reddit(user_agent="Samachar Bot for /r/india by /u/sallurocks")

# implement oauth soon ---done

uname = os.environ['uname']
pwd = os.environ['pass']
r.login(uname, pwd)

scopes = {
    u'edit', u'submit', u'read', u'privatemessages', u'identity', u'history'
}
oauth_helper = PrawOAuth2Mini(r,
                              app_key=os.environ['app_key'],
                              app_secret=os.environ['app_secret'],
                              access_token=os.environ['access_token'],
                              refresh_token=os.environ['refresh_token'],
                              scopes=scopes)

subreddit = r.get_subreddit('india+TESTBOTTEST')

while True:

    # File to keep track of posts already looked, gets refreshed if bot is restarted.
    # put pointer at start, then reads the file to string and then puts the pointer back at the end.

    fo = open("looked.txt", "a+")
    position = fo.tell()
    fo.seek(0, 0)
    str1 = fo.read()
    fo.seek(position)
예제 #18
0
#!/usr/bin/env python
#cfb_info_bot version 1.0
import urllib
import os
import praw
from prawoauth2 import PrawOAuth2Mini
import time
already_done = []
user_agent = 'a tool for cfb'
r = praw.Reddit(user_agent=user_agent)
oauth_helper = PrawOAuth2Mini(r,
                              app_key='redacted',
                              app_secret='redacted',
                              access_token='redacted',
                              refresh_token='redacted',
                              scopes=('save', 'submit', 'read', 'identity'))


def lookup(team, start, end):
    z = open('html.txt', 'w')
    url = "http://cfbtrivia.com/cfbt_team_page.php?teamname=%s&teamyrfrom=%s&teamyrthru=%s" % (
        team, start, end)
    urlr = urllib.urlopen(url)
    z.write(urlr.read())
    z.close()
    z = open('html.txt', 'r')
    doc = z.readlines()
    block = doc[339]
    block = block.split('>')
    z.close
    os.system('rm html.txt')