Ejemplo n.º 1
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
 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.,{}()[\]?\\/!\"$%^&*:;_@'~#<>=+\-\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
Ejemplo n.º 3
0
 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
Ejemplo n.º 4
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
Ejemplo n.º 5
0
 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
Ejemplo n.º 6
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 [""]
Ejemplo n.º 7
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]
Ejemplo n.º 8
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."]
Ejemplo n.º 9
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
Ejemplo n.º 10
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
Ejemplo n.º 11
0
 def __init_answers__(self, complete):
     self.answers = [
         x[0]
         for x in settingsHandler.readSetting("'" + complete.cmd()[0] +
                                              "'", "answer")
     ]
     random.shuffle(self.answers)
Ejemplo n.º 12
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 [""]
Ejemplo n.º 13
0
Archivo: np.py Proyecto: 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]
Ejemplo n.º 14
0
 def action(self, complete):
     if not (isAllowed(complete.userMask()) >= getLevel(complete.cmd()[0])):
         return [""]
     msg = complete.message().strip()
     firstspace = msg.index(' ')
     message = msg[firstspace + 1:]
     recipients = msg[0:firstspace].lower()
     recipients = list(set(recipients.split(',')))
     recipients = [re.sub('[^0-9a-z-[\]*?]', '?', x) for x in recipients]
     sender = complete.user()
     senderMask = complete.userMask()
     timestamp = str(int(time.time()))
     message = message.replace('$U$', '$recipient$')
     for recipient in recipients:
         print recipient
         lastid = int(settingsHandler.readSetting("laterd", "COUNT(id)"))
         id = str(lastid + 1)
         settingsHandler.writeSetting("laterd", [
             "id", "recipient", "sender", "senderMask", "timestamp",
             "message", "channel", "anonymous", "sent"
         ], [
             id, recipient, sender, senderMask, timestamp,
             "dispatch " + message, "", "0", "0"
         ])
         settingsHandler.db.commit()
     msg = ', '.join(recipients[:-1]) + (
         (" and " + recipients[-1] if len(recipients) > 1 else
          recipients[-1]) + " will be informed when they next speak.")
     return ["PRIVMSG $C$ :" + msg]
Ejemplo n.º 15
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
Ejemplo n.º 16
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
Ejemplo n.º 17
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 [""]
Ejemplo n.º 18
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
Ejemplo n.º 19
0
 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.,{}()[\]?\\/!\"$%^&*:;_@'~#<>=+\-\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
Ejemplo n.º 20
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]
Ejemplo n.º 21
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 [""]
Ejemplo n.º 22
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]
Ejemplo n.º 23
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!"]
Ejemplo n.º 24
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."]
Ejemplo n.º 25
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
Ejemplo n.º 26
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]
Ejemplo n.º 27
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(":nothing!nobody@nowhere 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:''})
Ejemplo n.º 28
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]
Ejemplo n.º 29
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
Ejemplo n.º 30
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!"
         ]
Ejemplo n.º 31
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 [""]
Ejemplo n.º 32
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]
Ejemplo n.º 33
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!"]
Ejemplo n.º 34
0
Archivo: ban.py Proyecto: 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 [""]
Ejemplo n.º 35
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
Ejemplo n.º 36
0
def getLevel(*pluginName):
    try:
        level = settingsHandler.readSetting("'core-userlevels'",
                                            "level",
                                            where="plugin='%s'" %
                                            pluginName[0])
        if level == []:
            level = 0
        else:
            level = int(level)
        print "Level of plugin %s is %d" % (pluginName[0], level)
        return level
    except Exception as detail:
        print "An Exception Occured grabbing the user requirements for", pluginName, ":" + str(
            detail)
        return 10000
Ejemplo n.º 37
0
 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 [""]
Ejemplo n.º 38
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!"]
Ejemplo n.º 39
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
Ejemplo n.º 40
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:
        print 'Initializing tables for plugin "' + name + '"'
        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
Ejemplo n.º 41
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 [""]
Ejemplo n.º 42
0
 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]
