def action(self, complete):
     argument=urllib.quote(complete.message())
     url=readSetting(complete.cmd()[0],"url")
     regex=readSetting(complete.cmd()[0],"regex")
     url = url.replace('$*$', argument)
     print url
     page=urllib2.urlopen(urllib2.Request(url, headers={
         'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; rv:19.0) Gecko/20100101 Firefox/19.0',
         'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
     }))
     print page
     page = page.read()
     matches=re.findall(regex,page, re.DOTALL)
     try:
         matches=[re.sub("<br\s?/?>", " ", match) for match in matches]
         matches=[re.sub("<.*?>","",match).replace('\n',' ').replace('\r',' ') for match in matches]
         matches=[re.sub("\s+"," ",match) for match in matches]
         #matches=[re.sub("x3c.*?x3e","",match) for match in matches]
     except Exception as detail:
         print detail
         print "printRandomRegexMatchFromWebpage didn't go so well in the removing HTML tags thing"
     ret=[]
     print regex
     if readSetting(complete.cmd()[0],"matchText")!="":
         ret.append(readSetting(complete.cmd()[0],"matchText"))
     for i in range(len(matches)):
         if type(matches[i])==str:
             ret.append(re.sub("[^a-zA-Z0-9.,{}()[\]?\\/!\"$%^&*:;[email protected]'~#<>=+\-\s]","",matches[i]))
         elif type(matches[i])==tuple:
             ret.append(' '.join(matches[i]))
     if ret==[]:
         ret.append("No matches.")
     ret = random.choice(ret)
     ret=["PRIVMSG $C$ :"+ret.decode('utf-8')]
     return ret
Example #2
0
    def action(self, complete):
        msg=complete.message()
        plugins=settingsHandler.readSetting("'core-userlevels'","plugin,level")
        returner=[]
        output=[]
        if msg=="":
            for plugin, level in plugins:
                if int(level)>0:
                    returner.append(':'.join((plugin,level)))
                out=', '.join(returner)
            output.append("PRIVMSG $C$ :"+out)
            output.append("PRIVMSG $C$ :All other functions do not require elevation")
        elif msg.split()[0]=="-list":
            if len(msg.split())==1:
                for plugin, level in plugins:
                    returner.append(':'.join((plugin,level)))
                out=', '.join(returner)
                output.append("PRIVMSG $C$:"+out)
            else:
                yes=[]
                no=[]
                if msg.split()[1].isdigit():
                    userlevel=int(msg.split()[1])
                else:
                    userlevel=settingsHandler.readSetting("autoidentifyd","level",where="nickname='%s'"%msg.split()[1])
                    if userlevel==[]:
                        userlevel="0"
                    userlevel=int(userlevel)
                for plugin, level in plugins:
                    if len(msg.split())!=2 or int(level)>0:
                        if int(level)>userlevel:
                            no.append(plugin)
                        else:
                            yes.append(plugin)
                output.append("PRIVMSG $C$ :Can use: "+', '.join(yes))
                output.append("PRIVMSG $C$ :Can not use: "+', '.join(no))
                if userlevel>=100:
                    output.append("PRIVMSG $C$ :Can not be ignored.")
                elif userlevel>=20:
                    output.append("PRIVMSG $C$ :Channelwide ignores will not take effect.")
                else:
                    output.append("PRIVMSG $C$ :All ignores take effect")

        elif msg.split()[0] in globalv.loadedPlugins.keys():
            if len(msg.split())==1:
                for plugin, level in plugins:
                    if plugin.lower()==msg.split()[0].lower():
                        output.append("PRIVMSG $C$ :"+plugin+":"+level)
            elif msg.split()[1].isdigit():
                settingsHandler.updateSetting("'core-userlevels'","level", msg.split()[1], where="plugin='%s'"%msg.split()[0])
                output.append("PRIVMSG $C$ :Altered access requirements for that plugin")
            elif msg.split()[1] in globalv.loadedPlugins.keys():
                 for plugin, level in plugins:
                    if plugin.lower()==msg.split()[1].lower():
                        newLevel=level
                        break
                 settingsHandler.updateSetting("'core-userlevels'","level", newLevel, where="plugin='%s'"%msg.split()[0])
                 output.append("PRIVMSG $C$ :Equalised plugin requirements")

        return output
