Example #1
0
 def action(self, complete):
     msg=complete.message()
     isElevated=(isAllowed(complete.userMask())>=getLevel(complete.cmd()[0]))
     self.__init_answers__(complete)
     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)
     elif cmd=="-delete" and isElevated:
         settingsHandler.deleteSetting("'"+complete.cmd()[0]+"'","answer",msg)
         toReturn="Wiped that answer."
         self.__init_answers__(complete)
     elif cmd=="-wipe" and isElevated:
         settingsHandler.dropTable("'"+complete.cmd()[0]+"'")
         settingsHandler.newTable("'"+complete.cmd()[0]+"'","answer")
         toReturn="Answer table wiped!"
         self.__init_answers__(complete)
     elif cmd=="-dump":
         self.__init_answers__(complete)
         return ["PRIVMSG $C$ :[%s]"%', '.join(["'"+x+"'" for x in self.answers])]
     else:
         toReturn=self.answers.pop()
         if complete.message()=="":
             toReturn=toReturn.replace("$1$","$U$")
         else:
             toReturn=toReturn.replace("$1$",complete.message())
     return ["PRIVMSG $C$ :"+toReturn]
Example #2
0
 def action(self, complete):
     msg = complete.message()
     nick = complete.userMask()
     amsg = msg
     nickname = "*Unknown*"
     if securityHandler.isAllowed(nick) >= getLevel(complete.cmd()[0]):
         if msg[0] == "#":
             nmsg = msg
             nickname = ""
         elif msg in globalv.miscVars[0]:
             nmsg = ".*@" + globalv.miscVars[0][msg].split('@')[1]
             nickname = msg
         else:
             nmsg = msg
             nmsg = nmsg.replace('*', '.*').replace('..*', '.*')
         fullCMD = nmsg
         if fullCMD not in [
                 x[0] for x in settingsHandler.readSettingRaw(
                     "coreIgnorance", "ignorance")
         ]:
             settingsHandler.writeSetting("coreIgnorance",
                                          ["ignorance", "nickname"],
                                          [fullCMD, nickname])
             return [
                 "PRIVMSG $C$ :" + amsg + " successfully ignored, cap'n!"
             ]
         else:
             return [
                 "PRIVMSG $C$ :" + amsg + " is already ignored, m'lord!"
             ]
     else:
         return ["PRIVMSG $C$ :Go away."]
Example #3
0
def load_plugin(input, loadAs=""): #Loads a plugin, placing it in it's correct category.
    state=0
    #arguments=shlex.split(' '.join(input.split()[1:]))
    name=input.split()[0]
    x=__import__(name)
    if loadAs!="":
        name=loadAs
    else:
        loadAs = name
    if name in globalv.loadedPlugins:
        state=1
    if name in globalv.loadedRealtime:
        state=1
    if name in globalv.loadedSpecial:
        state=1
    reload(x)
    y=x.pluginClass()
    if y.gettype()=="command":
        globalv.loadedPlugins.update({name:y})
    if y.gettype()=="realtime":
        globalv.loadedRealtime.update({name:y})
    if y.gettype()=="special":
        globalv.loadedSpecial.update({name:y})
    if y.gettype()=="preprocess":
        globalv.loadedPreprocess.update({name:y})
    if y.gettype()=="postprocess":
        globalv.loadedPostprocess.update({name:y})
    globalv.aliasExtensions.update({name:''})
    if settingsHandler.tableExists(name)==0:
        y.__init_db_tables__(name)
    if name not in [x[0] for x in settingsHandler.readSetting("'core-userlevels'", "plugin")]:
        settingsHandler.writeSetting("'core-userlevels'", ["plugin", "level"],[name, str(y.__level__())])
    globalv.basePlugin[loadAs]=input.split()[0]
    return state
Example #4
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]
Example #5
0
    def action(self, complete):
        msg = complete.message()
        if isAllowed(complete.userMask()) >= getLevel(complete.cmd()[0]):
            trigger = msg.split()[0]
            command = ' '.join(msg.split()[1:])
            try:
                if trigger not in [
                        x[0] for x in settingsHandler.readSettingRaw(
                            "'core-expansions'", "trigger")
                ]:
                    settingsHandler.writeSetting("'core-expansions'",
                                                 ["trigger", "command"],
                                                 [trigger, command])
                else:
                    settingsHandler.updateSetting("'core-expansions'",
                                                  "command",
                                                  command,
                                                  where="trigger='%s'" %
                                                  trigger)
                msg = "%s will now substitute to the output of %s" % (trigger,
                                                                      command)
            except Exception as detail:
                msg = "Failure: %s" % detail
        else:
            msg = "Sorry, you need to be elevated to use this command!"

        return ["PRIVMSG $C$ :" + msg]
Example #6
0
def save_alias(
    name
):  #Saves alias to a file, to stick around between sessions. Returns 1 for complete, 0 for the plugin not existing in the current instnace, and 2 if it fails for some reason.
    if name in globalv.loadedAliases.keys(
    ):  #To check if the alias is in the current instance (IE, it actually works)
        isIn = 0
        for plugin in [
                plugin[0] for plugin in settingsHandler.readSetting(
                    "alias", "aliasName")
        ]:
            if name == plugin:
                isIn = 1
        plugin = globalv.loadedAliases[name].split()[0]
        arguments = ' '.join(globalv.loadedAliases[name].split()[1:])
        if not isIn:
            settingsHandler.writeSetting(
                "alias", ['aliasName', 'aliasPlugin', 'aliasArguments'],
                [name, plugin, arguments])
        else:
            settingsHandler.updateSetting("alias", "aliasPlugin", plugin,
                                          "aliasName='" + name + "'")
            settingsHandler.updateSetting("alias", "aliasArguments", arguments,
                                          "aliasName='" + name + "'")
        return 1
    else:
        return 0