Ejemplo n.º 43
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
Ejemplo n.º 44
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]
Ejemplo n.º 45
0
from plugins import plugin
Ejemplo n.º 46
0
# -*- coding: utf-8 -*-
Ejemplo n.º 47
0
    def action(self, complete):
        msg = complete.message().split()
        nick = complete.user()
        if self.userScores == {}:
            userScores = settingsHandler.readSetting("chohan", "nick, points")
            print userScores
            if len(userScores) != 2 and type(userScores[1]) != unicode:
                for user, score, in userScores:
                    self.userScores[user] = int(score)
            else:
                user, score = userScores
                self.userScores[user] = int(score)
        if msg[0].lower() == "guess":
            if self.total == 0:
                return [
                    "PRIVMSG $C$ :Nobody's rolled the dice, yet! Roll with roll!"
                ]
            elif nick not in self.userGuesses.keys():
                self.userGuesses[nick] = msg[1]
            else:
                return ["PRIVMSG $C$ :You have already guessed!"]
            msg = "Today could be your lucky day! Putting 1/5th of your points into the pot for a total prize of "
            if nick in self.userScores.keys():
                self.prize += (self.userScores[nick] / 5) + 100
                self.userScores[nick] -= self.userScores[nick] / 5
            msg += str(self.prize)
        elif msg[0].lower() == "roll":
            if self.total == 0:
                self.total = 0
                self.dice = []
                for i in range(2):
                    rtd = random.randint(1, 6)
                    self.total += rtd
                    self.dice.append(rtd)
                    print i, rtd
                self.prize = 100
                msg = "Dice rolled!"
            else:
                msg = "Dice already rolled! Start guessing!"
        elif msg[0].lower() == "reveal":
            if self.total == 0:
                return ["PRIVMSG $C$ :No game in progress!"]
            print "revealan"
            oddEven = "odd!" if self.total % 2 != 0 else "even!"
            winners = []
            msg = [
                "PRIVMSG $C$ :The result is " + oddEven + " (" +
                str(self.dice[0]) + "+" + str(self.dice[1]) + ")"
            ]
            print "winnerappendan"
            for user in self.userGuesses.keys():
                if self.userGuesses[user] == oddEven[:-1]:
                    winners.append(user)
            if winners != []:
                prize = self.prize / len(winners)
            else:
                prize = 0
            print "winnerpointdistributan", winners
            for winner in winners:
                print winner
                if winner in self.userScores.keys():
                    self.userScores[winner] += prize
                    settingsHandler.updateSetting("chohan", "points",
                                                  self.userScores[winner],
                                                  "nick='" + winner + "'")
                else:
                    self.userScores[winner] = prize
                    print "settanwritan"
                    settingsHandler.writeSetting("chohan", ["nick", "points"],
                                                 [winner, str(prize)])
                    print "settanwrittan"
            print "dbhandlan"
            if len(winners) > 1:
                winners = ', '.join(winners[:-1]) + " and " + winners[-1]
                winString = ["winners are ", " each"]
            elif len(winners) == 1:
                winners = winners[0]
                winString = ["winner is ", ""]
            else:
                winners = ""
                winString = ["", ""]
            if winners != "":
                msg += [
                    "PRIVMSG $C$ :The " + winString[0] + winners +
                    ", and they" + winString[1] + " win " + str(prize) +
                    " points"
                ]
            else:
                msg += ["PRIVMSG $C$ :Nobody wins!"]
            self.total = 0
            self.userGuesses = {}
            return msg
        elif msg[0].lower() == "points":
            if len(msg) == 1:
                return [
                    "PRIVMSG $C$ :You have " + str(self.userScores[nick]) +
                    " points"
                ]
            else:
                nick = msg[1]
                if nick in self.userScores.keys():
                    return [
                        "PRIVMSG $C$ :" + nick + " has " +
                        str(self.userScores[nick]) + " points"
                    ]
                else:
                    return ["PRIVMSG $C$ :" + nick + " has 0 points"]
        elif msg[0].lower() == "e-penis":
            if len(msg) == 1:
                return [
                    "PRIVMSG $C$ :8=" + ('=' * (self.userScores[nick] / 100)) +
                    'D'
                ]
            else:
                nick = msg[1]
                if nick in self.userScores.keys():
                    return [
                        "PRIVMSG $C$ :8=" +
                        ('=' * (self.userScores[nick] / 100)) + 'D'
                    ]
                else:
                    return ["PRIVMSG $C$ :" + nick + " has 0 points"]
        elif msg[0].lower() == "scoreboard":
            num = 3 if len(msg) == 1 else int(msg[1])
            scoreNames = []
            for name in self.userScores.keys():
                if self.userScores[name] > 0:
                    scoreNames.append((self.userScores[name], name))
            scoreNames.sort(key=lambda scoreName: scoreName[0])
            scoreNames.reverse()
            msg = "The top " + str(num) + " users are: "
            for i in range(min(num, len(scoreNames))):
                msg += scoreNames[i][1] + " with " + str(
                    scoreNames[i][0]) + " points"
                if i != min(num, len(scoreNames)) - 1:
                    msg += ", "
                else:
                    msg += "!"
        elif msg[0].lower() == "donate":
            name = msg[1]
            amount = int(msg[2])
            if complete.user() not in self.userScores.keys(
            ) or name not in self.userScores.keys():
                msg = "At least ONE of you don't have any points at all! Play a game of chohan first"
            elif self.userScores[complete.user()] >= amount and amount > 0:
                self.userScores[name] += amount
                self.userScores[complete.user()] -= amount
                settingsHandler.updateSetting("chohan", "points",
                                              self.userScores[name],
                                              "nick='" + name + "'")
                settingsHandler.updateSetting("chohan", "points",
                                              self.userScores[complete.user()],
                                              "nick='" + complete.user() + "'")
                msg = "Donated points to " + name + ", oh generous one!"
            elif amount < 0:
                msg = "Nice try!"
            elif self.userScores[complete.user()] < amount:
                msg = "You don't have that much to give!"

        return ["PRIVMSG $C$ :" + msg]
