예제 #1
0
def main():
    logging.config.fileConfig(path_to_cfg)
    start_utc = datetime.utcnow()
    start_time = time()

    global r
    try:
        r = reddit.Reddit(user_agent=cfg_file.get('reddit', 'user_agent'))
        logging.info('Logging in as %s', cfg_file.get('reddit', 'username'))
        r.login(cfg_file.get('reddit', 'username'),
            cfg_file.get('reddit', 'password'))
    except Exception as e:
        logging.error('  ERROR: %s', e)

    mod_subreddit = r.get_subreddit('mod')


    #
    # Do actions on individual subreddits
    #
    
    # get subreddit list
    subreddits = Subreddit.query.filter(Subreddit.enabled == True).all()
    sr_dict = dict()
    for subreddit in subreddits:
        sr_dict[subreddit.name.lower()] = subreddit
    
    # do actions on subreddits
    do_subreddits(mod_subreddit, sr_dict, start_utc)
    

    #
    # Do actions on networks
    #
    mods_checked = 0

    # get network list
    networks = Network.query.filter(Network.enabled == True).all()
    
    # do actions on each network
    for network in networks:
        # get subreddits in network
        network_subs = Subreddit.query.filter(Subreddit.network == network.id, Subreddit.enabled == True).all()
        network_sr_dict = dict()
        for subreddit in network_subs:
            network_sr_dict[subreddit.name.lower()] = subreddit
        
        # do subreddit actions on subreddits
        do_subreddits(mod_subreddit, network_sr_dict, start_utc)
        
        # check network mods
        logging.info('Checking network moderators')
        for subreddit in network_sr_dict.itervalues():
            # only check subs in networks
            if subreddit.network:
                mods_checked += check_network_moderators(network, network_sr_dict)
    
    logging.info('  Checked %s networks, added %s moderators', len(networks), mods_checked)

    logging.info('Completed full run in %s', elapsed_since(start_time))
예제 #2
0
 def __init__(self, passwords):
     name = AmericanBot.myName
     print "Logging in: ", name
     self.r = reddit.Reddit(user_agent=name + ' by /u/punkgeek')
     self.r.login(name, passwords[name])
     locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
     self.lastCommentId = 0
예제 #3
0
def main():
    """Main function

    Instantiates game and reddit, and
    runs main loop.
    """

    reddit.Reddit().run_loop(game.Game())
예제 #4
0
 def __init__(self):
     self.name = 'RedBot'
     self.username = USERNAME
     self.password = PASSWORD
     #
     self.r = reddit.Reddit(user_agent=self.name)
     self.r.login(username=self.username, password=self.password)
     self.last_post = None  # Submission object
     self.permalink = None  # URL of the last post
예제 #5
0
파일: bot.py 프로젝트: r-nba/slapbot
    def __init__(self, botName):
        self.botName = botName

        self.r = reddit.Reddit()
        self.db = database.Database()
        self.comms = comms.Comms(self.db, self.r)

        self.botChannel = self.comms.bot.get_channel('410134097235673089')
        self.botServer = self.comms.bot.get_server('229123661624377345')
        self.pingOnStart = 1
        self.isReady = 0
예제 #6
0
    def __init__(self):
        self.top_submission = False
        # create custom gets
        reddit.objects.Subreddit.get_top_month = reddit.helpers._get_sorter(
            'top', t='month')
        reddit.objects.Subreddit.get_top_week = reddit.helpers._get_sorter(
            'top', t='week')

        # reddit config
        self.r = reddit.Reddit(user_agent=config.user_agent)
        self.r.login(config.r_login, config.r_pw)
예제 #7
0
 def buildDictionaryReddit(self, subredditList):
     print "[+] Beginning to Crawl Reddit\n"
     x = reddit.Reddit(subredditList)
     x.crawl()
     try:
         lex = LE.lexengine(x.rawText,
                            self.workingDirectory + "RedditDictionary.txt")
         print "[+] Beginning analysis..."
         lex.trimPercentage()
     except:
         print "[-] Could not process file."
예제 #8
0
async def on_ready():
    print("Connected.")
    if len(message_modules) == 0:
        message_modules.append(ps.TestModule(client))
        message_modules.append(ps.CouncilModule(client))
        message_modules.append(ps.SoundModule(client))
        # message_modules.append(ps.CatModule(client))

        red = reddit.Reddit(client)
        message_modules.append(ps.RedditModule(client, red))
        react_modules.append(ps.RedditReactModule(client, red))
예제 #9
0
def main():
    logging.config.fileConfig(path_to_cfg)
    start_utc = datetime.utcnow()
    start_time = time()

    global r
    try:
        r = reddit.Reddit(user_agent=cfg_file.get('reddit', 'user_agent'))
        logging.info('Logging in as %s', cfg_file.get('reddit', 'username'))
        r.login(cfg_file.get('reddit', 'username'),
                cfg_file.get('reddit', 'password'))

        subreddits = Subreddit.query.filter(Subreddit.enabled == True).all()
        sr_dict = dict()
        for subreddit in subreddits:
            sr_dict[subreddit.name.lower()] = subreddit
        mod_subreddit = r.get_subreddit('mod')
    except Exception as e:
        logging.error('  ERROR: %s', e)

    # check reports
    items = mod_subreddit.get_reports(limit=1000)
    stop_time = datetime.utcnow() - REPORT_BACKLOG_LIMIT
    check_items('report', items, sr_dict, stop_time)

    # check spam
    items = mod_subreddit.get_modqueue(limit=1000)
    stop_time = (db.session.query(func.max(
        Subreddit.last_spam)).filter(Subreddit.enabled == True).one()[0])
    check_items('spam', items, sr_dict, stop_time)

    # check new submissions
    items = mod_subreddit.get_new_by_date(limit=1000)
    stop_time = (db.session.query(func.max(
        Subreddit.last_submission)).filter(Subreddit.enabled == True).one()[0])
    check_items('submission', items, sr_dict, stop_time)

    # check new comments
    comment_multi = '+'.join(
        [s.name for s in subreddits if not s.reported_comments_only])
    if comment_multi:
        comment_multi_sr = r.get_subreddit(comment_multi)
        items = comment_multi_sr.get_comments(limit=1000)
        stop_time = (db.session.query(func.max(Subreddit.last_comment)).filter(
            Subreddit.enabled == True).one()[0])
        check_items('comment', items, sr_dict, stop_time)

    # respond to modmail
    try:
        respond_to_modmail(r.user.get_modmail(), start_utc)
    except Exception as e:
        logging.error('  ERROR: %s', e)

    logging.info('Completed full run in %s', elapsed_since(start_time))
예제 #10
0
 def __init__(self):
 
     """
     limit -- int, the numbers of news that would be load
     logged_in -- bool, if user is logged in
     info -- String, name of subreddit
     """
 
     self.r = reddit.Reddit(user_agent = "null")
     self.limit = 0
     self.logged_in = False
     self.info = "null"
예제 #11
0
 def __init__(self, main_window):
     self.ui = main_window
     self.image_path = None
     self.reddit_instance = reddit.Reddit()
     self.ui.redditNextWallButton.clicked.connect(self.next_wallpaper)
     self.ui.redditWallpaperButton.clicked.connect(self.set_wallpaper)
     self.ui.redditSaveButton.clicked.connect(self.save_wallpaper)
     self.screenSize = QDesktopWidget().screenGeometry(0)
     self.ui.redditPhoto.setMaximumHeight(
         int(0.7 * self.screenSize.height()))
     self.ui.redditPhoto.setMaximumWidth(int(0.99 *
                                             self.screenSize.width()))
     self.ui.redditSearchTextEdit.setMaximumWidth(
         int(0.15 * self.screenSize.width()))
예제 #12
0
파일: snippet.py 프로젝트: szabo92/gistable
def main():
    r = reddit.Reddit('PRAW loop test')
    r.login()

    last = None

    comm = r.get_subreddit('reddit_api_test')
    for i, sub in enumerate(comm.get_new_by_date()):
        handle_ratelimit(sub.add_comment, 'Test comment: %d' % i)
        cur = time.time()
        if not last:
            print '     %2d %s' % (i, sub.title)
        else:
            print '%.2f %2d %s' % (cur - last, i, sub.title)
        last = cur
예제 #13
0
    def __init__(self):
        self.version = "2.0.1"

        self.c = config.Config("config.json", {
            "id": "<IMGUR_CLIENT_ID>",
            "min": 100
        })

        self.d = config.Config("database.json", {"banned": [], "replied": []})

        print "> Started makeswordclouds, version " + self.version
        self.r = reddit.Reddit(
            self.c, self.d,
            praw.Reddit("makeswordclouds: running under version " +
                        self.version))
예제 #14
0
def scrape_reddit():
    docs = reddit.Reddit(user_agent='app').get_front_page(limit=250)
    for item in docs:
        url = item.url
        _id = md5.md5(url).hexdigest()
        title = item.title
        try:
            body = webarticle2text.extractFromURL(url)
            wordcount = len(body.split(" "))
        except:
            wordcount = -1

        coll.update(
            {"_id": _id},
            {"$set": {
                "title": title,
                "wordcount": wordcount,
                "url": url
            }},
            upsert=True)

        print 'Added url %s' % url
예제 #15
0
import reddit
import json
from ConfigParser import ConfigParser
from datetime import datetime

config = ConfigParser()
config.read('config.txt')

username = config.get('user', 'username')
password = config.get('user', 'password')
user_agent = config.get('client', 'user_agent')

posts = json.loads(open('postings.json', 'r').read())

r = reddit.Reddit(user_agent=user_agent)
r.login(username, password)

MONTHS = {
    1: 'Jan.',
    2: 'Feb.',
    3: 'Mar.',
    4: 'Apr',
    5: 'May',
    6: 'June',
    7: 'July',
    8: 'Aug.',
    9: 'Sept.',
    10: 'Oct.',
    11: 'Nov.',
    12: 'Dec.'
}
예제 #16
0
                            "name": "reddit username",
                            "type": "str"
                        },
                        "password": {
                            "name": "reddit password",
                            "type": "secret"
                        }
                    }
                }
            }
        }
    })
    # save config
    config.Config.save(conf)
    # create reddit API instance
    reddit = reddit.Reddit(conf["reddit"]["login_args"])
    # create database
    db = db_.DB(conf["db"]["path"])
    # get all nth subs
    nthsubs = list(db.search_nth_subs(tags=["thirdsub"]))

    def get_text_for_number(number: str, offset: int, posts: Dict[str, str]):
        try:
            sub = list(db.search_nth_subs(number_eq=int(number) + offset))[0].sub
        except ValueError:
            sub = None
        except IndexError:
            sub = None
        if sub not in posts:
            sub = None
        # noinspection PyTypeChecker
예제 #17
0
  Return a direct link url for imgur based on an indirect
  url tuple from urlparse

  url - a parsed url tuple from urlparse [TUPLE]

  returns direct link url [STRING]
