def checkMessages(self): if not os.path.exists("modules/data/tell.db"): ## ERRORII TÄHÄ !! return try: nick = self.get_nick() chan = self.msg[2].lstrip(":").strip() db = sqlite3.connect("modules/data/tell.db") cur = db.cursor() cur.execute("""SELECT * FROM tell WHERE nick = ? AND channel = ?""", (nick, chan)) results = cur.fetchall() if results: msgToUser = "******".format(nick) for row in results: if nick in row[1] and chan in row[3]: msgToUser += "[{0} has sent you a message: {1}] ".format( row[2], row[4]) cur.execute("""DELETE FROM tell WHERE id=?""", (row[0], )) db.commit() self.send_chan(msgToUser) else: return db.close() except Exception as e: self.errormsg = "[ERROR]-[tell] checkMessages() stating: {0}".format(e) sysErrorLog.log(self) if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end")))
def ylilauta(self): if len(self.msg) >= 4: url = "http://ylilauta.org/satunnainen/" try: html = syscmd.getHtml(self, url, True) except Exception as e: self.errormsg = "[ERROR]-[ylilauta] ylilauta()(1) stating: {0}".format( e) sysErrorLog.log(self) ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end"))) try: try: soup = BeautifulSoup(html, "lxml") except: soup = BeautifulSoup(html, "html5lib") data = soup.findAll("div", {"class": "postsubject"}) x = random.randrange(0, len(data)) string = "{0}: http:{1}".format(data[x].a.string, data[x].a.get('href')) self.send_chan(' '.join(string.split())) except Exception as e: self.errormsg = "[ERROR]-[ylilauta] ylilauta()(2) stating: {0}".format( e) sysErrorLog.log(self) ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end")))
def nicklList(self): print("[CREATING NAMES LIST]") nickList = [] if "353" in self.msg and self.listNames: ## ## Parse and create a nicklist ## try: index = self.msg.index("353") for i in range(index + 4, len(self.msg)): if "\r\n" in self.msg[i]: lastNick = self.msg[i].split("\r\n") nickList.append(lastNick[0]) return else: nickList.append(self.msg[i].strip(":")) except Exception as e: ## We dont bother to user if self.config["debug"] is on or not.. ## obviously it's OFF at this poinst self.errormsg = "[ERROR]-[userOutput] nickList() stating: {0}".format( e) sysErrorLog.log(self) finally: return (nickList)
def logger_daemon(self): usertxt = "" chanVerified = False chan = "" #Checking if log-path in config is valid and exists if os.path.exists(self.config["log-path"]): if len(self.msg) >= 4: #No logging if matching code received from the server if self.msg[1] in self.irc_codes: return else: #Looking brackets from the config file brackets = self.config["TimestampBrackets"].split(",") ## Checking if the channel is present if self.msg[2].lstrip(":").rstrip("\r\n")[0] == "#": chanVerified = True if chanVerified: chan = self.msg[2].lstrip(":").rstrip("\r\n") #Creating the string of text starting from the user output in console for i in range(3, len(self.msg)): usertxt += self.msg[i] + " " if chan: log = self.config["log-path"] + chan + ".log" #1-3 timestamp with brackets, 3 nick, 4 channel, 5 the message logline = "{0}{1}{2} {3} @ {4} >> {5}".format( brackets[0], strftime(self.config["timeformat"]), brackets[1], self.get_nick(), chan, usertxt.rstrip(" ")[1:]) with open( log, "a" ) as log: #Opening the log and appending the latest result log.write(logline) log.flush() else: try: self.errormsg = "[NOTICE]-[logger_daemon] Cannot find existing folder for logs, creating: {0}".format( self.config["log-path"]) sysErrorLog.log(self) if self.config[ "debug"]: #If the path set in config doesn't exist, create one print("{0}{1}{2}".format(self.color("blue"), self.errormsg, self.color("end"))) os.mkdir(self.config["log-path"]) except Exception as e: self.errormsg = "[ERROR]-[logger_daemon] logger_daemon() stating: {0}".format( e) sysErrorLog.log(self) ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end")))
def currency( self ): if len(self.msg) < 7: self.send_chan("Usage: !currency <amount> <from> <to>") if len(self.msg) == 7: try: amount = Decimal(re.sub(",", ".", self.msg[4])).quantize(Decimal("0.00")) except Exception as e: amount = Decimal(1.00) frm = self.msg[5].upper() to = self.msg[6].upper() ## If first value is float and currencies are valid if isinstance( amount, Decimal ) and syscmd.checkCurrency( frm, to): frm = urllib.parse.quote(frm) to = urllib.parse.quote(to) url = "https://www.google.com/finance/converter?a={0}&from={1}&to={2}".format(amount, frm, to) html = syscmd.getHtml(self, url, True) try: soup = BeautifulSoup(html) result = soup.findAll("span", {"class" : "bld"}) ## If there's a result, then send it to the chan if result: result = "{0} {1} = {2}".format(amount, frm.upper(), result[0]) trimmed = re.sub('<[^<]+?>', '', result) self.send_chan(trimmed) else: self.send_chan("Google failed to convert your request :(") except Exception as e: self.errormsg = "[ERROR]-[Currency] stating: {0}".format(e) sysErrorLog.log( self ) ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end"))) else: self.send_chan("Usage: !currency <amount> <from> <to>")
def wikiSearch(self): Cache.dataCache = [] Cache.dataIndex = 0 parameters = "" length = len(self.msg) for x in range(5, length): parameters += "{0} ".format(self.msg[x]) parameters_url = urllib.parse.quote(parameters.strip()) url = "http://{0}.m.wikipedia.org/w/index.php?search={1}&fulltext=Search".format(Cache.lang, parameters_url) try: html = syscmd.getHtml(self, url, True) except Exception as e: self.errormsg = "[ERROR]-[wiki] wikiSearch()(1) stating: {0}".format(e) sys.error_log.log(self) if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end"))) try: soup = BeautifulSoup(html) if len(soup.findAll("p", {"class": "mw-search-nonefound"})) == 0: Cache.dataCache = soup.findAll("div", {"class": "mw-search-result-heading"}) output = "{0}: http://{1}.wikipedia.org{2}".format( Cache.dataCache[Cache.dataIndex].a.get("title"), Cache.lang, Cache.dataCache[Cache.dataIndex].a.get("href"), ) self.send_chan(output) Cache.dataIndex += 1 else: self.send_chan("There were no results matching the query.") except Exception as e: self.errormsg = "[ERROR]-[wiki] wikiSearch()(2) stating: {0}".format(e) sysErrorLog.log(self) ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end")))
def getCity ( self ): nick = self.get_nick() try: db = sqlite3.connect("modules/data/fmiCities.db") cursor = db.cursor() ## Check if the city is saved in the db cursor.execute(""" SELECT city FROM nicks WHERE nick=? COLLATE NOCASE """, (nick.strip(),)) try: city = cursor.fetchone()[0] except TypeError: city = None return(city) except Exception as e: db.rollback() self.errormsg = "[ERROR]-[fmi] getCity() stating: {0}".format(e) sysErrorLog.log() ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end"))) raise e finally: db.close()
def userVisitedChannel( self, nick ): if not os.path.exists(self.config["log-path"]+"seen.db"): self.send_chan("Logging is not enabled and seendb is not running, check your config!!!") return else: try: db = sqlite3.connect(self.config["log-path"]+"seen.db") cur = db.cursor() cur.execute("""SELECT nick FROM seendb WHERE nick = ? GROUP BY nick""",(nick,)) try: result = cur.fetchone()[0] return(True) except TypeError: return(False) db.close() except Exception as e: self.errormsg = "[ERROR]-[syscmd] userVisitedChannel() stating: {0}".format(e) sysErrorLog.log ( self ) if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end"))) raise e
def title ( self, url ): if re.match("(?:[Hh]?[Tt]?[Tt]?[Pp])?(?:[sS]?)://(localhost|127.0.0.1|0.0.0.0)", url): return url = syscmd.replaceUmlauts(url) url = url.strip().rstrip(".") ## Until I figure out something better... if "http://t.co" in url.strip(): html = syscmd.getHtml( self, url, False, True ) else: html = syscmd.getHtml( self, url, True, True ) if html: try: try: soup = BeautifulSoup(html, "lxml") except: soup = BeautifulSoup(html, "html.parser") #else: # soup = BeautifulSoup(html, "html5lib") #broken!! ## We only want to parse the title if it has been found if soup.title: title = soup.title.string title = re.sub("\n", "", title) self.send_chan( "~ " + ' '.join(title.split()) ) ##Split words and join them with space else: self.send_chan( "~ Untitled" ) except Exception as e: self.errormsg = "[ERROR]-[title] title() stating: {0} ({1})".format(e, url) sysErrorLog.log( self ) ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end"))) else: return
def checkMessages( self ): if not os.path.exists("modules/data/tell.db"): ## ERRORII TÄHÄ !! return try: nick = self.get_nick() chan = self.msg[2].lstrip(":").strip() db = sqlite3.connect("modules/data/tell.db") cur = db.cursor() cur.execute("""SELECT * FROM tell WHERE nick = ? AND channel = ?""",(nick,chan)) results = cur.fetchall() if results: msgToUser = "******".format(nick) for row in results: if nick in row[1] and chan in row[3]: msgToUser += "[{0} has sent you a message: {1}] ".format(row[2] ,row[4]) cur.execute("""DELETE FROM tell WHERE id=?""",(row[0],)) db.commit() self.send_chan(msgToUser) else: return db.close() except Exception as e: self.errormsg = "[ERROR]-[tell] checkMessages() stating: {0}".format(e) sysErrorLog.log ( self ) if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end")))
def geo(self): if len(self.msg) == 4: self.send_chan("Usage: !geo <ip/host>") else: try: data = json.loads( urllib.request.urlopen("http://ip-api.com/json/{0}".format( self.msg[4])).read().decode("utf-8")) if data["status"] == "fail": return else: shortened = urllib.request.urlopen( "http://is.gd/create.php?format=simple&url={0}".format( urllib.parse.quote( "https://www.google.com/maps?q={0},{1}&output=classic" .format(data["lat"], data["lon"])))).read().decode("utf-8") self.send_chan( ("IP: {0} ISP: {1} COUNTRY: {2} MAP: {3}".format( data["query"], data["isp"], data["country"], shortened))) except Exception as e: self.errormsg = "[ERROR]-[geo] geo() stating: {0}".format(e) sysErrorLog.log(self) ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end")))
def delHtml( html ): try: html = re.sub('<[^<]+?>', '', html) return(html) except Exception as e: self.errormsg = "[ERROR]-[syscmd] delHtml() stating: {0}".format(e) sysErrorLog.log() ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end")))
def seendb(self): #Checking if log-path in config is valid and exists (path is generated in logger_daemon.py) if os.path.exists(self.config["log-path"]): #Recording only if server sends more than 5 parameters (0,1,2,3,4,5) etc... if len(self.msg) >= 4: #do nothing if server sends any of these parameters if self.msg[1] in self.irc_codes or "NOTICE" in self.msg[ 1] or "MODE" in self.msg[1]: return else: try: seendb = self.config["log-path"] + "seen.db" timestamp = int(time.time()) nick = self.get_nick() chan = self.msg[2].strip() usertxt = "" for i in range(3, len(self.msg)): usertxt += "{0} ".format(self.msg[i]) #usertxt = re.sub(r'\\n|\\r|\\t','', usertxt) usertxt = usertxt[1:] db = sqlite3.connect(seendb) cur = db.cursor() cur.execute("""SELECT id FROM seendb WHERE nick = ?""", (nick, )) try: resultId = cur.fetchone()[0] except TypeError: resultId = None if resultId: cur.execute( """UPDATE seendb SET channel = ?,time = ?, usertxt = ? WHERE id = ?""", (chan, timestamp, usertxt, resultId)) db.commit() else: cur.execute( """INSERT INTO seendb(nick,channel,time,usertxt) VALUES(?,?,?,?)""", (nick, chan, timestamp, usertxt)) db.commit() except Exception as e: self.errormsg = "[ERROR]-[seendb] seendb() stating: {0}".format( e) sysErrorLog.log(self) ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end"))) finally: db.close()
def git(self): if self.get_host() not in self.config["opers"]: self.errormsg = "[NOTICE]-[git] Unauthorized git reguest from {0}".format(self.get_host()) sysErrorLog.log( self ) return try: PIPE = subprocess.PIPE process = subprocess.Popen(['git', 'pull'], stdout=PIPE, stderr=PIPE) stdoutput, stderroutput = process.communicate() if self.config["debug"]: print(stdoutput.decode("utf-8")) print(stderroutput.decode("utf-8")) if "fatal" in stdoutput.decode("utf-8"): self.send_chan("Git pull failed!") elif "Already up-to-date." in stdoutput.decode("utf-8"): self.send_chan("Already up-to-date!") self.activitymsg = "git: Already up-to-date!" sysErrorLog.activity ( self ) syscmd.fileLatestCommit(self,syscmd.getCommits(self)) elif "overwritten by merge" in stderroutput.decode("utf-8"): self.send_chan("There was a conflict during merge! Please solve manually!") elif "pyBot.py" in stdoutput.decode("utf-8"): self.send_chan("Pull succeeded, core updated, restarting!") self.activitymsg = "git: Pull succeeded, core updated!" sysErrorLog.activity ( self ) syscmd.fileLatestCommit(self,syscmd.getCommits(self)) self.restart() elif "pyBotCore.py" in stdoutput.decode("utf-8"): self.send_chan("Pull succeeded, core updated, restarting!") self.activitymsg = "git: Pull succeeded, core updated!" sysErrorLog.activity ( self ) syscmd.fileLatestCommit(self,syscmd.getCommits(self)) self.restart() elif "create mode" in stdoutput.decode("utf-8"): mods = re.findall(r"\create mode 100644 modules/(.*.py)", stdoutput.decode("utf-8")) modules = "" for x in mods: modules += "{0} ".format(x[:-3]) self.load(x[:-3]) syscmd.fileLatestCommit(self,syscmd.getCommits(self)) else: self.send_chan("Pull succeeded, remember to reload the modules!") self.activitymsg = "git: Pull succeeded!" sysErrorLog.activity ( self ) syscmd.fileLatestCommit(self,syscmd.getCommits(self)) except Exception as e: self.errormsg = "[ERROR]-[git] git() stating: {0}".format(e) sysErrorLog.log( self ) ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end")))
def logger_daemon ( self ): usertxt = "" chanVerified = False chan = "" #Checking if log-path in config is valid and exists if os.path.exists(self.config["log-path"]): if len(self.msg) >= 4: #No logging if matching code received from the server if self.msg[1] in self.irc_codes: return else: #Looking brackets from the config file brackets = self.config["TimestampBrackets"].split(",") ## Checking if the channel is present if self.msg[2].lstrip(":").rstrip("\r\n")[0] == "#": chanVerified = True if chanVerified: chan = self.msg[2].lstrip(":").rstrip("\r\n") #Creating the string of text starting from the user output in console for i in range(3, len(self.msg)): usertxt += self.msg[i]+" " if chan: log = self.config["log-path"]+chan+".log" #1-3 timestamp with brackets, 3 nick, 4 channel, 5 the message logline = "{0}{1}{2} {3} @ {4} >> {5}".format( brackets[0], strftime(self.config["timeformat"]), brackets[1], self.get_nick(), chan, usertxt.rstrip(" ")[1:]) with open(log, "a") as log: #Opening the log and appending the latest result log.write(logline) log.flush() else: try: self.errormsg = "[NOTICE]-[logger_daemon] Cannot find existing folder for logs, creating: {0}".format(self.config["log-path"]) sysErrorLog.log( self ) if self.config["debug"]: #If the path set in config doesn't exist, create one print("{0}{1}{2}".format(self.color("blue"), self.errormsg, self.color("end"))) os.mkdir(self.config["log-path"]) except Exception as e: self.errormsg = "[ERROR]-[logger_daemon] logger_daemon() stating: {0}".format(e) sysErrorLog.log( self ) ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end")))
def ipv6Connectivity( self ): have_ipv6 = True s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) try: s.connect(('2a00:1450:400f:802::1000', 80)) ## Tries to establish an ipv6 connection to google.com in port 80 s.close() except Exception as e: self.errormsg = "[ERROR]-[ipv6Connectivity] stating: {0}".format(e) sysErrorLog.log ( self ) if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end"))) have_ipv6 = False return have_ipv6
def seendb ( self ): #Checking if log-path in config is valid and exists (path is generated in logger_daemon.py) if os.path.exists(self.config["log-path"]): #Recording only if server sends more than 5 parameters (0,1,2,3,4,5) etc... if len(self.msg) >= 4: #do nothing if server sends any of these parameters if self.msg[1] in self.irc_codes or "NOTICE" in self.msg[1] or "MODE" in self.msg[1]: return else: try: seendb = self.config["log-path"]+"seen.db" timestamp = int(time.time()) nick = self.get_nick() chan = self.msg[2].strip() usertxt = "" for i in range(3, len(self.msg)): usertxt += "{0} ".format(self.msg[i]) #usertxt = re.sub(r'\\n|\\r|\\t','', usertxt) usertxt = usertxt[1:] db = sqlite3.connect(seendb) cur = db.cursor() cur.execute("""SELECT id FROM seendb WHERE nick = ?""",(nick,)) try: resultId = cur.fetchone()[0] except TypeError: resultId = None if resultId: cur.execute("""UPDATE seendb SET channel = ?,time = ?, usertxt = ? WHERE id = ?""", (chan,timestamp,usertxt,resultId)) db.commit() else: cur.execute("""INSERT INTO seendb(nick,channel,time,usertxt) VALUES(?,?,?,?)""", (nick,chan,timestamp,usertxt)) db.commit() except Exception as e: self.errormsg = "[ERROR]-[seendb] seendb() stating: {0}".format(e) sysErrorLog.log( self ) ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end"))) finally: db.close()
def getCommits( self ): url = "https://github.com/jasuka/pyBot" html = getHtml(self, url, True) result = "" try: soup = BeautifulSoup(html) span = soup.findAll("span", {"class" : "num"} ) result = "{0}".format(span[0]) result = delHtml(result) return(result.strip()) except Exception as e: self.errormsg = "[ERROR]-[syscm] getCommits() stating: {0}".format(e) sysErrorLog.log ( self.errormsg ) pass
def createCommitsDatabase( self ): try: db = sqlite3.connect("sysmodules/data/commits.db") cur = db.cursor() cur.execute("""DROP TABLE IF EXISTS commits""") cur.execute("""CREATE TABLE IF NOT EXISTS commits(id INTEGER PRIMARY KEY NOT NULL, rev INTEGER)""") db.commit() except Exception as e: db.rollback() self.errormsg = "[ERROR]-[syscmd] createCommitsDatabase() stating: {0}".format(e) sysErrorLog.log ( self ) if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end"))) raise e finally: db.close() return True
def youtubeSearch(self): try: Cache.dataCache = [] Cache.dataIndex = 0 parameters = "" length = len(self.msg) for x in range(4, length): parameters += "{0} ".format(self.msg[x]) parameters_url = urllib.parse.quote(parameters.strip()) url = "http://m.youtube.com/results?search_query={0}".format( parameters_url) html = syscmd.getHtml(self, url, True) except: self.errormsg = "[ERROR]-[youtube] youtubeSearch()(1) Someting went wrong getting the html" sysErrorLog.log(self) ## Log the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end"))) try: urls = "" try: soup = BeautifulSoup(html, "lxml") except: soup = BeautifulSoup(html, "html5lib") Cache.dataCache = soup.findAll("a", {"class": "yt-uix-tile-link"}) if len(Cache.dataCache) > 0: string = "{1}: http://youtube.com/watch?v={0}".format( Cache.dataCache[Cache.dataIndex].get('href')[-11:], Cache.dataCache[Cache.dataIndex].string) self.send_chan(string) Cache.dataIndex += 1 else: self.send_chan("No results for: {0}".format(parameters)) except Exception as e: self.errormsg = "[ERROR]-[youtube] youtubeSearch()(2) stating: {0}".format( e) sysErrorLog.log(self) ## Log the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end")))
def isup(self): if len(self.msg) == 4: self.send_chan("Usage: !isup http://www.domain.com") else: try: url = self.msg[4].strip() if "http://" not in url and "https://" not in url: url = "http://" + url if urllib.request.urlopen("{}".format(url), None, 5).getcode() == 200: self.send_chan("The site {0} seems to be up!".format(url)) else: self.send_chan("The site {0} seems to be down!".format(url)) except Exception as e: self.send_chan("The site {0} seems to be down!".format(url)) self.errormsg = "[ERROR]-[isup] isup() stating: {0}".format(e) sysErrorLog.log(self) ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end")))
def gt(self): if len(self.msg) == 4: self.send_chan("Usage: !gt <from> <to> <word/sentence>") else: try: parameters = "" frm = self.msg[4].strip() to = self.msg[5].strip() length = len(self.msg) for x in range(6, length): parameters += "{0} ".format(self.msg[x]) parameters_url = urllib.parse.quote(parameters.strip()) url = "http://translate.google.com/m?hl={0}&sl={1}&ie=UTF-8&q={2}".format( to, frm, parameters_url) html = syscmd.getHtml(self, url, True) except: self.errormsg = "[NOTICE]-[gt] Something went wrong getting the html" sysErrorLog.log(self) if self.config["debug"]: print("{0}{1}{2}".format(self.color("blue"), self.errormsg, self.color("end"))) try: try: soup = BeautifulSoup(html, "lxml") except: soup = BeautifulSoup(html, "html.parser") #else: # soup = BeautifulSoup(html, "html5lib") Umlauts Broken! ## Get the translation data = soup.findAll("div", {"class": "t0"}) if data: self.send_chan(data[0].string.strip()) else: return except Exception as e: self.errormsg = "[ERROR]-[gt] gt() stating: {0}".format(e) sysErrorLog.log(self) ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end")))
def isup (self): if len(self.msg) == 4: self.send_chan("Usage: !isup http://www.domain.com") else: try: url = self.msg[4].strip() if "http://" not in url and "https://" not in url: url = "http://" + url if urllib.request.urlopen("{}".format(url), None, 5).getcode() == 200: self.send_chan("The site {0} seems to be up!".format(url)) else: self.send_chan("The site {0} seems to be down!".format(url)) except Exception as e: self.send_chan("The site {0} seems to be down!".format(url)) self.errormsg = "[ERROR]-[isup] isup() stating: {0}".format(e) sysErrorLog.log( self ) ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end")))
def createSeenDatabase( self ): try: db = sqlite3.connect(self.config["log-path"]+"seen.db") cursor = db.cursor() cursor.execute("""DROP TABLE IF EXISTS seendb""") cursor.execute("""CREATE TABLE IF NOT EXISTS seendb(id INTEGER PRIMARY KEY NOT NULL, nick TEXT, channel TEXT, time TEXT, usertxt TEXT)""") db.commit() except Exception as e: db.rollback() self.errormsg = "[ERROR]-[syscmd] createSeenDataBase() stating: {0}".format(e) sysErrorLog.log ( self ) if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end"))) raise e finally: db.close() return True
def modecheck ( self ): try: chan = self.msg[2].lstrip(":") db = sqlite3.connect("modules/data/automodes.db") cursor = db.cursor() cursor.execute("""SELECT identhost, channel, mode FROM automodes WHERE identhost = ? AND channel = ? """,(self.get_host(),chan.strip(),)) result = cursor.fetchone() if result and result[1] in self.msg[2].lstrip(":"): if result[2] == "av": self.send_data("MODE {0} +v {1}".format(result[1], self.get_nick())) else: self.send_data("MODE {0} +o {1}".format(result[1], self.get_nick())) except Exception as e: self.errormsg = "[ERROR]-[syscmd] modecheck() stating: {0}".format(e) sysErrorLog.log (self) if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end"))) raise e
def googleSearch(self): try: Cache.dataCache = [] Cache.dataIndex = 0 parameters = "" length = len(self.msg) for x in range(4, length): parameters += "{0} ".format(self.msg[x]) parameters_url = urllib.parse.quote(parameters.strip()) url = "https://www.google.fi/search?q={0}".format(parameters_url) html = syscmd.getHtml(self, url, True) except: self.errormsg = "[NOTICE]-[google] googleSearch()(1) Something went wrong getting the html" sysErrorLog.log(self) if self.config["debug"]: print("{0}{1}{2}".format(self.color("blue"), self.errormsg, self.color("end"))) try: try: soup = BeautifulSoup(html, "lxml") except: soup = BeautifulSoup(html, "html5lib") Cache.dataCache = soup.findAll("h3", {"class": "r"}) if len(Cache.dataCache) > 0: title = "{0}".format(Cache.dataCache[Cache.dataIndex].a) title = syscmd.delHtml(title) string = "{0}: {1}".format( title, Cache.dataCache[Cache.dataIndex].a.get('href')) self.send_chan(string) Cache.dataIndex += 1 else: self.send_chan("No results for: {0}".format(parameters)) except Exception as e: self.errormsg = "[ERROR]-[google] googleSearch()(2) stating: {0}".format( e) sysErrorLog.log(self) ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end")))
def setCity ( self, city ): nick = self.get_nick() city = city.title().strip() try: db = sqlite3.connect("modules/data/fmiCities.db") cursor = db.cursor() ## Check if nick is in the db cursor.execute(""" SELECT id FROM nicks WHERE nick=? """, (nick.strip(),)) try: nickId = cursor.fetchone()[0] except TypeError: nickId = None ## If a nick is found, update the row if nickId: cursor.execute(""" UPDATE nicks SET city=? WHERE id=? """, (city, nickId)) db.commit() return(True) ## If not found, insert it else: cursor.execute(""" INSERT INTO nicks(nick, city) VALUES(?, ?) """, (nick.strip(), city)) db.commit() return(True) except Exception as e: db.rollback() self.errormsg = "[ERROR]-[fmi] setCity() stating: {0}".format(e) sysErrorLog.log() ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end"))) raise e finally: db.close()
def getHtml( self, url, useragent, title = False): try: cookies = http.cookiejar.CookieJar() opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookies)) if useragent: headers = { 'User-Agent' : 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)' } req = urllib.request.Request(url, None, headers) else: req = urllib.request.Request(url, None) ## We check that the url is text/html, else we return None, without fetching the data if title: response = urllib.request.urlopen(req) if "text/html" in response.info()['content-type']: html = opener.open(req) return(html) else: return(None) else: html = opener.open(req) return(html) except urllib.error.URLError as e: if e.reason == "Forbidden": self.send_chan("~ Forbidden") self.errormsg = "[ERROR]-[syscmd] getHtml() stating: Forbidden {0}".format(url) elif "infinite loop" in e.reason: self.send_chan("~ The site is causing an infinite redirect loop") self.errormsg = "[ERROR]-[syscmd] getHtml() stating: site is causing an infinite redirect loop {0}".format(url) elif "Bad Request" in e.reason: self.send_chan("~ Bad Request") self.errormsg = "[ERROR]-[syscmd] getHtml() stating: Bad Request {0}".format(url) #else: # self.send_chan("~ Couldn't resolve host") # self.errormsg = "[ERROR]-[syscmd] getHtml() stating: Couldn't resolve host {0}".format(url) sysErrorLog.log ( self, False ) ## LOG the error return(None) except Exception as e: self.errormsg = "[ERROR]-[syscmd] getHtml() stating: {0}".format(e) sysErrorLog.log ( self ) ## LOG the error self.send_chan( "~ {0}".format(e)) return(None)
def fap(self): if len(self.msg) >= 4: if len(self.msg) == 4: page = random.randrange(1,6000) url = "http://www.p**n.com/videos.html?p={0}".format(page) elif len(self.msg) > 4: parameters = "" for x in range (4, len(self.msg)): parameters += "{0} ".format(self.msg[x]) parameters_url = urllib.parse.quote(parameters.strip()) url = "http://www.p**n.com/search.html?q={0}".format(parameters_url) try: html = syscmd.getHtml(self, url, True ) except Exception as e: self.errormsg = "[ERROR]-[fap] fap()(1) stating: {0}".format(e) sysErrorLog.log( self ) ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end"))) if html: try: try: soup = BeautifulSoup(html, "lxml") except: soup = BeautifulSoup(html, "html.parser") data = soup.findAll("a", {"class" : "title"}) if len(data) > 0: x = random.randrange(0,len(data)) string = "{0}: http://www.p**n.com{1}".format(data[x].get('title'), data[x].get('href')) self.send_chan(' '.join(string.split())) else: self.send_chan("No results for: {0}".format(parameters)) except Exception as e: print(e) self.errormsg = "[ERROR]-[fap] fap()(2) stating: {0}".format(e) sysErrorLog.log( self ) ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end"))) else: self.send_chan("No results for: {0}".format(parameters))
def gt(self): if len(self.msg) == 4: self.send_chan("Usage: !gt <from> <to> <word/sentence>") else: try: parameters = "" frm = self.msg[4].strip() to = self.msg[5].strip() length = len(self.msg) for x in range (6, length): parameters += "{0} ".format(self.msg[x]) parameters_url = urllib.parse.quote(parameters.strip()) url = "http://translate.google.com/m?hl={0}&sl={1}&ie=UTF-8&q={2}".format(to, frm, parameters_url) html = syscmd.getHtml(self, url, True ) except: self.errormsg = "[NOTICE]-[gt] Something went wrong getting the html" sysErrorLog.log( self ) if self.config["debug"]: print("{0}{1}{2}".format(self.color("blue"), self.errormsg, self.color("end"))) try: try: soup = BeautifulSoup(html, "lxml") except: soup = BeautifulSoup(html, "html.parser") #else: # soup = BeautifulSoup(html, "html5lib") Umlauts Broken! ## Get the translation data = soup.findAll("div", {"class" : "t0"}) if data: self.send_chan(data[0].string.strip()) else: return except Exception as e: self.errormsg = "[ERROR]-[gt] gt() stating: {0}".format(e) sysErrorLog.log( self ) ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end")))
def youtubeSearch(self): try: Cache.dataCache = [] Cache.dataIndex = 0 parameters = "" length = len(self.msg) for x in range (4, length): parameters += "{0} ".format(self.msg[x]) parameters_url = urllib.parse.quote(parameters.strip()) url = "http://m.youtube.com/results?search_query={0}".format(parameters_url) html = syscmd.getHtml(self, url, True ) except: self.errormsg = "[ERROR]-[youtube] youtubeSearch()(1) Someting went wrong getting the html" sysErrorLog.log( self ) ## Log the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end"))) try: urls = "" try: soup = BeautifulSoup(html, "lxml") except: soup = BeautifulSoup(html, "html5lib") Cache.dataCache = soup.findAll("a", {"class" : "yt-uix-tile-link"}) if len(Cache.dataCache) > 0: string = "{1}: http://youtube.com/watch?v={0}".format( Cache.dataCache[Cache.dataIndex].get('href')[-11:], Cache.dataCache[Cache.dataIndex].string) self.send_chan(string) Cache.dataIndex += 1 else: self.send_chan("No results for: {0}".format(parameters)) except Exception as e: self.errormsg = "[ERROR]-[youtube] youtubeSearch()(2) stating: {0}".format(e) sysErrorLog.log ( self ) ## Log the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end")))
def geo (self): if len(self.msg) == 4: self.send_chan("Usage: !geo <ip/host>") else: try: data = json.loads(urllib.request.urlopen("http://ip-api.com/json/{0}".format( self.msg[4])).read().decode("utf-8")) if data["status"] == "fail": return else: shortened = urllib.request.urlopen("http://is.gd/create.php?format=simple&url={0}".format( urllib.parse.quote("https://www.google.com/maps?q={0},{1}&output=classic".format( data["lat"],data["lon"])))).read().decode("utf-8") self.send_chan(("IP: {0} ISP: {1} COUNTRY: {2} MAP: {3}".format( data["query"], data["isp"], data["country"], shortened))) except Exception as e: self.errormsg = "[ERROR]-[geo] geo() stating: {0}".format(e) sysErrorLog.log( self ) ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end")))
def currency(self): if len(self.msg) < 7: self.send_chan("Usage: !currency <amount> <from> <to>") if len(self.msg) == 7: try: amount = Decimal(re.sub(",", ".", self.msg[4])).quantize(Decimal("0.00")) except Exception as e: amount = Decimal(1.00) frm = self.msg[5].upper() to = self.msg[6].upper() ## If first value is float and currencies are valid if isinstance(amount, Decimal) and syscmd.checkCurrency(frm, to): frm = urllib.parse.quote(frm) to = urllib.parse.quote(to) url = "https://www.google.com/finance/converter?a={0}&from={1}&to={2}".format( amount, frm, to) html = syscmd.getHtml(self, url, True) try: soup = BeautifulSoup(html) result = soup.findAll("span", {"class": "bld"}) ## If there's a result, then send it to the chan if result: result = "{0} {1} = {2}".format(amount, frm.upper(), result[0]) trimmed = re.sub('<[^<]+?>', '', result) self.send_chan(trimmed) else: self.send_chan("Google failed to convert your request :(") except Exception as e: self.errormsg = "[ERROR]-[Currency] stating: {0}".format(e) sysErrorLog.log(self) ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end"))) else: self.send_chan("Usage: !currency <amount> <from> <to>")
def googleSearch(self): try: Cache.dataCache = [] Cache.dataIndex = 0 parameters = "" length = len(self.msg) for x in range (4, length): parameters += "{0} ".format(self.msg[x]) parameters_url = urllib.parse.quote(parameters.strip()) url = "https://www.google.fi/search?q={0}".format(parameters_url) html = syscmd.getHtml(self, url, True ) except: self.errormsg = "[NOTICE]-[google] googleSearch()(1) Something went wrong getting the html" sysErrorLog.log( self ) if self.config["debug"]: print("{0}{1}{2}".format(self.color("blue"), self.errormsg, self.color("end"))) try: try: soup = BeautifulSoup(html, "lxml") except: soup = BeautifulSoup(html, "html5lib") Cache.dataCache = soup.findAll("h3", {"class" : "r"}) if len(Cache.dataCache) > 0: title = "{0}".format(Cache.dataCache[Cache.dataIndex].a) title = syscmd.delHtml(title) string = "{0}: {1}".format(title, Cache.dataCache[Cache.dataIndex].a.get('href')) self.send_chan(string) Cache.dataIndex += 1 else: self.send_chan("No results for: {0}".format(parameters)) except Exception as e: self.errormsg = "[ERROR]-[google] googleSearch()(2) stating: {0}".format(e) sysErrorLog.log( self ) ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end")))
def wikiSearch(self): Cache.dataCache = [] Cache.dataIndex = 0 parameters = "" length = len(self.msg) for x in range(5, length): parameters += "{0} ".format(self.msg[x]) parameters_url = urllib.parse.quote(parameters.strip()) url = "http://{0}.m.wikipedia.org/w/index.php?search={1}&fulltext=Search".format( Cache.lang, parameters_url) try: html = syscmd.getHtml(self, url, True) except Exception as e: self.errormsg = "[ERROR]-[wiki] wikiSearch()(1) stating: {0}".format(e) sys.error_log.log(self) if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end"))) try: soup = BeautifulSoup(html) if len(soup.findAll("p", {"class": "mw-search-nonefound"})) == 0: Cache.dataCache = soup.findAll( "div", {"class": "mw-search-result-heading"}) output = "{0}: http://{1}.wikipedia.org{2}".format( Cache.dataCache[Cache.dataIndex].a.get('title'), Cache.lang, Cache.dataCache[Cache.dataIndex].a.get('href')) self.send_chan(output) Cache.dataIndex += 1 else: self.send_chan("There were no results matching the query.") except Exception as e: self.errormsg = "[ERROR]-[wiki] wikiSearch()(2) stating: {0}".format(e) sysErrorLog.log(self) ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end")))
def nicklList ( self ): print("[CREATING NAMES LIST]") nickList = [] if "353" in self.msg and self.listNames: ## ## Parse and create a nicklist ## try: index = self.msg.index("353") for i in range(index+4, len(self.msg)): if "\r\n" in self.msg[i]: lastNick = self.msg[i].split("\r\n") nickList.append(lastNick[0]) return else: nickList.append(self.msg[i].strip(":")) except Exception as e: ## We dont bother to user if self.config["debug"] is on or not.. ## obviously it's OFF at this poinst self.errormsg = "[ERROR]-[userOutput] nickList() stating: {0}".format(e) sysErrorLog.log ( self ) finally: return(nickList)
def automodes (self): if len(self.msg) >= 5: if self.msg[4].strip() == "me": try: db = sqlite3.connect("modules/data/automodes.db") cur = db.cursor() cur.execute("""SELECT mode FROM automodes WHERE identhost = ? """,(self.get_host(),)) result = cur.fetchone() if result: self.send_chan("User {0} has currently mode +{1}".format(self.get_host(), result[0])) else: self.send_chan("Unfortunately you are not on the automodes list :(") except Exception as e: self.errormsg = "[ERROR]-[automodes] automodes() stating: {0}".format(e) sysErrorLog.log (self) if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end"))) raise e finally: db.close() elif len(self.msg) > 5 and self.msg[4].strip() == "reset": if self.get_host() in self.config["opers"]: self.modes = "reset" self.channel = self.msg[2].strip() nick = self.msg[5].strip() self.automodesWhoisEnabled = True self.whois(nick) else: self.errormsg = "[NOTICE]-[automodes] Unauthorized command from {0} at reset".format(self.get_host()) sysErrorLog.log ( self ) self.send_chan("Unauthorized command") elif len(self.msg) > 6 and self.msg[4].strip() == "set": if self.get_host() in self.config["opers"]: ## As for a quick fix, these are made bot wide variables self.modes = self.msg[6].strip() self.channel = self.msg[2].strip() ## End section of system wide variables ... nick = self.msg[5].strip() self.automodesWhoisEnabled = True self.whois(nick) else: self.errormsg = "[NOTICE]-[automodes] Unauthorized command from {0} at set".format(self.get_host()) sysErrorLog.log ( self ) self.send_chan("Unauthorized command") else: pass else: self.send_chan("Usage: !automodes set <nick> <flag> ## To add a mode av or ao to the user") self.send_chan("Usage: !automodes reset <nick> ## To remove user from database") self.send_chan("Usage: !automodes me ## To see modes the user has")
def seen(self): if self.config[ "logging"]: #If logging is False, we cannot get results, so make sure it's on in order to have this on. if len( self.msg ) >= 5: #If given string is only !seen, it will print out the usage of the script try: seendb = self.config[ "log-path"] + "seen.db" #making sure seen.db file exists os.path.exists(seendb) except Exception as e: self.errormsg = "[ERROR]-[seen] seen() stating: {0}".format(e) sysErrorLog.log(self) ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end"))) else: nick = self.msg[4].rstrip( "\r\n" ) #getting the nick we are looking for (the second param. given; !seen nick) if self.get_nick( ) != nick: #if you're not looking yourself, run the search, other wise not. if self.nick != nick: db = sqlite3.connect(seendb) cur = db.cursor() cur.execute( """SELECT nick, channel, time, usertxt FROM seendb WHERE nick = ?""", (nick, )) result = cur.fetchone() if result: name = result[0] dbtime = result[2] dbconvert = datetime.datetime.fromtimestamp( int(dbtime)).strftime('[%d.%m.%Y // %H:%M:%S]') past = datetime.datetime.fromtimestamp(int(dbtime)) current = datetime.datetime.fromtimestamp( int(time.time())) diff = dateutil.relativedelta.relativedelta( current, past) output = "" #Looking from filed database time if any of these conditions will meet and appending them in output if diff.years: output += " {0} year(s)".format(diff.years) if diff.months: output += " {0} months(s)".format(diff.months) if diff.days: output += " {0} day(s)".format(diff.days) if diff.hours: output += " {0} hour(s)".format(diff.hours) if diff.minutes: output += " {0} minute(s)".format(diff.minutes) if diff.seconds: output += " {0} seconds".format(diff.seconds) self.send_chan( "{0} spoke last time: {1} which is exactly {2} ago. Stating: {3}" .format(name, dbconvert, output, result[3])) else: self.send_chan( "I have never logged {0} while being on any channel" .format(nick)) else: self.send_chan("Hah, you're funny :)") else: self.send_chan("Hah, nice try!") else: self.send_chan("Usage: !seen <nick>") else: self.send_chan( "Logging must be enabled from config in order to use this module")
def seen ( self ): if self.config["logging"]: #If logging is False, we cannot get results, so make sure it's on in order to have this on. if len(self.msg) >= 5: #If given string is only !seen, it will print out the usage of the script try: seendb = self.config["log-path"]+"seen.db" #making sure seen.db file exists os.path.exists(seendb) except Exception as e: self.errormsg = "[ERROR]-[seen] seen() stating: {0}".format(e) sysErrorLog.log( self ) ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end"))) else: nick = self.msg[4].rstrip("\r\n") #getting the nick we are looking for (the second param. given; !seen nick) if self.get_nick() != nick: #if you're not looking yourself, run the search, other wise not. if self.nick != nick: db = sqlite3.connect(seendb) cur = db.cursor() cur.execute("""SELECT nick, channel, time, usertxt FROM seendb WHERE nick = ?""",(nick,)) result = cur.fetchone() if result: name = result[0] dbtime = result[2] dbconvert = datetime.datetime.fromtimestamp(int(dbtime)).strftime('[%d.%m.%Y // %H:%M:%S]') past = datetime.datetime.fromtimestamp(int(dbtime)) current = datetime.datetime.fromtimestamp(int(time.time())) diff = dateutil.relativedelta.relativedelta(current, past) output = "" #Looking from filed database time if any of these conditions will meet and appending them in output if diff.years: output += " {0} year(s)".format(diff.years) if diff.months: output += " {0} months(s)".format(diff.months) if diff.days: output += " {0} day(s)".format(diff.days) if diff.hours: output += " {0} hour(s)".format(diff.hours) if diff.minutes: output += " {0} minute(s)".format(diff.minutes) if diff.seconds: output += " {0} seconds".format(diff.seconds) self.send_chan("{0} spoke last time: {1} which is exactly {2} ago. Stating: {3}" .format(name, dbconvert, output, result[3])) else: self.send_chan("I have never logged {0} while being on any channel".format(nick)) else: self.send_chan("Hah, you're funny :)") else: self.send_chan("Hah, nice try!") else: self.send_chan("Usage: !seen <nick>") else: self.send_chan("Logging must be enabled from config in order to use this module")
def show( self, nick ): timeStamp = "{0}".format(time.strftime("%H:%M")) if self.activeOnchan: try: ## Checking if MODE is present if self.msg[1] == "MODE": modeFound = True else: modeFound = False ## Checking if the channel is present if self.msg[2].lstrip(":").rstrip("\r\n")[0] == "#": chanVerified = True bot = False elif self.msg[1].lstrip(":").rstrip("\r\n")[0] == "#": chanVerified = True bot = True else: chanVerified = False if chanVerified: chan = self.msg[2].lstrip(":").rstrip("\r\n") listOfevents = ["QUIT", "PART", "JOIN"] if self.msg[1] in listOfevents and chanVerified: if self.msg[1] == "JOIN": print("{0} *** {1} ({3}) JOINS {2}".format(timeStamp, self.get_nick(), chan, self.get_host())) elif self.msg[1] == "PART": print("{0} *** {1} ({3}) PARTS {2}".format(timeStamp, self.get_nick(), chan, self.get_host())) elif self.msg[1] == "QUIT": print("{0} *** {1} ({2}) has quit irc".format(timeStamp, self.get_nick(), self.get_host())) ## Something's matter with this line o_O... otherwise pretty cool ## If the even is MODE , we don't want to show it as other stuff if modeFound and chanVerified: print("{0} [{1}] MODE ({2} {3}) by {4}".format( timeStamp, chan, self.msg[3], self.msg[4].rstrip("\r\n"), self.get_nick())) if chanVerified and not modeFound and self.msg[1] not in listOfevents: rawText = [] if not bot: for i in range(3, len(self.msg)): rawText.append(self.msg[i].rstrip("\r\n")) else: for i in range(2, len(self.msg)): rawText.append(self.msg[i].rstrip("\r\n")) text = "" for x in range(0, len(rawText)): text += "%s " % (rawText[x]) text = text[1:] print("{0} [{1}] <{2}> {3}".format( timeStamp,chan, nick, text)) except Exception as e: ## We dont bother to show errors to user if self.config["debug"] is False ## obviously it's False at this poinst self.errormsg = "[ERROR]-[userOutput] show() stating: {0}".format(e) sysErrorLog.log ( self ) pass
def getNickFromNicklist( self ): ## ## Do we really need to import nicks from nickList into preprefixing ## just feels like it's not needed... ( ? ) ## if self.activeOnchan: try: try: if not self.donePrefixing: for i in self.nickList: self.prePrefix.append(i) self.donePrefixing = True except Exception as e: ## We dont bother to show errors to user if self.config["debug"] is False ## obviously it's False at this poinst self.errormsg = "[ERROR]-[userOutput] getNickFromNicklist() stating: {0}".format(e) sysErrorLog.log ( self ) ## Checking prefixes according to MODE events if self.msg[1] == "MODE": user = self.msg[4].rstrip("\r\n") if self.msg[3] == "+o": findUser = "******".format(user) if user in self.prePrefix: index = self.prePrefix.index(user) self.prePrefix[index] = "@{0}".format(user) elif findUser in self.prePrefix: index = self.prePrefix.index(findUser) self.prePrefix[index] = "@{0}".format(user) elif self.msg[3] == "-o": findUser = "******".format(user) if findUser in self.prePrefix: index = self.prePrefix.index(findUser) self.prePrefix[index] = user elif self.msg[3] == "+v": findUser = "******".format(user) if user in self.prePrefix: index = self.prePrefix.index(user) self.prePrefix[index] = "+{0}".format(user) elif findUser in self.prePrefix: index = self.prePrefix.index(findUser) self.prePrefix[index] = "+{0}".format(user) elif self.msg[3] == "-v": findUser = "******".format(user) if findUser in self.prePrefix: index = self.prePrefix.index(findUser) self.prePrefix[index] = user ## Checking that prefix follows with a new nick elif self.msg[1] == "NICK": newNick = self.msg[2][1:].rstrip("\r\n") oldNick = self.get_nick() if oldNick in self.prePrefix: index = self.prePrefix.index(oldNick) self.prePrefix[index] = newNick elif "+"+oldNick in self.prePrefix: index = self.prePrefix.index("+"+oldNick) self.prePrefix[index] = "+"+newNick elif "@"+oldNick in self.prePrefix: index = self.prePrefix.index("@"+oldNick) self.prePrefix[index] = "@"+newNick elif self.msg[1] == "JOIN": self.prePrefix.append(self.get_nick()) ## On PART / QUIT we want to remove user from the nicklist elif self.msg[1] == "PART": if self.get_nick() in self.prePrefix: index = self.prePrefix.index(self.get_nick()) del self.prePrefix[index] elif "@"+self.get_nick() in self.prePrefix: index = self.prePrefix.index("@"+self.get_nick()) del self.prePrefix[index] elif "+"+self.get_nick() in self.prePrefix: index = self.prePrefix.index("+"+self.get_nick()) del self.prePrefix[index] elif self.msg[1] == "QUIT": if self.get_nick() in self.prePrefix: index = self.prePrefix.index(self.get_nick()) del self.prePrefix[index] elif "@"+self.get_nick() in self.prePrefix: index = self.prePrefix.index("@"+self.get_nick()) del self.prePrefix[index] elif "+"+self.get_nick() in self.prePrefix: index = self.prePrefix.index("+"+self.get_nick()) del self.prePrefix[index] ## Lets parse the nick with a prefix and return it to core prefix = [] prefix = [i for i in self.prePrefix if self.get_nick() in i] try: prefixedNick = prefix[0] except Exception as e: prefixedNick = self.get_nick() return(prefixedNick) except Exception as e: ## PASS this exception ## otherwise 'in <string>' requires string as left operand, not NoneType pass
def show(self, nick): timeStamp = "{0}".format(time.strftime("%H:%M")) if self.activeOnchan: try: ## Checking if MODE is present if self.msg[1] == "MODE": modeFound = True else: modeFound = False ## Checking if the channel is present if self.msg[2].lstrip(":").rstrip("\r\n")[0] == "#": chanVerified = True bot = False elif self.msg[1].lstrip(":").rstrip("\r\n")[0] == "#": chanVerified = True bot = True else: chanVerified = False if chanVerified: chan = self.msg[2].lstrip(":").rstrip("\r\n") listOfevents = ["QUIT", "PART", "JOIN"] if self.msg[1] in listOfevents and chanVerified: if self.msg[1] == "JOIN": print("{0} *** {1} ({3}) JOINS {2}".format( timeStamp, self.get_nick(), chan, self.get_host())) elif self.msg[1] == "PART": print("{0} *** {1} ({3}) PARTS {2}".format( timeStamp, self.get_nick(), chan, self.get_host())) elif self.msg[1] == "QUIT": print("{0} *** {1} ({2}) has quit irc".format( timeStamp, self.get_nick(), self.get_host())) ## Something's matter with this line o_O... otherwise pretty cool ## If the even is MODE , we don't want to show it as other stuff if modeFound and chanVerified: print("{0} [{1}] MODE ({2} {3}) by {4}".format( timeStamp, chan, self.msg[3], self.msg[4].rstrip("\r\n"), self.get_nick())) if chanVerified and not modeFound and self.msg[ 1] not in listOfevents: rawText = [] if not bot: for i in range(3, len(self.msg)): rawText.append(self.msg[i].rstrip("\r\n")) else: for i in range(2, len(self.msg)): rawText.append(self.msg[i].rstrip("\r\n")) text = "" for x in range(0, len(rawText)): text += "%s " % (rawText[x]) text = text[1:] print("{0} [{1}] <{2}> {3}".format(timeStamp, chan, nick, text)) except Exception as e: ## We dont bother to show errors to user if self.config["debug"] is False ## obviously it's False at this poinst self.errormsg = "[ERROR]-[userOutput] show() stating: {0}".format( e) sysErrorLog.log(self) pass
def createCitiesDatabase( self ): cities = """Akaa, Alahärmä, Alajärvi, Alastaro, Alastaro, Alavieska, Alavus, Anjala, Artjärvi, Asikkala, Askainen, Askola, Aura, Auttoinen, Dragsfjärd, Ekenäs, Elimäki, Eno, Enonkoski, Enontekiö, Espoo, Eura, Eurajoki, Evijärvi, Forssa, Haapajärvi, Haapavesi, Hailuoto, Halikko, Halsua, Hamina, Hankasalmi, Hanko, Harjavalta, Hartola, Hauho, Haukipudas, Haukivuori, Hausjärvi, Heinola, Heinävesi, Helsinki, Himanka, Hirvensalmi, Hollola, Honkajoki, Houtskär, Huittinen, Humppila, Hyrynsalmi, Hyvinkää, Hämeenkoski, Hämeenkyrö, Hämeenlinna, Ii, Iisalmi, Iitti, Ikaalinen, Ilmajoki, Ilomantsi, Imatra, Inari, Ingå, Iniö, Isojoki, Isokyrö, Ivalo, Jaala, Jakobstad, Jalasjärvi, Janakkala, Joensuu, Jokioinen, Joroinen, Joutsa, Joutseno, Juankoski, Jurva, Juuka, Juupajoki, Juva, Jyväskylä, Jämijärvi, Jämsä, Jämsänkoski, Jäppilä, Järvenpää, Kaarina, Kaavi, Kajaani, Kalajoki, Kalvola, Kangasala, Kangaslampi, Kangasniemi, Kankaanpää, Kannonkoski, Kannus, Karhula, Karijoki, Karinainen, Karis, Karjalohja, Karkkila, Karleby, Karstula, Karttula, Karvia, Karvia, Kaskinen, Kauhajoki, Kauhava, Kauniainen, Kaustinen, Keitele, Kemi, Kemijärvi, Keminmaa, Kempele, Kerava, Kerimäki, Kestilä, Kesälahti, Keuruu, Kihniö, Kiihtelysvaara, Kiikala, Kiikoinen, Kiiminki, Kilo, Kilpisjärvi, Kimito, Kinnula, Kinnula, Kirkkonummi, Kisko, Kitee, Kittilä, Kiukainen, Kiuruvesi, Kivijärvi, Kokemäki, Kolari, Konnevesi, Kontiolahti, Korpilahti, Korsholm, Korsnäs, Kortesjärvi, Koski, Kotka, Koukkuniemi, Kouvola, Kristinestad, Kronoby, Kuhmalahti, Kuhmo, Kuhmoinen, Kuivaniemi, Kullaa, Kuopio, Kuortane, Kurikka, Kuru, Kuusamo, Kuusankoski, Kuusjoki, Kylmäkoski, Kyyjärvi, Kälviä, Kärkölä, Kärkölä, Kärsämäki, Köyliö, Lahti, Laihia, Laitila, Lammi, Lapinjärvi, Lapinlahti, Lappajärvi, Lappeenranta, Lappi, Lapua, Larsmo, Laukaa, Lavia, Lehtimäki, Leivonmäki, Lemi, Lempäälä, Lemu, Leppävirta, Lestijärvi, Lieksa, Lieto, Liljendal, Liminka, Liperi, Lohja, Lohtaja, Loimaa, Loimaan Kunta, Loppi, Lovisa, Luhanka, Lumijoki, Luopioinen, Luumäki, Luvia, Längelmäki, Länsi-Turunmaa, Maaninka, Malax, Marttila, Masku, Mellilä, Merijärvi, Merikarvia, Merimasku, Miehikkälä, Mietoinen, Mikkeli, Mouhijärvi, Muhos, Muhos, Multia, Muonio, Muurame, Muurla, Mynämäki, Myrskylä, Mäntsälä, Mänttä, Mäntyharju, Naantali, Nagu, Nakkila, Nastola, Nilsiä, Nivala, Nokia, Noormarkku, Nousiainen, Nurmes, Nurmijärvi, Nurmo, Nykarleby, Oravais, Orimattila, Oripää, Orivesi, Otaniemi, Oulainen, Oulu, Oulunsalo, Outokumpu, Padasjoki, Paimio, Paltamo, Pargas, Parikkala, Parkano, Pedersöre, Pelkosenniemi, Pello, Perho, Perniö, Pernå, Pertteli, Pertunmaa, Petäjävesi, Pieksämäen Maalaiskunta, Pieksämäki, Pielavesi, Pihtipudas, Piikkiö, Piippola, Pirkkala, Pohja, Polvijärvi, Pomarkku, Pori, Pornainen, Porvoo, Posio, Pudasjärvi, Pukkila, Pulkkila, Punkaharju, Punkalaidun, Puolanka, Puumala, Pyhtää, Pyhäjoki, Pyhäjärvi, Pyhäjärvi, Pyhäntä, Pyhäranta, Pyhäselkä, Pylkönmäki, Pälkäne, Pöytyä, Raahe, Raisio, Rantasalmi, Rantsila, Ranua, Rauma, Rautalampi, Rautavaara, Rautjärvi, Reisjärvi, Renko, Replot, Riihimäki, Ristiina, Ristijärvi, Ristinummi, Rovaniemi, Ruokolahti, Ruotsinpyhtää, Ruovesi, Rusko, Ruukki, Rymättylä, Rääkkylä, Saari, Saarijärvi, Sahalahti, Salla, Salo, Sammatti, Sauvo, Savitaipale, Savonlinna, Savonranta, Savukoski, Seinäjoki, Sibbo, Sievi, Siikainen, Siikajoki, Siilinjärvi, Simo, Simo, Siuntio, Sodankylä, Soini, Somero, Sonkajärvi, Sotkamo, Sulkava, Sumiainen, Suodenniemi, Suolahti, Suomusjärvi, Suomussalmi, Suonenjoki, Sysmä, Säkylä, Särkisalo, Säynätsalo, Taipalsaari, Taivalkoski, Taivassalo, Tammela, Tampere, Tarvasjoki, Teekkarikylä, Tervakoski, Tervo, Tervola, Teuva, Tohmajärvi, Toholampi, Toijala, Toivakka, Tornio, Turku, Tuulos, Tuupovaara, Tuusniemi, Tuusula, Tyrnävä, Töysä, Ullava, Ulvila, Urjala, Utajärvi, Utsjoki, Uurainen, Uusikaupunki, Vaala, Vaasa, Vahto, Valkeakoski, Valkeala, Valtimo, Vammala, Vampula, Vantaa, Varkaus, Varpaisjärvi, Vehmaa, Vehmersalmi, Velkua, Vesanto, Vesilahti, Veteli, Vieremä, Vihanti, Vihti, Viiala, Viitasaari, Viljakkala, Vilppula, Vimpeli, Virrat, Virtasalmi, Vuolijoki, Vähäkyrö, Västanfjärd, Vörå, Yli-Ii, Ylihärmä, Ylikiiminki, Ylistaro, Ylitornio, Ylivieska, Ylämaa, Yläne, Ylöjärvi, Ypäjä, Äetsä, Ähtäri, Äänekoski""" citiesList = cities.split(",") try: db = sqlite3.connect("modules/data/fmiCities.db") cursor = db.cursor() ## Drop the table if it exists cursor.execute(""" DROP TABLE IF EXISTS cities """) ## Create cities table cursor.execute(""" CREATE TABLE IF NOT EXISTS cities(id INTEGER PRIMARY KEY NOT NULL, city TEXT) """) ## Create nicks table cursor.execute(""" CREATE TABLE IF NOT EXISTS nicks(id INTEGER PRIMARY KEY NOT NULL, nick TEXT, city TEXT) """) ## Loop through the cities and add them to the db for city in citiesList: cursor.execute(""" INSERT INTO cities(city) VALUES (?) """, (city.strip(),)) ## Commit changes to the db db.commit() except Exception as e: ## Roll back if some error occured db.rollback() self.errormsg = "[ERROR]-[syscmd] createCitiesDatabase() stating: {0}".format(e) sysErrorLog.log( self ) ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end"))) raise e finally: db.close() return True
def tell(self): if len(self.msg) <= 4: self.send_chan("Usage: !tell <nick> <message>") return else: ## Gotta check if the file realy exists if not os.path.exists("modules/data/tell.db"): self.errormsg = "{0}[ERROR]-[tell] tell()(1): No database file found!{1}".format( self.color("red"), self.color("end")) sysErrorLog.log(self) return try: ## Get needed data from the stream nick = self.msg[4].strip() tellCount = self.config["tellCount"] - 1 userInbox = self.config["userInbox"] - 1 if self.get_nick() == nick or self.nick == nick: self.send_chan("This doesn't seem right now, does it?") return if self.msg[2][0] == "#": channel = self.msg[2] else: #Not valid channel, do nothing.. return message = "" for i in range(5, len(self.msg)): message += "{0} ".format(self.msg[i].strip()) message = message.rstrip("\r\n") if syscmd.userVisitedChannel(self, nick): db = sqlite3.connect("modules/data/tell.db") cur = db.cursor() cur.execute( """SELECT COUNT(who) AS count FROM tell WHERE who = ?""", (self.get_nick(), )) checkCount = cur.fetchone()[0] cur.execute( """SELECT COUNT(nick) AS count FROM tell WHERE nick = ?""", (nick, )) checkInbox = cur.fetchone()[0] if checkCount > tellCount: self.send_chan( "{0}, The message count is limited in to {1} messages per user" .format(self.get_nick(), tellCount + 1)) elif checkInbox > userInbox: self.send_chan( "{0}, {1}'s message inbox is full :(".format( self.get_nick(), nick)) else: cur.execute( """INSERT INTO tell (nick, who, channel, message) VALUES (?, ?, ?, ?)""", (nick, self.get_nick(), channel, message)) db.commit() self.send_chan("Your message has been saved") db.close() else: self.send_chan( "I cannot tell something to someone who doesn't exists :(") except Exception as e: self.errormsg = "[ERROR]-[tell] tell() stating: {0}".format(e) sysErrorLog.log(self) if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end")))
def getNickFromNicklist(self): ## ## Do we really need to import nicks from nickList into preprefixing ## just feels like it's not needed... ( ? ) ## if self.activeOnchan: try: try: if not self.donePrefixing: for i in self.nickList: self.prePrefix.append(i) self.donePrefixing = True except Exception as e: ## We dont bother to show errors to user if self.config["debug"] is False ## obviously it's False at this poinst self.errormsg = "[ERROR]-[userOutput] getNickFromNicklist() stating: {0}".format( e) sysErrorLog.log(self) ## Checking prefixes according to MODE events if self.msg[1] == "MODE": user = self.msg[4].rstrip("\r\n") if self.msg[3] == "+o": findUser = "******".format(user) if user in self.prePrefix: index = self.prePrefix.index(user) self.prePrefix[index] = "@{0}".format(user) elif findUser in self.prePrefix: index = self.prePrefix.index(findUser) self.prePrefix[index] = "@{0}".format(user) elif self.msg[3] == "-o": findUser = "******".format(user) if findUser in self.prePrefix: index = self.prePrefix.index(findUser) self.prePrefix[index] = user elif self.msg[3] == "+v": findUser = "******".format(user) if user in self.prePrefix: index = self.prePrefix.index(user) self.prePrefix[index] = "+{0}".format(user) elif findUser in self.prePrefix: index = self.prePrefix.index(findUser) self.prePrefix[index] = "+{0}".format(user) elif self.msg[3] == "-v": findUser = "******".format(user) if findUser in self.prePrefix: index = self.prePrefix.index(findUser) self.prePrefix[index] = user ## Checking that prefix follows with a new nick elif self.msg[1] == "NICK": newNick = self.msg[2][1:].rstrip("\r\n") oldNick = self.get_nick() if oldNick in self.prePrefix: index = self.prePrefix.index(oldNick) self.prePrefix[index] = newNick elif "+" + oldNick in self.prePrefix: index = self.prePrefix.index("+" + oldNick) self.prePrefix[index] = "+" + newNick elif "@" + oldNick in self.prePrefix: index = self.prePrefix.index("@" + oldNick) self.prePrefix[index] = "@" + newNick elif self.msg[1] == "JOIN": self.prePrefix.append(self.get_nick()) ## On PART / QUIT we want to remove user from the nicklist elif self.msg[1] == "PART": if self.get_nick() in self.prePrefix: index = self.prePrefix.index(self.get_nick()) del self.prePrefix[index] elif "@" + self.get_nick() in self.prePrefix: index = self.prePrefix.index("@" + self.get_nick()) del self.prePrefix[index] elif "+" + self.get_nick() in self.prePrefix: index = self.prePrefix.index("+" + self.get_nick()) del self.prePrefix[index] elif self.msg[1] == "QUIT": if self.get_nick() in self.prePrefix: index = self.prePrefix.index(self.get_nick()) del self.prePrefix[index] elif "@" + self.get_nick() in self.prePrefix: index = self.prePrefix.index("@" + self.get_nick()) del self.prePrefix[index] elif "+" + self.get_nick() in self.prePrefix: index = self.prePrefix.index("+" + self.get_nick()) del self.prePrefix[index] ## Lets parse the nick with a prefix and return it to core prefix = [] prefix = [i for i in self.prePrefix if self.get_nick() in i] try: prefixedNick = prefix[0] except Exception as e: prefixedNick = self.get_nick() return (prefixedNick) except Exception as e: ## PASS this exception ## otherwise 'in <string>' requires string as left operand, not NoneType pass
def stats(self): if self.config["logging"]: # Logging must be enabled from config to run this module if len(self.msg) >= 5: # if no atributes, give the usage. if self.msg[4].strip(): # prevent searching whitespaces chan = self.msg[2] logfile = self.config["log-path"] + chan + ".log" looking = self.msg[4].lower().rstrip("\r\n") try: with open(logfile): pass # trying if such logfile exists or not except IOError: # But yet i dont know, if this is a useless checkup self.send_chan("I think i have not been loggin on that channel yet") try: # If no errors were occured, open the log file and read lines. log = open(logfile, "r") line = log.readlines() log.close() nick_counter = 0 word_counter = 0 line_counter = 0 pct = 0 for x in range(0, len(line)): # reading every line individually line2 = line[x].lower().strip().split(" ") # stripping the line and splitting it into list logNick = line2[1].lower().strip() # the nick in log will be always the second in the list [1] line_counter += 1 # counts every line in the logfile if looking == logNick: # if we are looking the nick, count it in here nick_counter += 1 else: # otherwise we will loop the list trough to search for the word for y in range( 0, len(line2) ): # this kind of double looping might slow down the performance..? if looking in line2[y]: # if we have a match, count it in. word_counter += 1 if nick_counter is not 0: pct = nick_counter / line_counter * 100 self.send_chan( "{0} has written '{1}' lines on this channel ({2}) which is {3:.1f}% of the total amount.".format( looking, nick_counter, chan, round(pct, 1) ) ) elif word_counter is not 0: word_counter -= 1 self.send_chan( "{0} has been mentioned '{1}' times on this channel ({2})".format( looking, word_counter, chan ) ) else: self.send_chan( "I don't remember seeing '{0}' on this channel before ({1})".format(looking, chan) ) except Exception as e: self.errormsg = "[ERROR]-[stats] stats() stating: {0}".format(e) sysErrorLog.log(self) ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end"))) else: self.send_chan( "Received a whitespace as a search string, aborting" ) # if searching whitespaces, give an error else: self.send_chan("Usage: !stats <nick> or !stats <word>") # if not enough parameters, give away the usage else: self.send_chan("First enable logging from config to use this module")
def automodes(self): if len(self.msg) >= 5: if self.msg[4].strip() == "me": try: db = sqlite3.connect("modules/data/automodes.db") cur = db.cursor() cur.execute( """SELECT mode FROM automodes WHERE identhost = ? """, (self.get_host(), )) result = cur.fetchone() if result: self.send_chan("User {0} has currently mode +{1}".format( self.get_host(), result[0])) else: self.send_chan( "Unfortunately you are not on the automodes list :(") except Exception as e: self.errormsg = "[ERROR]-[automodes] automodes() stating: {0}".format( e) sysErrorLog.log(self) if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end"))) raise e finally: db.close() elif len(self.msg) > 5 and self.msg[4].strip() == "reset": if self.get_host() in self.config["opers"]: self.modes = "reset" self.channel = self.msg[2].strip() nick = self.msg[5].strip() self.automodesWhoisEnabled = True self.whois(nick) else: self.errormsg = "[NOTICE]-[automodes] Unauthorized command from {0} at reset".format( self.get_host()) sysErrorLog.log(self) self.send_chan("Unauthorized command") elif len(self.msg) > 6 and self.msg[4].strip() == "set": if self.get_host() in self.config["opers"]: ## As for a quick fix, these are made bot wide variables self.modes = self.msg[6].strip() self.channel = self.msg[2].strip() ## End section of system wide variables ... nick = self.msg[5].strip() self.automodesWhoisEnabled = True self.whois(nick) else: self.errormsg = "[NOTICE]-[automodes] Unauthorized command from {0} at set".format( self.get_host()) sysErrorLog.log(self) self.send_chan("Unauthorized command") else: pass else: self.send_chan( "Usage: !automodes set <nick> <flag> ## To add a mode av or ao to the user" ) self.send_chan( "Usage: !automodes reset <nick> ## To remove user from database") self.send_chan("Usage: !automodes me ## To see modes the user has")
def stats(self): if self.config[ "logging"]: #Logging must be enabled from config to run this module if len(self.msg) >= 5: #if no atributes, give the usage. if self.msg[4].strip(): #prevent searching whitespaces chan = self.msg[2] logfile = self.config["log-path"] + chan + ".log" looking = self.msg[4].lower().rstrip("\r\n") try: with open(logfile): pass #trying if such logfile exists or not except IOError: #But yet i dont know, if this is a useless checkup self.send_chan( "I think i have not been loggin on that channel yet") try: #If no errors were occured, open the log file and read lines. log = open(logfile, "r") line = log.readlines() log.close() nick_counter = 0 word_counter = 0 line_counter = 0 pct = 0 for x in range( 0, len(line)): #reading every line individually line2 = line[x].lower().strip().split( " " ) #stripping the line and splitting it into list logNick = line2[1].lower().strip( ) #the nick in log will be always the second in the list [1] line_counter += 1 #counts every line in the logfile if looking == logNick: #if we are looking the nick, count it in here nick_counter += 1 else: #otherwise we will loop the list trough to search for the word for y in range( 0, len(line2) ): #this kind of double looping might slow down the performance..? if looking in line2[ y]: #if we have a match, count it in. word_counter += 1 if nick_counter is not 0: pct = nick_counter / line_counter * 100 self.send_chan( "{0} has written '{1}' lines on this channel ({2}) which is {3:.1f}% of the total amount." .format(looking, nick_counter, chan, round(pct, 1))) elif word_counter is not 0: word_counter -= 1 self.send_chan( "{0} has been mentioned '{1}' times on this channel ({2})" .format(looking, word_counter, chan)) else: self.send_chan( "I don't remember seeing '{0}' on this channel before ({1})" .format(looking, chan)) except Exception as e: self.errormsg = "[ERROR]-[stats] stats() stating: {0}".format( e) sysErrorLog.log(self) ## LOG the error if self.config["debug"]: print("{0}{1}{2}".format(self.color("red"), self.errormsg, self.color("end"))) else: self.send_chan( "Received a whitespace as a search string, aborting" ) #if searching whitespaces, give an error else: self.send_chan("Usage: !stats <nick> or !stats <word>" ) #if not enough parameters, give away the usage else: self.send_chan("First enable logging from config to use this module")