Revision: 24486
Initial Code
Initial URL
Initial Description
Initial Title
Initial Tags
Initial Language
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