"""


def build_imgur_dl(url):
    return 'http://' + 'i.' + url.netloc + url.path + '.jpg'
    # to be added: exceptions for if it's a png or gif


# initialize reddit object
r = reddit.Reddit(user_agent='sample_app')

# get submissions as a list of objects
subr_name = options.subreddit
subr_filter = options.filter
subr_limit = int(options.limit)  # make this an int instead of a string, duh!
if verbose_mode:
    print "Scouring subreddit " + subr_name + " for " + subr_filter + " submissions (limit " + str(
        subr_limit) + ")\nPlease wait..."

sublist = submissions(subr_name, subr_filter,
                      subr_limit)  #replace default with user input
sublist = list(sublist)

# main parse & download loop
success = len(sublist)
예제 #18
0
 def __init__(self, username, password):
     super(RedditAccount, self).__init__(username)
     self.api = reddit.Reddit(user_agent="reddit-notify")
     self.username = username.strip()
     self.password = password.strip()
예제 #19
0
def submit_to_reddit(title, url, subreddit):
    r = reddit.Reddit(user_agent="submit to reddit script")
    r.login(user=cfg.USERNAME, password=cfg.PASSWORD)

    return r.submit(subreddit, url, title)
예제 #20
0
SOURCE_SUBREDDIT = 'sfwpornnetworkcss'
NETWORK_SUBREDDITS = ['lolsfwhappyfuntime']

# login info for the script to log in as, this user must be a mod in the main subreddit
REDDIT_USERNAME = cfg_file.get('reddit', 'username')
REDDIT_PASSWORD = cfg_file.get('reddit', 'password')
REDDIT_UA = cfg_file.get('reddit', 'user_agent')

# don't change unless you want different delimiter strings for some reason
START_DELIM = '>* [VideoPorn](/r/VideoPorn)'
END_DELIM = '* [Moderator Log](http://reddit.com/r/moderationporn/new)'


# log into reddit
print "Logging in as /u/"+REDDIT_USERNAME+"..."
r = reddit.Reddit(user_agent=REDDIT_UA)
r.login(REDDIT_USERNAME, REDDIT_PASSWORD)
print "  Success!"


# get the source stylesheet
print "Getting source sidebar from /r/"+SOURCE_SUBREDDIT+"..."
source_subreddit = r.get_subreddit(SOURCE_SUBREDDIT)
# fetch the stylesheet from the main subreddit
source_sidebar = source_subreddit.get_settings()['description']
print source_sidebar
# construct the regex object
replace_pattern = re.compile('%s.*?%s' % (re.escape(START_DELIM), re.escape(END_DELIM)), re.IGNORECASE|re.DOTALL|re.UNICODE)
# extract sidebar from source stylesheet
source_sidebar = HTMLParser.HTMLParser().unescape(source_sidebar)
source_sidebar = re.search(replace_pattern, source_sidebar).group(0)
예제 #21
0
    def __init__(self, username=None, password=None):
        self.r = reddit.Reddit(user_agent='stalkerbot')

        if username and password:
            self.r.login(username, password)
            print self.r
예제 #22
0
 def __init__(self, parent=None):
   Tkinter.TK.__init(self,parent)
   self.reddit=reddit.Reddit("Bla!")
   self.posts = []
   self.setupUI()
   self.loadData()
예제 #23
0
logging.basicConfig(filename='logging.log', level=logging.ERROR)
settings = cfg.readJson('settings.json')

# Bot constants
BOT_NAME = 'stickybot'
BOT_ID = settings['stickybot']['bot_id']
BOT_CALL = '<@{}>'.format(BOT_ID)
BOT_CMD = '!sticky'
BOT_CMD_UNSTICKY = '!unsticky'

slack_client = SlackClient(settings['stickybot']['token'])
SOCKET_READ_DELAY = 1

# Setup the reddit object for StickyBot
sticky_bot = reddit.Reddit()
sticky_bot.get_praw_instance()


def firehose():
    if slack_client.rtm_connect():
        logging.INFO(
            'StickyBot has begun. Total word domination will begin soon...')
        while True:
            try:
                cmd, channel, user = parser(slack_client.rtm_read())
                if cmd and channel and user:
                    handle(cmd, channel, user)
                time.sleep(SOCKET_READ_DELAY)
            except (websocket.WebSocketConnectionClosedException,
                    TimeoutError) as e:
예제 #24
0
import os
import sys
import time
import reddit
import types
import random
list = ["str1", "str2", "str3"]
r = reddit.Reddit(user_agent='TrantBot')
r.login(usrname, pword)
user = r.get_redditor('nothix')
for post in user.get_submitted():
    for k in range(1):
        i = random.randint(1, len(list))
    strComment = list[i - 1]
    print "10 Minute wait time starts now : " + strComment
    time.sleep(610)
    try:
        post.downvote()
        post.add_comment(strComment)
        print "Commented: %s" % post.__unicode__()
    except:
        exception('Cannot Comment or Vote!')
예제 #25
0
def run_reddit_python():
    v_reddit = reddit.Reddit('Python')
    v_reddit.publish()
예제 #26
0
                    target=_blank>{2}</a>
                    </td><td>{4}</td><td>{3}</td>
                    <td>{0.desc}</td></tr>
                    """.format(
                baller, submission.permalink.encode('ascii', 'ignore'),
                submission.title.encode('ascii', 'ignore'),
                time.strftime("%d-%m-%Y", time.gmtime(submission.created)),
                submission.score)
        body += """
         </table>
         </div>
    </div><br /><br />"""
    return header + body + footer


def main():
    APPROVED_USERS_PAGES = ('p9mkj', 'p9mqn', 'qpyfl', 'sshyn')
    ballers = get_ballers(APPROVED_USERS_PAGES)
    paired = build_subs(ballers)
    splitted = split_by_role(paired)
    sorted_roles = sort_pairings_in_roles(splitted)
    output = build_html(sorted_roles)
    with open('created_baller.html', 'w') as out:
        out.write(output)


if __name__ == '__main__':
    r = reddit.Reddit(user_agent="""Starcraft 2 Baller Overview creator by 
                                 '/u/_Daimon_""")
    main()
예제 #27
0
def run_reddit_ctf():
    v_reddit = reddit.Reddit('securityCTF')
    v_reddit.publish()
예제 #28
0
logging.basicConfig(level=logging.INFO)  #INFO/DEBUG

textChatIDlist = [
    "170682390786605057", "302137557896921089", "302965414793707522",
    "293186321395220481"
]  #general, dev, nsf, other

#bot instantiator
bot = commands.Bot(command_prefix='!',
                   description='The official Waffle House bot')
#add functionalities from each file
bot.add_cog(music.Music(bot))
bot.add_cog(localPictureUpload.LocalPictureUpload(bot))
bot.add_cog(databaseProxy.DatabaseProxy(bot))
bot.add_cog(reddit.Reddit(bot))
bot.add_cog(tweets.Twitter(bot))
bot.add_cog(botSpeak.BotSpeak(bot))
bot.add_cog(toneReactions.ToneReacts(bot))
bot.add_cog(personality.Personality(bot))
bot.add_cog(phoneCall.Phone(bot))


#prints to console when bot starts up
@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('------')
예제 #29
0
REMEMBER_HIT = True
TARGET_REDDIT = ''
NEW_SUBMISSIONS_REDDIT = ''
SUBMISSIONS_TO_MONITOR = 5
MONITOR_INTERVAL = 30  # seconds
NEW_SUBMISSION_INTERVAL = 3600  # seconds
COMMENT_THRESHOLD = 25
PICKLE_FILE_SUBMISSIONS = 'hitSubmissions.pkl'
PICKLE_FILE_COMMENTS = 'hitComments.pkl'

try:
    from settings import *
except ImportError:
    pass

r = reddit.Reddit(user_agent='reader')
r.login(REDDIT_USERNAME, REDDIT_PASSWORD)

# get already-hit submissions and comments
hitSubmissions = []
hitComments = []
if REMEMBER_HIT:
    try:
        pklSubmissions = open(PICKLE_FILE_SUBMISSIONS, 'rb')
        pklComments = open(PICKLE_FILE_COMMENTS, 'rb')
        hitSubmissions = pickle.load(pklSubmissions)
        hitComments = pickle.load(pklComments)
        pklSubmissions.close()
        pklComments.close()
    except IOError:
        pass  # move on with empty arrays
예제 #30
0
def run_reddit_django():
    v_reddit = reddit.Reddit('djangolearning')
    v_reddit.publish()