def ParsePlatformSearchXml(self, text): xmlDocument = minidom.parseString(text) if self.TestXmlDocumentErrorStatus(xmlDocument) == False: raise Exception("Invalid response for search platform XML") gameTagResultList = xmlDocument.getElementsByTagName("platform") #print "PLATFORM SEARCH TEXT: " + text resultDictList = [] for gameTag in gameTagResultList: romDict = {} romDict[ 'giantBombPlatformId'] = XmlHelper.FindFirstDataInXmlTagList( gameTag, 'id') romDict['name'] = XmlHelper.FindFirstDataInXmlTagList( gameTag, 'name') romDict['abbreviation'] = XmlHelper.FindFirstDataInXmlTagList( gameTag, 'abbreviation') romDict['description'] = XmlHelper.FindFirstDataInXmlTagList( gameTag, 'deck') resultDictList.append(romDict) return resultDictList
def ParseGenreDetailsXml(self, text): xmlDocument = minidom.parseString(text) if self.TestXmlDocumentErrorStatus(xmlDocument) == False: raise Exception("Invalid response for get genre details XML") # print "XML: " + text gameTagResultList = xmlDocument.getElementsByTagName("results") if len(gameTagResultList) == 0: raise Exception("Could not find result for genre") if len(gameTagResultList) > 1: raise Exception("Unexpected number of results for genre") gameTag = gameTagResultList[0] romDict = {} romDict['name'] = XmlHelper.FindFirstDataInXmlTagList(gameTag, 'name') romDict['description'] = XmlHelper.FindFirstDataInXmlTagList( gameTag, 'deck') romDict['giantBombId'] = XmlHelper.FindFirstDataInXmlTagList( gameTag, 'id') imageNode = XmlHelper.FindFirstChildNodeByTagName(gameTag, 'image') if imageNode is not None: self.SaveImageToRomCache( Config.config.GetGenresImageCachePath(romDict['name']), romDict['name'], imageNode) return romDict
def ParseSimilarGamesData(self, xmlTag): ret = [] if xmlTag != None: gameTags = XmlHelper.FindChildNodesByTagName(xmlTag, 'game') for gameTag in gameTags: dict = {} dict['giantBombRomId'] = XmlHelper.FindFirstDataInXmlTagList( gameTag, 'id') dict['name'] = XmlHelper.FindFirstDataInXmlTagList( gameTag, 'name') ret.append(dict) return ret
def changeTheme(name): #Get this themes('name') path import os, xml.dom.minidom, os.path, sys, XmlHelper path="" for f in os.listdir("../themes"): if f.endswith(".xml"): themeXmlDoc=xml.dom.minidom.parse("../themes/" + f) nameElement = themeXmlDoc.getElementsByTagName("name")[0] tName = XmlHelper.getText(nameElement.childNodes) if tName.lower() == name.lower(): path = "/themes/" + f if path == "": return "" #Parse the settings.xml file...os.path.abspath(os.path.dirname(sys.argv[0])) get's the scripts directory xmlDoc=xml.dom.minidom.parse(os.path.abspath(os.path.dirname(sys.argv[0])) + "/settings.xml") try: themeElement = xmlDoc.getElementsByTagName("theme")[0] except: pDebug("theme element was not found in settings.xml, creating one.") themeElement = xmlDoc.createElement("theme") themeElement.setAttribute("name", name) themeElement.setAttribute("path", path) xmlDoc.documentElement.appendChild(themeElement) f = open(os.path.abspath(os.path.dirname(sys.argv[0])) + "/settings.xml","w").write(xmlDoc.toxml()) return True themeElement.setAttribute("name", name) themeElement.setAttribute("path", path) f = open(os.path.abspath(os.path.dirname(sys.argv[0])) + "/settings.xml","w").write(xmlDoc.toxml()) return True
def ParseDeveloperData(self, developersNode, xmlNodeName): devList = [] if developersNode is not None: for developerNode in XmlHelper.FindChildNodesByTagName( developersNode, xmlNodeName): dev = {} dev['giantBombId'] = XmlHelper.FindFirstDataInXmlTagList( developerNode, 'id') dev['name'] = XmlHelper.FindFirstDataInXmlTagList( developerNode, 'name') dev['apiurl'] = XmlHelper.FindFirstDataInXmlTagList( developerNode, 'api_detail_url') devList.append(dev) return devList
def ParseSearchXml(self, text, giantBombPlatformId): xmlDocument = minidom.parseString(text) if self.TestXmlDocumentErrorStatus(xmlDocument) == False: raise Exception("Invalid response for search XML") gameTagResultList = xmlDocument.getElementsByTagName("game") # print "ROM SEARCH TEXT: " + text resultDictList = [] for gameTag in gameTagResultList: romDict = {} romDict['giantBombRomId'] = XmlHelper.FindFirstDataInXmlTagList( gameTag, 'id') romDict['name'] = XmlHelper.FindFirstDataInXmlTagList( gameTag, 'name') romDict['aliases'] = XmlHelper.FindFirstDataInXmlTagList( gameTag, 'aliases') platformList = XmlHelper.FindFirstChildNodeByTagName( gameTag, 'platforms') if platformList != None: romDict['platforms'] = FormatPlatformsData(platformList) romDict[ 'giantBombApiDetailsUrl'] = XmlHelper.FindFirstDataInXmlTagList( gameTag, 'api_detail_url') # filter by giantBombPlatformId (can't do this directly in the url search string) foundPlatformId = False if len(giantBombPlatformId) > 0: for platform in romDict['platforms']: # print "Platform: " + platform[ 'name' ] if int(platform['giantBombPlatformId']) == int( giantBombPlatformId): foundPlatformId = True break else: foundPlatformId = True if foundPlatformId == True: resultDictList.append(romDict) return resultDictList
def FormatPlatformsData(dom): ret = [] if dom != None: platformList = dom.getElementsByTagName('platform') for platform in platformList: platformData = {} platformData['name'] = XmlHelper.FindFirstDataInXmlTagList( platform, 'name') platformData['abbreviation'] = XmlHelper.FindFirstDataInXmlTagList( platform, 'abbreviation') platformData[ 'giantBombPlatformId'] = XmlHelper.FindFirstDataInXmlTagList( platform, 'id') ret.append(platformData) return ret
def ensure_xml_data(): try: if os.stat('output.xml').st_size > 0: print('Prepared XML ready, Skipping generation') tree, root = XmlHelper.parse_file('output.xml') else: print('Empty XML file, Generating new') tree, root = generate_clean_xml('Flags.xml') except OSError: print('No output.xml file, Generating new') tree, root = generate_clean_xml('Flags.xml') return tree, root
def loadTheme(self, path): loadedTheme = self import xml.dom.minidom, os.path, sys, XmlHelper xmlDoc=xml.dom.minidom.parse(os.path.abspath(os.path.dirname(sys.argv[0])) + path) #Get the name of the theme nameTag=xmlDoc.getElementsByTagName("name")[0] nameTagText=XmlHelper.getText(nameTag.childNodes) loadedTheme.name = nameTagText #Get all the REPLACE Tags replaceTags=xmlDoc.getElementsByTagName("replace") for replaceTag in replaceTags: key = XmlHelper.getAttribute(replaceTag.attributes,"key") text = XmlHelper.getAttribute(replaceTag.attributes,"text") loadedTheme.replaces.append(dict({"key": self.replaceEscapes(key), "text": self.replaceEscapes(text)})) #Get the STYLE Tags styleTags=xmlDoc.getElementsByTagName("style") for styleTag in styleTags: name = XmlHelper.getAttribute(styleTag.attributes,"name") insert = XmlHelper.getAttribute(styleTag.attributes,"insert") ifStatmnt = XmlHelper.getAttribute(styleTag.attributes,"if") loadedTheme.styles.append(dict({'name': self.replaceEscapes(name), "insert": self.replaceEscapes(insert), "if": self.replaceEscapes(ifStatmnt)})) return loadedTheme
def ParseRomDetailsXml(self, romName, text): xmlDocument = minidom.parseString(text) if self.TestXmlDocumentErrorStatus(xmlDocument) == False: raise Exception("Invalid response for get rom details XML") #print "XML: " + text gameTagResultList = xmlDocument.getElementsByTagName("results") if len(gameTagResultList) == 0: raise Exception("Could not find result for rom") if len(gameTagResultList) > 1: raise Exception("Unexpected number of results for rom") gameTag = gameTagResultList[0] romDict = {} #romDict[ 'name' ] = XmlHelper.FindFirstDataInXmlTagList( gameTag, 'name' ) romDict['description'] = XmlHelper.FindFirstDataInXmlTagList( gameTag, 'deck') romDict['giantBombRomId'] = XmlHelper.FindFirstDataInXmlTagList( gameTag, 'id') # string is provided in ISO standard format anyway so can be stored in DB like that romDict['releaseDate'] = XmlHelper.FindFirstDataInXmlTagList( gameTag, 'original_release_date') # similar games are map of { 'giantBombRomId', 'name' } romDict['similarGames'] = self.ParseSimilarGamesData( XmlHelper.FindFirstChildNodeByTagName(gameTag, 'similar_games')) romDict['developers'] = self.ParseDeveloperData( XmlHelper.FindFirstChildNodeByTagName(gameTag, 'developers'), 'company') romDict['publishers'] = self.ParseDeveloperData( XmlHelper.FindFirstChildNodeByTagName(gameTag, 'publishers'), 'publisher') romDict['genres'] = self.ParseDeveloperData( XmlHelper.FindFirstChildNodeByTagName(gameTag, 'genres'), 'genre') imageNode = XmlHelper.FindFirstChildNodeByTagName(gameTag, 'image') if imageNode is not None: self.SaveImageToRomCache( Config.config.GetRomsImageCachePath(romName), romName, imageNode) return romDict
def SaveImageToRomCache(self, cacheDirectory, romName, imageXmlNode): # pick an image priority for imageSizeName in Config.config.imagePriorityOrder: try: apiUrl = XmlHelper.FindFirstDataInXmlTagList( imageXmlNode, imageSizeName + '_url') if apiUrl is not None and len(apiUrl) > 0: imageUrl = apiUrl imageFilenameNoExtension = imageSizeName # print "[" + romName + "] TRYING " + imageUrl + " FILE: " + imageFilenameNoExtension if imageUrl is not None and imageFilenameNoExtension is not None and len( imageUrl) > 0 and len( imageFilenameNoExtension) > 0: if not os.path.exists(cacheDirectory): os.makedirs(cacheDirectory) # get image file extension from imageUrl (dummy, imageExtension) = os.path.splitext(imageUrl) imageFilename = imageFilenameNoExtension + imageExtension romImageFilename = os.path.join( cacheDirectory, imageFilename) if os.path.isfile(romImageFilename): return # file already exists if imageUrl != None and len(imageUrl) > 0: imageResp = urllib2.urlopen(imageUrl) imageData = imageResp.read() if len(imageData) > 0: imageFile = open(romImageFilename, 'wb') imageFile.write(imageData) imageFile.close() return except Exception as e: logging.exception(e)
#!/usr/bin/env python ''' Created on 2009-12-16 @author: Dominik ''' from IRCLibrary import IRC print "MDSBot 0.2 initialized" print "Using version " + IRC.version + " IRCLibrary" import XmlHelper; print "Loading users..." usrManager = XmlHelper.load_users() print "Loading settings..." loadedSettings = XmlHelper.loadSettings() import relay relayManager = relay.relay_manager() addresses = loadedSettings['addresses'] s = IRC.connection(addresses, loadedSettings['nicks'], \ loadedSettings['realname'], loadedSettings['username']) s.autojoinchans = loadedSettings['channels'] # Load the modules print "Loading modules..." loadedModules = {} for module in loadedSettings['modules']: import imp, os, sys try: modulePath = os.path.join(os.path.dirname(sys.argv[0]), "modules/%s/%s.py" % (module, module)) sys.path.append(os.path.dirname(modulePath))
def Init(self, resourcesPath): self.resourcesPath = resourcesPath self.configFilePath = os.path.join(resourcesPath, 'config.xml') try: if (os.path.isfile(self.configFilePath)): dom = parse(self.configFilePath) rootNode = XmlHelper.FindFirstChildNodeByTagName(dom, 'config') displayNodeList = XmlHelper.FindChildNodesByTagName( rootNode, 'display') if len(displayNodeList) > 0: displayNode = displayNodeList[0] try: self.RomItemCount = int( displayNode.getAttribute('romItemCount')) except: pass dateTimeNodeList = XmlHelper.FindChildNodesByTagName( rootNode, 'datetime') if len(dateTimeNodeList) > 0: dateTimeNode = dateTimeNodeList[0] self.dateFormatString = dateTimeNode.getAttribute('format') scraperNodeList = XmlHelper.FindChildNodesByTagName( rootNode, 'scraper') if len(scraperNodeList) > 0: scraperNode = scraperNodeList[0] self.scaperType = scraperNode.getAttribute('type') self.scaperImageQuality = scraperNode.getAttribute( 'imageQuality') self.scraperCacheDirectory = scraperNode.getAttribute( 'cacheDirectory') launcherNodeList = XmlHelper.FindChildNodesByTagName( rootNode, 'ziptool') if len(launcherNodeList) > 0: launcherNode = launcherNodeList[0] self.zipToolPath = launcherNode.getAttribute('path') self.zipToolArgs = launcherNode.getAttribute('args') # read in supported platforms emulatorNodeList = XmlHelper.FindChildNodesByTagName( rootNode, 'emulator') for emulatorNode in emulatorNodeList: name = emulatorNode.getAttribute('name') romsPath = emulatorNode.getAttribute('romsPath') romFilter = emulatorNode.getAttribute('romFilter') exe_file = emulatorNode.getAttribute('exe_file') exe_args = emulatorNode.getAttribute('exe_args') giantBombPlatformId = emulatorNode.getAttribute( 'giantBombPlatformId') emuMap = { "name": name, "romsPath": romsPath, "romFilter": romFilter, "exe_file": exe_file, "exe_args": exe_args, "giantBombPlatformId": giantBombPlatformId } self.emulatorTypeMap.append(emuMap) except: pass if len(self.scraperCacheDirectory) == 0: self.scraperCacheDirectory = os.path.join(resourcesPath, 'cache')
def recursive_link_children(_graph, parent): for child in list(parent): _graph.edge(XmlHelper.safe_caption(parent), XmlHelper.safe_caption(child)) recursive_link_children(_graph, child)
def generate_clean_xml(_file): _tree, _root = XmlHelper.parse_file(_file) # clean up flags file XmlHelper.remove_namespace_from_branch(_root) XmlHelper.remove_tag_from_branch(_root, 'Changes') XmlHelper.collapse_tag_from_branch(_root, 'Flags') XmlHelper.collapse_tag_from_branch(_root, 'Categories') XmlHelper.collapse_empty_nodes(_root) XmlHelper.clean_long_tails(_root) _root.tag = 'Categories' # save flags output _tree.write('output.xml') return _tree, _root
#coding:utf-8 import os import sys FilePath = os.path.abspath(os.path.dirname(__file__) + '/../') sys.path.append(FilePath) from XmlHelper import * if __name__ == '__main__': xmlFilePath = os.path.abspath( os.path.dirname(__file__) + '/DataBaseCfg.xml') XmlHelpers = XmlHelper(xmlFilePath) print(XmlHelpers.parse())
def loadSettings(): loadedSettings=settings() import xml.dom.minidom, os.path, sys, XmlHelper #Parse the settings.xml file...os.path.abspath(os.path.dirname(sys.argv[0])) get's the scripts directory xmlDoc=xml.dom.minidom.parse(os.path.abspath(os.path.dirname(sys.argv[0])) + "/settings/settings.xml") """1.Get the nicks:""" #""1a.Get the nicks tag, and use getText() to get the TEXT_NODE of the nicks tag nicksTag=xmlDoc.getElementsByTagName("nicks")[0] nicksTagText=XmlHelper.getText(nicksTag.childNodes) #""1b.Split it into space( ) and add it to settings.nicks[] for i in nicksTagText.split(" "): loadedSettings.nicks.append(i); """2.Get the username""" usernameTag=xmlDoc.getElementsByTagName("username")[0] usernameTagText=XmlHelper.getText(usernameTag.childNodes) loadedSettings.username=usernameTagText """3.Get the realname""" realnameTag=xmlDoc.getElementsByTagName("realname")[0] realnameTagText=XmlHelper.getText(usernameTag.childNodes) loadedSettings.realname=realnameTagText """4.Get the chatTextView colors""" chatColorsTag=xmlDoc.getElementsByTagName("chatColors") for colorTag in chatColorsTag[0].childNodes: if colorTag.nodeType == colorTag.ELEMENT_NODE: name = XmlHelper.getAttribute(colorTag.attributes,"name") r = int(XmlHelper.getAttribute(colorTag.attributes,"red")) g = int(XmlHelper.getAttribute(colorTag.attributes,"green")) b = int(XmlHelper.getAttribute(colorTag.attributes,"blue")) sColor = gtk.gdk.Color(red=r * 257,green=g * 257,blue=b * 257,pixel=0) setChatColorVar(loadedSettings,name,sColor) """5.Get the treeviews Colors""" treeColorsTag=xmlDoc.getElementsByTagName("treeviewColors") for colorTag in treeColorsTag[0].childNodes: if colorTag.nodeType == colorTag.ELEMENT_NODE: name = XmlHelper.getAttribute(colorTag.attributes,"name") r = int(XmlHelper.getAttribute(colorTag.attributes,"red")) g = int(XmlHelper.getAttribute(colorTag.attributes,"green")) b = int(XmlHelper.getAttribute(colorTag.attributes,"blue")) sColor = gtk.gdk.Color(red=r * 257,green=g * 257,blue=b * 257,pixel=0) setTreeColorVar(loadedSettings,name,sColor) """6.Get the server""" serversTag=xmlDoc.getElementsByTagName("servers")[0] for serverTag in serversTag.childNodes: if serverTag.nodeType == serverTag.ELEMENT_NODE: if serverTag.nodeName == "server": nServer = sServer() nServer.cName = XmlHelper.getAttribute(serverTag.attributes,"name") #Name of the server nServer.autoconnect = makeBool(XmlHelper.getAttribute(serverTag.attributes,"autoconnect")) #Determines whether to connect to this server when Nyx starts nServer.addresses = [] #Addresses for this server(If the first server is unavailable, Nyx tries connecting to the enxt one) #Get the addresses to connect to. for addressTag in serverTag.childNodes: if addressTag.nodeType == addressTag.ELEMENT_NODE: #address() address = sServer() address.cAddress = XmlHelper.getText(addressTag.childNodes) address.cPort = int(XmlHelper.getAttribute(addressTag.attributes,"port")) address.cSsl = makeBool(XmlHelper.getAttribute(addressTag.attributes,"ssl")) address.cPass = XmlHelper.getAttribute(addressTag.attributes,"pass") nServer.addresses.append(address) loadedSettings.servers.append(nServer) #Get the themePath themeTag=xmlDoc.getElementsByTagName("theme")[0] loadedSettings.themePath = XmlHelper.getAttribute(themeTag.attributes,"path") return loadedSettings
def cmd(server, word, word_eol, usrManager, relayManager, loadedModules): # if this is not a PRIVMSG to a channel make word[2] the nick of the # person that is sending this. if word[2] == server.nick: word[2] = word[0].split("!")[0] if word[3] == "|about": aboutMsg = "MDSBot 0.2 :D" server.send("PRIVMSG %s :%s" % (word[2], aboutMsg)) return True elif word[3] == "VERSION": server.send("NOTICE %s :%s" % (word[0].split("!")[0], "VERSION MDSBot 0.2 :D")) return True elif word[3].startswith("|quit"): if usrManager.logged_in(word[0].split("!")[0], "quit") \ or usrManager.logged_in(word[0].split("!")[0], "*"): quitMsg = "Quitting on request of " + word[0].split("!")[0] if len(word[3].split()) > 1: quitMsg = server.gen_eol(word[3])[1] #Quit the relays(remove them) for i in range(len(relayManager.relays)): relayManager.rem(i, quitMsg=quitMsg) server.send("QUIT :%s" % (quitMsg)) else: usrManager.print_insufficient_privils(word, server, "quit") return True elif word[3].startswith("|say"): if usrManager.logged_in(word[0].split("!")[0], ["say", "*"]): chann = word[2] msg = server.gen_eol(word[3])[1] if word[3].split()[1].startswith("#"): chann = word[3].split()[1] msg = server.gen_eol(word[3])[2] server.send("PRIVMSG %s :%s" % (chann, msg)) else: usrManager.print_insufficient_privils(word, server, "say") return True ########################################################################## # USERS # elif word[3].startswith("register") and (word[2].startswith("#") == False): if len(word[3].split()) > 1: nick = word[0].split("!")[0] password = word[3].split()[1] email = word[3].split()[2] else: reply = "register: \x02register password email" server.send("PRIVMSG %s :%s" % (word[0].split("!")[0], reply)) return True #Check if there already is a user by this nick if usrManager.get_user(nick) == False: usrManager.add(nick, password, email) XmlHelper.save_users(usrManager) #Send a message confirming. server.send("PRIVMSG %s :%s" % (word[0].split("!")[0], "You have registered successfully")) else: reply = "An account for " + nick + " already exists." server.send("PRIVMSG %s :%s" % (word[0].split("!")[0], reply)) return True elif word[3].startswith("identify") and (word[2].startswith("#") == False): #Check if the user didn't just say identify if len(word[3].split()) > 1: nick = word[0].split("!")[0] password = word[3].split()[1] else: reply = "Identify: \x02identify password" server.send("PRIVMSG %s :%s" % (word[0].split("!")[0], reply)) return True user = usrManager.get_user(nick) if user != False: #Check if the password is correct if user.password == password: usrManager.change_user_status(nick, True) #Send a message confirming. server.send("PRIVMSG %s :%s" % (word[0].split("!")[0], "You are now identified as \x02" + nick)) else: server.send("PRIVMSG %s :%s" % (word[0].split("!")[0], "\x0305Incorrect password")) else: server.send("PRIVMSG %s :%s" % (word[0].split("!")[0], "\x0305No user by this nickname found")) return True elif word[3].startswith("logout") and (word[2].startswith("#") == False): #Check if the user didn't just say logout if len(word[3].split()) > 2: nick = word[3].split()[1] password = word[3].split()[2] user = usrManager.get_user(nick) if user != False: #Check if the password is correct if user.password == password: usrManager.change_user_status(nick, False) #Send a message confirming. server.send("PRIVMSG %s :%s" % (word[0].split("!")[0], "\x02" + nick + "\x02 is now logged out")) else: server.send("PRIVMSG %s :%s" % (word[0].split("!")[0], "\x0305Incorrect password")) else: server.send("PRIVMSG %s :%s" % (word[0].split("!")[0], "\x0305User doesn't exist")) else: reply = "logout: \x02logout nick password" server.send("PRIVMSG %s :%s" % (word[0].split("!")[0], reply)) return True elif word[3].startswith("|privileges"): if usrManager.logged_in(word[0].split("!")[0], ""): user = usrManager.get_user(word[0].split("!")[0]) server.send("PRIVMSG %s :%s" % (word[2],"Your privileges are \x0307" + ", ".join(user.privileges))) else: server.send("PRIVMSG %s :%s" % (word[2], \ "\x0305You don't have any privileges because your not logged in.")) return True elif word[3].startswith("|user") and len(word[3].split()) > 3: if word[3].split()[2] == "privileges": #Check if the user exists user = usrManager.get_user(word[3].split()[1]) if user == False: server.send("PRIVMSG %s :%s" % (word[2], \ "\x0305User doesn't exist")) return True if len(word[3].split()) > 4: #Adds privileges to a user if word[3].split()[3] == "add": #Check if the user is logged in and has privileges if usrManager.logged_in(word[0].split("!")[0], ["user_privils_add", "*"]) \ and usrManager.has_privil(word[0].split("!")[0], [word[3].split()[4], "*"]): user = usrManager.modify_privil(word[3].split()[1], word[3].split()[4]) XmlHelper.save_users(usrManager) server.send("PRIVMSG %s :%s" % (word[2], \ "\x0303Privileges for \x0307" + word[3].split()[1] + " \x0303added successfully")) else: usrManager.print_insufficient_privils(word, server, "user_privils_add") return True #Removes privileges from a user elif word[3].split()[3] == "rem": #Check if the user is logged in and has privileges #Also check if the user from who you want to remove privileges doesn't have * if usrManager.logged_in(word[0].split("!")[0], ["user_privils_rem", "*"]) \ and (usrManager.has_privil(word[3].split()[1], "*") == False \ or usrManager.has_privil(word[0].split("!")[0], "*")): user = usrManager.modify_privil(word[3].split()[1], word[3].split()[4], True) XmlHelper.save_users(usrManager) server.send("PRIVMSG %s :%s" % (word[2], \ "\x0303Privileges for \x0307" + word[3].split()[1] + " \x0303removed successfully")) else: usrManager.print_insufficient_privils(word, server, "user_privils_rem") return True #Lists users privileges if word[3].split()[3] == "list": #Check if the user is logged in and has privileges if usrManager.logged_in(word[0].split("!")[0], ["user_privils_list", "*"]): user = usrManager.get_user(word[3].split()[1]) server.send("PRIVMSG %s :%s" % (word[2], \ word[3].split()[1] + " privileges are \x0307" + ", ".join(user.privileges))) else: usrManager.print_insufficient_privils(word, server, "user_privils_list") #If the command is incorrect, print the help else: print_user_help(word, server) #Print the help if the command is incorrect else: print_user_help(word, server) return True elif word[3].startswith("|users"): if usrManager.logged_in(word[0].split("!")[0], ["list_users", "*"]): loggedInUsers = [] for usr in usrManager.users: if usr.loggedIn: loggedInUsers.append(usr.nick) msg = ", ".join(loggedInUsers) server.send("PRIVMSG %s :%s" % (word[2], "Users that are logged in: " + msg)) else: usrManager.print_insufficient_privils(word, server, "list_users") return True elif word[3].startswith("|user"): print_user_help(word, server); return True # USERS END # ########################################### # RELAY START # elif word[3].startswith("|relay"): try: if word[3].split()[1] == "add": if len(word[3].split()) > 3: if usrManager.logged_in(word[0].split("!")[0], ["relay", "*"]): addr = word[3].split()[2] chan = word[3].split()[3] port = 6667 relayToChan = word[2] nick = "MDSBot" silent = True if len(word[3].split()) > 4: port = int(word[3].split()[4]) if len(word[3].split()) > 5: relayToChan = word[3].split()[5] if len(word[3].split()) > 6: nick = word[3].split()[6] if len(word[3].split()) > 7: if word[3].split()[7] == "t": silent = True if word[3].split()[7] == "f": silent = False #Join relayToChan server.send("JOIN %s" % (relayToChan)) #Check if a relay with this address already exists if relayManager.get_relay(addr=addr) == False: relayManager.add(relayToChan.lower(), [chan.lower()], server, addr, port, nick, silent) else: server.send("PRIVMSG %s :%s" % (word[2], \ "\x0305A relay which is connected to \x0301" + addr + " \x0305already exists.")) return True server.send("PRIVMSG %s :%s" % (word[2], "Connecting to %s:%s/%s" % (addr, port, chan))) else: usrManager.print_insufficient_privils(word, server, "relay") else: server.send("PRIVMSG %s :%s" % (word[2], "|relay add server #chan [port] [#relayToChan] [nick] [silent(t/f)]")) elif word[3].split()[1] == "rem": if len(word[3].split()) > 2: if usrManager.logged_in(word[0].split("!")[0], ["relay", "*"]): index = word[3].split()[2] #This is either the index or the address if "." in index: result = relayManager.rem(addr=index, quitMsg="Relay terminated") else: result = relayManager.rem(index, quitMsg="Relay terminated") if result == True: server.send("PRIVMSG %s :%s" % (word[2], "\x0303Relay removed")) else: server.send("PRIVMSG %s :%s" % (word[2], "\x0305Error removing relay")) else: usrManager.print_insufficient_privils(word, server, "relay") else: server.send("PRIVMSG %s :%s" % (word[2], "|relay rem index/address")) elif word[3].split()[1] == "info": if len(word[3].split()) > 2: if usrManager.logged_in(word[0].split("!")[0], ["default", "*"]): index = word[3].split()[2] #This is either the index or the address relay = relayManager.get_relay(index) if "." in index: relay = relayManager.get_relay(addr=index) if relay != False: message = "\x0305Address: \x0304%s \x0305Port: \x0304%s " % \ (relay.server.address, str(relay.server.port)) message += "\x0305Channel(s): \x0304%s \x0305Relays to channel: \x0304%s \x0305Nick: \x0304%s \x0305Silent: \x0304%s" % \ (", ".join(relay.chans), relay.relayToChan, relay.server.nick, relay.silent) server.send("PRIVMSG %s :%s" % (word[2], message)) else: server.send("PRIVMSG %s :%s" % (word[2], "\x0305Error retrieving relay info")) else: usrManager.print_insufficient_privils(word, server, "relay") else: server.send("PRIVMSG %s :%s" % (word[2], "|relay info index/address")) elif word[3].split()[1] == "join": if len(word[3].split()) > 3: if usrManager.logged_in(word[0].split("!")[0], ["relay", "*"]): index = word[3].split()[2] #This is either the index or the address chan = word[3].split()[3] relay = relayManager.get_relay(index) if "." in index: relay = relayManager.get_relay(addr=index) if relay != False: relay.chans.append(chan.lower()) relay.server.send("JOIN %s" % chan) server.send("PRIVMSG %s :%s" % (word[2], "\x0303Joining " + chan)) else: server.send("PRIVMSG %s :%s" % (word[2], "\x0305Error relay could not be found")) else: usrManager.print_insufficient_privils(word, server, "relay") else: server.send("PRIVMSG %s :%s" % (word[2], "|relay join index/address #chan")) elif word[3].split()[1] == "part": if len(word[3].split()) > 3: if usrManager.logged_in(word[0].split("!")[0], ["relay", "*"]): index = word[3].split()[2] #This is either the index or the address chan = word[3].split()[3] relay = relayManager.get_relay(index) if "." in index: relay = relayManager.get_relay(addr=index) if relay != False: if chan in relay.chans: relay.chans.remove(chan.lower()) relay.server.send("PART %s" % chan) server.send("PRIVMSG %s :%s" % (word[2], "\x0303Leaving " + chan)) else: server.send("PRIVMSG %s :%s" % (word[2], "\x0305The relay isn't in that channel")) else: server.send("PRIVMSG %s :%s" % (word[2], "\x0305Error relay could not be found")) else: usrManager.print_insufficient_privils(word, server, "relay") else: server.send("PRIVMSG %s :%s" % (word[2], "|relay part index/address #chan")) else: server.send("PRIVMSG %s :%s" % (word[2], "|relay add server #chan [port] [nick] [silent(t/f)]")) except Exception as err: print str(err) server.send("PRIVMSG %s :%s" % (word[2], "|relay [add/info/rem/join/part]")) return True # RELAY END # ################## elif word[3].startswith("|join") and len(word[3].split()) > 1: if usrManager.logged_in(word[0].split("!")[0], ["join", "*"]): server.send("JOIN %s" % (word[3].split()[1])) else: usrManager.print_insufficient_privils(word, server, "join") return True elif word[3].startswith("|part") and len(word[3].split()) > 1: if usrManager.logged_in(word[0].split("!")[0], ["part", "*"]): server.send("PART %s" % (word[3].split()[1])) else: usrManager.print_insufficient_privils(word, server, "part") return True elif word[3].startswith("|nick") and len(word[3].split()) > 1: if usrManager.logged_in(word[0].split("!")[0], ["nick", "*"]): server.send("NICK %s" % (word[3].split()[1])) else: usrManager.print_insufficient_privils(word, server, "nick") return True elif word[3].startswith("|modules"): if word[3].split()[1] == "load": if usrManager.logged_in(word[0].split("!")[0], ["modules_load", "*"]): if len(word[3].split()) > 2: name = word[3].split()[2] import imp, os, sys try: modulePath = os.path.join(os.path.dirname(sys.argv[0]), "modules/%s/%s.py" % (name, name)) sys.path.append(os.path.dirname(modulePath)) loadedModules[name] = imp.load_source(name, modulePath) loadedModules[name].main(server, word[2], usrManager) XmlHelper.saveSettings(loadedModules) except IOError: import traceback;traceback.print_exc() server.send("PRIVMSG %s :%s" % (word[2], "\x0305Module not found")) else: usrManager.print_insufficient_privils(word, server, "modules_load") return True elif word[3].split()[1] == "unload": if usrManager.logged_in(word[0].split("!")[0], ["modules_unload", "*"]): if len(word[3].split()) > 2: name = word[3].split()[2] try: loadedModules[name].destroy(server) del loadedModules[name] import os, sys modulePath = os.path.join(os.path.dirname(sys.argv[0]), "modules/%s/%s.py" % (name, name)) sys.path.remove(sys.path.index(os.path.dirname(modulePath))) XmlHelper.saveSettings(loadedModules) except KeyError: server.send("PRIVMSG %s :%s" % (word[2], "\x0305Module not found")) else: usrManager.print_insufficient_privils(word, server, "modules_unload") return True elif word[3].split()[1] == "reload": if usrManager.logged_in(word[0].split("!")[0], ["modules_load", "*"]): if len(word[3].split()) > 2: name = word[3].split()[2] try: # Unload the module loadedModules[name].destroy(server) del loadedModules[name] # Load the module import imp, os, sys loadedModules[name] = imp.load_source(name, \ os.path.join(os.path.dirname(sys.argv[0]), "modules/%s/%s.py" % (name, name))) loadedModules[name].main(server, word[2], usrManager) XmlHelper.saveSettings(loadedModules) except KeyError: server.send("PRIVMSG %s :%s" % (word[2], "\x0305Module not found")) return True return True elif word[3].split()[1] == "list": if len(loadedModules.keys()) != 0: server.send("PRIVMSG %s :%s" % (word[2], "Currently loaded modules: " + \ ", ".join(loadedModules.keys()))) else: server.send("PRIVMSG %s :%s" % (word[2], "There are no loaded modules")) return True elif word[3].split()[1] == "about": if len(word[3].split()) > 2: name = word[3].split()[2] try: server.send("PRIVMSG %s :%s" % (word[2], loadedModules[name].about)) except KeyError: server.send("PRIVMSG %s :%s" % (word[2], "\x0305Module not found")) except AttributeError: server.send("PRIVMSG %s :%s" % (word[2], "\x0305Module has no about message.")) return True # Call the modules .cmd for i in iter(loadedModules): try: if loadedModules[i].cmd(server, word, word_eol, usrManager): return True except: # Print the error... import traceback, sys exc_type, exc_value, exc_traceback = sys.exc_info() error = traceback.extract_tb(exc_traceback) msg = "\x0305Error, line: %s at function \'%s\'" % \ (error[len(error)-1][1], error[len(error)-1][2]) msg2 = " " + error[len(error)-1][3] server.send("PRIVMSG %s :%s" % (word[2], msg)) server.send("PRIVMSG %s :%s" % (word[2], " " + str(exc_value))) server.send("PRIVMSG %s :%s" % (word[2], msg2)) return True #if word[3].startswith("|"): # server.send("PRIVMSG %s :%s" % (word[2], "\x0305Unknown command")) return True