Example #3
0
 def action(self, complete):
     msg=complete.message()
     votes=int(settingsHandler.readSetting(complete.cmd()[0], "votes"))
     plugin=settingsHandler.readSetting(complete.cmd()[0], "plugin")
     user=complete.userMask().split('!')[1]
     if msg.lower() in self.Voted.keys():
         if user in self.Voted[msg.lower()]:
             return ["PRIVMSG $C$ :You have already voted!"]
         else:
             self.Voted[msg.lower()].append(user)
             numRequired=votes-len(self.Voted[msg.lower()])
             if numRequired>0:
                 if msg!="":
                     msg=" "+msg
                 if numRequired!=1:
                     s="s"
                 else:
                     s=""
                 return ["PRIVMSG $C$ :Voted to %s%s. %s more vote%s required."%(plugin,msg,numRequired,s)]
     else:
         self.Voted[msg.lower()]=[user]
         numRequired=votes-len(self.Voted[msg.lower()])
         if msg!="":
             msg=" "+msg
         if numRequired!=1:
             s="s"
         else:
             s=""
         return ["PRIVMSG $C$ :Voted to %s%s. %s more vote%s required."%(plugin,msg,numRequired,s)]
     if len(self.Voted[msg.lower()])>=votes:
         input=":%s!%s PRIVMSG %s :!%s %s"%(globalv.nickname,globalv.miscVars[0][globalv.nickname],complete.channel(),plugin, msg)
         inputObj=formatInput(pluginArguments(input))
         output=globalv.loadedPlugins[plugin.split()[0]].action(inputObj)
         self.Voted[msg.lower()]=[]
         return output
 def action(self, complete):
     argument=urllib.quote(complete.message())
     url=readSetting(complete.cmd()[0],"url")
     regex=readSetting(complete.cmd()[0],"regex")
     numReturns=int(readSetting(complete.cmd()[0],"numMatches"))
     page=urllib2.urlopen(url.replace('$*$',argument)).read()
     matches=re.findall(regex,page, re.DOTALL)
     try:
         matches=[re.sub("<br\s?/?>", " ", match) for match in matches]
         matches=[re.sub("<.*?>","",match).replace('\n',' ').replace('\r',' ') for match in matches]
         matches=[re.sub("\s+"," ",match) for match in matches]
         #matches=[re.sub("x3c.*?x3e","",match) for match in matches]
     except Exception as detail:
         print detail
         print "printRegexMatchFromWebpage didn't go so well in the removing HTML tags thing"
     ret=[]
     if readSetting(complete.cmd()[0],"matchText")!="":
         ret.append(readSetting(complete.cmd()[0],"matchText"))
     for i in range(min(len(matches), numReturns)):
         if type(matches[i])==str:
             ret.append(re.sub("[^a-zA-Z0-9.,{}()[\]?\\/!\"$%^&*:;@'~#<>=+\-\s]","",matches[i]))
         elif type(matches[i])==tuple:
             ret.append(' '.join(matches[i]))
     if ret==[]:
         ret.append("No matches.")
     ret=["PRIVMSG $C$ :"+r.decode('utf-8') for r in ret]
     return ret
Example #5
0
 def action(self, complete):
     showDomain = True if settingsHandler.readSetting("urlFollow", "showDomainLink")=="true" else False
     if "urlFollowQueue" not in globalv.communication.keys():
         return self.urlFollow(complete, showDomain)
     else:
         globalv.communication["urlFollowQueue"].put((complete, self.urlFollow))
         return [""]
Example #6
0
def load_plugin(input, loadAs=""): #Loads a plugin, placing it in it's correct category.
    state=0
    #arguments=shlex.split(' '.join(input.split()[1:]))
    name=input.split()[0]
    x=__import__(name)
    if loadAs!="":
        name=loadAs
    else:
        loadAs = name
    if name in globalv.loadedPlugins:
        state=1
    if name in globalv.loadedRealtime:
        state=1
    if name in globalv.loadedSpecial:
        state=1
    reload(x)
    y=x.pluginClass()
    if y.gettype()=="command":
        globalv.loadedPlugins.update({name:y})
    if y.gettype()=="realtime":
        globalv.loadedRealtime.update({name:y})
    if y.gettype()=="special":
        globalv.loadedSpecial.update({name:y})
    if y.gettype()=="preprocess":
        globalv.loadedPreprocess.update({name:y})
    if y.gettype()=="postprocess":
        globalv.loadedPostprocess.update({name:y})
    globalv.aliasExtensions.update({name:''})
    if settingsHandler.tableExists(name)==0:
        y.__init_db_tables__(name)
    if name not in [x[0] for x in settingsHandler.readSetting("'core-userlevels'", "plugin")]:
        settingsHandler.writeSetting("'core-userlevels'", ["plugin", "level"],[name, str(y.__level__())])
    globalv.basePlugin[loadAs]=input.split()[0]
    return state
Example #7
0
 def action(self, complete):
     idMessages=["identified for this nick","a registered nick","a registered nick"]
     if complete.user() in self.users and ".*!"+complete.userMask().split('!')[1] not in [x[0] for x in globalv.miscVars[2]]:
         if complete.user() not in self.giveup.keys():
                 self.giveup[complete.user()]=0
         if self.giveup[complete.user()]<=0:
             self.giveup[complete.user()]=10
             return ["WHOIS "+complete.user()]
         else:
             self.giveup[complete.user()]-=1
     if complete.complete().split()[1]=="JOIN":
         return ["WHOIS %s"%complete.user()]
     if complete.complete().split()[1] in ["330","307"]:
         level=settingsHandler.readSetting("autoidentifyd","level",where="nickname='%s'"%complete.complete()[1:].split(':')[0].split()[3])
         level="1" if level==[] else level
         if (".*!"+globalv.miscVars[0][complete.complete()[1:].split(':')[0].split()[3]],level) not in globalv.miscVars[2]:
             globalv.miscVars[2].append((".*!"+globalv.miscVars[0][complete.complete()[1:].split(':')[0].split()[3]],level))
     elif complete.complete().split()[1]=="353":
         returns=[]
         for name in complete.message().split():
             try:
                 if name[0] in ["@","+",'&']:
                     name=name[1:]
                 if name in self.users:
                     returns.append("WHOIS %s"%name)
             except:
                 print "Autoidentifyd;whois-on-join;%s;"%name
         return returns
     return [""]
Example #8
0
	def action(self, complete):
		noKickUsers=settingsHandler.readSetting("noKick","noKickUsers")
		noKickUsers=[x[0] if type(x)==tuple else x for x in noKickUsers]
		if complete.split()[0]=="KICK" and complete.split()[2] in noKickUsers:
			return ""
		else:
			return complete
Example #9
0
File: np.py Project: Phoshi/OMGbot
 def action(self, complete):
     msg = complete.message()
     user = complete.user()
     users = {}
     for nicknick in settingsHandler.readSetting(complete.cmd()[0], "IRCnick, LASTFMnick"):
         users.update({nicknick[0].lower(): nicknick[1]})
     if msg != "":
         user = msg
     if len(msg.split()) >= 2:
         if msg.split()[0] == "-link":
             settingsHandler.writeSetting(
                 complete.cmd()[0], ["IRCnick", "LASTFMnick"], [complete.user(), " ".join(msg.split()[1:])]
             )
             return ["PRIVMSG $C$ :Linked %s to %s" % (complete.user(), " ".join(msg.split()[1:]))]
     try:
         if user.lower() in users.keys():
             name = users[user.lower()]
         else:
             name = user
         url = "http://ws.audioscrobbler.com/1.0/user/" + name + "/recenttracks.rss"
         p = urllib2.urlopen(url).read()
         p = re.search(
             "<description>Last 10 tracks submitted to Last.fm</description>(.*)</item>", p, re.DOTALL
         ).group(1)
         l = re.search("<link>(.*?)</link>", p, re.DOTALL).group(1)
         p = re.search("<title>(.*?)</title>", p, re.DOTALL).group(1)
         if len(l) > 50:
             l = bitly(l)
         p = p.split("\xe2\x80\x93")
         msg = user + " is listening to" + p[1].decode("utf-8") + " by " + p[0].decode("utf-8") + " (" + l + ")"
     except:
         msg = "I don't know what " + user + " is listening to. Sorry."
     return ["PRIVMSG $C$ :" + msg]
Example #10
0
 def action(self, complete):
     msg=complete.message()
     command=msg.split()[0]
     if command=="list":
         names=settingsHandler.readSettingRaw("laterd","recipient, sender, timestamp", where="sent='0' AND anonymous='0'")
         returns=[]
         for name in names:
             try:
                 recipient=name[0]
                 sender=name[1]
                 timestamp=name[2]
                 ctime=time.strftime("%H:%M on %d-%m-%Y",time.gmtime(int(timestamp)))
                 message=recipient+" has a message from "+sender+" (Sent on "+ctime+")"
                 returns.append(message)
             except:
                 pass
         if returns==[]:
             returns.append("No messages.")
         return ["PRIVMSG $C$ :"+', '.join(returns)]
     elif command=="remove":
         try:
             senderString=" and sender=='%s'"%complete.user()
             if isAllowed(complete.userMask())>=150:
                 senderString=""
             where  = "recipient=%s and sent='0'" % repr(msg.split()[1].lower())
             where += senderString
             print where
             settingsHandler.updateSetting("laterd","sent", "'2'", where=where)
             return ["PRIVMSG $C$ :Later successfully removed!"]
         except Exception as detail:
             return ["PRIVMSG $C$ :Later not removed"]
     else:
         anonymous = "0"
         secret_pfx = "secret::"
         if msg.startswith(secret_pfx):
             anonymous = "1"
             msg = msg[len(secret_pfx):]
         
         channels=[]
         while msg.split()[0][0]=="#":
             channels.append(msg.split()[0])
             msg=' '.join(msg.split()[1:])
         channel='|'.join(channels)
         recipients=list(set(msg.split()[0].lower().split(',')))
         recipients = [re.sub('[^0-9a-z-[\]*?]', '?', x) for x in recipients]
         sender=complete.user()
         senderMask=complete.userMask()
         timestamp=str(int(time.time()))
         message=' '.join(msg.split()[1:])
         message = message.replace('$U$','$recipient$')
         for recipient in recipients:
             print recipient
             id=str(int(settingsHandler.readSetting("laterd", "COUNT(id)"))+1)
             settingsHandler.writeSetting("laterd",["id", "recipient","sender","senderMask","timestamp","message", "channel", "anonymous",  "sent"],[id, recipient, sender, senderMask, timestamp, message, channel, anonymous, "0"])
             settingsHandler.db.commit()
         return ["PRIVMSG $C$ :Ok, I'll tell "+', '.join(recipients[:-1])+(" and "+recipients[-1] if len(recipients)>1 else recipients[-1])+" that when they next speak!"]
     return ["PRIVMSG $C$ :"+msg]
