Advertisement
Cadrin

bot ver. 0.1.0

Feb 11th, 2015
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.70 KB | None | 0 0
  1. #coding=utf-8
  2.  
  3. import requests,re,HTMLParser,shutil,time,datetime,codecs
  4. import models
  5. from time import sleep
  6. from pyquery import PyQuery
  7.  
  8. class MatchManager:
  9.    
  10.     def matcher(self,message_object):
  11.         youtubeResult = None
  12.         youtubeResult = re.search(self.youtubeRe, message_object.message)
  13.         if youtubeResult and message_object.author.rstrip() != "Malbolge":
  14.             return self.youtube(youtubeResult.group(0),message_object)
  15.  
  16.         return False
  17.            
  18.     def youtube(self,url,message):
  19.         headers = {
  20.         'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/37.0.2062.94 Chrome/37.0.2062.94 Safari/537.36'
  21.         }
  22.         if not re.search('(http://)|(https://)', url):
  23.             url = 'http://' + url
  24.         result = requests.get(url, headers=headers)
  25.         document = PyQuery(result.text)
  26.         content_meta = document('meta[itemprop="name"]').attr('content')
  27.         if content_meta:
  28.             ytMsg = message.author + 'has posted a video: ' + content_meta
  29.         else:
  30.             ytMsg = message.author + ', unrecognized video'
  31.         payload = {
  32.             'italic': '1',
  33.             'msg': ytMsg
  34.         }
  35.         return payload
  36.  
  37.     def __init__ (self):
  38.         self.youtubeRe = (
  39.             r'(https?://)?(www\.)?'
  40.             '(youtube|youtu|youtube-nocookie)\.(com|be)/'
  41.             '(watch\?v=|embed/|v/|.+\?v=)?([^&=%\?]{11})'
  42.     )
  43.  
  44.        
  45. class NetworkManager:
  46.     URL_BASE = 'http://forum.rpg-center.pl/index.php'
  47.     LIST_XML = '?action=shoutbox;sa=get;xml;row=0;restart'
  48.     LOGIN_URL = '?action=login2'
  49.  
  50.     def __init__(self):
  51.         self.session = requests.Session()
  52.         self.match_manager = MatchManager()
  53.         self.token = None
  54.         self.h = HTMLParser.HTMLParser()
  55.         self.lineCount = 0
  56.         self.ts = 0
  57.         self.st = "0"
  58.         self.stShortened = "0"
  59.         self.mainLoop()
  60.  
  61.     def logUpdate(self,messages):
  62.         self.lineCount = 0
  63.         with codecs.open('recentlines.txt','r','utf-8') as recentlines:
  64.             linesList = []
  65.             for line in recentlines:
  66.                 linesList.append(line.rstrip())
  67.         with codecs.open('logfile.txt','a','utf-8') as f:
  68.             with codecs.open('recentlines.txt','w','utf-8') as recentlines:
  69.                 for message in messages:
  70.                     if (message.author.rstrip() + " " + message.time + ": " + message.message) not in linesList:
  71.                         self.lineCount += 1
  72.                         self.__findMatches(message)
  73.                         f.write(self.h.unescape(message.author + message.time + ": " + message.message + "\n"))
  74.                     recentlines.write(message.author.rstrip() + " " + message.time + ": " + message.message + "\n")
  75.                     self.updateDate("logfile.txt")
  76.         shutil.copyfile("logfile.txt","E:/Program Files/EasyPHP-Webserver-14.1b2/www/logfile.txt")
  77.  
  78.     def updateDate(self,logfile):
  79.         with open("date.txt","r+") as currDate:
  80.             if currDate.readline() != self.stShortened:
  81.                 with codecs.open(logfile,'a','utf-8') as f:
  82.                     f.write("***Current Date: %s***\n" % self.stShortened)
  83.                 currDate.seek(0,0)
  84.                 currDate.truncate()
  85.                 currDate.write(self.stShortened)
  86.        
  87.     def acquireTime(self):
  88.         self.ts = time.time()
  89.         self.st = datetime.datetime.fromtimestamp(self.ts).strftime("%d-%m-%Y %H:%M:%S")
  90.         self.stShortened = datetime.datetime.fromtimestamp(self.ts).strftime("%d-%m-%Y")
  91.  
  92.     def login(self, username, password):
  93.         formdata = {
  94.             'user': username,
  95.             'passwrd': password,
  96.             'cookielength': '-1'
  97.         }
  98.         response = self.session.post(self.__class__.URL_BASE + self.__class__.LOGIN_URL, data=formdata)
  99.         m = re.search(r"sSessionId: '(?P<sessionToken>.+)'", response.text)
  100.         token = m.group('sessionToken').encode('ascii')
  101.         return token
  102.  
  103.     def __findMatches(self,message):
  104.         matcherResult = self.match_manager.matcher(message)
  105.         if matcherResult:
  106.             self.sendText(matcherResult)
  107.    
  108.     def sendText(self,message):
  109.         self.session.post(self.__class__.URL_BASE + "?action=shoutbox;sa=send;sesc=" + self.token + ";xml;row=99",data=message)
  110.  
  111.     def mainLoop(self):
  112.         self.token = self.login('Malbolge','password')
  113.         self.messages = self.session.get(self.__class__.URL_BASE + self.__class__.LIST_XML)
  114.         self.logFile = models.getMessageList(self.messages.text)
  115.         self.previousResponse = self.messages.text
  116.         self.firstLoop = 1
  117.         self.timer = 0
  118.         while True:
  119.             if self.previousResponse != self.messages.text or self.firstLoop == 1:
  120.                 self.logFile = models.getMessageList(self.messages.text)
  121.                 self.acquireTime()
  122.                 self.logUpdate(self.logFile)
  123.                 if self.lineCount > 1:
  124.                     print "Added %d lines on %s." % (self.lineCount, self.st)
  125.                 elif self.lineCount == 1:
  126.                     print "Added %d line on %s." % (self.lineCount, self.st)
  127.                 self.firstLoop = 0
  128.             for i in range(10):
  129.                 sleep(1) #update once every 10 seconds, "for" loop made in order to
  130.                          #catch keyboard interrupts faster
  131.             self.timer += 1
  132.             if self.timer == 30:
  133.                 self.timer = 0
  134.                 heartbeat = self.session.get(self.__class__.URL_BASE)
  135.             self.previousResponse = self.messages.text
  136.             self.messages = self.session.get(self.__class__.URL_BASE + self.__class__.LIST_XML)
  137.  
  138. m = NetworkManager()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement