Ejemplo n.º 1
0
def codyReload(self, trigger):
	FILE = self.FILE_PATH
	try:
		self.IRC.send ( 'QUIT :terminating..\r\n' )
		#TODO: Parameter to load new cody - stop current, start new cody
		#TODO: do compile check on all modules / also confirm that compileall actually comes back with compiler errors
		#TODO: Change logging path to dropbox folder?
		# call the daemon in a child process independant
		# to avoid killing the thread before it gets a chance to start cody
		def restart_daemon():
			#make sure the parent process has terminated before rebooting cody
			time.sleep(1)
			cmd = ["python", FILE, "restart"]
			pro = Popen(cmd, stdout = PIPE, stderr = PIPE)
			pro.communicate()
			# Terminate child process once complete
			os._exit(1) 

		# kick off the child process
		p = Process(target=restart_daemon)
		p.start()
		# Terminate parent process
		os._exit(1)

	except Exception as e:
		writeError("codyreload in admin.py "+str(e)+" line "+str((sys.exc_info()[2]).tb_lineno))

	"""
Ejemplo n.º 2
0
def codyAction(self, trigger):

	try:
		if len(self.MSG_BODY) > len(trigger + '\r\n'):

			inputstring = self.MSG_BODY.lower().split(" ")
			to_channel	= inputstring[1]
			action_msg	= " ".join(inputstring[2:]).strip("\r\n")

			print to_channel
			print action_msg

			if "#" in to_channel:
				if len(action_msg) > 1:
					try:
						self.IRC.send("PRIVMSG "+to_channel+ " :"+self.ACTIONSTART+action_msg+self.ACTIONEND+"\r\n")
					except Exception as e:
						print e

				else:
					self.IRC.send("PRIVMSG "+self.MSG_CHANNEL+ " :Usage: !cody.action <#channel> <message>\r\n")
			else:
				self.IRC.send("PRIVMSG "+self.MSG_CHANNEL+ " :Usage: !cody.action <#channel> <message>\r\n")

	except Exception as e:
		writeError("cody_Action() in public.py "+str(e)+" line "+str((sys.exc_info()[2]).tb_lineno))
Ejemplo n.º 3
0
def codyGetDefinition(self, trigger):

	try:
		if len(self.MSG_BODY) > len(trigger + '\r\n'):

			word 			= self.MSG_BODY.split()[1]

			url_prefix 		= 'http://dictionary.reference.com/browse/'
			page 			= urlopen(url_prefix + word).read()
			wordtype_start 	= page.find('<span class="pg">') + len('<span class="pg">')
			wordtype_end	= page[wordtype_start:].find('</span>') + wordtype_start
			def_start       = page.find('<meta name="description" content="') + len('<meta name="description" content="')
			def_end			= page.find('See more."/>')

			if def_end < 0:
				self.IRC.send("PRIVMSG "+self.MSG_CHANNEL+ " :" + random.choice(self.CODY_INSULTS) + "\r\n")

			else:

				wordtype 		= page[wordtype_start:wordtype_end].replace(' ', '')
				wordtype 		= wordtype.replace(',', '')
				definition  	= page[def_start:def_end].split(', ')[1]

				self.IRC.send("PRIVMSG "+self.MSG_CHANNEL+ " :" + wordtype + '; ' + definition + "\r\n")

		else:
			self.IRC.send("PRIVMSG "+self.MSG_CHANNEL+ " :Usage: !cody.dict <word to look up>\r\n")

	except Exception as e:
		writeError("cody_GetDefinition() in public.py "+str(e)+" line "+str((sys.exc_info()[2]).tb_lineno))
Ejemplo n.º 4
0
def codyMonitor(self, trigger):

    try:
        if (datetime.datetime.now().second == 59
            ) and self.MONITOR_CHECK != datetime.datetime.now().minute:

            used, total, _, _, _, _ = linux_metrics.mem_stat.mem_stats()
            used = float(used)
            total = float(total)
            output = round(((used / total) * 100), 2)

            if output > 90.0 and self.ALERT_HOUR != datetime.datetime.now(
            ).hour:

                self.IRC.send(
                    "PRIVMSG " + self.HOME_CHANNEL +
                    " :Inveracity, lmn, guys, I think the server is on fire. Memory load is currently at "
                    + str(output) + "%! Maybe restart it or something. \r\n")
                self.ALERT_HOUR = datetime.datetime.now().hour

            self.MONITOR_CHECK = datetime.datetime.now().minute

    except Exception as e:
        writeError("codyMonitor() in passive.py " + str(e) + " line " +
                   str((sys.exc_info()[2]).tb_lineno))
Ejemplo n.º 5
0
def codyName(self, trigger):

	try:
		length 		= random.randint(1,8)
		consonants 	= ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','x','z']
		vowels 		= ['a','e','i','o','u','y']
		word 		= ""
		i 			= 0
		
		while length >= i: 
			intC = random.randint(0,18)
			intV = random.randint(0,5)

			if i%2 != 0:
				word += vowels[intV]

			if i%2 == 0:
				word += consonants[intC]
			i = i+1

		word = word.title()
		
		self.IRC.send("PRIVMSG "+self.MSG_CHANNEL+ " :"+word+"\r\n")

	except Exception as e:
		writeError("cody_Name() in public.py "+str(e)+" line "+str((sys.exc_info()[2]).tb_lineno))
Ejemplo n.º 6
0
def codyQuit(self, trigger):
		
	try:
		self.IRC.send ( 'QUIT :terminating..\r\n' )
		# sys.exit(0) would only kill this particular thread, instead calling os._exit will find the process of the main thread and kill it there
		os._exit(1)

	except Exception as e:
		writeError("codyQuit() in admin.py "+str(e)+" line "+str((sys.exc_info()[2]).tb_lineno))
Ejemplo n.º 7
0
def codyPortscan(self, trigger):

	try:
		if len(self.MSG_BODY) > len(trigger + '\r\n'):
			if "/" not in self.MSG_BODY \
			and "," not in self.MSG_BODY \
			and "-" not in self.MSG_BODY:

				commandinput = self.MSG_BODY.split(' ')
				
				if len(commandinput) == 3:

					ip = str(commandinput[2][:-len('\r\n')])
					port = str(commandinput[1])
					cmd = ["nmap","-PN", "-p", port, ip]

					pro = Popen(cmd, stdout = PIPE, stderr = PIPE)

					output = pro.communicate()

					if output[0]:
						yanked 				= output[0]
						splityank 			= yanked.partition("SERVICE")
						
						print splityank[2]

						if "MAC" in splityank[2]:
							splityankagain 	= splityank[2].partition("MAC")
							result 			= splityankagain[0]
							result 			= result.split()

						else:
							splityankagain 	= splityank[2].partition("Nmap")
							result 			= splityankagain[0]
							
							if result:
								result 		= result.split()

						if len(result) > 0:
							self.IRC.send("PRIVMSG "+self.MSG_CHANNEL+ " :port: "+str(result[0])+" state: "+str(result[1])+"\r\n")

						else:
							self.IRC.send("PRIVMSG "+self.MSG_CHANNEL+ " :no information could be retrieved\r\n")
					else:
							self.IRC.send("PRIVMSG "+self.MSG_CHANNEL+ " :service not available\r\n")
				else:		
							self.IRC.send("PRIVMSG "+self.MSG_CHANNEL+ " :wrong command, try again\r\n")
			else:
							self.IRC.send("PRIVMSG "+self.MSG_CHANNEL+ " :Illegal character detected\r\n")
		else:
							self.IRC.send("PRIVMSG "+self.MSG_CHANNEL+ " :usage: !cody.portscan <portnumber> <ipaddress>\r\n")

	except Exception as e:
		writeError("codyPortscan() in admin.py "+str(e)+" line "+str((sys.exc_info()[2]).tb_lineno))
Ejemplo n.º 8
0
def partChannel(self, trigger):

	try:
		if len(self.MSG_BODY) > len('!cody.join\r\n') \
		and '#' in self.MSG_BODY :
			self.IRC.send 	( 'PRIVMSG '+self.MSG_CHANNEL+' :Leaving channel:'+self.MSG_BODY[len('!cody.part'):]+'\r\n')
			self.IRC.send 	( 'PART '+self.MSG_BODY[len('!cody.part'):]+'\r\n' )
		else:
			self.IRC.send 	('PRIVMSG '+self.MSG_CHANNEL+' :Usage: !cody.part [#channel] ' + '\r\n' )

	except Exception as e:
		writeError("join_Channel() in admin.py "+str(e)+" line "+str((sys.exc_info()[2]).tb_lineno))
Ejemplo n.º 9
0
def codyShorten(self, trigger):

	try:
		if len(self.MSG_BODY) > len(trigger + '\r\n'):

			query = self.MSG_BODY.split(None, 1)[1]
	        short = shorten_url(query)
	        
	        self.IRC.send("PRIVMSG "+self.MSG_CHANNEL+ " :" + short + "\r\n") 

	except Exception as e:
		writeError("codyShorten() in public.py "+str(e)+" line "+str((sys.exc_info()[2]).tb_lineno))
Ejemplo n.º 10
0
def codyGetSynonyms(self, trigger):

	try:
		if len(self.MSG_BODY) > len(trigger + '\r\n'):

			word 			= self.MSG_BODY.split()[1]

			url_prefix		= 'http://thesaurus.com/browse/'
			page 			= urlopen(url_prefix + word).read()

			print 'url = ' + url_prefix + word
			print 'thesaurus results?' + str('no thesaurus results' in page)

			if 'no thesaurus results' in page:
				self.IRC.send("PRIVMSG "+self.MSG_CHANNEL+ " :" + random.choice(self.CODY_INSULTS) + "\r\n")

			else:

				#locate synonyms
				syns_start 		= page.find('<div class="relevancy-list">') + len('<div class="relevancy-list"> ')
				syns_end		= page[syns_start:].find('<div id="filter-0">') + syns_start

				synonyms_list   = page[syns_start:syns_end].split('<span class="text">')

				result_list 	= []

				for synonym in synonyms_list[1:]:

					result_list.append(synonym[:synonym.find('</span>')])

				return_string   = '\"' + word + '\"' + ' has the following synonyms: '
			 
			 	for result in result_list:

			 		if len(result_list) != 10:

				 		if result_list.index(result) != len(result_list) - 1:

				 			return_string += result + ', '

				 		else:

				 			return_string += result


			 	self.IRC.send("PRIVMSG "+self.MSG_CHANNEL+ " :" + return_string + "\r\n")

		else:
			self.IRC.send("PRIVMSG "+self.MSG_CHANNEL+ " :Usage: !cody.thes <word to look up>\r\n")
			
	except Exception as e:
		writeError("cody_GetSynonyms() in public.py "+str(e)+" line "+str((sys.exc_info()[2]).tb_lineno))
Ejemplo n.º 11
0
def hiCody(self, trigger):

	try:
		proximityMaximum = 3

		for trigger in self.CODY_REPLY_TRIGGERS:
			if trigger in self.MSG_BODY.lower()\
			and self.MSG_BODY.lower().find(trigger) < self.MSG_BODY.lower().find('cody')\
			and self.MSG_BODY.lower().find(trigger) + len(trigger) + proximityMaximum >= self.MSG_BODY.lower().find('cody'):
			
				self.IRC.send ( 'PRIVMSG '+self.MSG_CHANNEL+' :'+random.choice(self.CODY_REPLIES)+'\r\n' )

	except Exception as e:
		writeError("hi_Cody() in public.py "+str(e)+" line "+str((sys.exc_info()[2]).tb_lineno))
Ejemplo n.º 12
0
def codyGhost(self, trigger):

	try:		
		if len(self.MSG_BODY) > len(trigger + '\r\n'):

			inputstring = self.MSG_BODY.split(" ")
			newnick	= " ".join(inputstring[1:]).strip("\r\n")

			self.IRC.send("PRIVMSG "+self.NICKSERV_ADRESS+' :ghost '+oldnick+'\r\n')

		else:
			self.IRC.send("PRIVMSG "+self.MSG_CHANNEL+ " :!cody.ghost <ghost nick>\r\n")			

	except Exception as e:
		writeError("codyGhost() in admin.py "+str(e)+" line "+str((sys.exc_info()[2]).tb_lineno))
Ejemplo n.º 13
0
def codyReport(self, trigger):
	bugReportsFile = self.FILE_DIR+"userFeedback/bugReports.txt"
	featureReqFile = self.FILE_DIR+"userFeedback/featureRequests.txt"
	try:
		if len(self.MSG_BODY) > len(trigger + '\r\n'):
		
			codyReport = self.MSG_BODY.split(' ', 1)
			codyReport = codyReport[1]
		
			#OPEN FILES FOR READ AND READ THEM INTO LOCAL
			if 'bug' in trigger:
				readReport = open(bugReportsFile, "r")

			if 'feature' in trigger:
				readReport = open(featureReqFile, "r")
								
			reportData = readReport.read().splitlines()
			startLine  = len(reportData) / 2
			codyReport = str(startLine) + '. ' + codyReport[:-2] + ' [' + self.MSG_NICK + ']' + '\r\n'
			reportData.append(codyReport)
				
			#WRITE STRINGS TO FILES
			if 'bug' in trigger:
				writeReport = open(bugReportsFile, "w")

			if 'feature' in trigger:
				writeReport = open(featureReqFile, "w")

			for element in reportData:

				print>>writeReport, reportData[int(reportData.index(element))]
			

			readReport.close()


			# REPORT THE RESULT TO CHANNEL
			if 'feature' in trigger:
				self.IRC.send ( 'PRIVMSG '+self.MSG_CHANNEL+' :Your feature request has been saved and will be reviewed by my developers.\r\n' )
			elif 'bug' in trigger:
				self.IRC.send ( 'PRIVMSG '+self.MSG_CHANNEL+' :Your bug has been saved and will be reviewed by my developers.\r\n' )
			else:
				self.IRC.send ( 'PRIVMSG '+self.MSG_CHANNEL+' :Usage: !cody.bug [your bug report]\r\n' )

	except Exception as e:
		writeError("cody_Report() in public.py "+str(e)+" line "+str((sys.exc_info()[2]).tb_lineno))
Ejemplo n.º 14
0
def codyImage(self, trigger):

	try:
		if len(self.MSG_BODY) > len(trigger + '\r\n'):

			query = self.MSG_BODY.split(None, 1)[1]
	        search = query.split()
	        search = '%20'.join(map(str, search))
	        url = 'http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=%s&safe=off' % search
	        search_results = urlopen(url)
	        js = json.loads(search_results.read().decode('utf-8'))
	        results = js['responseData']['results']
	        for i in results: rest = i['unescapedUrl']
	        
	        self.IRC.send("PRIVMSG "+self.MSG_CHANNEL+ " :" + rest + "\r\n") 

	except Exception as e:
		writeError("codyImage() in public.py "+str(e)+" line "+str((sys.exc_info()[2]).tb_lineno))
Ejemplo n.º 15
0
def codyConvert(self, trigger):

	try:
		findAmount 			= re.search(r'\d+', self.MSG_BODY)
		findOutputUnit		= re.search(r' in (.+)', self.MSG_BODY.lower())

		#check if any of the regex searches returned None. Calling group() on a variable == None would cause Cody to crash
		if findAmount 	   \
		and findOutputUnit :
		
			#fetch console from MESSAGE to be sent to google
			inputAmount  =  findAmount.group()
			inputUnit 	 =  self.MSG_BODY[findAmount.end() : findOutputUnit.start()]
			outputUnit 	 =  findOutputUnit.group(1)		

			if " " in inputAmount:
				inputAmount = inputAmount.replace(" ","")

			if " " in inputUnit:
				inputUnit = inputUnit.replace(" ","")

			if " " in outputUnit:
				outputUnit = outputUnit.replace(" ","")

			if len(inputUnit) <= 4 \
			and len(outputUnit) <= 4:
				try:
					google			= "https://www.google.com/finance/converter?a="+str(inputAmount)+"&from="+str(inputUnit)+"&to="+str(outputUnit)
					googlereq 		= Request(google)
					googleresult 	= urlopen(googlereq)
					html 			= googleresult.read()
					htmlsplit1 		= html.partition("<span class=bld>")
					outputAmount 	= htmlsplit1[2].partition("</span>")

					if outputAmount[0]:
						self.IRC.send('PRIVMSG '+self.MSG_CHANNEL+' :'+str(inputAmount)+" "+str(inputUnit)+' = '+str(outputAmount[0])+'\r\n' )

				except Exception as e:
					writeError("cody_Convert() in public.py "+str(e)+" line "+str((sys.exc_info()[2]).tb_lineno))
					self.IRC.send('PRIVMSG '+self.MSG_CHANNEL+' :something went wrong\r\n' )

	except Exception as e:
		writeError("cody_Convert() in public.py "+str(e)+" line "+str((sys.exc_info()[2]).tb_lineno))
Ejemplo n.º 16
0
def codyGreeting(self):

    try:
        if  self.HOME_CHANNEL in self.MSG_CHANNEL\
        and 'JOIN' in self.MSG_TYPE\
        and self.BOT_NICKNAME not in self.MSG_NICK:

            try:
                adminNumber = self.ADMIN_NICKS.index(self.MSG_NICK.lower())
                self.IRC.send(
                    'PRIVMSG #code :' +
                    str(random.choice(self.ADMIN_GREETINGS[adminNumber])) +
                    '\r\n')
            except:
                writeError("cody_Greeting in passive.py " + str(e) + " line " +
                           str((sys.exc_info()[2]).tb_lineno))

    except Exception as e:
        writeError("codyGreeting in passive.py " + str(e) + " line " +
                   str((sys.exc_info()[2]).tb_lineno))
Ejemplo n.º 17
0
def codyRoulette(self, trigger):

	try:
		gross = ['afterbirth', 's****a', 'mucus', 'surgery', 'gross', 'hidradinitis suppurativa', 'gore', 'myiasis']
		cute  = ['kitten', 'puppies', 'foal', 'lemur', 'baby giraffe', 'baby elephant', 'baby crocodile', 'baby deer', 'baby hedgehog', 'baby dolphin', 'baby panda', 'cute animal', 'lamb']
		winner = random.choice([gross, cute])
		query  = random.choice(winner)
		search = query.split()
		search = '%20'.join(map(str, search))
		url = 'http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=%s&safe=off' % search
		search_results = urlopen(url)
		js = json.loads(search_results.read().decode('utf-8'))
		results = js['responseData']['results']
		for i in results: rest = i['unescapedUrl']

		short = shorten_url(rest)
		
		self.IRC.send("PRIVMSG "+self.MSG_CHANNEL+ " :" + short + " (POTENTIALLY NSFW)\r\n") 

	except Exception as e:
		writeError("codyImage() in public.py "+str(e)+" line "+str((sys.exc_info()[2]).tb_lineno))
Ejemplo n.º 18
0
def codyGetTitle(self):

	try:
		URLstart = self.MSG_BODY.find("http://")
		URLend   = self.MSG_BODY[URLstart:].find(' ')
		url      = self.MSG_BODY[URLstart:URLend]

		page = '' #empty the variable
		try:
			page  = urlopen(url).read()
			title = page[page.find("<title>")+len("<title>"):page.find('</title>')]
			title = title.strip()
			if len(title) < 50:
				self.IRC.send ( 'PRIVMSG '+self.MSG_CHANNEL+' :'+title+'\r\n')
			else:
				print 'title was too big to post'
					
		except Exception as e:
			writeError("get_title() in home.py "+str(e))
			

	except Exception as e:
		writeError("get_title() in home.py "+str(e))
Ejemplo n.º 19
0
def codyGetTitle(self):

    try:
        URLstart = self.MSG_BODY.find("http://")
        URLend = self.MSG_BODY[URLstart:].find(' ')
        url = self.MSG_BODY[URLstart:URLend]

        page = ''  #empty the variable
        try:
            page = urlopen(url).read()
            title = page[page.find("<title>") +
                         len("<title>"):page.find('</title>')]
            title = title.strip()
            if len(title) < 50:
                self.IRC.send('PRIVMSG ' + self.MSG_CHANNEL + ' :' + title +
                              '\r\n')
            else:
                print 'title was too big to post'

        except Exception as e:
            writeError("get_title() in home.py " + str(e))

    except Exception as e:
        writeError("get_title() in home.py " + str(e))
Ejemplo n.º 20
0
def codyFeeds(self, trigger):

    try:
        #TURN OFF FEEDS
        if '!cody.feeds' in trigger \
        and self.POST_CODY_FEEDS:
            self.POST_CODY_FEEDS = False
            self.IRC.send('PRIVMSG ' + self.MSG_CHANNEL +
                          ' :RSS feeds are now turned off.\r\n')

        #TURN ON FEEDS
        elif '!cody.feeds' in trigger \
        and not self.POST_CODY_FEEDS:
            self.POST_CODY_FEEDS = True
            self.IRC.send('PRIVMSG ' + self.MSG_CHANNEL +
                          ' :RSS feeds are now turned on.\r\n')

    #CHECK FOR NEW DATA 4 TIMES AN HOUR
        elif 'codyFeeds' in trigger \
        and (datetime.datetime.now().minute % 14) == 0 \
        or '!cody.feedme' in trigger:

            #FETCH THE FEEDS AND PREPARE DATA FOR POSTING
            feed = feedparser.parse(self.RSS_FEEDS)

            #SPECIAL EXCEPTION - NYAA.EU
            feedData = {}
            checkfile = open(self.FILE_DIR + "resources/rssFeeds.db",
                             "r").read()
            newData = []

            #FILL A DICTIONARY WITH THE RESULTS OF THE FEEDPARSER.PARSE METHOD
            for item in feed["entries"]:
                feedData[feed["entries"].index(item)] = {}
                feedData[feed["entries"].index(item)]['torrentlink'] = feed[
                    "entries"][feed["entries"].index(item)]["id"]
                feedData[feed["entries"].index(item)]['title'] = feed[
                    "entries"][feed["entries"].index(item)]["title"]
                feedData[feed["entries"].index(item)]['subsFilter'] = feed[
                    "entries"][feed["entries"].index(item)]["tags"][0]["term"]
                feedData[feed["entries"].index(item)]['content'] = feedData[
                    feed["entries"].index(item)]['title'] + " --> " + feedData[
                        feed["entries"].index(item)]['torrentlink']

            #CHECK THE DICTIONARY
            for item in feedData.keys():

                #CREATE A TEMP VARIABLE
                newDataItem = ''

                #THROW OUT NON-ASCII CHARACTERS
                for char in feedData[item]['content']:
                    newDataItem = newDataItem + char.encode('ascii', 'ignore')

                #CHECK FOR AND THROW OUT RESULTS WITH BAD SUBS OR NON-ENGLISH SUBS
                if feedData[item]['subsFilter'] != "English-translated Anime" \
                or  "horrible"  in feedData[item]['title'].lower():
                    feedData.pop(item)

                #COMPARE DICTIONARY TO FILE, CHECK FOR NEW DATA
                elif newDataItem not in checkfile:
                    newData.append(newDataItem)

            #WRITE NEW DATA TO FILE IF IT EXISTS
            if newData:

                #REMAKE THE FILE IF THE FILE NOW EXCEEDS 500 LINES
                if len(checkfile.splitlines()) > 500:
                    with open(self.FILE_DIR + "resources/rssFeeds.db",
                              "w") as feedfile:
                        for item in feedData.keys():
                            feedfile.write('\n')
                            feedfile.write(
                                feedData[item]['content'].encode('utf-8') +
                                '\r\n')

                        feedfile.close()

                #IF NOT, JUST APPEND TO IT
                else:
                    with open(self.FILE_DIR + "resources/rssFeeds.db",
                              "a") as feedfile:
                        for item in newData:
                            feedfile.write('\n')
                            feedfile.write(newData[newData.index(item)] +
                                           '\r\n')

                        feedfile.close()

            #PRINT NEW DATA TO CHANNEL
            for item in newData:

                self.IRC.send('PRIVMSG ' + self.RSS_FEED_CHANNELS + ' :' +
                              newData[newData.index(item)] + '\r\n')
                time.sleep(1.5)

    except Exception as e:
        writeError("codyFeeds() in passive.py " + str(e) + " line " +
                   str((sys.exc_info()[2]).tb_lineno))
Ejemplo n.º 21
0
def codyFileUpdates(self, trigger):

    try:
        if '!cody.updates' in trigger\
        and self.POST_CODY_FILE_UPDATES:
            self.POST_CODY_FILE_UPDATES = False
            self.IRC.send('PRIVMSG ' + self.MSG_CHANNEL +
                          ' :File updates are now turned off.\r\n')

        elif '!cody.updates' in trigger\
        and not self.POST_CODY_FILE_UPDATES:
            self.POST_CODY_FILE_UPDATES = True
            self.IRC.send('PRIVMSG ' + self.MSG_CHANNEL +
                          ' :File updates are now turned on.\r\n')

        elif 'codyFileUpdates' in trigger:

            if (datetime.datetime.now().second % 3) == 0:

                #fetch current file update time - syntax is 'Sun Apr 21 20:24:36 2013'
                lastUpdatedRealTime = time.ctime(
                    os.path.getmtime(self.FILE_PATH))
                lastUpdatedCody = lastUpdatedRealTime.split()

                #fetch last recorded update time
                lastRecorded = open(self.FILE_DIR + "resources/lastupdated.db",
                                    "r")
                lastRecordedCody = lastRecorded.read().split()
                lastRecorded.close()

                #parse recorded time into datetime ints
                if len(lastRecordedCody) == 5:
                    lastRecordedYear = int(lastRecordedCody[4])
                    lastRecordedMonth = int(
                        time.strptime(lastRecordedCody[1], '%b').tm_mon)
                    lastRecordedDay = int(lastRecordedCody[2])
                    lastRecordedTime = lastRecordedCody[3].split(':')
                    lastRecordedHour = int(lastRecordedTime[0])
                    lastRecordedMinute = int(lastRecordedTime[1])
                    lastRecordedSecond = int(lastRecordedTime[2])

                #parse current time into datetime ints
                lastUpdatedYear = int(lastUpdatedCody[4])
                lastUpdatedMonth = int(
                    time.strptime(lastUpdatedCody[1], '%b').tm_mon)
                lastUpdatedDay = int(lastUpdatedCody[2])
                lastUpdatedTime = lastUpdatedCody[3].split(':')
                lastUpdatedHour = int(lastUpdatedTime[0])
                lastUpdatedMinute = int(lastUpdatedTime[1])
                lastUpdatedSecond = int(lastUpdatedTime[2])

                #turn them both into datetime objects
                if len(lastRecordedCody) == 5:
                    lastRecordedCody = datetime.datetime(
                        lastRecordedYear, lastRecordedMonth, lastRecordedDay,
                        lastRecordedHour, lastRecordedMinute,
                        lastRecordedSecond)

                else:
                    lastRecordedCody = datetime.datetime(2000, 1, 1)

                lastUpdatedCody = datetime.datetime(
                    lastUpdatedYear, lastUpdatedMonth, lastUpdatedDay,
                    lastUpdatedHour, lastUpdatedMinute, lastUpdatedSecond)

                #check if it has changed
                if lastRecordedCody < lastUpdatedCody:
                    if self.POST_CODY_FILE_UPDATES:
                        self.IRC.send('PRIVMSG ' + self.HOME_CHANNEL + ' :' +
                                      self.FILE_NAME +
                                      ' has been updated.\r\n')
                    dbWrite = open(self.FILE_DIR + "resources/lastupdated.db",
                                   "w")
                    dbWrite.write(lastUpdatedRealTime)
                    dbWrite.close()

    except Exception as e:
        writeError("codyFileUpdates() in passive.py " + str(e) + " line " +
                   str((sys.exc_info()[2]).tb_lineno))
Ejemplo n.º 22
0
def codyResolve(self, trigger):

	try:

		def iptocountry(ip):

			ipsite 		= "http://ipinfo.io/"
			ipaddress 	= ip
			ipquery 	= ipsite+ipaddress+"/json"

			request 	= Request(ipquery)
			result 		= urlopen(request)
			html 		= result.read()

			country 	= json.loads(html)

			countrycode = country["country"]

			with open(self.FILE_DIR+"resources/countrycodes_JSON.db","r") as countryCodeFile:
				countryCodeJSON = countryCodeFile.read()
			countryCodeFile.close()

			countryresult = json.loads(countryCodeJSON)

			for key, value in countryresult.iteritems():
			    if value == countrycode:
			    	return key

		if len(self.MSG_BODY) > len(trigger + '\r\n'):
			commandinput 	= self.MSG_BODY.split(' ')
			nameToResolve 	= str(commandinput[1][:-len('\r\n')])
			cmd 			= ["host", nameToResolve]
			pro 			= Popen(cmd, stdout = PIPE, stderr = PIPE)
			output			= pro.communicate()

			if output[0]:
				resolvedoutput 	= str(output[0]).split(' ')


				if "not" not in str(output):
					#resolving IP to hostname
					if "pointer" in resolvedoutput[3]:
						hostnameoutput = resolvedoutput[3].replace("pointer", resolvedoutput[4])
						country = iptocountry(nameToResolve)

						print "pointer"
						print str(nameToResolve)
						hostnameoutput = hostnameoutput.split()
					
						self.IRC.send("PRIVMSG "+self.MSG_CHANNEL+ " :"+nameToResolve+" resolved to "+str(hostnameoutput[0])+" in Country: "+country+"\r\n")
					
					#resolving hostname to IP	
					else: 
						newResolve = str(resolvedoutput[3]).split()	
						country = iptocountry(newResolve[0])

						self.IRC.send("PRIVMSG "+self.MSG_CHANNEL+ " :"+nameToResolve+" resolved to "+newResolve[0]+" in Country: "+country+"\r\n")

				else:
					self.IRC.send("PRIVMSG "+self.MSG_CHANNEL+ " :could not resolve "+str(nameToResolve)+"\r\n")
			else:
				self.IRC.send("PRIVMSG "+self.MSG_CHANNEL+ " :"+str(nameToResolve)+" returned an empty string, sorry."+"\r\n")
		else:
			self.IRC.send("PRIVMSG "+self.MSG_CHANNEL+ " :usage: !cody.resolve <hostname.com> or <ipaddress>\r\n")

	except Exception as e:
		writeError("codyResolve() in public.py "+str(e)+" line "+str((sys.exc_info()[2]).tb_lineno))
Ejemplo n.º 23
0
def codyDiag(self, trigger):
	
	msg_channel = self.MSG_CHANNEL #prevent NULL channel by storing the variable locally // Race Condition
	
	try:
		def cpuUsage():
			cpu_pcts = linux_metrics.cpu_stat.cpu_percents(sample_duration=1)
			output = '%.2f%%' % (100 - cpu_pcts['idle']) 
				
			return output

		def memStats():

			used, total, _, _, _, _ = linux_metrics.mem_stat.mem_stats()
			used   = float(used)
			total  = float(total)
			output = str(round(((used / total) * 100),2))

			return output			

		def disk_usage(path):

			st 		= os.statvfs(path)
			free 	= st.f_bavail  * st.f_frsize
			total 	= st.f_blocks  * st.f_frsize
			used 	= (st.f_blocks - st.f_bfree) * st.f_frsize

			total 	= total / (1024*1024)
			free 	= free  / (1024*1024)
			used 	= used  / (1024*1024)

			disk_stats = [total, used, free]

			return disk_stats

		def sys_uptime():
			cmd 	= ["uptime | cut -d ' ' -f 4"]
			pro 	= Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
			output 	= pro.communicate()

			if 'day' in output:
				output	= str(output[0]).split()

			else:
				output = [0]

			return output
		
		diskStats = disk_usage("/")
		cpuStats  = cpuUsage()
		sysUptime = sys_uptime()
		memStats  = memStats()

		if diskStats and cpuStats:
			orange 		= self.ircmsg_Color + self.ircmsg_Orange +" "
			lcyan 		= self.ircmsg_Color + self.ircmsg_LightCyan +" "
			dgreen 		= self.ircmsg_Color + self.ircmsg_DarkGreen +" "
			reset 		= self.ircmsg_Reset +" "
			self.IRC.send("PRIVMSG "+msg_channel+ " :"+ \
														        "Disk capacity: total " + orange +str(diskStats[0])+ "MB "	 +\
														reset + "used " 				+ orange +str(diskStats[1])+ "MB "	 +\
														reset + "free " 				+ orange +str(diskStats[2])+ "MB "	 +\
														reset + "| CPU Usage: " 		+ orange +str(cpuStats)              +\
														reset + "| Memory Usage: " 		+ orange +str(memStats)    + "% "    +\
														reset + "| System uptime: " 	+ orange +str(sysUptime[0])+ " days "+\
														"\r\n")
		else:
			self.IRC.send("PRIVMSG "+msg_channel+ " :An error occured while processing your request\r\n")

	except Exception as e:
		writeError("codyDiag() in admin.py "+str(e)+" line "+str((sys.exc_info()[2]).tb_lineno))
Ejemplo n.º 24
0
def codyTime(self, trigger):

	try:
		if len(self.MSG_BODY) > len(trigger + '\r\n'):

			location 	= self.MSG_BODY[self.MSG_BODY.find('!cody.time ')+len('!cody.time '):-len('\r\n')].title().replace(' ', '_')
			format 		= "%H:%M UTC%z"
			local_time 	= datetime.datetime.now(timezone('UTC'))
			offset 		= ''
			match_found = False
			exceptions  = {'CST':'Central', 'PST':'Pacific', 'MST':'Mountain', 'EST':'Eastern', \
						   'CDT':'UTC-5',   'PDT':'UTC-7',   'MDT':'UTC-6',    'EDT':'UTC-4' }
			zones 		= ['Europe/', 'America/', 'Australia/', 'Pacific/', 'Asia/', 'Africa/', 
						   'US/', 	  'Canada/',  'Atlantic/']



			#MAKE EXCEPTIONS FOR COMMON TIMEZONES WITH WEIRD NAMES
			if location.upper() in exceptions.keys():
				location = exceptions[location.upper()]

			#FIGURE OUT THE CONTINENT BY TRYING THEM ALL
			for zone in zones:

				try:
					converted_time = local_time.astimezone(timezone(zone+location)).strftime(format)
					match_found = True
									
				except:
					continue

				
			if not match_found:
				try:

					#if there's a + in the timezone, remove that stuff before we call pytz. we will be calculating it manually.
					if '+' in location:
						offset = location[location.find('+')+len('+'):]
						offsetType = '+'
						location = location[:location.find('+')].upper()

					elif '-' in location:
						offset = location[location.find('-')+len('-'):]
						offsetType = '-'
						location = location[:location.find('-')].upper()

					else:
						location = location.upper()

					converted_time = local_time.astimezone(timezone(location)).strftime(format)[:-len(' UTC+0100')]
					
					#check if the timezone has an offset (eg: GMT+1)
					if offset:
						
						if '+' in offsetType:
							offset_hours 		= int(converted_time[:len('xx')]) + int(offset)

						elif '-' in offsetType:
							offset_hours 		= int(converted_time[:len('xx')]) - int(offset)

						#check if we've gone over 24 hours
						if offset_hours > 23:
							offset_hours = offset_hours - 24

						#or under 0 hours
						if offset_hours < 0:
							offset_hours = offset_hours + 24
						
						#check if we need to add a 0 to make the number two digits
						if len(str(offset_hours)) < 2:
							offset_hours = '0' + str(offset_hours)

						#add it all together
						converted_time = str(offset_hours) + converted_time[2:]
						location = location + offsetType + str(offset)

				except:
					converted_time = 'not_found'
					location = location.title()

			location = location.replace('_', ' ')

			if 'not_found' not in converted_time:
				self.IRC.send('PRIVMSG '+self.MSG_CHANNEL+' :The current time in '+location+' is '+converted_time+'\r\n' )

			else: 
				self.IRC.send('PRIVMSG '+self.MSG_CHANNEL+' :'+str(location)+' was not found. '+'\r\n' )
			
		else:
			self.IRC.send('PRIVMSG '+self.MSG_CHANNEL+' :Usage: !cody.time [location], or !cody.time [timezone]' + '\r\n' )

	except Exception as e:
		writeError("cody_Time() in public.py "+str(e)+" line "+str((sys.exc_info()[2]).tb_lineno))