Example #11
0
 def action(self, complete):
     msg=complete.message()
     mode=plugin=setting=set=where=""
     mode=msg.split()[0]
     returns="No such mode '%s'" % mode
     plugin=msg.split()[1]
     try:
         setting=msg.split()[2]
     except:
         setting=""
     try:
         set=' '.join(msg.split()[3:])
     except:
         set=""
     if len(set.split())<3:
         where = '1==1'
     elif set.split()[-2].lower()=="where":
         where=set.split()[-1]
         set=' '.join(set.split()[:-2])
     else:
         where="1==1"
     if isAllowed(complete.userMask())>=getLevel(complete.cmd()[0]):
         if mode=="update":
             settingsHandler.updateSetting(plugin, setting, set, where=where)
             returns="Setting updated, sir!"
         if mode=="delete":
             settingsHandler.deleteSetting(plugin, setting, set)
             returns="Setting removed, my lord!"
         if mode=="add":
             setting=setting.split('||')
             set=set.split('||')
             settingsHandler.writeSetting(plugin, setting, set)
             returns="Setting Set, Cap'n!"
         if mode=="drop-table":
             settingsHandler.dropTable(plugin)
             returns="Settings lost, comrade!"
         if mode=="list":
             columns=settingsHandler.readColumns(plugin)
             returns=', '.join(columns)
         if mode=="current":
             results=settingsHandler.readSetting(plugin, setting)
             results=[str(x[0]) if len(x)==1 and type(x)==tuple else x for x in results] if type(results)==list else str(results)
             results=', '.join(results) if type(results)==list else results
             returns=results
         if mode=="commit":
             settingsHandler.db.commit()
             returns="Committed!"
         if mode=="copy":
             settingsHandler.executeQuery("INSERT INTO '%s' SELECT * FROM '%s'"%(msg.split()))
         if mode=="query":
             results=settingsHandler.executeQuery(' '.join(msg.split()[1:]))
             if results!=[]:
                 returns=str(results)
     else:
         returns="Sorry, you can't do this."
     return ["PRIVMSG $C$ :"+returns]
Example #12
0
 def action(self, complete):
     msg=complete.message()
     sender=complete.userMask()
     userAllowed=(isAllowed(sender)>=getLevel(complete.cmd()[0])) if readSetting(complete.cmd()[0],"userRequirement")=="elevated" else sender==readSetting(complete.cmd()[0],"username") if readSetting(complete.cmd()[0],"userRequirement")=="owner" else 1
     if userAllowed:
         if msg=="":
             msg="QQ"
         return ["QUIT :"+msg]
     else:
         return ["KICK $C$ $U$ :Yeah, no."]
Example #13
0
 def action(self, complete):
     if isAllowed(complete.userMask())>=getLevel(complete.cmd()[0]):
         url=complete.message()
         location=settingsHandler.readSetting(complete.cmd()[0],"location")
         wgetString="wget -N --directory-prefix=%s %s &"%(location, url)
         print wgetString
         os.system(wgetString)
         return ["PRIVMSG $C$ :Downloading %s to %s."%(url, location)]
     else:
         return ["PRIVMSG $C$ :Sorry, you need higher priviledges to download files!"]
