예제 #1
0
    def action(self, complete):
        reload(braceParser)
        parseBraces = braceParser.parseBraces
        try:
            msg = parseBraces(complete.fullMessage())
        except Exception as detail:
            return ["PRIVMSG $C$ :Parse Failure: " + str(detail)]
        conditionState = True
        toReturn = []
        for condition in msg[0]:
            try:
                calcInput = ":%s PRIVMSG %s :!%s %s" % (complete.userMask(),
                                                        complete.channel(),
                                                        "calculate", condition)
                inputObj = formatInput(pluginArguments(calcInput))
                output = ':'.join(globalv.loadedPlugins["calculate"].action(
                    inputObj)[0].split(':')[1:])
                if output == "False":
                    conditionState = False
                    break
            except Exception as detail:
                return [
                    "PRIVMSG $C$ :Conditional execution failure in %s" %
                    condition,
                    "PRIVMSG $C$ :Reason:%s" % str(detail)
                ]

        if conditionState == True:
            commandList = msg[1][0].split(';')
        elif len(msg[1]) > 1:
            commandList = msg[1][1].split(';')
        else:
            commandList = []
        for command in commandList:
            try:
                plugin = command.split()[0]
                args = ' '.join(command.split()[1:])
                input = ":%s PRIVMSG %s :!%s %s" % (
                    complete.userMask(), complete.channel(), plugin, args)
                inputObj = formatInput(pluginArguments(input))
                toReturn += [
                    x.replace('\x00', '').encode('utf-8') for x in
                    globalv.loadedPlugins[plugin.split()[0]].action(inputObj)
                ]
            except Exception as detail:
                return [
                    "PRIVMSG $C$ :!if failure in command %s" % command,
                    "PRIVMSG $C$ :Reason:%s" % str(detail)
                ]
        return toReturn
예제 #2
0
파일: foreach.py 프로젝트: Phoshi/OMGbot
 def action(self, complete):
     commands = shlex.split(complete.message())
     commands = [c.replace("\x00","") for c in commands] #Working around a unicode bug in shlex
     commandString = commands[0]
     commands = commands[1:15]
     commandString = commandString.split(' ',1)
     outputList=[]
     for command in commands:
         if len(commandString)>1:
             argumentsToRun = self.expand(commandString[1], command)
         else:
             argumentsToRun = command 
         commandToRun = commandString[0]
         print "Running command", commandToRun, "with arguments", argumentsToRun
         print "Constructing plugin object"
         arguments = pluginArguments(complete.complete())
         firstBit=arguments.complete().split(':')[1]
         arguments.setComplete(":"+firstBit+":"+globalv.commandCharacter+commandToRun+" "+argumentsToRun)
         print "Pre-formatting plugin object:", arguments.complete()
         arguments=formatInput(arguments)
         print "Running command"
         pluginOutput=globalv.loadedPlugins[commandToRun].action(arguments)
         print "Formatting output"
         output = formatOutput(pluginOutput, complete)
         print "Decoding output"
         output = [o for o in output]
         print "Success! Adding output to output list",output
         outputList+=output
     return outputList
예제 #3
0
파일: vote.py 프로젝트: Phoshi/OMGbot
 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
예제 #4
0
파일: var.py 프로젝트: JoshDreamland/xbot
    def action(self, complete):
        msg = complete.message().split()
        if len(msg) > 1:
            if isAllowed(complete.userMask()) >= getLevel(complete.cmd()[0]):
                try:
                    calcInput = ":%s PRIVMSG %s :!%s %s" % (complete.userMask(
                    ), complete.channel(), "calculate", ' '.join(msg[1:]))
                    inputObj = formatInput(pluginArguments(calcInput))
                    output = ':'.join(
                        globalv.loadedPlugins["calculate"].action(
                            inputObj)[0].split(':')[1:])
                    globalv.variables[msg[0]] = str(output)
                    with open(os.path.join("config", "variables"),
                              'w') as file:
                        pickle.dump(globalv.variables, file,
                                    pickle.HIGHEST_PROTOCOL)
                except Exception as detail:
                    return [
                        "PRIVMSG $C$ :Variable setting failure with expression !var %s: %s"
                        % (complete.message(), detail)
                    ]

        else:
            if msg[0] in globalv.variables.keys():
                return ["PRIVMSG $C$ :%s" % globalv.variables[msg[0]]]
            else:
                return ["PRIVMSG $C$ :Undefined"]
        return [""]