Ejemplo n.º 48
0
class pluginClass(plugin):
    def gettype(self):
        return "realtime"

    def __init__(self):
        self.lastURLs = []

    def __init_db_tables__(self, name):
        settingsHandler.newTable("tumblrdIgnores", "ignore")
        settingsHandler.newTable("tumblrd", "username", "password")

    def action(self, completeargs):
        def makeRequest(reqData, async=True):
            success = False
            failed = 0 if async else 14
            while not success:
                try:
                    con = urllib2.urlopen(req, None, 10)
                    success = True
                except:
                    failed += 1
                    print "Tumblrd failed", failed, "times."
                    if failed > 15:
                        success = True
                    time.sleep(30)

        if not settingsHandler.tableExists("tumblrdIgnores"):
            settingsHandler.newTable("tumblrdIgnores", "ignore")
        complete = completeargs.complete()[1:].split(' :', 1)
        imageFileTypes = [".jpg", ".png", ".bmp"]
        username = settingsHandler.readSetting("tumblrd", "username")
        password = settingsHandler.readSetting("tumblrd", "password")
        ignores = [
            x[0].lower()
            for x in settingsHandler.readSettingRaw("tumblrdIgnores", "ignore")
        ]
        if completeargs.channel().lower() in ignores or completeargs.user(
        ).lower() in ignores:
            return [""]
        if len(complete[0].split()) > 2:
            if complete[0].split()[1] == "PRIVMSG":
                msg = complete[1]
                sender = complete[0].split(' ')
                sender = sender[2]
                if msg.find('http://') != -1 or msg.find('https://') != -1:
                    url = re.search(".*(?P<url>https?://.+?)[\".,?!]?\s",
                                    msg + " ").group("url")
                    if url in self.lastURLs:
                        return [""]
                    else:
                        self.lastURLs.append(url)
                        if len(self.lastURLs) > 10:
                            self.lastURLs.pop(0)
                    logindata = {
                        'email':
                        username,
                        "password":
                        password,
                        "tags":
                        ','.join((completeargs.channel(), completeargs.user()))
                    }
                    if url[-4:].lower() in imageFileTypes:
                        uploaddata = {"type": "photo", "source": url}
                    elif url.lower().find("youtube.com/watch") != -1:
                        request = urllib2.urlopen(url)
                        page = request.read(10000).replace('\n', '')
                        print page
                        title = re.findall("<\s*title\s*>(.*?)</title\s*>",
                                           page, re.I)
                        print title
                        title = title[0]
                        uploaddata = {
                            "type": "video",
                            "embed": url,
                            "caption": title
                        }
                    else:
                        uploaddata = {"type": "link", "url": url}
                    logindata.update(uploaddata)
                    print logindata
                    uploadData = urllib.urlencode(logindata)
                    req = urllib2.Request("http://www.tumblr.com/api/write",
                                          uploadData)
                    print "Constructing thread..."
                    thread = threading.Thread(target=makeRequest, args=(req, ))
                    print "Launching thread..."
                    try:
                        thread.start()
                        print "Thread launched..."
                    except:
                        print "Thread failed to launch - using synchronous fallback"
                        makeRequest(req, False)
                        print "Sucessfully submitted data"
        return [""]
Ejemplo n.º 49
0
 def __init_answers__(self, complete):
     self.answers=[x[0] for x in settingsHandler.readSetting("'"+complete.cmd()[0]+"'","answer")]
     random.shuffle(self.answers)
Ejemplo n.º 50
0
def getAnonymous(id):
    return settingsHandler.readSetting("laterd","anonymous",where="id='%s'"%id)=="1"
Ejemplo n.º 51
0
def getTimestamp(id):
    return datetime.datetime.fromtimestamp(int(settingsHandler.readSetting("laterd","timestamp",where="id='%s'"%id)))
Ejemplo n.º 52
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=="")
Ejemplo n.º 53
0
def getMessage(id):
    return settingsHandler.readSetting("laterd","message",where="id='%s'"%id)
Ejemplo n.º 54
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"
Ejemplo n.º 55
0
    def action(self, complete):
        msg = complete.message()
        nick = complete.userMask()
        sender = complete.channel()
        amsg = msg
        if not os.path.exists(
                os.path.join(
                    "config",
                    settingsHandler.readSetting(complete.cmd()[0],
                                                "quotesLocation") + ".txt")):
            file = open(
                os.path.join(
                    "config",
                    settingsHandler.readSetting(
                        complete.cmd()[0], "quotesLocation") + ".txt"), "w")
            file.close()
        if msg == "":
            zozo = open(
                os.path.join(
                    "config",
                    settingsHandler.readSetting(
                        complete.cmd()[0], "quotesLocation") + ".txt"), 'r')
            lines = zozo.read()
            zozo.close()
            lines = lines.split('\n\n')[:-1]
            retNum = random.randint(0, len(lines) - 1)
            returner = [
                "PRIVMSG $C$ :Quote #" + str(retNum + 1) + " of " +
                str(len(lines)) + ":"
            ]
            for line in lines[retNum].split('\n'):
                returner.append("PRIVMSG $C$ :" + str(line))
            return returner
        elif msg.split()[0].isdigit():
            msg = msg.split()[0]
            quotes = open(
                os.path.join(
                    "config",
                    settingsHandler.readSetting(
                        complete.cmd()[0], "quotesLocation") + ".txt"), 'r')
            lines = quotes.read()
            quotes.close()
            lines = lines.split('\n\n')[:-1]
            retNum = int(msg)
            if retNum > len(lines):
                return ["PRIVMSG $C$ :There is no quote #" + str(retNum)]
            returner = [
                "PRIVMSG $C$ :Quote #" + str(retNum) + " of " +
                str(len(lines)) + ":"
            ]
            for line in lines[retNum - 1].split('\n'):
                returner.append("PRIVMSG $C$ :" + str(line.decode('utf-8')))
            return returner
        elif msg.split()[0] == "modify":
            quoteNum = int(msg.split()[1]) - 1
            toAppend = ' '.join(msg.split()[2:])
            quotes = open(
                os.path.join(
                    "config",
                    settingsHandler.readSetting(
                        complete.cmd()[0], "quotesLocation") + ".txt"), 'r')
            lines = quotes.read()
            quotes.close()
            lines = lines.split('\n\n')[:-1]
            if int(quoteNum) > len(lines):
                return ["PRIVMSG $C$ :There is no quote #" + str(retNum)]
            lines[int(quoteNum)] = toAppend.replace('| ', '\n')
            quotes = open(
                os.path.join(
                    "config",
                    settingsHandler.readSetting(
                        complete.cmd()[0], "quotesLocation") + ".txt"), 'w')
            quotes.write('\n\n'.join(lines) + '\n\n')
            quotes.close()
            return ["PRIVMSG $C$ :Modified that quote!"]

        elif msg.split()[0] == "append":
            quoteNum = int(msg.split()[1]) - 1
            toAppend = ' '.join(msg.split()[2:])
            quotes = open(
                os.path.join(
                    "config",
                    settingsHandler.readSetting(
                        complete.cmd()[0], "quotesLocation") + ".txt"), 'r')
            lines = quotes.read()
            quotes.close()
            lines = lines.split('\n\n')[:-1]
            if int(quoteNum) > len(lines):
                return ["PRIVMSG $C$ :There is no quote #" + str(retNum)]
            lines[int(quoteNum)] += toAppend.replace('| ', '\n')
            quotes = open(
                os.path.join(
                    "config",
                    settingsHandler.readSetting(
                        complete.cmd()[0], "quotesLocation") + ".txt"), 'w')
            quotes.write('\n\n'.join(lines) + '\n\n')
            quotes.close()
            return ["PRIVMSG $C$ :Appended onto that quote!"]

        elif msg.split()[0].lower() == "dump":
            quotes = open(
                os.path.join(
                    "config",
                    settingsHandler.readSetting(
                        complete.cmd()[0], "quotesLocation") + ".txt"), 'r')
            data = {"paste_code": quotes.read()}
            data = urllib.urlencode(data)
            req = urllib2.Request("http://pastebin.com/api_public.php", data)
            response = urllib2.urlopen(req)
            msg = response.read()
            return ["PRIVMSG $C$ :" + msg]
        else:
            allowedRemove=(isAllowed(nick)>=getLevel(complete.cmd()[0])) if settingsHandler.readSetting(complete.cmd()[0],"userRequirementRemove")=="elevated" \
                    else complete.user()==settingsHandler.readSetting("core","owner") if settingsHandler.readSetting(complete.cmd()[0],"userRequirementRemove")=="owner" else 1
            allowedAdd=(isAllowed(nick)>=getLevel(complete.cmd()[0])) if settingsHandler.readSetting(complete.cmd()[0],"userRequirementAdd")=="elevated" \
                    else complete.user()==settingsHandler.readSetting("core","owner") if settingsHandler.readSetting(complete.cmd()[0],"userRequirementAdd")=="owner" else 1
            if msg.split()[0].lower() == "remove" and allowedRemove:
                with open(
                        os.path.join(
                            "config",
                            settingsHandler.readSetting(
                                complete.cmd()[0], "quotesLocation") + ".txt"),
                        'r') as file:
                    lines = file.read()
                lines = lines.split('\n\n')
                lines.pop(int(msg.split()[1]) - 1)
                with open(
                        os.path.join(
                            "config",
                            settingsHandler.readSetting(
                                complete.cmd()[0], "quotesLocation") + ".txt"),
                        'w') as file:
                    file.write('\n\n'.join(lines))
                return ["PRIVMSG $C$ :Alright, removed that quote!"]
            elif msg.split()[0].lower() == "add" and allowedAdd:
                msg = ' '.join(msg.split()[1:])
                zozo = open(
                    os.path.join(
                        "config",
                        settingsHandler.readSetting(
                            complete.cmd()[0], "quotesLocation") + ".txt"),
                    'r')
                lines = zozo.read()
                zozo.close()
                lines = lines.split('\n\n')
                fullCMD = msg.replace(' | ', '\n')
                file = open(
                    os.path.join(
                        "config",
                        settingsHandler.readSetting(
                            complete.cmd()[0], "quotesLocation") + ".txt"),
                    'a')
                file.write(fullCMD + "\n\n")
                file.close()
                return ["PRIVMSG $C$ :Quote added as #" + str(len(lines))]
        if len(msg.split()) > 0:
            with open(
                    os.path.join(
                        "config",
                        settingsHandler.readSetting(
                            complete.cmd()[0], "quotesLocation") + ".txt"),
                    'r') as file:
                fileLines = file.read()
            lines = []
            for index, line in enumerate(fileLines.split('\n\n')):
                lines.append((index, line))
            random.shuffle(lines)
            if msg.split()[0] == "find":
                searchFor = ' '.join(msg.lower().split()[1:])
            else:
                searchFor = msg

            for index, line in lines:
                if line.lower().find(searchFor.lower()) != -1:
                    returner = []
                    returner.append("PRIVMSG $C$ :Quote #%s of %s:" %
                                    (index + 1, len(lines) - 1))
                    for l in line.split('\n'):
                        returner.append("PRIVMSG $C$ :" + l)
                    return returner
            return ["PRIVMSG $C$ :No quotes matching your input!"]
        return [
            "PRIVMSG $C$ :The input you have given is invalid! Try !help :)"
        ]
Ejemplo n.º 56
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))