Example #14
0
 def action(self, complete):
     name=complete.message()
     msg="There was an error in your input!"
     if isAllowed(complete.userMask())<getLevel(complete.cmd()[0]):
         return [""]
     if name.split()[0]=="list":
         return ["PRIVMSG $C$ :"+' '.join(globalv.loadedInputs.keys())]
     elif name.split()[0]=="clean":
         newDict={}
         for plugin in globalv.loadedInputs.keys():
             if globalv.loadedInputs[plugin].isSet()==False:
                 newDict[plugin]=globalv.loadedInputs[plugin]
         globalv.loadedInputs=newDict
         return ["PRIVMSG $C$ :ID list cleaned up manually"]
     elif name.split()[0]=="kickstart":
         globalv.input.startInputDaemons()
         return ["PRIVMSG $C$ :Kickstarted stalling plugins manually"]
     elif name.split()[0]=="reboot":
         definition=settingsHandler.readSetting("'core-input'","definition",where="input='%s'"%name.split()[1])
         print "def"
         x=__import__(str(definition.split()[0]))
         reload(x)
         arguments=str(' '.join(definition.split()[1:]))
         arguments=shlex.split(arguments)
         globalv.loadedInputs[name.split()[1]]=globalv.input.addInputSource(x.asyncInput,tuple(arguments))
         globalv.input.startInputDaemons()
         msg="Rebooting input plugin..."
     elif name.split()[0]=="add":
         name= ' '.join(name.split()[1:])
         try:
             if name.split()[0] in globalv.loadedInputs.keys():
                 raise Exception("An input module with that ID already exists!")
             x=__import__(name.split()[1])
             reload(x)
             arguments=shlex.split(' '.join(name.split()[2:]))
             globalv.loadedInputs[name.split()[0]]=globalv.input.addInputSource(x.asyncInput,tuple(arguments))
             print arguments
             settingsHandler.writeSetting("'core-input'", ["input", "definition"], [name.split()[0], ' '.join(name.split()[1:])])
             globalv.input.startInputDaemons()
             msg="Plugin loaded successfully!"
         except Exception as detail:
             msg="Load failure: "+str(detail)
     elif name.split()[0]=="send":
         plugin = name.split()[1]
         command = " ".join(name.split()[2:])
         globalv.loadedInputs[plugin].put(command)
         msg = "Sent message to plugin"
     elif name.split()[0]=="autosend":
         name= ' '.join(name.split()[1:])
         settingsHandler.writeSetting("'core-input'", ["input", "definition"], [name.split()[0], ' '.join(name.split()[1:])])
         msg = "Plugin configuration added"
     elif name.split()[0]=="unautosend":
         settingsHandler.deleteSetting("'core-input'", "definition", ' '.join(name.split()[1:]))
         msg="Configuration removed!"
     return ["PRIVMSG $C$ :"+msg]
Example #15
0
    def action(self, complete):
        msg=complete.message()
        if msg.split()[0]=="-list":
           users=settingsHandler.readSetting("autoidentifyd","nickname, level")
           out=[]
           for name,level in users:
               if len(msg.split())==1:
                   out.append(name+":"+str(level))
               elif msg.split()[1].lower()==name.lower():
                   out.append(name+":"+str(level))
           msg=', '.join(out)
        elif len(msg.split())==1:
           users=settingsHandler.readSetting("autoidentifyd","nickname, level")
           for name,level in users:
               if name==msg:
                   return ["PRIVMSG $C$ :%s"%(level)]
           return ["PRIVMSG $C$ :0"]


        elif isAllowed(complete.userMask())>=getLevel(complete.cmd()[0]):
            nick = msg.split()[0]
            level = msg.split()[1]

            if nick not in globalv.miscVars[0]:
                return ["PRIVMSG $C$ :That user does not exist."]
            
            if nick in [x[0] for x in settingsHandler.readSetting("autoidentifyd","nickname")]:
                settingsHandler.updateSetting("autoidentifyd","level",str(level), where="nickname='%s'"%nick)
                msg="Level updated"
            else:
                settingsHandler.writeSetting("autoidentifyd",["nickname","level"], [nick, level])
                msg="User Elevated"

            user = '.*!' + globalv.miscVars[0][nick]
            
            globalv.miscVars[2] = filter(lambda (x,y): x != user, globalv.miscVars[2])
            globalv.miscVars[2].append((user, level))

            print globalv.miscVars[2]
        else:
            msg="Only elevated users can do this!"
        return ["PRIVMSG $C$ :"+msg]
Example #16
0
def load_alias(name, plugin): #Loads an alias
    try:
        if plugin.split()[0] in globalv.loadedPlugins:
            if plugin.split()[0] in globalv.aliasExtensions:
                argumentsObject = pluginArguments(":[email protected] PRIVMSG #NARChannel :%s%s"%(globalv.commandCharacter, plugin))
                argumentsObject = formatInput(argumentsObject, globalv.aliasExtensions, False)
                plugin = argumentsObject.fullMessage()[len(globalv.commandCharacter):]
                print plugin

            globalv.loadedPlugins.update({name:globalv.loadedPlugins[plugin.split()[0]]})
            if settingsHandler.tableExists(name)==0:
                globalv.loadedPlugins[plugin.split()[0]].__init_db_tables__(name)
            if name not in [x[0] for x in settingsHandler.readSetting("'core-userlevels'", "plugin")]:
                settingsHandler.writeSetting("'core-userlevels'", ["plugin", "level"],[name, str(globalv.loadedPlugins[plugin.split()[0]].__level__())])
        else: #If the aliases dependancy isn't loaded, load it, then get rid of it afterwards.
            load_plugin(plugin.split()[0])
            globalv.loadedPlugins.update({name:globalv.loadedPlugins[plugin.split()[0]]})
            if settingsHandler.tableExists(name)==0:
                globalv.loadedPlugins[plugin.split()[0]].__init_db_tables__(name)
            if name not in [x[0] for x in settingsHandler.readSetting("'core-userlevels'", "plugin")]:
                settingsHandler.writeSetting("'core-userlevels'", ["plugin", "level"],[name, str(globalv.loadedPlugins[plugin.split()[0]].__level__())])
            unload_plugin(plugin.split()[0])
        globalv.loadedAliases.update({name:plugin})
        globalv.basePlugin[name] = plugin.split()[0]
    except Exception as detail:
        print detail
        try:
            message("Function syntax: "+globalv.commandCharacter+"alias [word] [command] [arguments]",info[2])
        except:
            print "Plugin",name,"failed to load"
    try:
        print "Adding Extensions"
        print plugin
        globalv.aliasExtensions.update({name:" "+' '.join(plugin.split()[1:])})
    except:
        globalv.aliasExtensions.update({name:''})
    if globalv.aliasExtensions[plugin.split()[0]]!="":
        try:
            #globalv.aliasExtensions.update({name:globalv.aliasExtensions[plugin.split()[0]]})
            print "Would have broken here"
        except:
            globalv.aliasExtensions.update({name:''})
Example #17
0
def getLevel(*pluginName):
    try:
        level = settingsHandler.readSetting("'core-userlevels'", "level", where="plugin='%s'" % pluginName[0])
        if level == []:
            level = 0
        else:
            level = int(level)
        return level
    except Exception as detail:
        print "An Exception Occured grabbing the user requirements for", pluginName, ":" + str(detail)
        return 10000
Example #18
0
 def action(self, args):
     complete=args.complete()[1:].split(':',1)
     if len(complete)==2:
         if len(complete[0].split())==3:
             msg=args.message()
             if complete[1].startswith(globalv.commandCharacter):
                 self.userlist.append([complete[0].split('!')[0],time.time()])
                 earliestTimes={}
                 latestTimes={}
                 numberOfTimes={}
                 for line in self.userlist:
                     if line[0] not in earliestTimes.keys():
                         earliestTimes[line[0]]=line[1]
                     else:
                         if earliestTimes[line[0]]>line[1]:
                             earliestTimes[line[0]]=line[1]
                     if line[0] not in latestTimes.keys():
                         latestTimes[line[0]]=line[1]
                     else:
                         if latestTimes[line[0]]<line[1]:
                             latestTimes[line[0]]=line[1]
                     if line[0] not in numberOfTimes.keys():
                         numberOfTimes[line[0]]=0
                     else:
                         numberOfTimes[line[0]]+=1
                 for user in earliestTimes.keys():
                     if latestTimes[user]-earliestTimes[user]<int(settingsHandler.readSetting("noSpam","timeLimit")):
                         if numberOfTimes[user]>=int(settingsHandler.readSetting("noSpam","numberLimit")):
                             userMask=globalv.miscVars[0][user]
                             if not userMask in globalv.ignoredUsers:
                                 settingsHandler.writeSetting("coreIgnorance",["ignorance","nickname"],['.*@'+userMask.split('@')[1],user])
                                 self.userlist=[]
                                 return ["PRIVMSG $C$ :Oi, $U$, shut up for christ's sake."]
                         elif numberOfTimes[user]==int(settingsHandler.readSetting("noSpam","numberLimit")):
                             return ["PRIVMSG $C$ :Hey, $U$, shut up. One more command and I'm ignoring you."]
                     elif numberOfTimes[user]>=2:
                         self.userlist=[]
     return [""]