Example #7
0
 def __init_db_tables__(self, name):
     import settingsHandler
     settingsHandler.newTable(name, "url", "regex", "matchText")
     settingsHandler.writeSetting(name, ["url", "regex", "matchText"], [
         "http://google.com/complete/search?output=toolbar&q=$*$", ".*",
         "Autocomplete Results:"
     ])
Example #8
0
 def action(self, complete):
     msg = complete.message()
     sender = complete.userMask()
     if len(msg.split()) > 1:
         mode = msg.split()[1].lower()
     else:
         mode = "on"
     msg = msg.split()[0]
     print sender
     print globalv.basePlugin
     if msg == "list":
         return [
             "PRIVMSG $C$ :" + ', '.join([
                 x[0] for x in settingsHandler.readSettingRaw(
                     "coreAutoLoad", "loadAs")
             ])
         ]
     if isAllowed(sender) >= getLevel(complete.cmd()[0]):
         if mode == "on":
             settingsHandler.writeSetting("coreAutoLoad",
                                          ["plugin", "loadAs"],
                                          [globalv.basePlugin[msg], msg])
             return ["PRIVMSG $C$ :Plugin set to autoload"]
         else:
             settingsHandler.deleteSetting("coreAutoLoad", "loadAs", msg)
             return ["PRIVMSG $C$ :Plugin no longer autoloading"]
     return ["PRIVMSG $C$ :You do not have the required access rights!"]
Example #9
0
File: np.py Project: Phoshi/OMGbot
 def action(self, complete):
     msg = complete.message()
     user = complete.user()
     users = {}
     for nicknick in settingsHandler.readSetting(complete.cmd()[0], "IRCnick, LASTFMnick"):
         users.update({nicknick[0].lower(): nicknick[1]})
     if msg != "":
         user = msg
     if len(msg.split()) >= 2:
         if msg.split()[0] == "-link":
             settingsHandler.writeSetting(
                 complete.cmd()[0], ["IRCnick", "LASTFMnick"], [complete.user(), " ".join(msg.split()[1:])]
             )
             return ["PRIVMSG $C$ :Linked %s to %s" % (complete.user(), " ".join(msg.split()[1:]))]
     try:
         if user.lower() in users.keys():
             name = users[user.lower()]
         else:
             name = user
         url = "http://ws.audioscrobbler.com/1.0/user/" + name + "/recenttracks.rss"
         p = urllib2.urlopen(url).read()
         p = re.search(
             "<description>Last 10 tracks submitted to Last.fm</description>(.*)</item>", p, re.DOTALL
         ).group(1)
         l = re.search("<link>(.*?)</link>", p, re.DOTALL).group(1)
         p = re.search("<title>(.*?)</title>", p, re.DOTALL).group(1)
         if len(l) > 50:
             l = bitly(l)
         p = p.split("\xe2\x80\x93")
         msg = user + " is listening to" + p[1].decode("utf-8") + " by " + p[0].decode("utf-8") + " (" + l + ")"
     except:
         msg = "I don't know what " + user + " is listening to. Sorry."
     return ["PRIVMSG $C$ :" + msg]
Example #10
0
 def __init_db_tables__(self, name):
     settingsHandler.newTable(name, "quotesLocation", "userRequirementAdd",
                              "userRequirementRemove")
     settingsHandler.writeSetting(
         name,
         ["quotesLocation", "userRequirementAdd", "userRequirementRemove"],
         [name, "None", "elevated"])
Example #11
0
 def action(self, complete):
     if isAllowed(complete.userMask())<1:
         return [""]
     MCName=complete.message().split()[0]
     IRCName=complete.user()
     settingsHandler.writeSetting("stripMCBotNames", ["minecraft", "irc"], [MCName, IRCName])
     return ["PRIVMSG $C$ :Names linked - please reload stripMCBotNames for the changes to take effect"]
Example #12
0
 def action(self, complete):
     msg=complete.message()
     command=msg.split()[0]
     if command=="list":
         names=settingsHandler.readSettingRaw("laterd","recipient, sender, timestamp", where="sent='0' AND anonymous='0'")
         returns=[]
         for name in names:
             try:
                 recipient=name[0]
                 sender=name[1]
                 timestamp=name[2]
                 ctime=time.strftime("%H:%M on %d-%m-%Y",time.gmtime(int(timestamp)))
                 message=recipient+" has a message from "+sender+" (Sent on "+ctime+")"
                 returns.append(message)
             except:
                 pass
         if returns==[]:
             returns.append("No messages.")
         return ["PRIVMSG $C$ :"+', '.join(returns)]
     elif command=="remove":
         try:
             senderString=" and sender=='%s'"%complete.user()
             if isAllowed(complete.userMask())>=150:
                 senderString=""
             where  = "recipient=%s and sent='0'" % repr(msg.split()[1].lower())
             where += senderString
             print where
             settingsHandler.updateSetting("laterd","sent", "'2'", where=where)
             return ["PRIVMSG $C$ :Later successfully removed!"]
         except Exception as detail:
             return ["PRIVMSG $C$ :Later not removed"]
     else:
         anonymous = "0"
         secret_pfx = "secret::"
         if msg.startswith(secret_pfx):
             anonymous = "1"
             msg = msg[len(secret_pfx):]
         
         channels=[]
         while msg.split()[0][0]=="#":
             channels.append(msg.split()[0])
             msg=' '.join(msg.split()[1:])
         channel='|'.join(channels)
         recipients=list(set(msg.split()[0].lower().split(',')))
         recipients = [re.sub('[^0-9a-z-[\]*?]', '?', x) for x in recipients]
         sender=complete.user()
         senderMask=complete.userMask()
         timestamp=str(int(time.time()))
         message=' '.join(msg.split()[1:])
         message = message.replace('$U$','$recipient$')
         for recipient in recipients:
             print recipient
             id=str(int(settingsHandler.readSetting("laterd", "COUNT(id)"))+1)
             settingsHandler.writeSetting("laterd",["id", "recipient","sender","senderMask","timestamp","message", "channel", "anonymous",  "sent"],[id, recipient, sender, senderMask, timestamp, message, channel, anonymous, "0"])
             settingsHandler.db.commit()
         return ["PRIVMSG $C$ :Ok, I'll tell "+', '.join(recipients[:-1])+(" and "+recipients[-1] if len(recipients)>1 else recipients[-1])+" that when they next speak!"]
     return ["PRIVMSG $C$ :"+msg]
Example #13
0
 def action(self, complete):
     msg = complete.message()
     returner = ""
     elevated = getLevel(complete.userMask()) >= isAllowed(
         complete.cmd()[0])
     if msg == "":
         returner = "This is the %s dictionary. Run !%s -list for a list of known values!" % (
             complete.cmd()[0], complete.cmd()[0])
     elif msg.split()[0] == "-add" and elevated:
         settingsHandler.writeSetting(
             complete.cmd()[0], ["key", "value"],
             [msg.split()[1], ' '.join(msg.split()[2:])])
         returner = "Key:Value pair added!"
     elif msg.split()[0] == "-delete" and elevated:
         settingsHandler.deleteSetting(complete.cmd()[0], "key",
                                       msg.split()[1])
         returner = "Key removed!"
     elif msg.split()[0] == "-list":
         keypairs = [
             x[0] for x in settingsHandler.readSettingRaw(
                 complete.cmd()[0], "key")
         ]
         returner = ', '.join(keypairs)
     elif msg.split()[0] == "-random":
         keypairs = settingsHandler.readSettingRaw(complete.cmd()[0],
                                                   "key, value")
         pairs = {}
         for keypair in keypairs:
             pairs[keypair[0].lower()] = keypair[1]
         import random
         keys = pairs.keys()
         random.shuffle(keys)
         returner = keys[0] + ": " + pairs[keys[0]]
     else:
         keypairs = settingsHandler.readSettingRaw(complete.cmd()[0],
                                                   "key, value")
         pairs = {}
         for keypair in keypairs:
             pairs[keypair[0].lower()] = keypair[1]
         if unicode(msg.split()[0]).lower() in pairs.keys():
             returner = pairs[unicode(msg.split()[0]).lower()]
         elif "default" not in pairs.keys():
             returner = "No definition."
             matches = difflib.get_close_matches(msg.split()[0],
                                                 pairs.keys(), 10, 0.1)
             if len(matches) > 0:
                 returner += " Perhaps you meant: " + ', '.join(
                     matches[:-1])
                 if len(matches) > 1:
                     returner += " or " + matches[-1]
             else:
                 returner += " No similar definitions"
         else:
             returner = pairs['default']
     if returner == "":
         return [""]
     return ["PRIVMSG $C$ :" + returner]
Example #14
0
 def action(self, complete):
     msg=complete.message()
     mode=plugin=setting=set=where=""
     mode=msg.split()[0]
     returns="No such mode '%s'" % mode
     plugin=msg.split()[1]
     try:
         setting=msg.split()[2]
     except:
         setting=""
     try:
         set=' '.join(msg.split()[3:])
     except:
         set=""
     if len(set.split())<3:
         where = '1==1'
     elif set.split()[-2].lower()=="where":
         where=set.split()[-1]
         set=' '.join(set.split()[:-2])
     else:
         where="1==1"
     if isAllowed(complete.userMask())>=getLevel(complete.cmd()[0]):
         if mode=="update":
             settingsHandler.updateSetting(plugin, setting, set, where=where)
             returns="Setting updated, sir!"
         if mode=="delete":
             settingsHandler.deleteSetting(plugin, setting, set)
             returns="Setting removed, my lord!"
         if mode=="add":
             setting=setting.split('||')
             set=set.split('||')
             settingsHandler.writeSetting(plugin, setting, set)
             returns="Setting Set, Cap'n!"
         if mode=="drop-table":
             settingsHandler.dropTable(plugin)
             returns="Settings lost, comrade!"
         if mode=="list":
             columns=settingsHandler.readColumns(plugin)
             returns=', '.join(columns)
         if mode=="current":
             results=settingsHandler.readSetting(plugin, setting)
             results=[str(x[0]) if len(x)==1 and type(x)==tuple else x for x in results] if type(results)==list else str(results)
             results=', '.join(results) if type(results)==list else results
             returns=results
         if mode=="commit":
             settingsHandler.db.commit()
             returns="Committed!"
         if mode=="copy":
             settingsHandler.executeQuery("INSERT INTO '%s' SELECT * FROM '%s'"%(msg.split()))
         if mode=="query":
             results=settingsHandler.executeQuery(' '.join(msg.split()[1:]))
             if results!=[]:
                 returns=str(results)
     else:
         returns="Sorry, you can't do this."
     return ["PRIVMSG $C$ :"+returns]
Example #15
0
 def action(self, complete):
     if isAllowed(complete.userMask()) < 1:
         return [""]
     MCName = complete.message().split()[0]
     IRCName = complete.user()
     settingsHandler.writeSetting("stripMCBotNames", ["minecraft", "irc"],
                                  [MCName, IRCName])
     return [
         "PRIVMSG $C$ :Names linked - please reload stripMCBotNames for the changes to take effect"
     ]
Example #16
0
 def action(self, complete):
     name=complete.message()
     msg="There was an error in your input!"
     if isAllowed(complete.userMask())<getLevel(complete.cmd()[0]):
         return [""]
     if name.split()[0]=="list":
         return ["PRIVMSG $C$ :"+' '.join(globalv.loadedInputs.keys())]
     elif name.split()[0]=="clean":
         newDict={}
         for plugin in globalv.loadedInputs.keys():
             if globalv.loadedInputs[plugin].isSet()==False:
                 newDict[plugin]=globalv.loadedInputs[plugin]
         globalv.loadedInputs=newDict
         return ["PRIVMSG $C$ :ID list cleaned up manually"]
     elif name.split()[0]=="kickstart":
         globalv.input.startInputDaemons()
         return ["PRIVMSG $C$ :Kickstarted stalling plugins manually"]
     elif name.split()[0]=="reboot":
         definition=settingsHandler.readSetting("'core-input'","definition",where="input='%s'"%name.split()[1])
         print "def"
         x=__import__(str(definition.split()[0]))
         reload(x)
         arguments=str(' '.join(definition.split()[1:]))
         arguments=shlex.split(arguments)
         globalv.loadedInputs[name.split()[1]]=globalv.input.addInputSource(x.asyncInput,tuple(arguments))
         globalv.input.startInputDaemons()
         msg="Rebooting input plugin..."
     elif name.split()[0]=="add":
         name= ' '.join(name.split()[1:])
         try:
             if name.split()[0] in globalv.loadedInputs.keys():
                 raise Exception("An input module with that ID already exists!")
             x=__import__(name.split()[1])
             reload(x)
             arguments=shlex.split(' '.join(name.split()[2:]))
             globalv.loadedInputs[name.split()[0]]=globalv.input.addInputSource(x.asyncInput,tuple(arguments))
             print arguments
             settingsHandler.writeSetting("'core-input'", ["input", "definition"], [name.split()[0], ' '.join(name.split()[1:])])
             globalv.input.startInputDaemons()
             msg="Plugin loaded successfully!"
         except Exception as detail:
             msg="Load failure: "+str(detail)
     elif name.split()[0]=="send":
         plugin = name.split()[1]
         command = " ".join(name.split()[2:])
         globalv.loadedInputs[plugin].put(command)
         msg = "Sent message to plugin"
     elif name.split()[0]=="autosend":
         name= ' '.join(name.split()[1:])
         settingsHandler.writeSetting("'core-input'", ["input", "definition"], [name.split()[0], ' '.join(name.split()[1:])])
         msg = "Plugin configuration added"
     elif name.split()[0]=="unautosend":
         settingsHandler.deleteSetting("'core-input'", "definition", ' '.join(name.split()[1:]))
         msg="Configuration removed!"
     return ["PRIVMSG $C$ :"+msg]
Example #17
0
 def action(self, args):
     complete = args.complete()[1:].split(':', 1)
     if len(complete) == 2:
         if len(complete[0].split()) == 3:
             msg = args.message()
             if complete[1].startswith(globalv.commandCharacter):
                 self.userlist.append(
                     [complete[0].split('!')[0],
                      time.time()])
                 earliestTimes = {}
                 latestTimes = {}
                 numberOfTimes = {}
                 for line in self.userlist:
                     if line[0] not in earliestTimes.keys():
                         earliestTimes[line[0]] = line[1]
                     else:
                         if earliestTimes[line[0]] > line[1]:
                             earliestTimes[line[0]] = line[1]
                     if line[0] not in latestTimes.keys():
                         latestTimes[line[0]] = line[1]
                     else:
                         if latestTimes[line[0]] < line[1]:
                             latestTimes[line[0]] = line[1]
                     if line[0] not in numberOfTimes.keys():
                         numberOfTimes[line[0]] = 0
                     else:
                         numberOfTimes[line[0]] += 1
                 for user in earliestTimes.keys():
                     if latestTimes[user] - earliestTimes[user] < int(
                             settingsHandler.readSetting(
                                 "noSpam", "timeLimit")):
                         if numberOfTimes[user] >= int(
                                 settingsHandler.readSetting(
                                     "noSpam", "numberLimit")):
                             userMask = globalv.miscVars[0][user]
                             if not userMask in globalv.ignoredUsers:
                                 settingsHandler.writeSetting(
                                     "coreIgnorance",
                                     ["ignorance", "nickname"],
                                     ['.*@' + userMask.split('@')[1], user])
                                 self.userlist = []
                                 return [
                                     "PRIVMSG $C$ :Oi, $U$, shut up for christ's sake."
                                 ]
                         elif numberOfTimes[user] == int(
                                 settingsHandler.readSetting(
                                     "noSpam", "numberLimit")):
                             return [
                                 "PRIVMSG $C$ :Hey, $U$, shut up. One more command and I'm ignoring you."
                             ]
                     elif numberOfTimes[user] >= 2:
                         self.userlist = []
     return [""]
Example #18
0
    def action(self, complete):
        msg = complete.message()
        if msg.split()[0] == "-list":
            users = settingsHandler.readSetting("autoidentifyd",
                                                "nickname, level")
            out = []
            for name, level in users:
                if len(msg.split()) == 1:
                    out.append(name + ":" + str(level))
                elif msg.split()[1].lower() == name.lower():
                    out.append(name + ":" + str(level))
            msg = ', '.join(out)
        elif len(msg.split()) == 1:
            users = settingsHandler.readSetting("autoidentifyd",
                                                "nickname, level")
            for name, level in users:
                if name == msg:
                    return ["PRIVMSG $C$ :%s" % (level)]
            return ["PRIVMSG $C$ :0"]

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

            if nick not in globalv.miscVars[0]:
                return ["PRIVMSG $C$ :That user does not exist."]

            if nick in [
                    x[0] for x in settingsHandler.readSetting(
                        "autoidentifyd", "nickname")
            ]:
                settingsHandler.updateSetting("autoidentifyd",
                                              "level",
                                              str(level),
                                              where="nickname='%s'" % nick)
                msg = "Level updated"
            else:
                settingsHandler.writeSetting("autoidentifyd",
                                             ["nickname", "level"],
                                             [nick, level])
                msg = "User Elevated"

            user = '******' + globalv.miscVars[0][nick]

            globalv.miscVars[2] = filter(lambda (x, y): x != user,
                                         globalv.miscVars[2])
            globalv.miscVars[2].append((user, level))

            print globalv.miscVars[2]
        else:
            msg = "Only elevated users can do this!"
        return ["PRIVMSG $C$ :" + msg]
