Return to Snippet

Revision: 24486
at March 2, 2010 14:34 by andrewkolesnikov


Initial Code
#!/usr/bin/python
# -*- coding: utf-8 -*-
# code by andrewkolesnikov.com
import re
import sys
import time
import random
import feedparser
import logging
from datetime import datetime
from mechanize import Browser

class LJAutoComment:
    def __init__(self, url = 'http://tema.livejournal.com/data/rss', username = '', password = '', comments = [], age_threshold = 0.5, interval= 5, logLevel = logging.DEBUG):
        self.__dry = False
        self.__url = url
        self.__comments = comments
        self.__username = username
        self.__password = password
        self.__age_threshold = age_threshold
        self.__log_filename = '/tmp/posts_' + self.__slugify(url)
        self.__interval = interval
     	logging.basicConfig(level=logLevel)

    def generate_comment(self, entry):	
        comment = random.choice(self.__comments); 
        theID = re.match(r"\D*(\d*).*", entry.link).group(1); 
        return comment + (' <img src="http://andrewkolesnikov.com/img/%s.jpg" >' % int(theID))

    def __call__(self, dry = False):
        self.__dry = dry
        if self.__dry:
            logging.info('Dry-run. Comments will not be posted.')            
            
        logging.info('Fetching RSS feed: ' + self.__url);
        while True:                        
            self.__feed = feedparser.parse(self.__url)
            entry = self.__feed.entries[0]
            if	not entry:
              logging.error('Couldn\'t fetch the RSS feed from %s', self.__url)

            logging.info('Latest entry is: ' + entry['title']);

            if self.is_commentable(entry):
                 logging.info('Entry is commentable.');
                 self.post_comment(entry, self.generate_comment(entry))
                 self.log_write(entry.link)
            else:
                 logging.info('Entry isn\'t commentable. Skipping..');

            logging.info('Sleeping for %d seconds.', self.__interval);
            time.sleep(self.__interval)
        logging.info('Done.');
    
    def is_commentable(self, entry):
        postedHoursAgo = (time.mktime(time.gmtime()) - time.mktime(entry.updated_parsed)) / 3600
        
        logging.info('Entry posted %f hours ago, threshold is %1.2f hours', postedHoursAgo, self.__age_threshold);

        alreadyCommented = self.log_check(entry.link);
        if alreadyCommented:
            logging.info('Already commented on this entry.');
        
        if (postedHoursAgo < self.__age_threshold) and not alreadyCommented:
            return True
        return False

    def post_comment(self, entry, comment):
        br = Browser()
        br.open(entry.link + '?mode=reply')
        br.select_form(nr=0)
        br['usertype'] = ['user']
        br['userpost'] = self.__username
        br['password'] = self.__password
        br['body'] = comment.encode('utf8');

        if not self.__dry:
            logging.info('Posting the comment..')
            br.submit()   
            print br.response()
        else:
            logging.info('Pretending to be posting the comment.. (dry run)')
		
    def log_check(self, link):
        """docstring for log_check"""        
        try:
			log = open(self.__log_filename, 'r+')
			line = 1
			while line:        
				line = log.readline()
				logging.debug('Checking link: %s against %s', link, line);
				if line.find(link) >= 0:
					log.close()
					return True;
			log.close()
        except Exception, e:
            pass
        return False

    def log_write(self, link):
        """docstring for log_write"""
        logging.debug('Writing link: %s to %s', link, self.__log_filename);
        log = open(self.__log_filename, 'w+')
        log.write(link + "
")
        log.close()
        
    def __slugify(self, inStr):
        removelist = ["a", "an", "as", "at", "before", "but", "by", "for","from","is", "in", "into", "like", "of", "off", "on", "onto","per","since", "than", "the", "this", "that", "to", "up", "via","with"];
        for a in removelist:
            aslug = re.sub(r'\b'+a+r'\b','',inStr)
        aslug = re.sub('[^\w\s-]', '', aslug).strip().lower()
        aslug = re.sub('\s+', '-', aslug)
        return aslug

if __name__ == '__main__':
    comments = [u'я подумал тебе стоит начать выкладывать видеопосты. Я уже заебался читать. Второуровневики сосут хуй.', 
				u'послушай сюда. Я отсюда из Бостона вижу недоебит в твоих глазах. Второуровневики сосут хуй.',
				u'тут недавно у кого-то в статусе увидел: Чупа-чупс со вкусом лука, соси и плачь тупая сука) ',
				u'Мне в команду в Бостонский офис нужен iPhone-разработчик. Подскажешь кого-нибудь? Второуровневики сосут хуй.',
				u'Всегда интересно было спросить Второуровневики сосут хуй.',
                u'Я хотел сказать, приду к тебе в ресторан, проебу $100. Просто потому что могу блять. Второуровневики сосут хуй.',
                u'Вот да, как всегда хуйня какая-то. Я бы уже стал выкладывать видеопосты и не ебать читателям мозги. Второуровневики сосут хуй.',
                u'что ты думаешь про грядущую смерть Флеша? Почему начал диверсификацию, доходы упали? Приедешь в Бостон пивом угощу. Второуровневики сосут хуй.']

    engine = LJAutoComment('http://target-blog-name.livejournal.com/data/rss', 'myusername', 'mypassword', comments, 5)
    engine()

Initial URL


Initial Description
This code allows automatically posting comments to LiveJournal to be the first commenter.

Usage: $ python auto-post-comment.py

Initial Title
LiveJournal auto post comments

Initial Tags
python

Initial Language
Python