Example #19
0
 def action(self, complete):
     msg=complete.message()
     url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q='+msg.replace(' ', '%20')
     try:
         response = urllib2.urlopen(url)
         page = response.read()
         result = re.search("(?P<url>\"url\":\"[^\"]+)", page).group('url').decode('utf-8')
         result=result[7:]
         title = re.search("(?P<url>\"titleNoFormatting\":\"[^\"]+)", page).group('url').decode('utf-8')
         title=title[21:]
         titleString=unescape(title)+" (at "+urllib.unquote(result)+')' if settingsHandler.readSetting(complete.cmd()[0],"showTitle")=="True" else urllib.unquote(result)
     except:
         titleString="No results!"
     return ["PRIVMSG $C$ :"+titleString]
Example #20
0
 def action(self, complete):
     msg=complete.message()
     name=msg.split()[0]
     if isAllowed(complete.userMask())<getLevel(complete.cmd()[0]):
         return ["PRIVMSG $C$ :Sorry, only elevated users can do that!"]
     if name=="load" and complete[0].split()[0].split('!')[0]!=readSetting("core","username"):
         return ["PRIVMSG $C$ :Silly bugger, that would break the world!"]
     success=unload_plugin(name)
     if name in globalv.loadedAliases.keys():
         del globalv.loadedAliases[name]
     if msg.split()[1:]==['silently']:
         return [""]
     if success:
         return ["PRIVMSG $C$ :Unload successful!"]
     else:
         return ["PRIVMSG $C$ :Plugin is not loaded!"]
Example #21
0
File: ban.py Project: Phoshi/OMGbot
 def action(self, complete):
     msg=complete.message().split()[0]
     kickReason=' '.join(complete.message().split()[1:])
     if kickReason=="":
         kickReason="Go Away."
     if isAllowed(complete.userMask())>=getLevel(complete.cmd()[0]):
         if msg in globalv.miscVars[0].keys():
             hostmask=globalv.miscVars[0][msg]
         print hostmask
         toReturn=['MODE $C$ +b '+hostmask]
         if settingsHandler.readSetting(complete.cmd()[0], "kickAfterBan")=="True":
             toReturn.append("KICK $C$ "+msg+" :"+kickReason)
         return toReturn
     else:
         print "ID failure:",msg,"not in",globalv.miscVars[0][msg]
         return [""]
Example #22
0
def save_alias(name): #Saves alias to a file, to stick around between sessions. Returns 1 for complete, 0 for the plugin not existing in the current instnace, and 2 if it fails for some reason.
    if name in globalv.loadedAliases.keys(): #To check if the alias is in the current instance (IE, it actually works)
        isIn=0
        for plugin in [plugin[0] for plugin in settingsHandler.readSetting("alias","aliasName")]:
            if name==plugin:
                isIn=1
        plugin=globalv.loadedAliases[name].split()[0]
        arguments=' '.join(globalv.loadedAliases[name].split()[1:])
        if not isIn:
            settingsHandler.writeSetting("alias",['aliasName', 'aliasPlugin', 'aliasArguments'],[name, plugin, arguments])
        else:
            settingsHandler.updateSetting("alias","aliasPlugin", plugin, "aliasName='"+name+"'")
            settingsHandler.updateSetting("alias","aliasArguments", arguments, "aliasName='"+name+"'")
        return 1
    else:
        return 0
Example #23
0
    def action(self, complete):
        user=complete.user()
        if complete.type()!="JOIN":
            return [""]
        returns=[]
        messages=settingsHandler.readSettingRaw("greetd","channel,greet")
        if complete.channel().lower() in [message[0].lower() for message in messages]:
            greetPlugin=settingsHandler.readSetting("greetd","greet",where="channel='%s'"%complete.channel())
            senderMask=complete.userMask()
            arguments=pluginArguments(str(':'+senderMask+" PRIVMSG "+complete.channel()+" :!"+greetPlugin+" "+complete.user()))
            arguments=formatInput(arguments)
            print [arguments.complete()]
            arguments.argument = str(arguments.argument)
            message=globalv.loadedPlugins[greetPlugin].action(arguments)
            print message
            message = formatOutput(message, arguments)
            returns+=message

        return returns
Example #24
0
 def __init_answers__(self, complete):
     self.answers=[x[0] for x in settingsHandler.readSetting("'"+complete.cmd()[0]+"'","answer")]
     random.shuffle(self.answers)
