예제 #1
0
def nickname_comand_update(bot, trigger, botcom):

    if not SpiceBot.users.command_permissions_check(
            bot, trigger, ['admins', 'owner', 'OP', 'ADMIN', 'OWNER']):
        SpiceBot.messagelog.messagelog_error(
            botcom.dict["log_id"],
            "I was unable to process this Bot Nick command due to privilege issues."
        )
        return

    if not len(botcom.dict['args']):
        commandused = 'nodeps'
    else:
        commandused = spicemanip(botcom.dict['args'], 1).lower()

    if commandused not in ['deps', 'nodeps']:
        SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"],
                                             "Please specify deps or nodeps")
        return

    botcom.dict['args'] = spicemanip(botcom.dict['args'], '2+', 'list')

    quitmessage = "Received command from " + trigger.nick + " to update from Github and restart"
    SpiceBot.logs.log('SpiceBot_Update', quitmessage)
    bot.osd(quitmessage, list(bot.channels.keys()))

    if commandused == 'nodeps':
        SpiceBot.spicebot_update(False)
    if commandused == 'deps':
        SpiceBot.spicebot_update(True)

    # service_manip(bot.nick, 'restart', 'SpiceBot_Update')
    SpiceBot.spicebot_reload(bot, 'SpiceBot_Update', quitmessage)
예제 #2
0
파일: AI.py 프로젝트: sk99sk/SpiceBot
    def bot_message_precipher(self, bot, trigger, message):

        # punctuation
        puct_dict = {
            "!": "exclamationmark",
            ".": "period",
            "?": "questionmark",
            ",": "comma"
        }
        for puctuation in list(puct_dict.keys()):
            message = message.replace(puctuation, puct_dict[puctuation])

        # bot items
        for botitem in ["nick"]:
            messagelist = spicemanip(message, "create")
            for i in range(len(messagelist)):
                if messagelist[i].upper() == str(eval("bot." +
                                                      botitem)).upper():
                    messagelist[i] = str("bot" + botitem).upper()
            message = spicemanip(messagelist, 0)

        for triggeritem in ["nick", "sender"]:
            messagelist = spicemanip(message, "create")
            for i in range(len(messagelist)):
                if messagelist[i].upper() == str(eval("trigger." +
                                                      botitem)).upper():
                    messagelist[i] = str("trigger" + botitem).upper()
            message = spicemanip(messagelist, 0)

        return message
예제 #3
0
def nickname_comand_regnicks(bot, trigger, botcom):
    reggedusers = SpiceBot.users.dict["registered"]
    bot.osd(
        ["These users are registered:",
         spicemanip(reggedusers, 'andlist')], trigger.nick, 'notice')
    notregged = []
    for user in SpiceBot.users.dict["online"]:
        usernick = SpiceBot.users.ID(user)
        if str(usernick).lower() not in [
                x.lower() for x in SpiceBot.users.dict["registered"]
        ]:
            if usernick != bot.nick:
                notregged.append(usernick)
    bot.osd([
        "These online users are not registered:",
        spicemanip(notregged, 'andlist')
    ], trigger.nick, 'notice')

    identusers = []
    for user in SpiceBot.users.identified:
        usernick = SpiceBot.users.ID(user)
        identusers.append(str(usernick))
    bot.osd([
        "These online users are identified:",
        spicemanip(identusers, 'andlist')
    ], trigger.nick, 'notice')
예제 #4
0
파일: DictComs.py 프로젝트: sk99sk/SpiceBot
def bot_dictcom_gif(bot, trigger, botcom):

    if botcom.dict["dict"][botcom.dict["responsekey"]][
            "blank_required"] and not botcom.dict["completestring"]:
        botcom.dict["dict"][
            botcom.dict["responsekey"]]["responses"] = botcom.dict["dict"][
                botcom.dict["responsekey"]]["blank_fail"]
        return bot_dictcom_reply_shared(bot, trigger, botcom)
    elif botcom.dict["dict"][botcom.dict["responsekey"]][
            "blank_required"] and botcom.dict["completestring"]:
        queries = [botcom.dict["completestring"]]
    else:
        queries = botcom.dict["dict"][botcom.dict["responsekey"]]["responses"]

    # which api's are we using to search
    if "queryapi" in list(botcom.dict["dict"].keys()):
        searchapis = botcom.dict["dict"][
            botcom.dict["responsekey"]]["queryapi"]
    else:
        searchapis = list(SpiceBot.gif.valid_api.keys())

    if botcom.dict["specified"]:
        if botcom.dict["specified"] > len(queries):
            botcom.dict["specified"] = len(queries)
        query = spicemanip(queries, botcom.dict["specified"], 'return')
    else:
        query = spicemanip(queries, 'random', 'return')

    searchdict = {"query": query, "gifsearch": searchapis}

    # nsfwenabled = get_database_value(bot, bot.nick, 'channels_nsfw') or []
    # if trigger.sender in nsfwenabled:
    #    searchdict['nsfw'] = True
    # TODO

    gifdict = SpiceBot.gif.get_gif(searchdict)

    if gifdict["error"]:
        botcom.dict["success"] = False
        if botcom.dict["dict"][botcom.dict["responsekey"]]["search_fail"]:
            gifdict["error"] = botcom.dict["dict"][
                botcom.dict["responsekey"]]["search_fail"]
        botcom.dict["dict"][botcom.dict["responsekey"]]["responses"] = [
            gifdict["error"]
        ]
    else:
        botcom.dict["dict"][botcom.dict["responsekey"]]["responses"] = [
            str(gifdict['gifapi'].title() + " Result (" + str(query) + " #" +
                str(gifdict["returnnum"]) + "): " + str(gifdict["returnurl"]))
        ]

    botcom.dict["specified"] = False
    bot_dictcom_reply_shared(bot, trigger, botcom)
예제 #5
0
def trigger_argsdict_single(argsdict_default, trigger_args_part):
    argsdict_part = copy.deepcopy(argsdict_default)
    argsdict_part["args"] = spicemanip(trigger_args_part, 'create')
    if len(argsdict_part["args"]) and (argsdict_part["args"][0] == "-a" or argsdict_part["args"][-1] == "-a"):
        argsdict_part["adminswitch"] = True
        if argsdict_part["args"][0] == "-a":
            argsdict_part["args"] = spicemanip(argsdict_part["args"], '2+', 'list')
        elif argsdict_part["args"][-1] == "-a":
            del argsdict_part["args"][-1]
    else:
        argsdict_part["adminswitch"] = False
    return argsdict_part
예제 #6
0
파일: Reddit.py 프로젝트: sk99sk/SpiceBot
    def trigger_handler(self, trigger):
        trigger_args = spicemanip(trigger.args[1], 'create')
        trigger_argsdict = {
            "slashcomm": spicemanip(trigger_args, 1).lower()[:1],
            "command": spicemanip(trigger_args, 1).lower()[2:],
            "args": spicemanip(trigger_args, "2+", 'list')
        }
        if trigger_argsdict["slashcomm"] == "u":
            trigger_argsdict["urltypetxt"] = "user"
        if trigger_argsdict["slashcomm"] == "r":
            trigger_argsdict["urltypetxt"] = "subreddit"

        return trigger_argsdict
예제 #7
0
def bot_command_logs(bot, trigger, botcom):

    if not SpiceBot.users.command_permissions_check(
            bot, trigger, ['admins', 'owner', 'OP', 'ADMIN', 'OWNER']):
        SpiceBot.messagelog.messagelog_error(
            botcom.dict["log_id"],
            "I was unable to process this Bot Nick command due to privilege issues."
        )
        return

    logtype = spicemanip(botcom.dict['args'], 1) or None
    if not logtype:
        bot.osd(
            "Current valid log(s) include: " +
            spicemanip(list(SpiceBot.logs.dict["list"].keys()), 'andlist'),
            trigger.sender, 'action')
        return

    if not SpiceBot.inlist(logtype, list(SpiceBot.logs.dict["list"].keys())):
        closestmatches = SpiceBot.similar_list(
            logtype, list(SpiceBot.logs.dict["list"].keys()), 10, 'reverse')
        if not len(closestmatches):
            SpiceBot.messagelog.messagelog_error(
                botcom.dict["log_id"],
                "No valid logs match " + str(logtype) + ".", trigger.nick,
                'notice')
        else:
            SpiceBot.messagelog.messagelog_error(
                botcom.dict["log_id"],
                "The following commands may match " + str(logtype) + ": " +
                spicemanip(closestmatches, 'andlist') + ".", trigger.nick,
                'notice')

        return

    logtype = SpiceBot.inlist_match(logtype,
                                    list(SpiceBot.logs.dict["list"].keys()))

    logindex = SpiceBot.logs.get_logs(logtype)

    if not len(logindex):
        SpiceBot.messagelog.messagelog_error(
            botcom.dict["log_id"], "No logs found for " + str(logtype) + ".")
        return

    bot.osd("Is Examining " + str(logtype) + " log(s).")
    for line in logindex:
        bot.osd("    " + str(line))
    bot.osd(str(logtype) + " log(s) Complete.")
예제 #8
0
def trigger_argsdict_list(argsdict_default, and_split):
    prerun_split = []
    for trigger_args_part in and_split:
        argsdict_part = copy.deepcopy(argsdict_default)
        argsdict_part["args"] = spicemanip(trigger_args_part, 'create')
        if len(argsdict_part["args"]) and (argsdict_part["args"][0] == "-a" or argsdict_part["args"][-1] == "-a"):
            argsdict_part["adminswitch"] = True
            if argsdict_part["args"][0] == "-a":
                argsdict_part["args"] = spicemanip(argsdict_part["args"], '2+', 'list')
            elif argsdict_part["args"][-1] == "-a":
                del argsdict_part["args"][-1]
        else:
            argsdict_part["adminswitch"] = False
        prerun_split.append(argsdict_part)
    return prerun_split
예제 #9
0
def nickname_comand_commands(bot, trigger, botcom):

    if not len(botcom.dict['args']):
        commandused = 'list'
    else:
        commandused = spicemanip(botcom.dict['args'], 1).lower()

    if commandused == 'list':
        availablecomsnum, availablecomsfiles = 0, []
        for commandstype in list(SpiceBot.commands.dict['commands'].keys()):
            availablecomsnum += len(
                list(SpiceBot.commands.dict['commands'][commandstype].keys()))
            for validcom in list(
                    SpiceBot.commands.dict['commands'][commandstype].keys()):
                if "filepath" in list(SpiceBot.commands.dict['commands']
                                      [commandstype][validcom].keys()):
                    filepath = SpiceBot.commands.dict['commands'][
                        commandstype][validcom]["filepath"].lower()
                    if filepath not in availablecomsfiles:
                        availablecomsfiles.append(filepath)
        availablecomsfiles = len(availablecomsfiles)
        displayval = "There are " + str(
            availablecomsnum) + " commands available in " + str(
                availablecomsfiles) + " files."
        bot.osd(displayval)
        return

    commands_list = []
    for commandstype in list(SpiceBot.commands.dict['commands'].keys()):
        if commandstype not in ['rule']:
            for com in list(
                    SpiceBot.commands.dict['commands'][commandstype].keys()):
                if com not in commands_list:
                    if commandstype in ['nickname']:
                        commands_list.append(bot.nick + " " + com)
                    else:
                        commands_list.append(com)

    if commandused == 'total':
        bot.osd("I have " + str(len(commands_list)) + " commands available.")
        return

    if commandused == 'random':
        bot.osd([
            "Here's a random command for you:",
            spicemanip(commands_list, 'random')
        ])
        return
예제 #10
0
    def register(self, command_dict):

        self.lock.acquire()

        command_type = command_dict["comtype"]
        if command_type not in list(self.dict['commands'].keys()):
            self.dict['commands'][command_type] = dict()

        # default command to filename
        if "validcoms" not in list(command_dict.keys()):
            command_dict["validcoms"] = [command_dict["filename"]]

        validcoms = command_dict["validcoms"]
        if not isinstance(validcoms, list):
            validcoms = [validcoms]

        maincom = command_dict["validcoms"][0]
        if len(command_dict["validcoms"]) > 1:
            comaliases = spicemanip(command_dict["validcoms"], '2+', 'list')
        else:
            comaliases = []

        self.dict['commands'][command_type][maincom] = command_dict
        for comalias in comaliases:
            if comalias not in list(
                    self.dict['commands'][command_type].keys()):
                self.dict['commands'][command_type][comalias] = {
                    "aliasfor": maincom
                }

        self.lock.release()
예제 #11
0
def bot_command_http_codes(bot, trigger, botcom):

    query = spicemanip(botcom.dict["args"], 1) or None
    query = str(query)

    result = SpiceBot.httpcodes.fetch_result(query)

    message = ["[HTTP code search for " + str(query or "") + "]"]

    if not result["error"] or not query:
        message.extend([result["basic"], result["explanation"]])

    elif query in ["urmom", "yourmom"]:
        message.extend([
            "Too Many Results",
            "There are too many pages on the internet regarding your mother."
        ])

    elif query == "42":
        message.extend([
            "The Hitchhiker's Guide To The Galaxy",
            "The answer to life, the world, and everything."
        ])

    elif query == "69":
        message.extend([
            "Oral Fixation",
            "Round and Round they go, where they stop: nobody knows"
        ])

    else:
        message.extend([result["basic"], result["explanation"]])

    bot.osd(message)
예제 #12
0
def channels_thread(bot):
    while True:
        time.sleep(1800)
        SpiceBot.channels.bot_part_empty(bot)

        oldlist = SpiceBot.channels.chanlist()
        SpiceBot.channels.channel_list_request(bot)

        while SpiceBot.channels.channel_lock:
            pass

        currentlist = SpiceBot.channels.chanlist()
        newlist = []
        for channel in currentlist:
            if channel not in oldlist:
                newlist.append(channel)
        if "*" in newlist:
            newlist.remove("*")
        if len(newlist) and SpiceBot.config.SpiceBot_Channels.announcenew:
            bot.osd([
                "The Following channel(s) are new:",
                spicemanip(newlist, 'andlist')
            ], list(bot.channels.keys()))

        SpiceBot.channels.join_all_channels(bot)

        SpiceBot.channels.bot_part_empty(bot)
예제 #13
0
def gifapi_triggers(bot, trigger, botcom):

    if botcom.dict['com'] not in list(SpiceBot.search.valid_api.keys()):
        return

    searchterm = spicemanip(botcom.dict['args'], 0) or None
    if not searchterm:
        SpiceBot.messagelog.messagelog_error(
            botcom.dict["log_id"], "Not sure what you want me to look for.")
        return

    searchdict = {
        "query": searchterm,
        "query_type": botcom.dict["realcom"],
    }

    searchreturn = SpiceBot.search.search(searchdict)
    if not searchreturn:
        SpiceBot.messagelog.messagelog_error(
            botcom.dict["log_id"],
            "[" + botcom.dict["realcom"].title() + " search for '" +
            str(searchterm) + "']    " + 'I cannot find anything about that')
    else:
        bot.osd([
            "[" + botcom.dict["realcom"].title() + " search for '" +
            str(searchterm) + "']",
            str(searchreturn)
        ])
예제 #14
0
def bot_command_process(bot, trigger, botcom):

    if not botcom.dict['com'].endswith("s"):
        botcom.dict['com'] = str(botcom.dict['com'] + "s")

    privlist = spicemanip(SpiceBot.bot_privs(botcom.dict['com']), 'andlist')
    bot.osd(str(bot.nick) + " " + botcom.dict['com'] + ": " + privlist)
예제 #15
0
파일: Reddit.py 프로젝트: sk99sk/SpiceBot
    def user_handler(self, trigger_argsdict):
        subcommand_valid = ['check']
        subcommand = spicemanip(
            [x for x in trigger_argsdict["args"] if x in subcommand_valid],
            1) or 'check'

        userreal = self.reddit_user_exists(trigger_argsdict["command"])
        if not userreal["exists"]:
            return userreal["error"]

        fulluurul = str("https://www.reddit.com/" +
                        trigger_argsdict["slashcomm"] + "/" +
                        trigger_argsdict["command"])
        if subcommand == 'check':
            u = self.praw.redditor(trigger_argsdict["command"])
            message = ['[REDDITOR] ' + u.name]
            is_cakeday = self.user_cakeday(u.created_utc)
            if is_cakeday:
                message.append(bold(color('Cake day', colors.LIGHT_PURPLE)))
            message.append(fulluurul)
            if u.is_gold:
                message.append(bold(color('Gold', colors.YELLOW)))
            if u.is_mod:
                message.append(bold(color('Mod', colors.GREEN)))
            message.append('Link: ' + str(u.link_karma))
            message.append('Comment: ' + str(u.comment_karma))
            return message
예제 #16
0
파일: Tools.py 프로젝트: sk99sk/SpiceBot
def similar_list(searchitem, searchlist, matchcount=1, searchorder='reverse'):

    if sys.version_info.major >= 3:
        if isinstance(searchlist, abc.KeysView):
            searchlist = [x for x in searchlist]
    if isinstance(searchlist, dict):
        searchlist = [x for x in searchlist]

    if not isinstance(searchlist, list):
        searchlist = [searchlist]

    sim_listitems, sim_num = [], []
    for listitem in searchlist:
        similarlevel = SequenceMatcher(None, searchitem.lower(),
                                       listitem.lower()).ratio()
        if similarlevel >= .75:
            sim_listitems.append(listitem)
            sim_num.append(similarlevel)

    if len(sim_listitems) and len(sim_num):
        sim_num, sim_listitems = (list(x) for x in zip(
            *sorted(zip(sim_num, sim_listitems), key=itemgetter(0))))

    if searchorder == 'reverse':
        sim_listitems = spicemanip(sim_listitems, 'reverse', "list")

    sim_listitems[-matchcount:]

    return sim_listitems
예제 #17
0
def bot_command_process(bot, trigger, botcom):

    if not SpiceBot.users.command_permissions_check(bot, trigger,
                                                    ['admins', 'owner']):
        SpiceBot.messagelog.messagelog_error(
            botcom.dict["log_id"],
            "I was unable to process this Bot Nick command due to privilege issues."
        )
        return

    if botcom.dict['com'] in ['say', 'msg']:
        botcom.dict['com'] = 'privmsg'

    if not len(botcom.dict['args']):
        SpiceBot.messagelog.messagelog_error(
            botcom.dict["log_id"], "You must specify a channel or nick.")
        return

    target = spicemanip(botcom.dict['args'], 1)
    if (target not in ['allchans', 'allnicks']
            and not SpiceBot.channels.ischannel(target)
            and not SpiceBot.inlist(target.lower(), bot.users)):
        SpiceBot.messagelog.messagelog_error(
            botcom.dict["log_id"],
            "Channel/nick name {} not valid.".format(target))
        return

    botcom.dict['args'] = spicemanip(botcom.dict['args'], '2+', 'list')

    if target == 'allchans':
        targetsendlist = list(bot.channels.keys())
    elif target == 'allnicks':
        targetsendlist = bot.users
    else:
        targetsendlist = [target]

    botmessage = spicemanip(botcom.dict['args'], 0)
    if not botmessage:
        SpiceBot.messagelog.messagelog_error(
            botcom.dict["log_id"], "You must specify a message to send.")
        return

    bot.osd(botmessage, targetsendlist, botcom.dict['com'].upper())
예제 #18
0
def special_handling(botcom):
    botcom.dict["responsekey"] = "?default"

    if "nonstockoptions" not in list(botcom.dict["dict"].keys()):
        botcom.dict["dict"]["nonstockoptions"] = []

    # handling for special cases
    posscom = spicemanip(botcom.dict['args'], 1)
    if posscom.lower() in [command.lower() for command in botcom.dict["dict"]["nonstockoptions"]]:
        for command in botcom.dict["dict"]["nonstockoptions"]:
            if command.lower() == posscom.lower():
                posscom = command
        botcom.dict["responsekey"] = posscom

    botcom = dictkey_defaults(botcom)

    if botcom.dict["responsekey"] != "?default":
        botcom.dict['args'] = spicemanip(botcom.dict['args'], '2+', 'list')

    return botcom
예제 #19
0
def nickname_comand_releasenotes(bot, trigger, botcom):
    newnotes = False
    for notefile in list(SpiceBot.releasenotes.notes.keys()):
        if len(SpiceBot.releasenotes.notes[notefile]["new"]):
            bot.osd([
                "[" + str(notefile) + "]",
                spicemanip(SpiceBot.releasenotes.notes[notefile]["new"],
                           'andlist')
            ])
            newnotes = True
    if not newnotes:
        bot.osd("This bot restart contains no new release notes.")
예제 #20
0
 def systemd_logs_fetch(self):
     servicepid = self.get_running_pid()
     debuglines = []
     for line in os.popen(str("sudo journalctl _PID=" +
                              str(servicepid))).read().split('\n'):
         line = str(line).split(str(os.uname()[1] + " "))[-1]
         lineparts = str(line).split(": ")
         del lineparts[0]
         line = spicemanip(lineparts, 0)
         if not line.isspace():
             debuglines.append(str(line))
     return debuglines
예제 #21
0
 def random_valid_target(self, bot, trigger, outputtype):
     validtargs = []
     if trigger.is_privmsg:
         validtargs.extend([str(bot.nick), trigger.nick])
     else:
         for nick_id in self.dict["online"]:
             if str(trigger.sender).lower(
             ) in self.dict["current"][nick_id]["channels"]:
                 nick = self.dict["all"][nick_id][0]
                 validtargs.append(nick)
     if outputtype == 'list':
         return validtargs
     elif outputtype == 'random':
         return spicemanip(validtargs, 'random')
예제 #22
0
def make_trigger_args(triggerargs_one, trigger_command_type='module'):
    trigger_args = spicemanip(triggerargs_one, 'create')
    if trigger_command_type in ['nickname']:
        trigger_prefix = None
        # if trigger_prefix.isupper() or trigger_prefix.islower():
        #    trigger_prefix = None
        trigger_command = spicemanip(trigger_args, 2).lower()
        trigger_args = spicemanip(trigger_args, '3+', 'list')
    elif trigger_command_type in ['action']:
        trigger_prefix = None
        trigger_command = spicemanip(trigger_args, 1).lower()
        trigger_args = spicemanip(trigger_args, '2+', 'list')
    else:
        trigger_prefix = spicemanip(trigger_args, 1).lower()[0]
        trigger_command = spicemanip(trigger_args, 1).lower()[1:]
        trigger_args = spicemanip(trigger_args, '2+', 'list')
    return trigger_args, trigger_command, trigger_prefix
예제 #23
0
파일: Sherlock.py 프로젝트: sk99sk/SpiceBot
def bot_command_sherlock(bot, trigger, botcom):

    netlist = list(SpiceBot.sherlock.dict.keys())

    username = spicemanip(botcom.dict["args"], 1) or trigger.nick
    botcom.dict["args"] = spicemanip(botcom.dict["args"], "2+", 'list')

    checklist = netlist
    checklistname = 'all'
    if SpiceBot.inlist(username, netlist):
        checklistname = SpiceBot.inlist_match(username, netlist)
        checklist = [checklistname]
        username = spicemanip(botcom.dict["args"], 1) or trigger.nick

    bot.osd([
        "Checking username " + username + " in " + checklistname + " network.",
        "This takes time, please be patient."
    ])

    inlist, notinlist = [], []

    for social_network in checklist:

        in_social = SpiceBot.sherlock.check_network(username, social_network)
        if in_social:
            inlist.append(social_network)
        else:
            notinlist.append(social_network)

    if len(inlist):
        if checklistname != 'all':
            bot.osd([
                "The username " + username + " is in " + checklist[0],
                SpiceBot.sherlock.dict.get(social_network).get("url").format(
                    username)
            ])
        else:
            bot.osd([
                "The username " + username + " is in the following:",
                spicemanip(inlist, "andlist")
            ], trigger.nick, 'NOTICE')
    if len(notinlist):
        if checklistname != 'all':
            bot.osd([
                "The username " + username + " is NOT in the following:",
                spicemanip(notinlist, "andlist")
            ])
        else:
            bot.osd([
                "The username " + username + " is NOT in the following:",
                spicemanip(notinlist, "andlist")
            ], trigger.nick, 'NOTICE')
예제 #24
0
파일: Gif.py 프로젝트: sk99sk/SpiceBot
def gif_trigger(bot, trigger, botcom):

    if not len(botcom.dict['args']):
        return SpiceBot.messagelog.messagelog_error(
            botcom.dict["log_id"], "Please present a query to search.")

    query = spicemanip(botcom.dict['args'], 0)
    searchapis = list(SpiceBot.gif.valid_api.keys())
    searchdict = {"query": query, "gifsearch": searchapis}

    gifdict = SpiceBot.gif.get_gif(searchdict)

    if gifdict["error"]:
        SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"],
                                             gifdict["error"])
    else:
        bot.osd(
            str(gifdict['gifapi'].title() + " Result (" + str(query) + " #" +
                str(gifdict["returnnum"]) + "): " + str(gifdict["returnurl"])))
예제 #25
0
def search_what(bot, trigger, botcom):

    searchterm = spicemanip(botcom.dict['args'], 0) or None
    if not searchterm:
        SpiceBot.messagelog.messagelog_error(
            botcom.dict["log_id"], "Not sure what you want me to look for.")
        return
    searchdict = {
        "query": searchterm,
    }

    searchreturn = SpiceBot.search.search(searchdict)
    if not searchreturn:
        SpiceBot.messagelog.messagelog_error(
            botcom.dict["log_id"], "[Information search for '" +
            str(searchterm) + "']    " + 'I cannot find anything about that')
    else:
        bot.osd([
            "[Information search for '" + str(searchterm) + "']",
            str(searchreturn)
        ])
예제 #26
0
    def stdio_logs_fetch(self):

        stdio_ignore = []
        for logtype in list(self.dict["list"].keys()):
            stdio_ignore.append("[" + logtype + "]")

        try:
            log_file_lines = []
            log_file = open(botconfig.logs_stdio, 'r')
            lines = log_file.readlines()
            for line in lines:
                log_file_lines.append(line)
            log_file.close()

            currentline, linenumindex = 0, []
            for line in log_file_lines:
                if line.startswith("Welcome to Sopel. Loading modules..."):
                    linenumindex.append(currentline)
                currentline += 1
            last_start = max(linenumindex)
            filelines = log_file_lines[last_start:]
        except Exception as e:
            debuglines = e
            filelines = []

        debuglines = []
        loadedmodules = []
        for line in filelines:
            if line.startswith("Loaded:"):
                loadedmodules.append(str(line).split("Loaded:")[-1])
            else:
                if not line.startswith(
                        tuple(stdio_ignore)) and not line.isspace():
                    debuglines.append(str(line))
        loadedmodules = "Loaded: " + spicemanip(loadedmodules, 'andlist')
        debuglines.insert(1, loadedmodules)

        return debuglines
예제 #27
0
파일: Channels.py 프로젝트: sk99sk/SpiceBot
def trigger_channel_list_recurring(bot, trigger):
    while True:
        time.sleep(1800)
        SpiceBot.channels.bot_part_empty(bot)

        oldlist = list(SpiceBot.channels.dict['list'].keys())
        SpiceBot.channels.channel_list_request(bot)

        while SpiceBot.channels.channel_lock:
            pass

        newlist = [item.lower() for item in oldlist if item.lower() not in list(SpiceBot.channels.dict['list'].keys())]
        if "*" in newlist:
            newlist.remove("*")
        if len(newlist) and SpiceBot.config.SpiceBot_Channels.announcenew:
            bot.osd(["The Following channel(s) are new:", spicemanip(newlist, 'andlist')], list(bot.channels.keys()))

        SpiceBot.channels.join_all_channels(bot)

        SpiceBot.channels.chanadmin_all_channels(bot)

        if "*" in list(SpiceBot.channels.dict['list'].keys()):
            del SpiceBot.channels.dict['list']["*"]
        SpiceBot.channels.bot_part_empty(bot)
예제 #28
0
    def target_check(self, bot, trigger, target, targetbypass):
        targetgood = {"targetgood": True, "error": "None", "reason": None}

        if not isinstance(targetbypass, list):
            targetbypass = [targetbypass]

        if "notarget" not in targetbypass:
            if not target or target == '':
                return {
                    "targetgood": False,
                    "error": "No target Given.",
                    "reason": "notarget"
                }

        # Optional don't allow self-target
        if "self" not in targetbypass:
            if inlist(target, trigger.nick):
                return {
                    "targetgood": False,
                    "error":
                    "This command does not allow you to target yourself.",
                    "reason": "self"
                }

        # cannot target bots
        if "bot" not in targetbypass:
            if inlist(target, bot.nick):
                return {
                    "targetgood": False,
                    "error": "I am a bot and cannot be targeted.",
                    "reason": "bot"
                }
        if "bots" not in targetbypass:
            if inlist(target, bot.nick):
                return {
                    "targetgood": False,
                    "error": self.nick_actual(target) +
                    " is a bot and cannot be targeted.",
                    "reason": "bots"
                }

        # Not a valid user
        if "unknown" not in targetbypass:
            if not botdb.check_nick_id(target):
                sim_user, sim_num = [], []
                for nick_id in list(self.dict["all"].keys()):
                    nick_list = self.dict["all"][nick_id]
                    for nick in nick_list:
                        similarlevel = similar(
                            str(target).lower(), nick.lower())
                        if similarlevel >= .75:
                            sim_user.append(nick)
                            sim_num.append(similarlevel)
                if sim_user != [] and sim_num != []:
                    sim_num, sim_user = array_arrangesort(sim_num, sim_user)
                    closestmatch = spicemanip(sim_user, 'reverse', "list")
                    listnumb, relist = 1, []
                    for item in closestmatch:
                        if listnumb <= 3:
                            relist.append(str(item))
                        listnumb += 1
                    closestmatches = spicemanip(relist, "andlist")
                    targetgooderror = "It looks like you're trying to target someone! Did you mean: " + str(
                        closestmatches) + "?"
                else:
                    targetgooderror = "I am not sure who that is."
                return {
                    "targetgood": False,
                    "error": targetgooderror,
                    "reason": "unknown"
                }

        nick_id = self.whois_ident(target, usercreate=False)

        # User offline
        if "offline" not in targetbypass:
            if not self.target_online(target, nick_id):
                return {
                    "targetgood": False,
                    "error": "It looks like " + self.nick_actual(target) +
                    " is offline right now!",
                    "reason": "offline"
                }

        # Private Message
        if "privmsg" not in targetbypass:
            if trigger.is_privmsg and not inlist(target, trigger.nick):
                return {
                    "targetgood": False,
                    "error": "Leave " + self.nick_actual(target) +
                    " out of this private conversation!",
                    "reason": "privmsg"
                }

        # not in the same channel
        if "diffchannel" not in targetbypass:
            if not trigger.is_privmsg and self.target_online(target, nick_id):
                if str(trigger.sender).lower(
                ) not in self.dict["current"][nick_id]["channels"]:
                    return {
                        "targetgood": False,
                        "error": "It looks like " + self.nick_actual(target) +
                        " is online right now, but in a different channel.",
                        "reason": "diffchannel"
                    }

        # not a registered nick
        # TODO
        # if "unregged" not in targetbypass:
        #    if bot.config.SpiceBot_regnick.regnick:
        #        if str(target).lower() not in [x.lower() for x in self.dict["registered"]]:
        #            return {"targetgood": False, "error": "It looks like " + self.nick_actual(target) + " is not a registered nick.", "reason": "unregged"}
        # TODO identified

        return targetgood
예제 #29
0
def nickname_comand_channels(bot, trigger, botcom):

    if not len(botcom.dict['args']):
        commandused = 'list'
    else:
        commandused = spicemanip(botcom.dict['args'], 1).lower()

    botcom.dict['args'] = spicemanip(botcom.dict['args'], '2+', 'list')

    if commandused == 'list':
        botcount = SpiceBot.channels.total_bot_channels()
        servercount = SpiceBot.channels.total_channels()
        displayval = "I am in " + str(botcount) + " of " + str(
            servercount) + " channel(s) available on this server."
        chanlist = spicemanip(SpiceBot.channels.chanlist_bot(), 'andlist')
        bot.osd([displayval, "You can find me in " + chanlist])
        return

    elif commandused == 'total':
        botcount = SpiceBot.channels.total_bot_channels()
        servercount = SpiceBot.channels.total_channels()
        bot.osd("I am in " + str(botcount) + " of " + str(servercount) +
                " channel(s) available on this server.")
        return

    elif commandused == 'random':
        channel = spicemanip(list(SpiceBot.channels.chandict), 'random')
        topic = SpiceBot.channels.chandict[channel]['topic']
        msg = [
            "Random channel for you: {}.".format(
                SpiceBot.channels.chandict[channel]['name'])
        ]
        if topic and not topic.isspace():
            msg.append("The topic is: {}".format(topic))
        else:
            msg.append("Its topic is empty.")
        bot.osd(msg)
        return

    elif commandused == 'update':
        if not trigger.admin:  # TODO
            SpiceBot.messagelog.messagelog_error(
                botcom.dict["log_id"],
                "You do not have permission to update the channel listing.")
            return
        SpiceBot.channels.bot_part_empty(bot)
        SpiceBot.channels.channel_list_request(bot)
        bot.osd([
            "[SpiceBot_Channels]",
            "I am now updating the channel listing for this server."
        ])
        while SpiceBot.channels.channel_lock:
            pass
        SpiceBot.channels.join_all_channels(bot)
        foundchannelcount = len(list(SpiceBot.channels.chandict.keys()))
        bot.osd("[SpiceBot_Channels]", "Channel listing finished!",
                str(foundchannelcount) + " channel(s) found.")
        SpiceBot.channels.bot_part_empty(bot)
        return

    elif commandused == 'topic':
        if not len(botcom.dict['args']):
            SpiceBot.messagelog.messagelog_error(
                botcom.dict["log_id"], "Channel name input missing.")
            return
        channel = spicemanip(botcom.dict['args'], 1)
        if not SpiceBot.inlist(channel.lower(),
                               list(SpiceBot.channels.chandict.keys())):
            SpiceBot.messagelog.messagelog_error(
                botcom.dict["log_id"],
                "Channel name {} not valid.".format(channel))
            return
        channel = str(channel).lower()
        topic = SpiceBot.channels.chandict[channel]['topic']
        channelname = SpiceBot.channels.chandict[channel]['name']
        bot.osd("Topic for {}: {}".format(channelname, topic))
        return

    if commandused.upper() in ['OP', 'HOP', 'VOICE', 'OWNER', 'ADMIN']:
        if not len(botcom.dict['args']):
            if trigger.is_privmsg:
                SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"],
                                                     "Channel name required.")
                return
            else:
                channel = trigger.sender
        else:
            channel = spicemanip(botcom.dict['args'], 1)
            if not SpiceBot.inlist(channel.lower(),
                                   list(SpiceBot.channels.chandict.keys())):
                SpiceBot.messagelog.messagelog_error(
                    botcom.dict["log_id"],
                    "Channel name {} not valid.".format(channel))
                return
            if not SpiceBot.inlist(channel.lower(), list(bot.channels.keys())):
                SpiceBot.messagelog.messagelog_error(
                    botcom.dict["log_id"],
                    "I need to be in {} to see nick privileges.".format(
                        channel))
                return

        privlist = SpiceBot.channel_privs(bot, channel, commandused.upper())
        dispmsg = []
        if not len(privlist):
            dispmsg.append("There are no Channel " + commandused.upper() +
                           "s for " + str(channel))
        else:
            oplist = spicemanip(privlist, 'andlist')
            dispmsg.append("Channel " + commandused.upper() + "s for " +
                           str(channel) + "  are: " + oplist)
        bot.osd(dispmsg, trigger.nick, 'notice')
        return

    # Users List
    if commandused == 'users':
        channel = spicemanip(botcom.dict['args'], 1)
        if not SpiceBot.inlist(channel.lower(),
                               list(SpiceBot.channels.chandict.keys())):
            SpiceBot.messagelog.messagelog_error(
                botcom.dict["log_id"],
                "Channel name {} not valid.".format(channel))
            return
        if not SpiceBot.inlist(channel.lower(), list(bot.channels.keys())):
            SpiceBot.messagelog.messagelog_error(
                botcom.dict["log_id"],
                "I need to be in {} to see user list.".format(channel))
            return
        dispmsg = []
        if not len(list(bot.channels[channel].privileges.keys())):
            dispmsg.append("There are no Channel users for " + str(channel))
        else:
            userslist = spicemanip(
                list(bot.channels[channel].privileges.keys()), 'andlist')
            dispmsg.append("Channel users for " + str(channel) + " are: " +
                           userslist)
        bot.osd(dispmsg, trigger.nick, 'notice')
        return
예제 #30
0
파일: Gif.py 프로젝트: sk99sk/SpiceBot
    def get_gif(self, searchdict):

        # list of defaults
        query_defaults = {
            "query": None,
            "searchnum": 'random',
            "gifsearch": list(self.valid_api.keys()),
            "gifsearchremove": ['gifme'],  # TODO make a config setting
            "searchlimit": 'default',
            "nsfw": False,
        }

        # set defaults if they don't exist
        for key in query_defaults:
            if key not in list(searchdict.keys()):
                searchdict[key] = query_defaults[key]
                if key == "gifsearch":
                    for remx in query_defaults["gifsearchremove"]:
                        searchdict["gifsearch"].remove(remx)

        if botconfig.SpiceBot_Gif.nsfw:
            query_defaults["nsfw"] = True

        # verify query is there to search
        if not searchdict["query"]:
            return {"error": 'No Query to Search'}

        # Replace spaces in search query
        searchdict["searchquery"] = urllib.request.pathname2url(
            searchdict["query"])

        # set api usage
        if not isinstance(searchdict['gifsearch'], list):
            if str(searchdict['gifsearch']) in list(self.valid_api.keys()):
                searchdict['gifsearch'] = [searchdict['gifsearch']]
            else:
                searchdict['gifsearch'] = list(self.valid_api.keys())
        for apis in searchdict['gifsearch']:
            if apis not in list(self.valid_api.keys()):
                searchdict['gifsearch'].remove(apis)

        # Verify search limit
        if searchdict['searchlimit'] == 'default' or not isinstance(
                searchdict['searchlimit'], int):
            searchdict['searchlimit'] = 50

        # Random handling for searchnum
        if searchdict["searchnum"] == 'random':
            searchdict["searchnum"] = random.randint(0,
                                                     searchdict['searchlimit'])

        # verify valid search parameters
        if not str(searchdict["searchnum"]).isdigit():
            return {"error": 'No Search Number or Random Specified'}

        # perform search
        gifapiresults = []
        for currentapi in searchdict['gifsearch']:

            # check if query is already cached
            searchfor = True
            if searchdict["searchquery"].lower() in list(
                    self.valid_api[currentapi]["cache"].keys()):
                if len(self.valid_api[currentapi]["cache"][str(
                        searchdict["searchquery"]).lower()]):
                    searchfor = False
                    verifygoodlinks = []
                    for gifresult in self.valid_api[currentapi]["cache"][str(
                            searchdict["searchquery"])]:
                        if gifresult["returnurl"] not in self.badlinks:
                            verifygoodlinks.append(gifresult)
                    self.valid_api[currentapi]["cache"][str(
                        searchdict["searchquery"])] = verifygoodlinks

            if searchfor:
                self.valid_api[currentapi]["cache"][str(
                    searchdict["searchquery"]).lower()] = []
                # assemble url
                url = self.gif_url_assemble(currentapi,
                                            str(searchdict["searchquery"]),
                                            str(searchdict["searchlimit"]),
                                            searchdict['nsfw'])
                # fetch results
                self.fetch_gif_results(currentapi,
                                       str(searchdict["searchquery"]), url)

            if len(self.valid_api[currentapi]["cache"][
                    searchdict["searchquery"].lower()]):
                gifapiresults.extend(self.valid_api[currentapi]["cache"][
                    searchdict["searchquery"].lower()])

        if not len(gifapiresults):
            return {
                "error":
                "No Results were found for '" + searchdict["query"] +
                "' in the " +
                str(spicemanip(searchdict['gifsearch'], 'orlist')) + " api(s)"
            }

        random.shuffle(gifapiresults)
        random.shuffle(gifapiresults)
        randombad = True
        while randombad:
            gifdict = spicemanip(gifapiresults, "random")

            try:
                gifpage = requests.get(gifdict["returnurl"], headers=None)
            except Exception as e:
                gifpage = str(e)
                gifpage = None

            if gifpage and not str(gifpage.status_code).startswith(
                    tuple(["4", "5"])):
                randombad = False
            else:
                self.badlinks.append(str(gifdict["returnurl"]))
                newlist = []
                for tempdict in gifapiresults:
                    if tempdict["returnurl"] != gifdict["returnurl"]:
                        newlist.append(tempdict)
                gifapiresults = newlist

        if not len(gifapiresults):
            return {
                "error":
                "No Results were found for '" + searchdict["query"] +
                "' in the " +
                str(spicemanip(searchdict['gifsearch'], 'orlist')) + " api(s)"
            }

        # return dict
        gifdict['error'] = None
        return gifdict