예제 #5
0
    def action(self, complete):
        msg = complete.message()
        output = msg.split('>')[-1]
        if output == msg or len(output.split()) != 1:
            output = "$C$"
        else:
            msg = msg.split('>')[0]
        commandlist = msg.split('&&')
        returns = []
        for msg in commandlist:
            msg = msg.replace('\|', '__PIPE__')
            commands = msg.split('|')
            commands = map(lambda x: x.replace('__PIPE__', '|'), commands)
            pluginOutput = ""
            for command in commands:
                plugin = command.split()[0]
                args = ' '.join(command.split()[1:])
                if globalv.loadedPlugins[plugin].__append_seperator__(
                ) == True:
                    args += "::"
                args += pluginOutput
                arguments = pluginArguments(complete.complete())
                # print "======", arguments.complete()
                firstBit = arguments.complete().split(' :')[0]
                if isinstance(args, unicode):
                    args = args.encode('utf-8')
                arguments.setComplete(firstBit + " :" +
                                      globalv.commandCharacter + plugin + " " +
                                      args)
                arguments = formatInput(arguments)
                pluginOutput = globalv.loadedPlugins[plugin].action(arguments)
                # print pluginOutput
                if pluginOutput != [""]:
                    starter = pluginOutput[0].split(' :')[0]
                    # print starter
                    if starter.split()[0] == "PRIVMSG":
                        content = ""
                        pluginOutput = [x for x in pluginOutput if x != ""]
                        for i, line in enumerate(pluginOutput):
                            content += ' :'.join(line.split(' :')[1:]) + (
                                " | " if i != len(pluginOutput) - 1 else "")
                            # print content
                        pluginOutput = starter + (' :' + content
                                                  if content != "" else "")
                        pluginOutput = ' :'.join(
                            pluginOutput.split(' :')
                            [1:]) if command != commands[-1] else pluginOutput
                        # print pluginOutput
                else:
                    pluginOutput = ""

            if type(pluginOutput) != list:
                pluginOutput = pluginOutput.replace('$C$', output)
            else:
                pluginOutput = [x.replace('$C$', output) for x in pluginOutput]
            outputstr = formatOutput(pluginOutput, complete)
            if outputstr != "":
                #returns.append(outputstr)
                returns += outputstr
        return returns
예제 #6
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
예제 #7
0
 def action(self, complete):
     commands = shlex.split(complete.message())
     commands = [c.replace("\x00", "")
                 for c in commands]  #Working around a unicode bug in shlex
     commandString = commands[0]
     commands = commands[1:15]
     commandString = commandString.split(' ', 1)
     outputList = []
     for command in commands:
         if len(commandString) > 1:
             argumentsToRun = self.expand(commandString[1], command)
         else:
             argumentsToRun = command
         commandToRun = commandString[0]
         print "Running command", commandToRun, "with arguments", argumentsToRun
         print "Constructing plugin object"
         arguments = pluginArguments(complete.complete())
         firstBit = arguments.complete().split(':')[1]
         arguments.setComplete(":" + firstBit + ":" +
                               globalv.commandCharacter + commandToRun +
                               " " + argumentsToRun)
         print "Pre-formatting plugin object:", arguments.complete()
         arguments = formatInput(arguments)
         print "Running command"
         pluginOutput = globalv.loadedPlugins[commandToRun].action(
             arguments)
         print "Formatting output"
         output = formatOutput(pluginOutput, complete)
         print "Decoding output"
         output = [o for o in output]
         print "Success! Adding output to output list", output
         outputList += output
     return outputList
예제 #8
0
def run_command(commandString, arguments):
    pluginIn = ":%s PRIVMSG %s :!%s"%(arguments.userMask(), arguments.channel(), commandString)
    args = pluginArguments(pluginIn)
    formatted = formatInput(args)

    pluginToRun = commandString.split()[0]

    output = globalv.loadedPlugins[pluginToRun].action(formatted)
    return output
예제 #9
0
def run_command(commandString, arguments):
    pluginIn = ":%s PRIVMSG %s :!%s" % (arguments.userMask(),
                                        arguments.channel(), commandString)
    args = pluginArguments(pluginIn)
    formatted = formatInput(args)

    pluginToRun = commandString.split()[0]

    output = globalv.loadedPlugins[pluginToRun].action(formatted)
    return output
예제 #10
0
파일: choose.py 프로젝트: Phoshi/OMGbot
 def action(self, complete):
     msg=complete.message()
     commands=msg.split('|')
     random.shuffle(commands)
     command=commands[0]
     plugin=command.split()[0]
     arguments=' '.join(command.split()[1:])
     arguments=":%s PRIVMSG %s :!%s %s"%(complete.userMask(), complete.channel(),plugin ,arguments)
     arguments=formatInput(pluginArguments(arguments))
     pluginOutput=globalv.loadedPlugins[plugin].action(arguments)
     return pluginOutput 
예제 #11
0
 def action(self, complete):
     msg = complete.message()
     commands = msg.split('|')
     random.shuffle(commands)
     command = commands[0]
     plugin = command.split()[0]
     arguments = ' '.join(command.split()[1:])
     arguments = ":%s PRIVMSG %s :!%s %s" % (
         complete.userMask(), complete.channel(), plugin, arguments)
     arguments = formatInput(pluginArguments(arguments))
     pluginOutput = globalv.loadedPlugins[plugin].action(arguments)
     return pluginOutput
예제 #12
0
파일: chain.py 프로젝트: rpjohnst/xbot
    def action(self, complete):
        msg=complete.message()
        output=msg.split('>')[-1]
        if output==msg or len(output.split())!=1:
            output="$C$"
        else:
            msg=msg.split('>')[0]
        commandlist=msg.split('&&')
        returns=[]
        for msg in commandlist:
            msg=msg.replace('\|','__PIPE__')
            commands=msg.split('|')
            commands=map(lambda x: x.replace('__PIPE__','|'), commands)
            pluginOutput=""
            for command in commands:
                plugin=command.split()[0]
                args=' '.join(command.split()[1:])
                if globalv.loadedPlugins[plugin].__append_seperator__()==True:
                    args+="::"
                args+=pluginOutput
                arguments=pluginArguments(complete.complete())
                # print "======", arguments.complete()
                firstBit=arguments.complete().split(' :')[0]
                if isinstance(args, unicode):
                    args = args.encode('utf-8')
                arguments.setComplete(firstBit+" :"+globalv.commandCharacter+plugin+" "+args)
                arguments=formatInput(arguments)
                pluginOutput=globalv.loadedPlugins[plugin].action(arguments)
                # print pluginOutput
                if pluginOutput!=[""]:
                    starter=pluginOutput[0].split(' :')[0]
                    # print starter
                    if starter.split()[0]=="PRIVMSG":
                        content=""
                        pluginOutput=[x for x in pluginOutput if x!=""]
                        for i,line in enumerate(pluginOutput):
                            content+=' :'.join(line.split(' :')[1:])+(" | " if i!=len(pluginOutput)-1 else "")
                            # print content
                        pluginOutput=starter+(' :'+content if content!="" else "")
                        pluginOutput=' :'.join(pluginOutput.split(' :')[1:]) if command!=commands[-1] else pluginOutput
                        # print pluginOutput
                else:
                    pluginOutput=""

            if type(pluginOutput)!=list:
                pluginOutput=pluginOutput.replace('$C$', output)
            else:
                pluginOutput=[x.replace('$C$', output) for x in pluginOutput]
            outputstr=formatOutput(pluginOutput,complete)
            if outputstr!="":
                #returns.append(outputstr)
                returns+=outputstr
        return returns