Example #25
0
def parse(msg):
    arguments=pluginArguments(msg)
    global load_plugin
    global unload_plugin
    global isAllowed
    global isBanned
    global load_alias
    global save_alias

    if not isBanned(arguments):
        if arguments.cmd()[0]=="reimportGlobalVariables" and arguments.user()==owner:
            reload(globalv)
            reload(pluginHandler)
            reload(aliasHandler)
            reload(securityHandler)
            load_plugin=pluginHandler.load_plugin
            unload_plugin=pluginHandler.unload_plugin
            isAllowed=securityHandler.isAllowed
            isBanned=securityHandler.isBanned
            load_alias=aliasHandler.load_alias
            save_alias=aliasHandler.save_alias
            load_plugin("load")
            message("Reloaded globalv variables. You may encounter some slight turbulence as we update.",arguments.channel())
        elif arguments.cmd()[0] in globalv.loadedPlugins.keys():
            if arguments.cmd()[0] not in globalv.accessRights[arguments.user()]:
                try:
                    arguments=formatInput(arguments)
                    output=globalv.loadedPlugins[arguments.cmd()[0]].action(arguments)
                    output=formatOutput(output,arguments)
                    if type(output)==list:
                        output=[x for x in output if x!=""]
                    send(output)
                except Exception as detail:
                    print arguments.cmd()[0], "failed:",str(detail)
                    traceback.print_tb(sys.exc_info()[2])
            else:
                output=globalv.loadedPlugins[arguments.cmd[0]].disallowed(formatInput(arguments))
                send(formatOutput(lines,arguments))
        else:
            verboseAutoComplete = True if settingsHandler.readSetting("coreSettings", "verboseAutoComplete")=="True" else False
            command=arguments.cmd()[0]
            nearMatches=difflib.get_close_matches(command, globalv.loadedPlugins.keys(), 6, 0.5)
            nearestMatch=difflib.get_close_matches(command, globalv.loadedPlugins.keys(),1,0.6)
            commandExists = os.path.exists(os.path.join("plugins","command",command+".py"))
            returns=[]
            if nearMatches==[]:
                if not commandExists:
                    if not verboseAutoComplete:
                        return
                    returns=["PRIVMSG $C$ :No such command!"]

                else:
                    returns=["PRIVMSG $C$ :Command not loaded!"]
            elif nearestMatch==[]:
                if not commandExists:
                    if not verboseAutoComplete:
                        return
                    returns=["PRIVMSG $C$ :No such command! Did you mean: %s"%', '.join(nearMatches)]
                else:
                    returns=["PRIVMSG $C$ :Command not loaded! Did you mean: %s"%', '.join(nearMatches)]
            else:
                newArguments=arguments.complete()[1:]
                constructArguments=newArguments.split(' :',1)
                commands=constructArguments[1].split()
                commands[0]=globalv.commandCharacter+nearestMatch[0]
                constructArguments[1]=' '.join(commands)
                newArguments=':'+' :'.join(constructArguments)
                parse(newArguments)
                if (arguments.cmd()[0].lower()!=nearestMatch[0].lower()):
                    if len(nearMatches)>1:
                        returns=["PRIVMSG $C$ :(Command name auto-corrected from %s to %s [Other possibilities were: %s])"%(arguments.cmd()[0], nearestMatch[0], ', '.join(nearMatches[1:]))]
                    else:
                        returns=["PRIVMSG $C$ :(Command name auto-corrected from %s to %s)"%(arguments.cmd()[0], nearestMatch[0])]



            send(formatOutput(returns, arguments))
Example #26
0
import shlex
from pluginArguments import pluginArguments
from pluginFormatter import formatOutput, formatInput
from asyncInputHandler import inputSystem
load_plugin=pluginHandler.load_plugin
unload_plugin=pluginHandler.unload_plugin
isAllowed=securityHandler.isAllowed
isBanned=securityHandler.isBanned
load_alias=aliasHandler.load_alias
save_alias=aliasHandler.save_alias

#local variables
on=1
lastChannelMessage=""
okToSend=False
nickname=settingsHandler.readSetting("core","nickname")
password=settingsHandler.readSetting("core","password")
owner=settingsHandler.readSetting("core","owner")
servers=[settingsHandler.readSetting("core","server"),
  "morgan.freenode.net",
  "asimov.freenode.net",
  "weber.freenode.net",
  "adams.freenode.net"]
port=int(settingsHandler.readSetting("core","port"))

#update global variables
globalv.nickname=nickname
globalv.owner=owner

#IRC protocol message type constants
privmsg="PRIVMSG"
Example #27
0
def getMessage(id):
    return settingsHandler.readSetting("laterd","message",where="id='%s'"%id)
Example #28
0
def correctChannel(id, channel):
    messageChannel=settingsHandler.readSetting("laterd", "channel", where="id='%s'"%id)
    return (channel.lower() in [messageC.lower() for messageC in messageChannel.split('|')] or messageChannel=="")
Example #29
0
def getAnonymous(id):
    return settingsHandler.readSetting("laterd","anonymous",where="id='%s'"%id)=="1"
Example #30
0
def getTimestamp(id):
    return datetime.datetime.fromtimestamp(int(settingsHandler.readSetting("laterd","timestamp",where="id='%s'"%id)))