Example #19
0
 def __init_db_tables__(self, name):
     if settingsHandler.tableExists("'" + name + "'") == False:
         settingsHandler.newTable("'" + name + "'", "answer")
         answers = [
             "As I see it, yes", "It is certain", "It is decidedly so",
             "Most likely", "Outlook good", "Signs point to yes",
             "Without a doubt", "Yes", "Yes - definitely",
             "You may rely on it", "Reply hazy, try again",
             "Ask again later", "Better not tell you now",
             "Cannot predict now", "Concentrate and ask again",
             "Don't count on it", "My reply is no", "My sources say no",
             "Outlook not so good", "Very doubtful"
         ]
         for answer in answers:
             settingsHandler.writeSetting("'" + name + "'", "answer",
                                          answer)
Example #20
0
def save_alias(name): #Saves alias to a file, to stick around between sessions. Returns 1 for complete, 0 for the plugin not existing in the current instnace, and 2 if it fails for some reason.
    if name in globalv.loadedAliases.keys(): #To check if the alias is in the current instance (IE, it actually works)
        isIn=0
        for plugin in [plugin[0] for plugin in settingsHandler.readSetting("alias","aliasName")]:
            if name==plugin:
                isIn=1
        plugin=globalv.loadedAliases[name].split()[0]
        arguments=' '.join(globalv.loadedAliases[name].split()[1:])
        if not isIn:
            settingsHandler.writeSetting("alias",['aliasName', 'aliasPlugin', 'aliasArguments'],[name, plugin, arguments])
        else:
            settingsHandler.updateSetting("alias","aliasPlugin", plugin, "aliasName='"+name+"'")
            settingsHandler.updateSetting("alias","aliasArguments", arguments, "aliasName='"+name+"'")
        return 1
    else:
        return 0
Example #21
0
 def action(self, complete):
     msg=complete.message()
     isElevated=(isAllowed(complete.userMask())>=getLevel(complete.cmd()[0]))
     self.__init_answers__(complete)
     hashDate = True
     hashUser = True
     if len(msg.split())>=1:
         cmd=msg.split()[0]
         msg=' '.join(msg.split()[1:])
         if "-date" in msg.split():
             hashUser = False
         if "-user" in msg.split():
             hashDate = False
     else:
         cmd=""
         msg=""
     if cmd=="-add" and isElevated:
         settingsHandler.writeSetting("'"+complete.cmd()[0]+"'","answer",msg)
         toReturn="Added that answer"
         self.__init_answers__(complete)
     elif cmd=="-delete" and isElevated:
         settingsHandler.deleteSetting("'"+complete.cmd()[0]+"'","answer",msg)
         toReturn="Wiped that answer."
         self.__init_answers__(complete)
     elif cmd=="-wipe" and isElevated:
         settingsHandler.dropTable("'"+complete.cmd()[0]+"'")
         settingsHandler.newTable("'"+complete.cmd()[0]+"'","answer")
         toReturn="Answer table wiped!"
         self.__init_answers__(complete)
     elif cmd=="-dump":
         self.__init_answers__(complete)
         return ["PRIVMSG $C$ :[%s]"%', '.join(["'"+x+"'" for x in self.answers])]
     else:
         totalHash = 0
         if hashDate:
             totalHash += hash(date.today())
         if hashUser:
             totalHash += hash(complete.user())
         answer = totalHash % len(self.answers)
         print answer, totalHash, self.answers
         toReturn=self.answers[answer]
         if complete.message()=="":
             toReturn=toReturn.replace("$1$","$U$")
         else:
             toReturn=toReturn.replace("$1$",complete.message())
     return ["PRIVMSG $C$ :"+toReturn]
Example #22
0
 def action(self, complete):
     msg=complete.message()
     returner=""
     elevated = getLevel(complete.userMask()) >= isAllowed(complete.cmd()[0])
     if msg=="":
         returner="This is the %s dictionary. Run !%s -list for a list of known values!"%(complete.cmd()[0], complete.cmd()[0])
     elif msg.split()[0]=="-add" and elevated:
         settingsHandler.writeSetting(complete.cmd()[0],["key","value"], [msg.split()[1],' '.join(msg.split()[2:])])
         returner="Key:Value pair added!"
     elif msg.split()[0]=="-delete" and elevated:
         settingsHandler.deleteSetting(complete.cmd()[0],"key",msg.split()[1])
         returner="Key removed!"
     elif msg.split()[0]=="-list":
         keypairs=[x[0] for x in settingsHandler.readSettingRaw(complete.cmd()[0],"key")]
         returner=', '.join(keypairs)
     elif msg.split()[0]=="-random":
         keypairs=settingsHandler.readSettingRaw(complete.cmd()[0],"key, value")
         pairs={}
         for keypair in keypairs:
             pairs[keypair[0].lower()]=keypair[1]
         import random
         keys=pairs.keys()
         random.shuffle(keys)
         returner=keys[0]+": "+pairs[keys[0]]
     else:
         keypairs=settingsHandler.readSettingRaw(complete.cmd()[0],"key, value")
         pairs={}
         for keypair in keypairs:
             pairs[keypair[0].lower()]=keypair[1]
         if unicode(msg.split()[0]).lower() in pairs.keys():
             returner=pairs[unicode(msg.split()[0]).lower()]
         elif "default" not in pairs.keys():
             returner="No definition."
             matches=difflib.get_close_matches(msg.split()[0],pairs.keys(),10,0.1)
             if len(matches)>0:
                 returner+=" Perhaps you meant: "+', '.join(matches[:-1])
                 if len(matches)>1:
                     returner+=" or "+matches[-1]
             else:
                 returner+=" No similar definitions"
         else:
             returner=pairs['default']
     if returner=="":
         return [""]
     return ["PRIVMSG $C$ :"+returner]
Example #23
0
    def action(self, complete):
        msg=complete.message()
        if isAllowed(complete.userMask())>=getLevel(complete.cmd()[0]):
            trigger=msg.split()[0]
            command=' '.join(msg.split()[1:])
            try:
                if trigger not in [x[0] for x in settingsHandler.readSettingRaw("'core-expansions'","trigger")]:
                    settingsHandler.writeSetting("'core-expansions'",["trigger","command"],[trigger,command])
                else:
                    settingsHandler.updateSetting("'core-expansions'","command",command,where="trigger='%s'"%trigger)
                msg="%s will now substitute to the output of %s"%(trigger, command)
            except Exception as detail:
                msg="Failure: %s"%detail
        else:
            msg="Sorry, you need to be elevated to use this command!"



        return ["PRIVMSG $C$ :"+msg]
Example #24
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:''})
Example #25
0
    def action(self, complete):
        msg=complete.message()
        if msg.split()[0]=="-list":
           users=settingsHandler.readSetting("autoidentifyd","nickname, level")
           out=[]
           for name,level in users:
               if len(msg.split())==1:
                   out.append(name+":"+str(level))
               elif msg.split()[1].lower()==name.lower():
                   out.append(name+":"+str(level))
           msg=', '.join(out)
        elif len(msg.split())==1:
           users=settingsHandler.readSetting("autoidentifyd","nickname, level")
           for name,level in users:
               if name==msg:
                   return ["PRIVMSG $C$ :%s"%(level)]
           return ["PRIVMSG $C$ :0"]


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

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

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

            print globalv.miscVars[2]
        else:
            msg="Only elevated users can do this!"
        return ["PRIVMSG $C$ :"+msg]
Example #26
0
 def action(self, complete):
     msg=complete.message()
     sender=complete.userMask()
     if len(msg.split())>1:
         mode=msg.split()[1].lower()
     else:
         mode="on"
     msg=msg.split()[0]
     print sender
     print globalv.basePlugin
     if msg=="list":
         return ["PRIVMSG $C$ :"+', '.join([x[0] for x in settingsHandler.readSettingRaw("coreAutoLoad", "loadAs")])]
     if isAllowed(sender)>=getLevel(complete.cmd()[0]):
         if mode=="on":
             settingsHandler.writeSetting("coreAutoLoad", ["plugin", "loadAs"], [globalv.basePlugin[msg], msg])
             return ["PRIVMSG $C$ :Plugin set to autoload"]
         else:
             settingsHandler.deleteSetting("coreAutoLoad", "loadAs", msg)
             return ["PRIVMSG $C$ :Plugin no longer autoloading"]
     return ["PRIVMSG $C$ :You do not have the required access rights!"]
Example #27
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
Example #28
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]
Example #29
0
 def action(self, complete):
     msg = complete.message()
     isElevated = (isAllowed(complete.userMask()) >= getLevel(
         complete.cmd()[0]))
     self.__init_answers__(complete)
     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)
     elif cmd == "-delete" and isElevated:
         settingsHandler.deleteSetting("'" + complete.cmd()[0] + "'",
                                       "answer", msg)
         toReturn = "Wiped that answer."
         self.__init_answers__(complete)
     elif cmd == "-wipe" and isElevated:
         settingsHandler.dropTable("'" + complete.cmd()[0] + "'")
         settingsHandler.newTable("'" + complete.cmd()[0] + "'", "answer")
         toReturn = "Answer table wiped!"
         self.__init_answers__(complete)
     elif cmd == "-dump":
         self.__init_answers__(complete)
         return [
             "PRIVMSG $C$ :[%s]" %
             ', '.join(["'" + x + "'" for x in self.answers])
         ]
     else:
         toReturn = self.answers.pop()
         if complete.message() == "":
             toReturn = toReturn.replace("$1$", "$U$")
         else:
             toReturn = toReturn.replace("$1$", complete.message())
     return ["PRIVMSG $C$ :" + toReturn]
Example #30
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]
Example #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 [""]
Example #32
0
 def action(self, complete):
     msg=complete.message()
     nick=complete.userMask()
     amsg=msg
     nickname="*Unknown*"
     if securityHandler.isAllowed(nick)>=getLevel(complete.cmd()[0]):
         if msg[0]=="#":
             nmsg = msg
             nickname=""
         elif msg in globalv.miscVars[0]:
             nmsg=".*@"+globalv.miscVars[0][msg].split('@')[1]
             nickname=msg
         else:
             nmsg=msg
             nmsg=nmsg.replace('*','.*').replace('..*','.*')
         fullCMD=nmsg
         if fullCMD not in [x[0] for x in settingsHandler.readSettingRaw("coreIgnorance","ignorance")]:
             settingsHandler.writeSetting("coreIgnorance",["ignorance","nickname"],[fullCMD,nickname])
             return ["PRIVMSG $C$ :"+amsg+ " successfully ignored, cap'n!"]
         else:
             return ["PRIVMSG $C$ :"+amsg+" is already ignored, m'lord!"]
     else:
         return ["PRIVMSG $C$ :Go away."]
Example #33
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]
Example #34
0
def createDatabase():
    settingsHandler.newTable("core", "nickname", "password", "owner", "server", "port")
    newName = raw_input("Bot Name? ")
    newPassword = raw_input("Nickname password? ")
    newOwner = raw_input("Owner name? ")
    newServer = raw_input("Connect to what server? ")
    newPort = raw_input("On what port (6667 is standard)? ")
    settingsHandler.writeSetting("core", ["nickname", "password", "owner", "server", "port"],
            [newName, newPassword, newOwner, newServer, newPort])
    settingsHandler.newTable("'core-nickmasks'", "nick", "hostmask")
    newChannel = raw_input("Channel to auto-join? ")
    settingsHandler.newTable("coreAutoJoin", "channel")
    settingsHandler.writeSetting("coreAutoJoin", ["channel"], [newChannel])

    settingsHandler.newTable("alias", "aliasName", "aliasPlugin", "aliasArguments")
    settingsHandler.newTable("'core-userlevels'", "plugin", "level")
    settingsHandler.newTable("coreIgnorance", "ignorance", "nickname")
    settingsHandler.newTable("'core-input'", "input", "definition")
    settingsHandler.newTable("'core-expansions'", "trigger", "command")
    settingsHandler.newTable("'core-doNotExpand'", "doNotExpand")
    settingsHandler.newTable("autoidentifyd", "nickname", "level")
    settingsHandler.newTable("coreSettings", "verboseAutoComplete")
    settingsHandler.writeSetting("coreSettings", ["verboseAutoComplete"], ["True"])
    settingsHandler.writeSetting("autoidentifyd", ["nickname", "level"], [newOwner, "1000"])
Example #35
0
 def __init_db_tables__(self, name):
     if settingsHandler.tableExists("'"+name+"'")==False:
         settingsHandler.newTable("'"+name+"'","answer")
         answers=["As I see it, yes","It is certain","It is decidedly so","Most likely","Outlook good","Signs point to yes", "Without a doubt", "Yes", "Yes - definitely","You may rely on it", "Reply hazy, try again","Ask again later", "Better not tell you now","Cannot predict now","Concentrate and ask again","Don't count on it","My reply is no","My sources say no","Outlook not so good","Very doubtful"]
         for answer in answers:
             settingsHandler.writeSetting("'"+name+"'", "answer",answer)
Example #36
0
 def __init_db_tables__(self, name):
     settingsHandler.newTable(name, "votes", "plugin")
     settingsHandler.writeSetting(name, ["votes", "plugin"], ["3", "9"])
Example #37
0
 def __init_db_tables__(self, name):
     settingsHandler.newTable(name, "nickname")
     settingsHandler.writeSetting(name, "nickname", globalv.owner)
Example #38
0
 def __init_db_tables__(self, name):
     settingsHandler.newTable(name, "timeLimit", "numberLimit")
     settingsHandler.writeSetting(name, ["timeLimit", "numberLimit"],
                                  ["30", "6"])
Example #39
0
 def __init_db_tables__(self, name):
     settingsHandler.newTable(name, "timeLimit", "numberLimit")
     settingsHandler.writeSetting(name,["timeLimit","numberLimit"],["30","6"])
Example #40
0
    def action(self, complete):
        msg = complete.message()
        command = msg.split()[0]
        if command == "list":
            names = settingsHandler.readSettingRaw(
                "laterd",
                "recipient, sender, timestamp",
                where="sent='0' AND anonymous='0'")
            returns = []
            for name in names:
                try:
                    recipient = name[0]
                    sender = name[1]
                    timestamp = name[2]
                    ctime = time.strftime("%H:%M on %d-%m-%Y",
                                          time.gmtime(int(timestamp)))
                    message = recipient + " has a message from " + sender + " (Sent on " + ctime + ")"
                    returns.append(message)
                except:
                    pass
            if returns == []:
                returns.append("No messages.")
            return ["PRIVMSG $C$ :" + ', '.join(returns)]
        elif command == "remove":
            try:
                senderString = " and sender=='%s'" % complete.user()
                if isAllowed(complete.userMask()) >= 150:
                    senderString = ""
                where = "recipient=%s and sent='0'" % repr(
                    msg.split()[1].lower())
                where += senderString
                print where
                settingsHandler.updateSetting("laterd",
                                              "sent",
                                              "'2'",
                                              where=where)
                return ["PRIVMSG $C$ :Later successfully removed!"]
            except Exception as detail:
                return ["PRIVMSG $C$ :Later not removed"]
        else:
            anonymous = "0"
            secret_pfx = "secret::"
            if msg.startswith(secret_pfx):
                anonymous = "1"
                msg = msg[len(secret_pfx):]

            channels = []
            while msg.split()[0][0] == "#":
                channels.append(msg.split()[0])
                msg = ' '.join(msg.split()[1:])
            channel = '|'.join(channels)
            recipients = list(set(msg.split()[0].lower().split(',')))
            recipients = [
                re.sub('[^0-9a-z-[\]*?]', '?', x) for x in recipients
            ]
            sender = complete.user()
            senderMask = complete.userMask()
            timestamp = str(int(time.time()))
            message = ' '.join(msg.split()[1:])
            message = message.replace('$U$', '$recipient$')
            for recipient in recipients:
                print recipient
                id = str(
                    int(settingsHandler.readSetting("laterd", "COUNT(id)")) +
                    1)
                settingsHandler.writeSetting("laterd", [
                    "id", "recipient", "sender", "senderMask", "timestamp",
                    "message", "channel", "anonymous", "sent"
                ], [
                    id, recipient, sender, senderMask, timestamp, message,
                    channel, anonymous, "0"
                ])
                settingsHandler.db.commit()
            return [
                "PRIVMSG $C$ :Ok, I'll tell " + ', '.join(recipients[:-1]) +
                (" and " +
                 recipients[-1] if len(recipients) > 1 else recipients[-1]) +
                " that when they next speak!"
            ]
        return ["PRIVMSG $C$ :" + msg]
Example #41
0
 def __init_db_tables__(self,name):
     import settingsHandler
     settingsHandler.newTable(name,"userRequirement")
     settingsHandler.writeSetting(name,"userRequirement","elevated")
Example #42
0
 if datum.split()[1]==motdEnd:
     okToSend=True
     send("NICKSERV IDENTIFY "+password)
     for channel in globalv.channels:
         send("JOIN "+channel)
 if datum.split()[1]=="TOPIC":
     globalv.miscVars[4].update({datum.split()[2]:' '.join(datum.split()[1:]).split(':',1)[1:]}) #Update the channel:topic disctionary whenever we get a topic change message
 if datum.split()[1]=="332":
     globalv.miscVars[4].update({datum.split()[3]:' '.join(datum.split()[1:]).split(':',1)[1:]}) #There are two different types of topic change message.
 if datum.split()[1]==privmsg:
     complete=datum[1:].split(' :',1) #Parse into [data, message] format
     if complete[0].split()[0].split('!')[0] in globalv.miscVars[0].keys():
         settingsHandler.updateSetting("'core-nickmasks'","hostmask",complete[0].split()[0].split('!')[1],where="nick='%s'"%complete[0].split()[0].split('!')[0])
     else:
         nickInfo=complete[0].split()[0].split('!')
         settingsHandler.writeSetting("'core-nickmasks'",["nick","hostmask"],[nickInfo[0],nickInfo[1]])
     stuff=datum.split()[0].split(':', 1)[1].split('!')
     globalv.miscVars[0].update({stuff[0]:stuff[1]})
     if stuff[0] not in globalv.accessRights.keys():
         globalv.accessRights[stuff[0]]=security.accessRight(stuff[0])
     if len(complete)>1:
         if complete[1].startswith(globalv.commandCharacter):
             try:
                 parse(datum)
             except Exception as detail:
                 print "Base Plugin Exection Failure:",detail
                 traceback.print_tb(sys.exc_info()[2])
 elif datum.split()[1]==join:
     stuff=datum.split()[0].split(':', 1)[1].split('!')
     globalv.miscVars[0].update({stuff[0]:stuff[1]})
 elif datum.split()[1]==nick and datum.split()[0].split('!')[0].split(':')[1]==globalv.nickname:
Example #43
0
 def __init_db_tables__(self, name):
     settingsHandler.newTable(name, "kickAfterBan")
     settingsHandler.writeSetting(name, "kickAfterBan", "False")
Example #44
0
 def __init_db_tables__(self, name):
     settingsHandler.newTable(name, "votes","plugin")
     settingsHandler.writeSetting(name,["votes","plugin"],["3","9"])
Example #45
0
 def __init_db_tables__(self, name):
     settingsHandler.newTable(name, "showDomainLink")
     settingsHandler.writeSetting(name, ["showDomainLink"], ["true"])
Example #46
0
def createAutoload():
    settingsHandler.newTable("coreAutoLoad", "plugin", "loadAs")
    settingsHandler.writeSetting("coreAutoLoad", ["plugin", "loadAs"], ["load", "load"])
    settingsHandler.writeSetting("coreAutoLoad", ["plugin", "loadAs"], ["autoidentifyd", "autoidentifyd"])
from plugins import plugin
Example #48
0
 def __init_db_tables__(self, name):
     settingsHandler.newTable(name, "location")
     settingsHandler.writeSetting(name, "location", "/home/py/")
Example #49
0
 def __init_db_tables__(self, name):
     settingsHandler.newTable(name, "showTitle","showLink","showLyrics","showPreview")
     settingsHandler.writeSetting(name,["showTitle","showLink","showLyrics","showPreview"],["True","False","False","False"])
 def __init_db_tables__(self,name):
     import settingsHandler
     settingsHandler.newTable(name, "url", "regex","numMatches","matchText")
     settingsHandler.writeSetting(name,["url","regex","numMatches","matchText"],["http://google.com/complete/search?output=toolbar&q=$*$",".*","1","Autocomplete Results:"])
Example #51
0
 def action(self, complete):
     name = complete.message()
     msg = "There was an error in your input!"
     if isAllowed(complete.userMask()) < getLevel(complete.cmd()[0]):
         return [""]
     if name.split()[0] == "list":
         return ["PRIVMSG $C$ :" + ' '.join(globalv.loadedInputs.keys())]
     elif name.split()[0] == "clean":
         newDict = {}
         for plugin in globalv.loadedInputs.keys():
             if globalv.loadedInputs[plugin].isSet() == False:
                 newDict[plugin] = globalv.loadedInputs[plugin]
         globalv.loadedInputs = newDict
         return ["PRIVMSG $C$ :ID list cleaned up manually"]
     elif name.split()[0] == "kickstart":
         globalv.input.startInputDaemons()
         return ["PRIVMSG $C$ :Kickstarted stalling plugins manually"]
     elif name.split()[0] == "reboot":
         definition = settingsHandler.readSetting("'core-input'",
                                                  "definition",
                                                  where="input='%s'" %
                                                  name.split()[1])
         print "def"
         x = __import__(str(definition.split()[0]))
         reload(x)
         arguments = str(' '.join(definition.split()[1:]))
         arguments = shlex.split(arguments)
         globalv.loadedInputs[name.split()
                              [1]] = globalv.input.addInputSource(
                                  x.asyncInput, tuple(arguments))
         globalv.input.startInputDaemons()
         msg = "Rebooting input plugin..."
     elif name.split()[0] == "add":
         name = ' '.join(name.split()[1:])
         try:
             if name.split()[0] in globalv.loadedInputs.keys():
                 raise Exception(
                     "An input module with that ID already exists!")
             x = __import__(name.split()[1])
             reload(x)
             arguments = shlex.split(' '.join(name.split()[2:]))
             globalv.loadedInputs[name.split()
                                  [0]] = globalv.input.addInputSource(
                                      x.asyncInput, tuple(arguments))
             print arguments
             settingsHandler.writeSetting(
                 "'core-input'", ["input", "definition"],
                 [name.split()[0], ' '.join(name.split()[1:])])
             globalv.input.startInputDaemons()
             msg = "Plugin loaded successfully!"
         except Exception as detail:
             msg = "Load failure: " + str(detail)
     elif name.split()[0] == "send":
         plugin = name.split()[1]
         command = " ".join(name.split()[2:])
         globalv.loadedInputs[plugin].put(command)
         msg = "Sent message to plugin"
     elif name.split()[0] == "autosend":
         name = ' '.join(name.split()[1:])
         settingsHandler.writeSetting(
             "'core-input'", ["input", "definition"],
             [name.split()[0], ' '.join(name.split()[1:])])
         msg = "Plugin configuration added"
     elif name.split()[0] == "unautosend":
         settingsHandler.deleteSetting("'core-input'", "definition",
                                       ' '.join(name.split()[1:]))
         msg = "Configuration removed!"
     return ["PRIVMSG $C$ :" + msg]
Example #52
0
 def __init_db_tables__(self, name):
     settingsHandler.newTable(name, "showTitle")
     settingsHandler.writeSetting(name,"showTitle","True")
Example #53
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]