예제 #13
0
파일: laterd.py 프로젝트: Phoshi/OMGbot
    def action(self, complete):
        user=complete.user()
        if complete.type()!="PRIVMSG":
            return [""]
        returns=[]
        messages=settingsHandler.readSettingRaw("laterd","id",where="('"+user.lower()+"' GLOB recipient OR recipient GLOB '*|"+user.lower()+"|*') AND sent='0'")
        if messages!=[]:
            for message in messages:
                wipeMessage=True

                messageID=str(message[0])
                try:
                    sender=getSender(messageID)
                    senderMask=getSenderMask(messageID)
                    timestamp=getTimestamp(messageID)
                    messageText=getMessage(messageID)
                    plugin=messageText.split()[0]
                    if not correctChannel(messageID, complete.channel()):
                        continue
                    if plugin in globalv.loadedPlugins.keys():
                        arguments=pluginArguments(':'+senderMask+" PRIVMSG "+complete.channel()+" :!"+messageText.replace('$recipient$', user).replace('$*$', complete.fullMessage()))
                        arguments=formatInput(arguments)
                        message=globalv.loadedPlugins[plugin].action(arguments)
                        if message in [[],[""]]:
                            wipeMessage=False
                        #returns+=[m.decode('utf-8') for m in message]
                        returns+=message
                        if message!=[""] and message!=[]:
                            msg=message[0]
                            if msg.split()[0]=="PRIVMSG" or msg.split()[0]=="NOTICE":
                                location=msg.split()[1]
                            else:
                                location="$C$"
                            if not getAnonymous(messageID):
                                returns.append("PRIVMSG "+location+" :From "+sender+" to "+user+" "+GetTimeUntilDatetime(timestamp))
                        if wipeMessage:
                            setMessageSent(messageID)
                    else:
                        returns.append("PRIVMSG $C$ :"+messageText)
                        if not getAnonymous(messageID):
                            returns.append("PRIVMSG $C$ :From "+sender+" to "+user+" "+GetTimeUntilDatetime(timestamp))
                        setMessageSent(messageID)
                    if len(returns) >= 13:
                        break
                except Exception as detail:
                    print "There was an error in one of the later messages:",detail
                    setMessageSent(messageID)

        return returns
예제 #14
0
파일: if.py 프로젝트: Phoshi/OMGbot
    def action(self, complete):
        reload(braceParser)
        parseBraces=braceParser.parseBraces
        try:
            msg=parseBraces(complete.fullMessage())
        except Exception as detail:
            return ["PRIVMSG $C$ :Parse Failure: "+str(detail)]
        conditionState=True
        toReturn=[]
        for condition in msg[0]:
            try:
                calcInput=":%s PRIVMSG %s :!%s %s"%(complete.userMask(),complete.channel(),"calculate", condition)
                inputObj=formatInput(pluginArguments(calcInput))
                output=':'.join(globalv.loadedPlugins["calculate"].action(inputObj)[0].split(':')[1:])
                if output=="False":
                    conditionState=False
                    break
            except Exception as detail:
                return ["PRIVMSG $C$ :Conditional execution failure in %s"%condition,"PRIVMSG $C$ :Reason:%s"%str(detail)]

        if conditionState==True:
            commandList=msg[1][0].split(';')
        elif len(msg[1])>1:
            commandList=msg[1][1].split(';')
        else:
            commandList=[]
        for command in commandList:
            try:
                plugin=command.split()[0]
                args=' '.join(command.split()[1:])
                input=":%s PRIVMSG %s :!%s %s"%(complete.userMask(),complete.channel(),plugin, args)
                inputObj=formatInput(pluginArguments(input))
                toReturn+=[x.replace('\x00','').encode('utf-8') for x in globalv.loadedPlugins[plugin.split()[0]].action(inputObj)]
            except Exception as detail:
                return ["PRIVMSG $C$ :!if failure in command %s"%command,"PRIVMSG $C$ :Reason:%s"%str(detail)]
        return toReturn 
예제 #15
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
예제 #16
0
파일: greetd.py 프로젝트: Phoshi/OMGbot
    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
