def nickname_comand_chanstats(bot, trigger): triggerargs = sopel_triggerargs(bot, trigger, 'nickname_command') if not len(triggerargs): commandused = 'nodeps' else: commandused = spicemanip.main(triggerargs, 1).lower() if commandused not in ['deps', 'nodeps']: bot.say("Please specify deps or nodeps") return triggerargs = spicemanip.main(triggerargs, '2+', 'list') if not trigger.admin: bot.say("You are not authorized to perform this function.") stderr("Recieved Command to update.") bot.osd( "Received command from " + trigger.nick + " to update from Github and restart. Be Back Soon!", bot.channels.keys()) if commandused == 'nodeps': spicebot_update(bot, "False") if commandused == 'deps': spicebot_update(bot, "True") service_manip(bot, bot.nick, 'restart')
def sayingsmodule(bot, databasekey, inputarray, thingtodo): """Handle the creation and manipulation of modules that return sayings.""" # Usage: message = sayingsmodule(bot, 'techsupport', triggerargsarray, 'random') # Usage: message = sayingsmodule(bot, 'techsupport', triggerargsarray, 'add') response = "Something went wrong. Oops." inputstring = spicemanip.main(inputarray, '2+') existingarray = get_database_value(bot, bot.nick, databasekey) or [] if thingtodo == "initialise": database_initialize(bot, bot.nick, inputarray, databasekey) elif thingtodo == "add": if inputstring not in existingarray: adjust_database_array(bot, bot.nick, inputstring, databasekey, 'add') response = "Added to database." else: response = "That is already in the database." elif thingtodo == "remove" or thingtodo == 'del': if inputstring not in existingarray: response = "That was not found in the database." else: adjust_database_array(bot, bot.nick, inputstring, databasekey, 'del') response = "Removed from database." elif thingtodo == "count": messagecount = len(existingarray) response = "I'm seeing " + str(messagecount) + " responses in the database." elif thingtodo == "last": response = spicemanip.main(existingarray, "last") or "I appear to have nothing for that." else: response = spicemanip.main(existingarray, "random") or '' if response == '': response = "I'm afraid I couldn't find an entry for that." return response
def sopel_triggerargs(bot, trigger, command_type): triggerargs = [] if len(trigger.args) > 1: triggerargs = spicemanip.main(trigger.args[1], 'create') triggerargs = spicemanip.main(triggerargs, 'create') if command_type in ['module_command']: triggerargs = spicemanip.main(triggerargs, '2+', 'list') elif command_type in ['nickname_command']: triggerargs = spicemanip.main(triggerargs, '3+', 'list') return triggerargs
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.main(trigger_args_part, 'create') prerun_split.append(argsdict_part) return prerun_split
def trigger_channel_list_initial(bot, trigger): # Unkickable bot.write(('SAMODE', bot.nick, '+q')) bot.write(['LIST']) bot.memory['SpiceBot_Channels']['ProcessLock'] = True stderr("[SpiceBot_Channels] Initial Channel list populating...") starttime = time.time() while not bot.memory['SpiceBot_Channels']['InitialProcess']: timesince = time.time() - starttime if timesince < 60: pass else: stderr( "[SpiceBot_Channels] Initial Channel list populating Timed Out." ) bot.memory['SpiceBot_Channels']['InitialProcess'] = True channel_list_current(bot) foundchannelcount = len(bot.memory['SpiceBot_Channels']['channels'].keys()) stderr("[SpiceBot_Channels] Channel listing finished! " + str(foundchannelcount) + " channel(s) found.") join_all_channels(bot) chanadmin_all_channels(bot) if "*" in bot.memory['SpiceBot_Channels']['channels']: del bot.memory['SpiceBot_Channels']['channels']["*"] while True: time.sleep(1800) oldlist = list(bot.memory['SpiceBot_Channels']['channels'].keys()) bot.write(['LIST']) bot.memory['SpiceBot_Channels']['ProcessLock'] = True while bot.memory['SpiceBot_Channels']['ProcessLock']: pass newlist = [ item.lower() for item in oldlist if item.lower() not in bot.memory['SpiceBot_Channels']['channels'] ] if "*" in newlist: newlist.remove("*") if len(newlist) and bot.config.SpiceBot_Channels.announcenew: bot.osd([ "The Following channel(s) are new:", spicemanip.main(newlist, 'andlist') ], bot.channels.keys()) join_all_channels(bot) chanadmin_all_channels(bot) if "*" in bot.memory['SpiceBot_Channels']['channels']: del bot.memory['SpiceBot_Channels']['channels']["*"]
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.main(lineparts, 0) if not line.isspace(): debuglines.append(str(line)) return debuglines
def moarlat(bot, trigger): coms = '' triggerargsarray = spicemanip.main(trigger, 'create') maincom = spicemanip.main(triggerargsarray, 1).lower()[1:] triggerargsarray = spicemanip.main(triggerargsarray, '2+', "list") coms = spicemanip.main(triggerargsarray, 1) nick = trigger.nick if not coms: bl = 0 bl = getbalancelat(bot, nick) bot.say(nick + " has " + str(bl) + " bars of latinum") elif coms == 'balance': bl = 0 bl = getbalancelat(bot, nick) bot.say(nick + " has " + str(bl) + " bars of latinum") elif coms == 'setlats': if bot.channels[trigger.sender].privileges[nick] < sopel.module.HALFOP: return bot.reply("Unauthorized access detected!") target = spicemanip.main(triggerargsarray, 3) or 0 amount = spicemanip.main(triggerargsarray, 2) if not landrushared.is_digit(amount): amount = 1 if not target == 0: nick = target latinum.setlats(bot, nick, amount) key = " now has: " #amount = abs(amount) bot.say(nick + key + str(amount) + " latinum bars") else: bot.say("Try checking again later")
def testbot(bot, trigger): triggerargsarray = spicemanip.main(trigger, 'create') triggerargsarray = spicemanip.main(triggerargsarray, '2+', "list") one = spicemanip.main(triggerargsarray, 1) two = spicemanip.main(triggerargsarray, 2) three = spicemanip.main(triggerargsarray, 3) four = spicemanip.main(triggerargsarray, 4) #bot.say(str(one) + ' ' + str(two) + " " + str(three) + " " + str(four)) bot.say("Testing") if one == 'one': bot.say("Number One") if two == 'two': bot.say("Two for One") elif two == 'three': bot.say("Three for one") elif one == 'two': bot.say('Number Two') elif one == 'three': bot.say('Number Three') elif one == 'four': bot.say('Number Four') else: bot.say(str(one) + ' ' + str(two) + " " + str(three) + " " + str(four))
def make_trigger_args(triggerargs_one, trigger_command_type='module'): trigger_args = spicemanip.main(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.main(trigger_args, 2).lower() trigger_args = spicemanip.main(trigger_args, '3+', 'list') elif trigger_command_type in ['action']: trigger_prefix = None trigger_command = spicemanip.main(trigger_args, 1).lower() trigger_args = spicemanip.main(trigger_args, '2+', 'list') else: trigger_prefix = spicemanip.main(trigger_args, 1).lower()[0] trigger_command = spicemanip.main(trigger_args, 1).lower()[1:] trigger_args = spicemanip.main(trigger_args, '2+', 'list') return trigger_args, trigger_command, trigger_prefix
def gif_trigger(bot, trigger): triggerargs = sopel_triggerargs(bot, trigger) if triggerargs == []: return bot.osd("Please present a query to search.") query = spicemanip.main(trigger.args[1], 0) searchapis = bot.memory["Sopel-GifSearch"]['valid_gif_api_dict'].keys() searchdict = {"query": query, "gifsearch": searchapis} gifdict = getGif(bot, searchdict) if gifdict["error"]: bot.osd(gifdict["error"]) else: bot.osd( str(gifdict['gifapi'].title() + " Result (" + str(query) + " #" + str(gifdict["returnnum"]) + "): " + str(gifdict["returnurl"])))
def sopel_triggerargs(bot, trigger, command_type='module_command'): triggerargs = [] if len(trigger.args) > 1: triggerargs = spicemanip.main(trigger.args[1], 'create') triggerargs = spicemanip.main(triggerargs, 'create') if command_type in ['module_command']: triggerargs = spicemanip.main(triggerargs, '2+', 'list') elif command_type in ['nickname_command']: triggerargs = spicemanip.main(triggerargs, '3+', 'list') elif command_type in ['prefix_command']: prefixcommand = spicemanip.main(triggerargs, 1).lower()[1:] triggerargs = spicemanip.main(triggerargs, '2+', 'list') return triggerargs, prefixcommand return triggerargs
def commandsquery_register(bot, command_type, validcoms, aliasfor=None): if not isinstance(validcoms, list): validcoms = [validcoms] if 'Sopel-CommandsQuery' not in bot.memory: bot.memory['Sopel-CommandsQuery'] = dict() if command_type not in bot.memory['Sopel-CommandsQuery'].keys(): bot.memory['Sopel-CommandsQuery'][command_type] = dict() bot.memory['Sopel-CommandsQuery'][command_type + "_count"] = 0 bot.memory['Sopel-CommandsQuery'][command_type + "_count"] += 1 dict_from_file = dict() # default command to filename if "validcoms" not in dict_from_file.keys(): dict_from_file["validcoms"] = validcoms if not aliasfor: maincom = dict_from_file["validcoms"][0] if len(dict_from_file["validcoms"]) > 1: comaliases = spicemanip.main(dict_from_file["validcoms"], '2+', 'list') else: comaliases = [] bot.memory['Sopel-CommandsQuery'][command_type][ maincom] = dict_from_file else: comaliases = validcoms for comalias in comaliases: if comalias not in bot.memory['Sopel-CommandsQuery'][ command_type].keys(): bot.memory['Sopel-CommandsQuery'][command_type][comalias] = { "aliasfor": aliasfor }
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(self.dict["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.main(loadedmodules, 'andlist') debuglines.insert(1, loadedmodules) return debuglines
def spicebot_prerun(bot, trigger, commandused): # Dyno Classes botcom = class_create('bot') # Enable Status default is 1 = don't run botcom.enablestatus = 1 # Custom args try: botcom.triggerargsarray = spicemanip.main(trigger.group(2), 'create') except IndexError: botcom.triggerargsarray = spicemanip.main(trigger.group(1), 'create') botcom.instigator = trigger.nick # time botcom.now = time.time() # User botcom = bot_command_users(bot, botcom) # Channels botcom = bot_command_channels(bot, botcom, trigger) # User was Blocked by a bot.admin or an OP blockedusersarray = get_database_value(bot, botcom.channel_current, 'users_blocked') or [] if botcom.instigator in blockedusersarray: osd(bot, botcom.instigator, 'notice', "It looks like you have been blocked from using commands in " + botcom.channel_current+".") return botcom.enablestatus, botcom.triggerargsarray, botcom, botcom.instigator # devmode bypass devenabledchannels = get_database_value(bot, bot.nick, 'channels_dev') or [] if botcom.channel_current in devenabledchannels: botcom.enablestatus = 0 return botcom.enablestatus, botcom.triggerargsarray, botcom, botcom.instigator # Channel activated status if botcom.channel_current.startswith("#"): channelmodulesarray = get_database_value(bot, botcom.channel_current, 'modules_enabled') or [] if commandused not in channelmodulesarray: if botcom.instigator in botcom.opadmin: adjust_database_array(bot, botcom.channel_current, commandused, 'modules_enabled', 'add') else: osd(bot, botcom.instigator, 'notice', "it looks like the " + str(commandused) + " command has not been enabled in " + botcom.channel_current+".") return botcom.enablestatus, botcom.triggerargsarray, botcom, botcom.instigator # Bot Enabled Status (botcom.now in an array) botusersarray = get_database_value(bot, bot.nick, 'botusers') or [] # bot_opted_users = get_database_value(bot, bot.nick, 'users_opted') or [] # if botcom.instigator not in bot_opted_users: # osd(bot, botcom.instigator, 'notice', "you have to run `" + bot.nick + " on` to allow her to listen to you. For help, see the wiki at https://github.com/SpiceBot/sopel-modulesold/wiki/Using-the-Bot.") # return botcom.enablestatus, botcom.triggerargsarray, botcom, botcom.instigator botcom.enablestatus = 0 increment_counter(bot, trigger, commandused) # Send Status Forward return botcom.enablestatus, botcom.triggerargsarray, botcom, botcom.instigator
def internal_prerun(bot, trigger, *args, **kwargs): bot.say(str(id(trigger))) bot.say(str(trigger.raw)) spicebot.comms.write(("PRIVMSG", "deathbybandaid"), "test") log_id = messagelog.messagelog_assign(trigger) messagelog.messagelog_start(bot, trigger, log_id) messagelog.messagelog_debug(log_id, "currun Prerun Process Started", lineno(), 1) messagelog.messagelog_debug(log_id, "Message Log System Started", lineno(), 2) # Create dynamic class currun = class_create('currun') currun.default = 'currun' messagelog.messagelog_debug(log_id, "currun class() Created", lineno(), 3) currun.instigator = str(trigger.nick) currun.start = time.time() messagelog.messagelog_debug(log_id, "currun Start Time Set", lineno(), 4) # bot valid prefix currun.prefix_list = str(bot.config.core.prefix).replace( "\\", '').split("|") if t_command_type == "nickname": check_nick = spicemanip.main(trigger.args[1], 1).lower() if check_nick != str(bot.nick).lower(): messagelog.messagelog_debug( log_id, "Command is a nickname_command but does not start with bot.nick", lineno(), 3) messagelog.messagelog_exit(bot, currun.messagesid) return messagelog.messagelog_debug(log_id, "Command is a nickname_command", lineno(), 3) elif t_command_type == "module": if not str(trigger.args[1]).startswith( tuple(currun.prefix_list)): messagelog.messagelog_debug( log_id, "Command is a module_command but doesn't have a prefix", lineno(), 3) messagelog.messagelog_exit(bot, currun.messagesid) return messagelog.messagelog_debug(log_id, "Command is a module_command", lineno(), 3) trigger_command_type = str(t_command_type) # Primary command used for trigger, and a list of all words trigger_args, trigger_command, trigger_prefix = make_trigger_args( trigger.args[1], trigger_command_type) messagelog.messagelog_debug(log_id, "triggerargs created", lineno(), 4) # Argsdict Defaults argsdict_default = {} argsdict_default["type"] = trigger_command_type argsdict_default["com"] = trigger_command argsdict_default["trigger_prefix"] = trigger_prefix # messagelog ID argsdict_default["log_id"] = log_id currun.messagesid = log_id if argsdict_default["type"] == 'nickname': argsdict_default[ "comtext"] = "'" + bot.nick + " " + argsdict_default[ "com"] + "'" else: argsdict_default[ "comtext"] = "'" + argsdict_default["com"] + "'" # split into && groupings and_split = trigger_and_split(trigger_args) messagelog.messagelog_debug(log_id, "triggerargs split by &&", lineno(), 4) # Create dict listings for currun.dict argsdict_list = trigger_argsdict_list(argsdict_default, and_split) messagelog.messagelog_debug( log_id, "argsdict assembled per triggerargs split", lineno(), 4) # Run the function for all splits runcount = 0 try: for argsdict in argsdict_list: runcount += 1 messagelog.messagelog_debug( log_id, "Processing Split " + str(runcount) + "/" + str(len(argsdict_list)), lineno(), 2) currun.dict = copy.deepcopy(argsdict) currun.adminswitch = False currun.dict["runcount"] = runcount currun.dict["args"], currun.dict[ "hyphen_args"], currun.dict[ "debuglevel"] = trigger_hyphen_args(currun) args_pass, currun = trigger_hyphen_arg_handler( bot, trigger, currun) currun.dict["completestring"] = spicemanip.main( currun.dict['args'], 0) if args_pass: currun.dict["comdict"] = trigger_subcom_info( currun.dict["args"]) if trigger_runstatus(bot, trigger, currun): function(bot, trigger, spicebot, currun, *args, **kwargs) except Exception as e: messagelog.messagelog(bot, currun.messagesid, str(e)) finally: messagelog.messagelog_exit(bot, currun.messagesid)
def trigger_and_split(trigger_args): trigger_args_list_split = spicemanip.main(trigger_args, "split_&&") if not len(trigger_args_list_split): trigger_args_list_split.append([]) return trigger_args_list_split
def setup_thread(bot): bot.memory['Sopel-CommandsQuery'] = dict() for comtype in ['module', 'nickname', 'rule']: bot.memory['Sopel-CommandsQuery'][comtype + "_commands"] = dict() bot.memory['Sopel-CommandsQuery'][comtype + "_commands_count"] = 0 filepathlisting = [] # main Modules directory main_dir = os.path.dirname(os.path.abspath(sopel.__file__)) modules_dir = os.path.join(main_dir, 'modules') filepathlisting.append(modules_dir) # Home Directory home_modules_dir = os.path.join(bot.config.homedir, 'modules') if os.path.isdir(home_modules_dir): filepathlisting.append(home_modules_dir) # pypi installed try: import sopel_modules pypi_modules = os.path.dirname(os.path.abspath(sopel_modules.__file__)) pypi_modules_dir = os.path.join(pypi_modules, 'modules') filepathlisting.append(pypi_modules_dir) except Exception: pass # Extra directories filepathlist = [] for directory in bot.config.core.extra: filepathlisting.append(directory) for directory in filepathlisting: for pathname in os.listdir(directory): path = os.path.join(directory, pathname) if (os.path.isfile(path) and path.endswith('.py') and not path.startswith('_')): filepathlist.append(str(path)) # CoreTasks ct_path = os.path.join(main_dir, 'coretasks.py') filepathlist.append(ct_path) for modulefile in filepathlist: module_file_lines = [] module_file = open(modulefile, 'r') lines = module_file.readlines() for line in lines: module_file_lines.append(line) module_file.close() dict_from_file = dict() filelinelist = [] for line in module_file_lines: if str(line).startswith("@"): line = str(line)[1:] # Commands if str(line).startswith( tuple([ "commands", "module.commands", "sopel.module.commands" ])): comtype = "module" line = str(line).split("commands(")[-1] line = str("(" + line) validcoms = eval(str(line)) if isinstance(validcoms, tuple): validcoms = list(validcoms) else: validcoms = [validcoms] validcomdict = {"comtype": comtype, "validcoms": validcoms} filelinelist.append(validcomdict) elif str(line).startswith( tuple([ "nickname_commands", "module.nickname_commands", "sopel.module.nickname_commands" ])): comtype = "nickname" line = str(line).split("commands(")[-1] line = str("(" + line) validcoms = eval(str(line)) if isinstance(validcoms, tuple): validcoms = list(validcoms) else: validcoms = [validcoms] nickified = [] for nickcom in validcoms: nickified.append(str(bot.nick) + " " + nickcom) validcomdict = {"comtype": comtype, "validcoms": nickified} filelinelist.append(validcomdict) elif str(line).startswith( tuple(["rule", "module.rule", "sopel.module.rule"])): comtype = "rule" line = str(line).split("rule(")[-1] validcoms = [str("(" + line)] validcomdict = {"comtype": comtype, "validcoms": validcoms} filelinelist.append(validcomdict) for atlinefound in filelinelist: comtype = atlinefound["comtype"] validcoms = atlinefound["validcoms"] comtypedict = str(comtype + "_commands") bot.memory['Sopel-CommandsQuery'][comtypedict + "_count"] += 1 # default command to filename if "validcoms" not in dict_from_file.keys(): dict_from_file["validcoms"] = validcoms maincom = dict_from_file["validcoms"][0] if len(dict_from_file["validcoms"]) > 1: comaliases = spicemanip.main(dict_from_file["validcoms"], '2+', 'list') else: comaliases = [] bot.memory['Sopel-CommandsQuery'][comtypedict][ maincom] = dict_from_file for comalias in comaliases: if comalias not in bot.memory['Sopel-CommandsQuery'][ comtypedict].keys(): bot.memory['Sopel-CommandsQuery'][comtypedict][ comalias] = { "aliasfor": maincom } for comtype in ['module_commands', 'nickname_commands', 'rule_commands']: stderr("[Sopel-CommandsQuery] Found " + str(len(bot.memory['Sopel-CommandsQuery'][comtype].keys())) + " " + comtype + " commands.") if botevents_installed: set_bot_event(bot, "Sopel-CommandsQuery")
def query_detection(bot, trigger): while "Sopel-CommandsQuery" not in bot.memory: pass # command must start with if not str(trigger).startswith(tuple(['?'])): return stderr(trigger.args) commands_list = dict() for commandstype in bot.memory['Sopel-CommandsQuery'].keys(): if not commandstype.endswith("_count"): for com in bot.memory['Sopel-CommandsQuery'][commandstype].keys(): if com not in commands_list.keys(): commands_list[com] = bot.memory['Sopel-CommandsQuery'][ commandstype][com] triggerargsarray = spicemanip.main(trigger, 'create') # command issued, check if valid querycommand = spicemanip.main(triggerargsarray, 1).lower()[1:] if len(querycommand) == 1: commandlist = [] for command in commands_list.keys(): if command.lower().startswith(querycommand): commandlist.append(command) if commandlist == []: bot.notice("No commands match " + str(querycommand) + ".", trigger.nick) return else: bot.notice( "The following commands match " + str(querycommand) + ": " + spicemanip.main(commandlist, 'andlist') + ".", trigger.nick) return elif querycommand.endswith(tuple(["+"])): querycommand = querycommand[:-1] if querycommand not in commands_list.keys(): bot.notice("The " + str(querycommand) + " does not appear to be valid.") return realcom = querycommand if "aliasfor" in commands_list[querycommand].keys(): realcom = commands_list[querycommand]["aliasfor"] validcomlist = commands_list[realcom]["validcoms"] bot.notice( "The following commands match " + str(querycommand) + ": " + spicemanip.main(validcomlist, 'andlist') + ".", trigger.nick) return elif querycommand.endswith(tuple(['?'])): querycommand = querycommand[:-1] sim_com, sim_num = [], [] for com in commands_list.keys(): similarlevel = SequenceMatcher(None, querycommand.lower(), com.lower()).ratio() sim_com.append(com) sim_num.append(similarlevel) sim_num, sim_com = (list(x) for x in zip( *sorted(zip(sim_num, sim_com), key=itemgetter(0)))) closestmatch = spicemanip.main(sim_com, 'reverse', "list") listnumb, relist = 1, [] for item in closestmatch: if listnumb <= 10: relist.append(str(item)) listnumb += 1 bot.notice( "The following commands may match " + str(querycommand) + ": " + spicemanip.main(relist, 'andlist') + ".", trigger.nick) return elif querycommand in commands_list.keys(): bot.notice( "The following commands match " + str(querycommand) + ": " + str(querycommand) + ".", trigger.nick) return elif not querycommand: return else: commandlist = [] for command in commands_list.keys(): if command.lower().startswith(querycommand): commandlist.append(command) if commandlist == []: bot.notice("No commands match " + str(querycommand) + ".", trigger.nick) return else: bot.notice( "The following commands match " + str(querycommand) + ": " + spicemanip.main(commandlist, 'andlist') + ".", trigger.nick) return
def get_trigger_arg(bot, inputs, outputtask, output_type='default'): return spicemanip.main(inputs, outputtask, output_type)
def getGif(bot, searchdict): # list of defaults query_defaults = { "query": None, "searchnum": 'random', "gifsearch": bot.memory["Sopel-GifSearch"]['valid_gif_api_dict'].keys(), "gifsearchremove": ['gifme'], "searchlimit": 'default', "nsfw": False, } if bot.config.SopelGifSearch.nsfw: query_defaults["nsfw"] = True # set defaults if they don't exist for key in query_defaults: if key not in searchdict.keys(): searchdict[key] = query_defaults[key] if key == "gifsearch": for remx in query_defaults["gifsearchremove"]: searchdict["gifsearch"].remove(remx) # Replace spaces in search query if not searchdict["query"]: return {"error": 'No Query to Search'} # searchdict["searchquery"] = searchdict["query"].replace(' ', '%20') searchdict["searchquery"] = urllib.request.pathname2url( searchdict["query"]) # set api usage if not isinstance(searchdict['gifsearch'], list): if str(searchdict['gifsearch'] ) in bot.memory["Sopel-GifSearch"]['valid_gif_api_dict'].keys(): searchdict['gifsearch'] = [searchdict['gifsearch']] else: searchdict['gifsearch'] = bot.memory["Sopel-GifSearch"][ 'valid_gif_api_dict'].keys() else: for apis in searchdict['gifsearch']: if apis not in bot.memory["Sopel-GifSearch"][ 'valid_gif_api_dict'].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']) # Make sure there is a valid input of query and search number if not searchdict["query"]: return {"error": 'No Query to Search'} if not str(searchdict["searchnum"]).isdigit(): return {"error": 'No Search Number or Random Specified'} gifapiresults = [] for currentapi in searchdict['gifsearch']: # url base url = str(bot.memory["Sopel-GifSearch"]['valid_gif_api_dict'] [currentapi]['url']) # query url += str(bot.memory["Sopel-GifSearch"]['valid_gif_api_dict'] [currentapi]['query']) + str(searchdict["searchquery"]) # limit url += str(bot.memory["Sopel-GifSearch"]['valid_gif_api_dict'] [currentapi]['limit']) + str(searchdict["searchlimit"]) # nsfw search? if searchdict['nsfw']: url += str(bot.memory["Sopel-GifSearch"]['valid_gif_api_dict'] [currentapi]['nsfw']) else: url += str(bot.memory["Sopel-GifSearch"]['valid_gif_api_dict'] [currentapi]['sfw']) # api key url += str(bot.memory["Sopel-GifSearch"]['valid_gif_api_dict'] [currentapi]['key']) + str( bot.memory["Sopel-GifSearch"]['valid_gif_api_dict'] [currentapi]['apikey']) if currentapi not in bot.memory["Sopel-GifSearch"]['cache'].keys(): bot.memory["Sopel-GifSearch"]['cache'][currentapi] = dict() if str( searchdict["searchquery"] ) not in bot.memory["Sopel-GifSearch"]['cache'][currentapi].keys(): bot.memory["Sopel-GifSearch"]['cache'][currentapi][str( searchdict["searchquery"])] = [] if bot.memory["Sopel-GifSearch"]['cache'][currentapi][str( searchdict["searchquery"])] == []: try: page = requests.get(url, headers=header) except Exception as e: page = None if page and not str(page.status_code).startswith(tuple(["4", "5" ])): data = json.loads( urllib.request.urlopen(url).read().decode('utf-8')) results = data[bot.memory["Sopel-GifSearch"] ['valid_gif_api_dict'][currentapi]['results']] resultsarray = [] for result in results: appendresult = False cururl = result[bot.memory["Sopel-GifSearch"][ 'valid_gif_api_dict'][currentapi]['cururl']] slashsplit = str(cururl).split("/") fileextension = slashsplit[-1] if not fileextension or fileextension == '': appendresult = True elif str(fileextension).endswith(".gif"): appendresult = True elif "." not in str(fileextension): appendresult = True if appendresult: resultsarray.append(cururl) # make sure there are results if resultsarray != []: # Create Temp dict for every result tempresultnum = 0 for tempresult in resultsarray: if tempresult not in bot.memory["Sopel-GifSearch"][ "badgiflinks"]: tempresultnum += 1 tempdict = dict() tempdict["returnnum"] = tempresultnum tempdict["returnurl"] = tempresult tempdict["gifapi"] = currentapi bot.memory["Sopel-GifSearch"]['cache'][currentapi][ str(searchdict["searchquery"])].append( tempdict) else: verifygoodlinks = [] for gifresult in bot.memory["Sopel-GifSearch"]['cache'][ currentapi][str(searchdict["searchquery"])]: if gifresult["returnurl"] not in bot.memory["Sopel-GifSearch"][ "badgiflinks"]: verifygoodlinks.append(gifresult) bot.memory["Sopel-GifSearch"]['cache'][currentapi][str( searchdict["searchquery"])] = verifygoodlinks if bot.memory["Sopel-GifSearch"]['cache'][currentapi][str( searchdict["searchquery"])] != []: gifapiresults.extend( bot.memory["Sopel-GifSearch"]['cache'][currentapi][str( searchdict["searchquery"])]) if gifapiresults == []: return { "error": "No Results were found for '" + searchdict["query"] + "' in the " + str(spicemanip.main(searchdict['gifsearch'], 'orlist')) + " api(s)" } random.shuffle(gifapiresults) random.shuffle(gifapiresults) randombad = True while randombad: gifdict = spicemanip.main(gifapiresults, "random") try: gifpage = requests.get(gifdict["returnurl"], headers=None) except Exception as e: gifpage = None if gifpage and not str(gifpage.status_code).startswith( tuple(["4", "5"])): randombad = False else: bot.memory["Sopel-GifSearch"]["badgiflinks"].append( gifdict["returnurl"]) newlist = [] for tempdict in gifapiresults: if tempdict["returnurl"] != gifdict["returnurl"]: newlist.append(tempdict) gifapiresults = newlist if gifapiresults == []: return { "error": "No Results were found for '" + searchdict["query"] + "' in the " + str(spicemanip.main(searchdict['gifsearch'], 'orlist')) + " api(s)" } # return dict gifdict['error'] = None return gifdict
def nickname_comand_chanstats(bot, trigger): triggerargs = sopel_triggerargs(bot, trigger, 'nickname_command') if not len(triggerargs): commandused = 'list' else: commandused = spicemanip.main(triggerargs, 1).lower() triggerargs = spicemanip.main(triggerargs, '2+', 'list') channel_list_current(bot) if commandused == 'list': chanlist = spicemanip.main(bot.channels.keys(), 'andlist') bot.osd("You can find me in " + chanlist) return elif commandused == 'total': botcount = len(bot.channels.keys()) servercount = len(bot.memory['SpiceBot_Channels']['channels'].keys()) bot.osd("I am in " + str(botcount) + " of " + str(servercount) + " channel(s) available on this server.") return elif commandused == 'random': channel = spicemanip.main(bot.memory['SpiceBot_Channels']['channels'], 'random') topic = bot.memory['SpiceBot_Channels']['channels'][channel]['topic'] msg = [ "Random channel for you: {}.".format( bot.memory['SpiceBot_Channels']['channels'][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: bot.osd( "You do not have permission to update the channel listing.") return bot.write(['LIST']) bot.osd([ "[SpiceBot_Channels]", "I am now updating the channel listing for this server." ]) bot.memory['SpiceBot_Channels']['ProcessLock'] = True while bot.memory['SpiceBot_Channels']['ProcessLock']: pass foundchannelcount = len( bot.memory['SpiceBot_Channels']['channels'].keys()) bot.osd("[SpiceBot_Channels]", "Channel listing finished!", str(foundchannelcount) + " channel(s) found.") return elif commandused == 'topic': if not len(triggerargs): bot.osd("Channel name input missing.") return channel = spicemanip.main(triggerargs, 1) if not inlist(bot, channel.lower(), bot.memory['SpiceBot_Channels']['channels'].keys()): bot.osd("Channel name {} not valid.".format(channel)) return topic = bot.memory['SpiceBot_Channels']['channels'][ channel.lower()]['topic'] channel = bot.memory['SpiceBot_Channels']['channels'][ channel.lower()]['name'] bot.osd("Topic for {}: {}".format(channel, topic)) return # OP list if commandused == 'op': channel = spicemanip.main(triggerargs, 1) if not inlist(bot, channel.lower(), bot.memory['SpiceBot_Channels']['channels'].keys()): bot.osd("Channel name {} not valid.".format(channel)) return if not inlist(bot, channel.lower(), bot.channels.keys()): bot.osd( "I need to be in {} to see nick privileges.".format(channel)) return privlist = 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.main(privlist, 'andlist') dispmsg.append("Channel " + commandused.upper() + "s for " + str(channel) + " are: " + oplist) bot.osd(dispmsg, trigger.nick, 'notice') return # HOP list if commandused == 'hop': channel = spicemanip.main(triggerargs, 1) if not inlist(bot, channel.lower(), bot.memory['SpiceBot_Channels']['channels'].keys()): bot.osd("Channel name {} not valid.".format(channel)) return if not inlist(bot, channel.lower(), bot.channels.keys()): bot.osd( "I need to be in {} to see nick privileges.".format(channel)) return privlist = 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.main(privlist, 'andlist') dispmsg.append("Channel " + commandused.upper() + "s for " + str(channel) + " are: " + oplist) bot.osd(dispmsg, trigger.nick, 'notice') return # Voice List if commandused == 'voice': channel = spicemanip.main(triggerargs, 1) if not inlist(bot, channel.lower(), bot.memory['SpiceBot_Channels']['channels'].keys()): bot.osd("Channel name {} not valid.".format(channel)) return if not inlist(bot, channel.lower(), bot.channels.keys()): bot.osd( "I need to be in {} to see nick privileges.".format(channel)) return privlist = 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.main(privlist, 'andlist') dispmsg.append("Channel " + commandused.upper() + "s for " + str(channel) + " are: " + oplist) bot.osd(dispmsg, trigger.nick, 'notice') return # owner List if commandused == 'owner': channel = spicemanip.main(triggerargs, 1) if not inlist(bot, channel.lower(), bot.memory['SpiceBot_Channels']['channels'].keys()): bot.osd("Channel name {} not valid.".format(channel)) return if not inlist(bot, channel.lower(), bot.channels.keys()): bot.osd( "I need to be in {} to see nick privileges.".format(channel)) return privlist = 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.main(privlist, 'andlist') dispmsg.append("Channel " + commandused.upper() + "s for " + str(channel) + " are: " + oplist) bot.osd(dispmsg, trigger.nick, 'notice') return # admin List if commandused == 'admin': channel = spicemanip.main(triggerargs, 1) if not inlist(bot, channel.lower(), bot.memory['SpiceBot_Channels']['channels'].keys()): bot.osd("Channel name {} not valid.".format(channel)) return if not inlist(bot, channel.lower(), bot.channels.keys()): bot.osd( "I need to be in {} to see nick privileges.".format(channel)) return privlist = 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.main(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.main(triggerargs, 1) if not inlist(bot, channel.lower(), bot.memory['SpiceBot_Channels']['channels'].keys()): bot.osd("Channel name {} not valid.".format(channel)) return if not inlist(bot, channel.lower(), bot.channels.keys()): bot.osd("I need to be in {} to see user list.".format(channel)) return dispmsg = [] if not len(bot.channels[channel].privileges.keys()): dispmsg.append("There are no Channel users for " + str(channel)) else: userslist = spicemanip.main( bot.channels[channel].privileges.keys(), 'andlist') dispmsg.append("Channel users for " + str(channel) + " are: " + userslist) bot.osd(dispmsg, trigger.nick, 'notice') return
def moarram(bot, trigger): coms = '' triggerargsarray = spicemanip.main(trigger, 'create') maincom = spicemanip.main(triggerargsarray, 1).lower()[1:] triggerargsarray = spicemanip.main(triggerargsarray, '2+', "list") # bot.say(str(triggerargsarray)) coms = spicemanip.main(triggerargsarray, 1) # bot.say(str(coms)) nick = trigger.nick if not coms: amount = 1 result = ramchips.makeram(bot, nick) if result == '0': bot.say(nick + " gets " + str(amount) + " ramchips") else: bot.say(str(result)) else: if coms == 'add': if bot.channels[ trigger.sender].privileges[nick] < sopel.module.HALFOP: return bot.reply("Unauthorized action detected!") target = spicemanip.main(triggerargsarray, 3) or 0 amount = spicemanip.main(triggerargsarray, 2) if not target == 0: nick = target if not landrushared.is_digit(amount): amount = 1 amount = int(amount) ramchips.addram(bot, nick, amount) if int(amount) > 0: key = " gets " else: key = " loses " amount = abs(amount) bot.say(nick + key + str(amount) + " ramchips") elif coms == 'balance': bl = 0 bl = ramchips.getbalanceram(bot, nick) bot.say(nick + " has " + str(bl) + " RAM chips") elif coms == 'stock': bl = ramchips.getbalanceram(bot, 'botstock') bot.say("The center warehouse has " + str(bl) + " RAM chips") payout = ramchips.sellram(bot) bot.say("Ram is currently selling for " + str(payout)) elif coms == 'ramhouse': amount = spicemanip.main(triggerargsarray, 2) if not landrushared.is_digit(amount): amount = 1 ramchips.addram(bot, 'botstock', amount) bot.say("Bot stock gets: " + amount + " RAM chips") elif coms == 'sell': payout = ramchips.sellram(bot) sale = ramchips.getbalanceram(bot, nick) if sale > 0: payment = sale * payout latinum.addlat(bot, nick, payment) bot.say(nick + " sells " + str(sale) + " for " + str(payment)) ramchips.addram(bot, 'botstock', sale) ramchips.addram(bot, nick, -abs(sale)) else: bot.say(nick + " does not have chips to sell") elif coms == 'bots': bl = 0 bl = ramchips.getrambot(bot, nick) bot.say(nick + " has " + str(bl) + " RAMBOTS") elif coms == 'buybot': amount = spicemanip.main(triggerargsarray, 2) if not landrushared.is_digit(amount): amount = 1 if ramchips.addrambot(bot, nick, amount): if amount == 1: key = " buys a worker bot " else: key = " buys " + str(amount) + " worker bots " bot.say(nick + key) elif coms == 'setbots': if bot.channels[ trigger.sender].privileges[nick] < sopel.module.HALFOP: return bot.reply("Unauthorized action detected!") target = spicemanip.main(triggerargsarray, 3) or 0 amount = spicemanip.main(triggerargsarray, 2) if not landrushared.is_digit(amount): amount = 1 if not target == 0: nick = target ramchips.setrambots(bot, nick, amount) key = " now has: " #amount = abs(amount) bot.say(nick + key + str(amount) + " rambots") elif coms == 'supplies': bl = ramchips.supplybalance(bot, nick) action = spicemanip.main(triggerargsarray, 2) pricing = landrushared.randprice(50) if not action == 'buy': bot.say(" You have: " + str(bl) + " supplies. One RAMCHIP currently cost: " + str(pricing)) else: if (action == 'buy'): purchase = ramchips.buysupplies(bot, nick, pricing) if not purchase == 0: bot.say(" You have refilled your supplies for " + str(purchase) + " bars of latinum") else: bot.says(str(purchase)) else: bot.say(" You already have: " + str(bl) + " supplies") elif coms == 'upgrades': bot.say("No upgrades for you") elif coms == 'help': helpcmd = spicemanip.main(triggerargsarray, 2) helpfile = "type help command name to see more: stock, add, balance, sell,buy,upgrades" if helpcmd == 'stock': helpfile = 'The stock command will show you how many ram chips are in the warehouse and what the current sell price is' elif helpcmd == 'balance': helpfile = 'The balance command will show you how many ram chips you have built' elif helpcmd == 'add': helpfile = 'The add command will build 1 ram chip, typing without a command also builds a chip. It takes 2 supply counts' elif helpcmd == 'sell': helpfile = 'The sell command will sell all the ram chips you have in storage for latinum see the stock command for current prices' elif helpcmd == 'buy': helpfile = 'The buy command will buy factory robots to make chips for you. You can include an amount. Bot prices are based your total bot count' elif helpcmd == 'upgrades': helpfile = 'The upgrades command with upgrade your factory you. Each lvl gives you more features for a higher cost.' #LVL 1: 500 bar: supplies storage goes to 100 # lvl 2:2500 bars ram uses half suppleis #lvl 3: 5000 bars marketingbot your ram sells for 1 extra bar per chips #lvl 4: 8000 bars auto buy supplies #lvl 5: 12000 bars: supplies bot.say(helpfile) else: bot.say( "I don't know what your trying to do. Type !ram help for help")