def get_content(url, pages=1): ''' Retrieves and iterates the posts/comments found at 'url' Args: url: URL on reddit containing posts/comments pages: Number of pages to view (loads 'next' page for pages-1 times) Yields: Each post or comment found at 'url' ''' page = 0 #Bot.log('Loading %s' % url) posts = Reddit.get(url) latency = int(strftime('%s', gmtime())) while True: page += 1 for post in posts: yield post if page < pages: #Bot.log('Loading %s (page %d)' % (url, page + 1)) posts = Reddit.next() else: break latency = int(strftime('%s', gmtime())) - latency
def check_messages(): ''' Checks for new messages, handles incoming messages Returns: true: New messages altered the database (added/removed filters) false: No messages, or the messages were innocuous ''' has_new_messages = False last_pm_time = Bot.db.get_config('last_pm_time') if last_pm_time == None: last_pm_time = 0 else: last_pm_time = int(float(last_pm_time)) for msg in Reddit.get('/message/inbox'): # TODO unread if msg.created <= last_pm_time or (type(msg) == Message and not msg.new): continue try: response = Filter.parse_pm(msg, Bot.db) while response.endswith('\n'): response = response[:-1] Bot.log('Bot.check_messages: Replying to %s with: %s' % (msg.author, response)) msg.reply(response) has_new_messages = True except Exception, e: # No need to reply Bot.log('Bot.check_messages: %s' % str(e)) last_pm_time = int(float(msg.created)) Bot.db.set_config('last_pm_time', str(last_pm_time)) msg.mark_as_read()
def update_modded_subreddits(): current = Reddit.get_modded_subreddits() if current == []: return for ignore in Bot.db.get_config('ignore_subreddits').split(','): if ignore in current: current.remove(ignore) existing = [] for (sub, ) in Bot.db.select('subreddit', 'subs_mod'): if not sub in current: Bot.db.delete('subs_mod', 'subreddit = ?', [sub]) else: existing.append(sub) for sub in current: if not sub in existing: Bot.db.insert('subs_mod', (sub, ) ) Bot.db.commit()
line = '%s%s' % (tstamp, txt.replace('\n', '\n%s' % gap)) Bot.logger.write('%s\n' % line) Bot.logger.flush() stderr.write('%s\n' % line) stderr.flush() @staticmethod def exit_if_already_started(): from commands import getstatusoutput (status, output) = getstatusoutput('ps aux') running_processes = 0 for line in output.split('\n'): if 'python' in line and 'Bot.py' in line and not '/bin/sh -c' in line: running_processes += 1 if running_processes > 1: exit(0) # Quit silently if the bot is already running if __name__ == '__main__': Bot.exit_if_already_started() username = Bot.db.get_config('reddit_user') password = Bot.db.get_config('reddit_pw') Bot.log('Bot.main: Logging in to %s...' % username) Reddit.login(username, password) while True: try: Bot.execute() except Exception, e: Bot.log('Bot.main: Exception: %s' % str(e)) Bot.log(format_exc())