예제 #17
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:''})
예제 #18
0
파일: var.py 프로젝트: Phoshi/OMGbot
    def action(self, complete):
        msg=complete.message().split()
        if len(msg)>1:
            if isAllowed(complete.userMask())>=getLevel(complete.cmd()[0]):
                try:
                    calcInput=":%s PRIVMSG %s :!%s %s"%(complete.userMask(),complete.channel(),"calculate", ' '.join(msg[1:]))
                    inputObj=formatInput(pluginArguments(calcInput))
                    output=':'.join(globalv.loadedPlugins["calculate"].action(inputObj)[0].split(':')[1:])
                    globalv.variables[msg[0]]=str(output)
                    with open(os.path.join("config","variables"),'w') as file:
                        pickle.dump(globalv.variables,file,pickle.HIGHEST_PROTOCOL)
                except Exception as detail:
                    return ["PRIVMSG $C$ :Variable setting failure with expression !var %s: %s"%(complete.message(), detail)]

        else:
            if msg[0] in globalv.variables.keys():
                return ["PRIVMSG $C$ :%s"%globalv.variables[msg[0]]]
            else:
                return ["PRIVMSG $C$ :Undefined"]
        return [""]
예제 #19
0
    def action(self, complete):
        msg = complete.message()
        isElevated = (isAllowed(complete.userMask()) >= getLevel(
            complete.cmd()[0]))
        beRandom = True
        if len(self.answers) == 0:
            self.__init_answers__(complete, beRandom)
        if len(msg.split()) >= 1:
            cmd = msg.split()[0]
            msg = ' '.join(msg.split()[1:])
        else:
            cmd = ""
            msg = ""
        if cmd == "-add" and isElevated:
            settingsHandler.writeSetting("'" + complete.cmd()[0] + "'",
                                         "answer", msg)
            toReturn = "Added that answer"
            self.__init_answers__(complete, beRandom)
        elif cmd == "-delete" and isElevated:
            settingsHandler.deleteSetting("'" + complete.cmd()[0] + "'",
                                          "answer", msg)
            toReturn = "Wiped that answer."
            self.__init_answers__(complete, beRandom)
        elif cmd == "-wipe" and isElevated:
            settingsHandler.dropTable("'" + complete.cmd()[0] + "'")
            settingsHandler.newTable("'" + complete.cmd()[0] + "'", "answer")
            toReturn = "Answer table wiped!"
            self.__init_answers__(complete, beRandom)
        elif cmd == "-reset" and isElevated:
            self.__init_answers__(complete, beRandom)
            toReturn = "Re-randomising list..."
        else:
            toReturn = self.answers.pop()
            inputs = ":%s PRIVMSG %s :!%s" % (complete.userMask(),
                                              complete.channel(), toReturn)
            input = formatInput(pluginArguments(inputs))
            pluginOut = globalv.loadedPlugins[toReturn.split()[0]].action(
                input)
            return pluginOut

        return ["PRIVMSG $C$ :" + toReturn]
예제 #20
0
파일: repeat.py 프로젝트: rpjohnst/xbot
    def action(self, complete):
        command=complete.message()
        print "To repeat:", command
        commands=command.split()

        repeatTimes = int(commands[0])
        plugin = commands[1]

        command = ' '.join(commands[1:])
        arguments=pluginArguments(complete.complete())
        firstBit=arguments.complete().split(' :')[0]
        arguments.setComplete(firstBit+" :"+globalv.commandCharacter+command)
        arguments=formatInput(arguments)

        if plugin in globalv.loadedPlugins:
            result = []
            for i in xrange(repeatTimes):
                result += globalv.loadedPlugins[plugin].action(arguments)
            return result

        return []
예제 #21
0
    def action(self, complete):
        argumentString = ":null!nobody@nowhere PRIVMSG nothing :!sr388"
        argumentsObject = formatInput(pluginArguments(argumentString))
        numbers = {}
        if complete.message().isdigit() == False:
            totalIterations = 10000
        else:
            totalIterations = int(complete.message())
        for i in xrange(0, totalIterations):
            output = globalv.loadedPlugins['sr388'].action(argumentsObject)[0]
            number = output.split()[3][1:]
            if number in numbers:
                numbers[number] += 1
            else:
                numbers[number] = 1
        sortedNumbers = sorted(numbers.iteritems(), key=operator.itemgetter(1))
        sortedNumbers.reverse()
        minHits = (0, totalIterations)
        maxHits = (0, 0)
        total = 0
        for number in sortedNumbers:
            total += number[1]
        mean = total / len(sortedNumbers)
        devTotal = 0

        for number in sortedNumbers:
            devTotal += (number[1] - mean)**2
            if number[1] > maxHits[1]:
                maxHits = number
            elif number[1] < minHits[1]:
                minHits = number

        devMean = devTotal / len(sortedNumbers)
        stdDev = devMean**0.5

        return [
            "PRIVMSG $C$ :Total iterations: %s; Most often picked quote: %s (with %s hits); Least often picked quote: %s (with %s hits); Results have a standard devation of %s"
            % (totalIterations, maxHits[0], maxHits[1], minHits[0], minHits[1],
               stdDev)
        ]
예제 #22
0
    def action(self, complete):
        command = complete.message()
        print "To repeat:", command
        commands = command.split()

        repeatTimes = int(commands[0])
        plugin = commands[1]

        command = ' '.join(commands[1:])
        arguments = pluginArguments(complete.complete())
        firstBit = arguments.complete().split(' :')[0]
        arguments.setComplete(firstBit + " :" + globalv.commandCharacter +
                              command)
        arguments = formatInput(arguments)

        if plugin in globalv.loadedPlugins:
            result = []
            for i in xrange(repeatTimes):
                result += globalv.loadedPlugins[plugin].action(arguments)
            return result

        return []
예제 #23
0
    def action(self, complete):
        user=complete.user()
        if complete.type()!="PRIVMSG":
            return [""]

        try:
            with open("autoCommands.dat") as file:
                regexes = pickle.load(file)
        except:
            return []

        message = complete.fullMessage()
        response = []
        for regex in regexes:
            try:
                m = re.search(regex, message, re.I)
                if m:
                    if not regex.startswith('^!') and message.startswith('!'):
                        continue
                    command = regexes[regex]
                    for i, g in enumerate(m.groups()):
                        command = command.replace(r'\%d' % (i+1), g if g else '')
                    plugin=command.split(' ')[0]

                    if plugin in globalv.loadedPlugins.keys():

                        arguments=pluginArguments(':'+complete.userMask()+" PRIVMSG "+complete.channel()+" :!"+command.replace('$*$', message).replace('$U$', complete.user()))
                        arguments=formatInput(arguments)
                        result = globalv.loadedPlugins[plugin].action(arguments)
                        if not isinstance(result, list):
                            result = [result]
                        response += result
            except:
                print "Failed to execute regex %s with command %s" % (regex, regexes[regex])
                traceback.print_exc(file=sys.stdout)

        return response
예제 #24
0
    def action(self, complete):
        argumentString = ":null!nobody@nowhere PRIVMSG nothing :!sr388"
        argumentsObject = formatInput(pluginArguments(argumentString))
        numbers={}
        if complete.message().isdigit()==False:
            totalIterations = 10000
        else:
            totalIterations=int(complete.message())
        for i in xrange(0,totalIterations):
            output = globalv.loadedPlugins['sr388'].action(argumentsObject)[0]
            number = output.split()[3][1:]
            if number in numbers:
                numbers[number]+=1
            else:
                numbers[number]=1
        sortedNumbers = sorted(numbers.iteritems(), key=operator.itemgetter(1))
        sortedNumbers.reverse()
        minHits=(0, totalIterations)
        maxHits=(0,0)
        total=0
        for number in sortedNumbers:
            total+=number[1]
        mean = total/len(sortedNumbers)
        devTotal=0

        for number in sortedNumbers:
            devTotal+= (number[1]-mean)**2
            if number[1]>maxHits[1]:
                maxHits = number
            elif number[1]<minHits[1]:
                minHits = number

        devMean = devTotal/len(sortedNumbers)
        stdDev = devMean**0.5


        return ["PRIVMSG $C$ :Total iterations: %s; Most often picked quote: %s (with %s hits); Least often picked quote: %s (with %s hits); Results have a standard devation of %s"%(totalIterations, maxHits[0], maxHits[1], minHits[0], minHits[1], stdDev)]
예제 #25
0
    def action(self, complete):
        msg=complete.message()
        isElevated=(isAllowed(complete.userMask())>=getLevel(complete.cmd()[0]))
        beRandom=True
        if len(self.answers)==0:
            self.__init_answers__(complete,beRandom)
        if len(msg.split())>=1:
            cmd=msg.split()[0]
            msg=' '.join(msg.split()[1:])
        else:
            cmd=""
            msg=""
        if cmd=="-add" and isElevated:
            settingsHandler.writeSetting("'"+complete.cmd()[0]+"'","answer",msg)
            toReturn="Added that answer"
            self.__init_answers__(complete,beRandom)
        elif cmd=="-delete" and isElevated:
            settingsHandler.deleteSetting("'"+complete.cmd()[0]+"'","answer",msg)
            toReturn="Wiped that answer."
            self.__init_answers__(complete,beRandom)
        elif cmd=="-wipe" and isElevated:
            settingsHandler.dropTable("'"+complete.cmd()[0]+"'")
            settingsHandler.newTable("'"+complete.cmd()[0]+"'","answer")
            toReturn="Answer table wiped!"
            self.__init_answers__(complete,beRandom)
        elif cmd=="-reset" and isElevated:
            self.__init_answers__(complete,beRandom)
            toReturn="Re-randomising list..."
        else:
            toReturn=self.answers.pop()
            inputs=":%s PRIVMSG %s :!%s"%(complete.userMask(), complete.channel(), toReturn)
            input=formatInput(pluginArguments(inputs))
            pluginOut=globalv.loadedPlugins[toReturn.split()[0]].action(input)
            return pluginOut

        return ["PRIVMSG $C$ :"+toReturn]
예제 #26
0
    def action(self, complete):
        user = complete.user()
        if complete.type() != "PRIVMSG":
            return [""]
        returns = []

        messages = readAllActions(user)
        if (user.lower() == "joshdreamland"):
            messages += readAllActions("josh")
        if (user.lower() == "ismavatar"):
            messages += readAllActions("ism")
        if (user.lower() == "goombert"):
            messages += readAllActions("robert")

        if messages != []:
            dispatches = []

            for message in messages:
                wipeMessage = True

                messageID = str(message[0])
                sender = message[1]
                senderMask = message[2]
                timestamp = datetime.datetime.fromtimestamp(int(message[3]))
                messageText = message[4]
                messageChannel = message[5]
                anonymous = message[6] == "1"
                if not correctChannel(messageChannel, complete.channel()):
                    continue

                try:
                    plugin = messageText.split()[0]
                    messageTextNew = messageText
                    messageTextNew = messageTextNew.replace(
                        '$recipient$', user)
                    messageTextNew = messageTextNew.replace(
                        '$*$',
                        complete.fullMessage().decode('utf-8'))

                    if plugin == "dispatch":
                        senderName = ""
                        if not anonymous:
                            senderName = sender
                        dispatches.append(
                            "%s: [%s] <%s>: %s" %
                            (user, GetTimeUntilDatetime(timestamp), senderName,
                             ' '.join(messageTextNew.split(' ')[1:])))
                        setMessageSent(messageID)
                        continue

                    if plugin not in globalv.loadedPlugins.keys():
                        plugin = 'say'
                        messageTextNew = 'say ' + messageTextNew
                    arguments = pluginArguments(':' + senderMask +
                                                " PRIVMSG " +
                                                complete.channel() + " :!" +
                                                messageTextNew)
                    arguments = formatInput(arguments)
                    try:
                        message = globalv.loadedPlugins[plugin].action(
                            arguments)
                    except:
                        message = ["PRIVMSG $C$ :%s" % messageText]
                    if message in [[], [""]]:
                        wipeMessage = False
                    #returns+=[m.decode('utf-8') for m in message]
                    returns += message
                    if message != [""] and message != []:
                        msg = message[0]
                        if msg.split()[0] == "PRIVMSG" or msg.split(
                        )[0] == "NOTICE":
                            location = msg.split()[1]
                        else:
                            location = "$C$"
                        if not anonymous:
                            returns.append("PRIVMSG " + location + " :From " +
                                           sender + " to " + user + " " +
                                           GetTimeUntilDatetime(timestamp))
                    if wipeMessage:
                        setMessageSent(messageID)
                    if len(returns) >= 13:
                        break
                except Exception as detail:
                    print "There was an error in one of the later messages:", detail
                    traceback.print_tb(sys.exc_info()[2])
                    setMessageSent(messageID)

            target = "$C$"
            if len(dispatches) > 1:
                target = user
                returns.append("PRIVMSG $C$ :%s: Messages incoming" % user)
            returns += [
                "PRIVMSG %s :%s" % (target, dispatch)
                for dispatch in dispatches
            ]

        return returns
예제 #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: ''})
예제 #28
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))
예제 #29
0
파일: laterd.py 프로젝트: rpjohnst/xbot
    def action(self, complete):
        user=complete.user()
        if complete.type()!="PRIVMSG":
            return [""]
        returns=[]
        messages=settingsHandler.readSettingRaw("laterd","id,sender,senderMask,timestamp,message,channel,anonymous",where="('%s' GLOB recipient OR recipient GLOB '*|%s|*' OR recipient GLOB '%s|*' OR recipient GLOB '*|%s') AND sent='0'" % (user.lower(), user.lower(), user.lower(), user.lower()))
        if messages!=[]:
            dispatches=[]

            for message in messages:
                wipeMessage=True

                messageID=str(message[0])
                sender=message[1]
                senderMask=message[2]
                timestamp=datetime.datetime.fromtimestamp(int(message[3]))
                messageText=message[4]
                messageChannel=message[5]
                anonymous=message[6]=="1"
                if not correctChannel(messageChannel, complete.channel()):
                    continue

                try:
                    plugin=messageText.split()[0]
                    messageTextNew = messageText
                    messageTextNew = messageTextNew.replace('$recipient$', user)
                    messageTextNew = messageTextNew.replace('$*$', complete.fullMessage().decode('utf-8'))

                    if plugin=="dispatch":
                        senderName=""
                        if not anonymous:
                            senderName=sender
                        dispatches.append("%s: [%s] <%s>: %s" % (user, GetTimeUntilDatetime(timestamp), senderName, ' '.join(messageTextNew.split(' ')[1:])))
                        setMessageSent(messageID)
                        continue

                    if plugin not in globalv.loadedPlugins.keys():
                        plugin = 'say'
                        messageTextNew = 'say ' + messageTextNew
                    arguments=pluginArguments(':'+senderMask+" PRIVMSG "+complete.channel()+" :!"+messageTextNew)
                    arguments=formatInput(arguments)
                    try:
                        message=globalv.loadedPlugins[plugin].action(arguments)
                    except:
                        message=["PRIVMSG $C$ :%s" % messageText]
                    if message in [[],[""]]:
                        wipeMessage=False
                    #returns+=[m.decode('utf-8') for m in message]
                    returns+=message
                    if message!=[""] and message!=[]:
                        msg=message[0]
                        if msg.split()[0]=="PRIVMSG" or msg.split()[0]=="NOTICE":
                            location=msg.split()[1]
                        else:
                            location="$C$"
                        if not anonymous:
                            returns.append("PRIVMSG "+location+" :From "+sender+" to "+user+" "+GetTimeUntilDatetime(timestamp))
                    if wipeMessage:
                        setMessageSent(messageID)
                    if len(returns) >= 13:
                        break
                except Exception as detail:
                    print "There was an error in one of the later messages:",detail
                    traceback.print_tb(sys.exc_info()[2])
                    setMessageSent(messageID)

            target="$C$"
            if len(dispatches) > 1:
                target=user
                returns.append("PRIVMSG $C$ :%s: Messages incoming" % user)
            returns += ["PRIVMSG %s :%s" % (target, dispatch) for dispatch in dispatches]

        return returns