Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #coding=utf-8
- import requests,re,HTMLParser,time,datetime,codecs,pastebin_python
- """import shutil #currently being replaced with the pastebin command"""
- import models
- from time import sleep
- from pyquery import PyQuery
- class MatchManager:
- def matcher(self,messageObject):
- youtubeResult = None
- if messageObject.message == "!log" and messageObject.author == "C":
- return self.pastebin()
- youtubeResult = re.search(self.youtubeRe, messageObject.message)
- if youtubeResult and messageObject.author != "Malbolge":
- return self.youtube(youtubeResult.group(0),messageObject)
- return False
- def pastebin(self):
- self.pasteBin.createAPIUserKey(self.pastebinVars["Name"],self.pastebinVars["Pass"])
- lines = codecs.open('logfile.txt','r','utf-8').read()
- response = self.pasteBin.createPaste(lines,"testpaste","","1","1D")
- payload = {
- 'msg': response
- }
- return payload
- def youtube(self,url,message):
- headers = {
- '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'
- }
- if not re.search('(http://)|(https://)', url):
- url = 'http://' + url
- result = requests.get(url, headers=headers)
- document = PyQuery(result.text)
- contentMeta = document('meta[itemprop="name"]').attr('content')
- if contentMeta:
- ytMsg = message.author + ' has posted a video: ' + contentMeta
- else:
- ytMsg = message.author + ', unrecognized video'
- payload = {
- 'italic': '1',
- 'msg': ytMsg
- }
- return payload
- def __init__ (self):
- self.youtubeRe = (
- r'(https?://)?(www\.)?'
- '(youtube|youtu|youtube-nocookie)\.(com|be)/'
- '(watch\?v=|embed/|v/|.+\?v=)?([^&=%\?]{11})'
- )
- self.pastebinVars = open("pastebin.txt","r").read().rsplit()
- self.pastebinVars = {
- "Name" : self.pastebinVars[0],
- "Pass" : self.pastebinVars[1],
- "DevKey" : self.pastebinVars[2]
- }
- self.pasteBin = pastebin_python.PastebinPython(api_dev_key=self.pastebinVars["DevKey"])
- class NetworkManager:
- URL_BASE = 'http://forum.rpg-center.pl/index.php'
- LIST_XML = '?action=shoutbox;sa=get;xml;row=0;restart'
- LOGIN_URL = '?action=login2'
- def __init__(self):
- self.session = requests.Session()
- self.match_manager = MatchManager()
- self.token = None
- self.h = HTMLParser.HTMLParser()
- self.currDate = open("date.txt","r").read()
- self.st = ""
- def getNewMessages(self,messages):
- newMsgs = []
- linesList = codecs.open('recentlines.txt','r','utf-8').read().splitlines()
- with codecs.open('recentlines.txt','w','utf-8') as recentlines:
- for message in messages: recentlines.write(message.author.rstrip() + " " + message.time + ": " + message.message + "\n")
- for message in messages:
- if (message.author.rstrip() + " " + message.time + ": " + message.message) not in linesList:
- newMsgs.append(message)
- return newMsgs
- def login(self, username, password):
- formdata = {
- 'user': username,
- 'passwrd': password,
- 'cookielength': '-1'
- }
- response = self.session.post(self.__class__.URL_BASE + self.__class__.LOGIN_URL, data=formdata)
- m = re.search(r"sSessionId: '(?P<sessionToken>.+)'", response.text)
- token = m.group('sessionToken').encode('ascii')
- return token
- def __findMatches(self,messages):
- for message in messages:
- #turn into a readable format and strip annoying trailing whitespaces ahead of time
- message.author = self.h.unescape(message.author).rstrip()
- matcherResult = self.match_manager.matcher(message)
- if matcherResult:
- self.sendText(matcherResult)
- def __logMessages(self,messages):
- with codecs.open('logfile.txt','a','utf-8') as f:
- for message in messages:
- f.write(self.h.unescape(message.author + message.time + ": " + message.message + "\n"))
- """shutil.copyfile("logfile.txt","E:/Program Files/EasyPHP-Webserver-14.1b2/www/logfile.txt")"""
- def __updateDate(self,logfile):
- ts = time.time()
- self.st = datetime.datetime.fromtimestamp(ts).strftime("%d-%m-%Y %H:%M:%S")
- stShortened = datetime.datetime.fromtimestamp(ts).strftime("%d-%m-%Y")
- if self.currDate != stShortened:
- self.currDate = stShortened
- codecs.open(logfile,'a','utf-8').write("***Current Date: %s***\n" % stShortened)
- open("date.txt","w").write(stShortened)
- def __printMessages(self,messages):
- if len(messages) > 0: print "@ " + self.st + " -",
- if len(messages) <= 5:
- for message in messages: print self.h.unescape(message.author + message.time + ": " + message.message)
- else:
- print "Logged a crapton (" + len(messages) + ") of messages at once!"
- def sendText(self,message):
- self.session.post(self.__class__.URL_BASE + "?action=shoutbox;sa=send;sesc=" + self.token + ";xml;row=99",data=message)
- def mainLoop(self):
- timer = 0
- previousResponse = ""
- while True:
- messagesXML = self.session.get(self.__class__.URL_BASE + self.__class__.LIST_XML).text
- timer += 1
- if previousResponse != messagesXML: #do nothing if there are no new messages
- newMessages = self.getNewMessages(models.getMessageList(messagesXML))
- self.__updateDate("logfile.txt")
- self.__logMessages(newMessages)
- self.__printMessages(newMessages)
- #don't parse messages on the very first loop in case there's been a lot of new matches
- if previousResponse: self.__findMatches(newMessages)
- previousResponse = messagesXML
- for i in range(10):
- sleep(1) #repeat the loop once every 10 seconds
- if timer == 30:
- timer = 0
- 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