Advertisement
Cadrin

bot ver. 0.1.1

Feb 17th, 2015
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.45 KB | None | 0 0
  1. #coding=utf-8
  2.  
  3. import requests,re,HTMLParser,time,datetime,codecs,pastebin_python
  4. """import shutil #currently being replaced with the pastebin command"""
  5. import models
  6. from time import sleep
  7. from pyquery import PyQuery
  8.  
  9. class MatchManager:
  10.    
  11.     def matcher(self,messageObject):
  12.         youtubeResult = None
  13.  
  14.         if messageObject.message == "!log" and messageObject.author == "C":
  15.             return self.pastebin()            
  16.        
  17.         youtubeResult = re.search(self.youtubeRe, messageObject.message)
  18.         if youtubeResult and messageObject.author != "Malbolge":
  19.             return self.youtube(youtubeResult.group(0),messageObject)
  20.  
  21.         return False
  22.  
  23.     def pastebin(self):
  24.         self.pasteBin.createAPIUserKey(self.pastebinVars["Name"],self.pastebinVars["Pass"])
  25.         lines = codecs.open('logfile.txt','r','utf-8').read()
  26.         response = self.pasteBin.createPaste(lines,"testpaste","","1","1D")
  27.         payload = {
  28.             'msg': response
  29.             }
  30.         return payload
  31.        
  32.    
  33.     def youtube(self,url,message):
  34.         headers = {
  35.         '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'
  36.         }
  37.         if not re.search('(http://)|(https://)', url):
  38.             url = 'http://' + url
  39.         result = requests.get(url, headers=headers)
  40.         document = PyQuery(result.text)
  41.         contentMeta = document('meta[itemprop="name"]').attr('content')
  42.         if contentMeta:
  43.             ytMsg = message.author + ' has posted a video: ' + contentMeta
  44.         else:
  45.             ytMsg = message.author + ', unrecognized video'
  46.         payload = {
  47.             'italic': '1',
  48.             'msg': ytMsg
  49.         }
  50.         return payload
  51.  
  52.     def __init__ (self):
  53.         self.youtubeRe = (
  54.             r'(https?://)?(www\.)?'
  55.             '(youtube|youtu|youtube-nocookie)\.(com|be)/'
  56.             '(watch\?v=|embed/|v/|.+\?v=)?([^&=%\?]{11})'
  57.     )
  58.  
  59.         self.pastebinVars = open("pastebin.txt","r").read().rsplit()
  60.         self.pastebinVars = {
  61.             "Name" : self.pastebinVars[0],
  62.             "Pass" : self.pastebinVars[1],
  63.             "DevKey" : self.pastebinVars[2]
  64.             }
  65.         self.pasteBin = pastebin_python.PastebinPython(api_dev_key=self.pastebinVars["DevKey"])
  66.        
  67.        
  68. class NetworkManager:
  69.     URL_BASE = 'http://forum.rpg-center.pl/index.php'
  70.     LIST_XML = '?action=shoutbox;sa=get;xml;row=0;restart'
  71.     LOGIN_URL = '?action=login2'
  72.  
  73.     def __init__(self):
  74.         self.session = requests.Session()
  75.         self.match_manager = MatchManager()
  76.         self.token = None
  77.         self.h = HTMLParser.HTMLParser()
  78.         self.currDate = open("date.txt","r").read()
  79.         self.st = ""
  80.  
  81.     def getNewMessages(self,messages):
  82.         newMsgs = []
  83.         linesList = codecs.open('recentlines.txt','r','utf-8').read().splitlines()
  84.         with codecs.open('recentlines.txt','w','utf-8') as recentlines:
  85.             for message in messages: recentlines.write(message.author.rstrip() + " " + message.time + ": " + message.message + "\n")
  86.         for message in messages:
  87.             if (message.author.rstrip() + " " + message.time + ": " + message.message) not in linesList:
  88.                 newMsgs.append(message)
  89.         return newMsgs
  90.  
  91.     def login(self, username, password):
  92.         formdata = {
  93.             'user': username,
  94.             'passwrd': password,
  95.             'cookielength': '-1'
  96.         }
  97.         response = self.session.post(self.__class__.URL_BASE + self.__class__.LOGIN_URL, data=formdata)
  98.         m = re.search(r"sSessionId: '(?P<sessionToken>.+)'", response.text)
  99.         token = m.group('sessionToken').encode('ascii')
  100.         return token
  101.  
  102.     def __findMatches(self,messages):
  103.         for message in messages:
  104.             #turn into a readable format and strip annoying trailing whitespaces ahead of time
  105.             message.author = self.h.unescape(message.author).rstrip()
  106.             matcherResult = self.match_manager.matcher(message)
  107.             if matcherResult:
  108.                 self.sendText(matcherResult)
  109.                
  110.     def __logMessages(self,messages):
  111.         with codecs.open('logfile.txt','a','utf-8') as f:
  112.             for message in messages:
  113.                 f.write(self.h.unescape(message.author + message.time + ": " + message.message + "\n"))
  114.         """shutil.copyfile("logfile.txt","E:/Program Files/EasyPHP-Webserver-14.1b2/www/logfile.txt")"""
  115.  
  116.     def __updateDate(self,logfile):
  117.         ts = time.time()
  118.         self.st = datetime.datetime.fromtimestamp(ts).strftime("%d-%m-%Y %H:%M:%S")
  119.         stShortened = datetime.datetime.fromtimestamp(ts).strftime("%d-%m-%Y")
  120.         if self.currDate != stShortened:
  121.             self.currDate = stShortened
  122.             codecs.open(logfile,'a','utf-8').write("***Current Date: %s***\n" % stShortened)
  123.             open("date.txt","w").write(stShortened)
  124.  
  125.     def __printMessages(self,messages):
  126.         if len(messages) > 0: print "@ " + self.st + " -",
  127.         if len(messages) <= 5:
  128.             for message in messages: print self.h.unescape(message.author + message.time + ": " + message.message)
  129.         else:
  130.             print "Logged a crapton (" + len(messages) + ") of messages at once!"
  131.    
  132.     def sendText(self,message):
  133.         self.session.post(self.__class__.URL_BASE + "?action=shoutbox;sa=send;sesc=" + self.token + ";xml;row=99",data=message)
  134.  
  135.     def mainLoop(self):
  136.         timer = 0
  137.         previousResponse = ""
  138.         while True:
  139.             messagesXML = self.session.get(self.__class__.URL_BASE + self.__class__.LIST_XML).text
  140.             timer += 1
  141.             if previousResponse != messagesXML: #do nothing if there are no new messages
  142.                 newMessages = self.getNewMessages(models.getMessageList(messagesXML))
  143.                 self.__updateDate("logfile.txt")
  144.                 self.__logMessages(newMessages)
  145.                 self.__printMessages(newMessages)
  146.                 #don't parse messages on the very first loop in case there's been a lot of new matches
  147.                 if previousResponse: self.__findMatches(newMessages)
  148.                 previousResponse = messagesXML
  149.             for i in range(10):
  150.                 sleep(1) #repeat the loop once every 10 seconds
  151.             if timer == 30:
  152.                 timer = 0
  153.                 heartbeat = self.session.get(self.__class__.URL_BASE) #fetch the main page to prevent logging out
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement