Merge pull request #100 from deathbybandaid/development

Development
This commit is contained in:
Deathbybandaid 2019-07-10 08:31:12 -04:00 committed by GitHub
commit fabd637540
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
30 changed files with 1376 additions and 568 deletions

View File

@ -15,7 +15,7 @@ from .Database import db as botdb
from .Config import config as botconfig from .Config import config as botconfig
from .Read import read as botread from .Read import read as botread
import spicemanip from sopel_modules.spicemanip import spicemanip
class SpiceBot_AI_MainSection(StaticSection): class SpiceBot_AI_MainSection(StaticSection):
@ -138,18 +138,18 @@ class SpiceBot_AI():
# bot items # bot items
for botitem in ["nick"]: for botitem in ["nick"]:
messagelist = spicemanip.main(message, "create") messagelist = spicemanip(message, "create")
for i in range(len(messagelist)): for i in range(len(messagelist)):
if messagelist[i].upper() == str(eval("bot." + botitem)).upper(): if messagelist[i].upper() == str(eval("bot." + botitem)).upper():
messagelist[i] = str("bot" + botitem).upper() messagelist[i] = str("bot" + botitem).upper()
message = spicemanip.main(messagelist, 0) message = spicemanip(messagelist, 0)
for triggeritem in ["nick", "sender"]: for triggeritem in ["nick", "sender"]:
messagelist = spicemanip.main(message, "create") messagelist = spicemanip(message, "create")
for i in range(len(messagelist)): for i in range(len(messagelist)):
if messagelist[i].upper() == str(eval("trigger." + botitem)).upper(): if messagelist[i].upper() == str(eval("trigger." + botitem)).upper():
messagelist[i] = str("trigger" + botitem).upper() messagelist[i] = str("trigger" + botitem).upper()
message = spicemanip.main(messagelist, 0) message = spicemanip(messagelist, 0)
return message return message

View File

@ -13,7 +13,7 @@ import os
import threading import threading
import copy import copy
import spicemanip from sopel_modules.spicemanip import spicemanip
import sopel_modules import sopel_modules
from .Logs import logs from .Logs import logs
@ -43,6 +43,7 @@ class BotCommands():
}, },
'disabled': {}, 'disabled': {},
} }
self.todo_list = []
self.module_files_parse() self.module_files_parse()
self.nickrules() self.nickrules()
for comtype in ['module', 'nickname', 'rule']: for comtype in ['module', 'nickname', 'rule']:
@ -196,7 +197,7 @@ class BotCommands():
maincom = command_dict["validcoms"][0] maincom = command_dict["validcoms"][0]
if len(command_dict["validcoms"]) > 1: if len(command_dict["validcoms"]) > 1:
comaliases = spicemanip.main(command_dict["validcoms"], '2+', 'list') comaliases = spicemanip(command_dict["validcoms"], '2+', 'list')
else: else:
comaliases = [] comaliases = []
@ -271,15 +272,16 @@ class BotCommands():
foldername = str(folderpath).split("/")[-1] foldername = str(folderpath).split("/")[-1]
# check for json reference file # check for json reference file
validcomdict = botread.module_json_to_dict(str(modulefile)) comdict = botread.module_json_to_dict(str(modulefile))
# replace json defaults # replace json defaults
validcomdict["filepath"] = str(modulefile) comdict["filepath"] = str(modulefile)
validcomdict["filename"] = str(filename_base) comdict["filename"] = str(filename_base)
validcomdict["folderpath"] = str(folderpath) comdict["folderpath"] = str(folderpath)
validcomdict["foldername"] = str(foldername) comdict["foldername"] = str(foldername)
detected_lines = [] detected_lines = []
todo_list = []
for line in module_file_lines: for line in module_file_lines:
if str(line).startswith("@"): if str(line).startswith("@"):
@ -302,27 +304,46 @@ class BotCommands():
if line: if line:
detected_lines.append(line) detected_lines.append(line)
elif "TODO" in str(line):
todo_list.append(str(line))
if len(todo_list):
self.todo_list.extend(todo_list)
if len(detected_lines): if len(detected_lines):
filelinelist = [] filelinelist = []
currentsuccesslines = 0
for detected_line in detected_lines: for detected_line in detected_lines:
try: validcomdict = copy.deepcopy(comdict)
validcomdict["TODO"] = todo_list
# Commands # Commands
if str(detected_line).startswith("commands"): if str(detected_line).startswith("commands"):
comtype = "module" comtype = "module"
try:
validcoms = eval(str(detected_line).split("commands")[-1]) validcoms = eval(str(detected_line).split("commands")[-1])
except Exception as e:
validcoms = e
validcoms = []
elif str(detected_line).startswith("nickname_commands"): elif str(detected_line).startswith("nickname_commands"):
comtype = "nickname" comtype = "nickname"
try:
validcoms = eval(str(detected_line).split("nickname_commands")[-1]) validcoms = eval(str(detected_line).split("nickname_commands")[-1])
except Exception as e:
validcoms = e
validcoms = []
elif str(detected_line).startswith("rule"): elif str(detected_line).startswith("rule"):
comtype = "rule" comtype = "rule"
try:
validcoms = eval(str(detected_line).split("rule")[-1]) validcoms = eval(str(detected_line).split("rule")[-1])
except Exception as e:
validcoms = e
validcoms = []
if isinstance(validcoms, tuple): if isinstance(validcoms, tuple):
validcoms = list(validcoms) validcoms = list(validcoms)
else: if not isinstance(validcoms, list):
validcoms = [validcoms] validcoms = [validcoms]
for regexcom in ["(.*)", '^\?(.*)']: for regexcom in ["(.*)", '^\?(.*)']:
if regexcom in validcoms: if regexcom in validcoms:
@ -333,15 +354,8 @@ class BotCommands():
validcomdict["comtype"] = comtype validcomdict["comtype"] = comtype
validcomdict["validcoms"] = validcoms validcomdict["validcoms"] = validcoms
filelinelist.append(validcomdict) filelinelist.append(validcomdict)
currentsuccesslines += 1
except Exception as e:
addnothing = e
if addnothing:
currentsuccesslines += 0
if len(filelinelist): self.register(validcomdict)
for vcomdict in filelinelist:
self.register(vcomdict)
commands = BotCommands() commands = BotCommands()

View File

@ -8,7 +8,7 @@ from .Config import config as botconfig
from .Read import read as botread from .Read import read as botread
from .Commands import commands as botcommands from .Commands import commands as botcommands
import spicemanip from sopel_modules.spicemanip import spicemanip
from fake_useragent import UserAgent from fake_useragent import UserAgent
import urllib import urllib
@ -134,13 +134,13 @@ class BotGif():
gifapiresults.extend(self.valid_api[currentapi]["cache"][searchdict["searchquery"].lower()]) gifapiresults.extend(self.valid_api[currentapi]["cache"][searchdict["searchquery"].lower()])
if not len(gifapiresults): if not len(gifapiresults):
return {"error": "No Results were found for '" + searchdict["query"] + "' in the " + str(spicemanip.main(searchdict['gifsearch'], 'orlist')) + " api(s)"} return {"error": "No Results were found for '" + searchdict["query"] + "' in the " + str(spicemanip(searchdict['gifsearch'], 'orlist')) + " api(s)"}
random.shuffle(gifapiresults) random.shuffle(gifapiresults)
random.shuffle(gifapiresults) random.shuffle(gifapiresults)
randombad = True randombad = True
while randombad: while randombad:
gifdict = spicemanip.main(gifapiresults, "random") gifdict = spicemanip(gifapiresults, "random")
try: try:
gifpage = requests.get(gifdict["returnurl"], headers=None) gifpage = requests.get(gifdict["returnurl"], headers=None)
@ -159,7 +159,7 @@ class BotGif():
gifapiresults = newlist gifapiresults = newlist
if not len(gifapiresults): if not len(gifapiresults):
return {"error": "No Results were found for '" + searchdict["query"] + "' in the " + str(spicemanip.main(searchdict['gifsearch'], 'orlist')) + " api(s)"} return {"error": "No Results were found for '" + searchdict["query"] + "' in the " + str(spicemanip(searchdict['gifsearch'], 'orlist')) + " api(s)"}
# return dict # return dict
gifdict['error'] = None gifdict['error'] = None

View File

@ -9,7 +9,7 @@ This Class stores logs in an easy to access manner
import threading import threading
import os import os
import sys import sys
import spicemanip from sopel_modules.spicemanip import spicemanip
from .Config import config as botconfig from .Config import config as botconfig
@ -98,7 +98,7 @@ class BotLogs():
else: else:
if not line.startswith(tuple(stdio_ignore)) and not line.isspace(): if not line.startswith(tuple(stdio_ignore)) and not line.isspace():
debuglines.append(str(line)) debuglines.append(str(line))
loadedmodules = "Loaded: " + spicemanip.main(loadedmodules, 'andlist') loadedmodules = "Loaded: " + spicemanip(loadedmodules, 'andlist')
debuglines.insert(1, loadedmodules) debuglines.insert(1, loadedmodules)
return debuglines return debuglines
@ -110,7 +110,7 @@ class BotLogs():
line = str(line).split(str(os.uname()[1] + " "))[-1] line = str(line).split(str(os.uname()[1] + " "))[-1]
lineparts = str(line).split(": ") lineparts = str(line).split(": ")
del lineparts[0] del lineparts[0]
line = spicemanip.main(lineparts, 0) line = spicemanip(lineparts, 0)
if not line.isspace(): if not line.isspace():
debuglines.append(str(line)) debuglines.append(str(line))
return debuglines return debuglines

View File

@ -9,8 +9,9 @@ from sopel.tools import Identifier
import functools import functools
import copy import copy
import datetime import datetime
from word2number import w2n
import spicemanip from sopel_modules.spicemanip import spicemanip
from .Tools import command_permissions_check, class_create from .Tools import command_permissions_check, class_create
from .Commands import commands as botcommands from .Commands import commands as botcommands
@ -40,7 +41,7 @@ def prerun(t_command_type='module', t_command_subtype=None):
botcom = class_create('botcom') botcom = class_create('botcom')
if t_command_type == "nickname": if t_command_type == "nickname":
check_nick = spicemanip.main(trigger.args[1], 1).lower() check_nick = spicemanip(trigger.args[1], 1).lower()
if check_nick != str(bot.nick).lower(): if check_nick != str(bot.nick).lower():
return return
else: else:
@ -52,7 +53,7 @@ def prerun(t_command_type='module', t_command_subtype=None):
# Primary command used for trigger, and a list of all words # 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) trigger_args, trigger_command, trigger_prefix = make_trigger_args(trigger.args[1], trigger_command_type)
if trigger_prefix == botconfig.SpiceBot_Commands.query_prefix: if trigger_prefix in [botconfig.SpiceBot_Commands.query_prefix]:
return return
trigger_command_type = botcommands.find_command_type(trigger_command) trigger_command_type = botcommands.find_command_type(trigger_command)
@ -87,7 +88,7 @@ def prerun(t_command_type='module', t_command_subtype=None):
# split into && groupings # split into && groupings
and_split = trigger_and_split(trigger_args) and_split = trigger_and_split(trigger_args)
# Create dict listings for trigger.sb # Create dict listings for botcom.dict
argsdict_list = trigger_argsdict_list(argsdict_default, and_split) argsdict_list = trigger_argsdict_list(argsdict_default, and_split)
# Run the function for all splits # Run the function for all splits
@ -95,17 +96,15 @@ def prerun(t_command_type='module', t_command_subtype=None):
runcount = 0 runcount = 0
for argsdict in argsdict_list: for argsdict in argsdict_list:
runcount += 1 runcount += 1
trigger.sb = copy.deepcopy(argsdict) botcom.dict = copy.deepcopy(argsdict)
trigger.sb["runcount"] = runcount botcom.dict["runcount"] = runcount
trigger.sb["args"], trigger.sb["hyphen_arg"] = trigger_hyphen_args(trigger.sb["args"]) botcom.dict["args"], botcom.dict["hyphen_arg"] = trigger_hyphen_args(botcom.dict["args"])
if not trigger.sb["hyphen_arg"]: args_pass = trigger_hyphen_arg_handler(bot, trigger, botcom)
# check if anything prohibits the nick from running the command if args_pass:
if trigger_runstatus(bot, trigger): if trigger_runstatus(bot, trigger, botcom):
function(bot, trigger, botcom, *args, **kwargs) function(bot, trigger, botcom, *args, **kwargs)
else:
trigger_hyphen_arg_handler(bot, trigger)
botmessagelog.messagelog_exit(bot, argsdict_default["log_id"]) botmessagelog.messagelog_exit(bot, argsdict_default["log_id"])
return internal_prerun return internal_prerun
@ -130,7 +129,7 @@ def prerun_query(t_command_type='module', t_command_subtype=None):
botcom = class_create('botcom') botcom = class_create('botcom')
if t_command_type == "nickname": if t_command_type == "nickname":
check_nick = spicemanip.main(trigger.args[1], 1).lower() check_nick = spicemanip(trigger.args[1], 1).lower()
if check_nick != str(bot.nick).lower(): if check_nick != str(bot.nick).lower():
return return
else: else:
@ -165,18 +164,18 @@ def prerun_query(t_command_type='module', t_command_subtype=None):
argsdict_default["dict"] = botcommands.get_command_dict("query", 'nickname') argsdict_default["dict"] = botcommands.get_command_dict("query", 'nickname')
# Create dict listings for trigger.sb # Create dict listings for botcom.dict
argsdict = trigger_argsdict_single(argsdict_default, trigger_args) argsdict = trigger_argsdict_single(argsdict_default, trigger_args)
# Run the function for all splits # Run the function for all splits
botmessagelog.messagelog_start(bot, trigger, argsdict_default["log_id"], argsdict_default["realcomtext"]) botmessagelog.messagelog_start(bot, trigger, argsdict_default["log_id"], argsdict_default["realcomtext"])
trigger.sb = copy.deepcopy(argsdict) botcom.dict = copy.deepcopy(argsdict)
trigger.sb["runcount"] = 1 botcom.dict["runcount"] = 1
# check if anything prohibits the nick from running the command # check if anything prohibits the nick from running the command
if trigger_runstatus_query(bot, trigger): if trigger_runstatus_query(bot, trigger, botcom):
function(bot, trigger, botcom, *args, **kwargs) function(bot, trigger, botcom, *args, **kwargs)
botmessagelog.messagelog_exit(bot, argsdict_default["log_id"]) botmessagelog.messagelog_exit(bot, argsdict_default["log_id"])
@ -208,22 +207,22 @@ def verify_channel(trigger):
def make_trigger_args(triggerargs_one, trigger_command_type='module'): def make_trigger_args(triggerargs_one, trigger_command_type='module'):
trigger_args = spicemanip.main(triggerargs_one, 'create') trigger_args = spicemanip(triggerargs_one, 'create')
if trigger_command_type in ['nickname']: if trigger_command_type in ['nickname']:
trigger_prefix = spicemanip.main(trigger_args, 2).lower()[0] trigger_prefix = spicemanip(trigger_args, 2).lower()[0]
if trigger_prefix.isupper() or trigger_prefix.islower(): if trigger_prefix.isupper() or trigger_prefix.islower():
trigger_prefix = None trigger_prefix = None
trigger_command = spicemanip.main(trigger_args, 2).lower() trigger_command = spicemanip(trigger_args, 2).lower()
trigger_args = spicemanip.main(trigger_args, '3+', 'list') trigger_args = spicemanip(trigger_args, '3+', 'list')
else: else:
trigger_prefix = spicemanip.main(trigger_args, 1).lower()[0] trigger_prefix = spicemanip(trigger_args, 1).lower()[0]
trigger_command = spicemanip.main(trigger_args, 1).lower()[1:] trigger_command = spicemanip(trigger_args, 1).lower()[1:]
trigger_args = spicemanip.main(trigger_args, '2+', 'list') trigger_args = spicemanip(trigger_args, '2+', 'list')
return trigger_args, trigger_command, trigger_prefix return trigger_args, trigger_command, trigger_prefix
def trigger_and_split(trigger_args): def trigger_and_split(trigger_args):
trigger_args_list_split = spicemanip.main(trigger_args, "split_&&") trigger_args_list_split = spicemanip(trigger_args, "split_&&")
if not len(trigger_args_list_split): if not len(trigger_args_list_split):
trigger_args_list_split.append([]) trigger_args_list_split.append([])
return trigger_args_list_split return trigger_args_list_split
@ -233,11 +232,11 @@ def trigger_argsdict_list(argsdict_default, and_split):
prerun_split = [] prerun_split = []
for trigger_args_part in and_split: for trigger_args_part in and_split:
argsdict_part = copy.deepcopy(argsdict_default) argsdict_part = copy.deepcopy(argsdict_default)
argsdict_part["args"] = spicemanip.main(trigger_args_part, 'create') 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"): if len(argsdict_part["args"]) and (argsdict_part["args"][0] == "-a" or argsdict_part["args"][-1] == "-a"):
argsdict_part["adminswitch"] = True argsdict_part["adminswitch"] = True
if argsdict_part["args"][0] == "-a": if argsdict_part["args"][0] == "-a":
argsdict_part["args"] = spicemanip.main(argsdict_part["args"], '2+', 'list') argsdict_part["args"] = spicemanip(argsdict_part["args"], '2+', 'list')
elif argsdict_part["args"][-1] == "-a": elif argsdict_part["args"][-1] == "-a":
del argsdict_part["args"][-1] del argsdict_part["args"][-1]
else: else:
@ -248,11 +247,11 @@ def trigger_argsdict_list(argsdict_default, and_split):
def trigger_argsdict_single(argsdict_default, trigger_args_part): def trigger_argsdict_single(argsdict_default, trigger_args_part):
argsdict_part = copy.deepcopy(argsdict_default) argsdict_part = copy.deepcopy(argsdict_default)
argsdict_part["args"] = spicemanip.main(trigger_args_part, 'create') 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"): if len(argsdict_part["args"]) and (argsdict_part["args"][0] == "-a" or argsdict_part["args"][-1] == "-a"):
argsdict_part["adminswitch"] = True argsdict_part["adminswitch"] = True
if argsdict_part["args"][0] == "-a": if argsdict_part["args"][0] == "-a":
argsdict_part["args"] = spicemanip.main(argsdict_part["args"], '2+', 'list') argsdict_part["args"] = spicemanip(argsdict_part["args"], '2+', 'list')
elif argsdict_part["args"][-1] == "-a": elif argsdict_part["args"][-1] == "-a":
del argsdict_part["args"][-1] del argsdict_part["args"][-1]
else: else:
@ -260,18 +259,18 @@ def trigger_argsdict_single(argsdict_default, trigger_args_part):
return argsdict_part return argsdict_part
def trigger_runstatus_query(bot, trigger): def trigger_runstatus_query(bot, trigger, botcom):
# Bots can't run commands # Bots can't run commands
if Identifier(trigger.nick) == bot.nick: if Identifier(trigger.nick) == bot.nick:
return False return False
# Allow permissions for enabling and disabling commands via hyphenargs # Allow permissions for enabling and disabling commands via hyphenargs
if trigger.sb["adminswitch"]: if botcom.dict["adminswitch"]:
if command_permissions_check(bot, trigger, ['admins', 'owner', 'OP', 'ADMIN', 'OWNER']): if command_permissions_check(bot, trigger, ['admins', 'owner', 'OP', 'ADMIN', 'OWNER']):
return True return True
else: else:
botmessagelog.messagelog_error(trigger.sb["log_id"], "The admin switch (-a) is for use by authorized nicks ONLY.") botmessagelog.messagelog_error(botcom.dict["log_id"], "The admin switch (-a) is for use by authorized nicks ONLY.")
return False return False
# don't run commands that are disabled in channels # don't run commands that are disabled in channels
@ -288,101 +287,105 @@ def trigger_runstatus_query(bot, trigger):
# don't run commands that are disabled in channels # don't run commands that are disabled in channels
if not trigger.is_privmsg: if not trigger.is_privmsg:
channel_disabled_list = botcommands.get_commands_disabled(str(trigger.sender)) channel_disabled_list = botcommands.get_commands_disabled(str(trigger.sender))
if trigger.sb["realcomref"] in list(channel_disabled_list.keys()): if botcom.dict["realcomref"] in list(channel_disabled_list.keys()):
reason = channel_disabled_list[trigger.sb["realcomref"]]["reason"] reason = channel_disabled_list[botcom.dict["realcomref"]]["reason"]
timestamp = channel_disabled_list[trigger.sb["realcomref"]]["timestamp"] timestamp = channel_disabled_list[botcom.dict["realcomref"]]["timestamp"]
bywhom = channel_disabled_list[trigger.sb["realcomref"]]["disabledby"] bywhom = channel_disabled_list[botcom.dict["realcomref"]]["disabledby"]
message = "The " + str(trigger.sb["comtext"]) + " command was disabled by " + bywhom + " for " + str(trigger.sender) + " at " + str(timestamp) + " for the following reason: " + str(reason) message = "The " + str(botcom.dict["comtext"]) + " command was disabled by " + bywhom + " for " + str(trigger.sender) + " at " + str(timestamp) + " for the following reason: " + str(reason)
return trigger_cant_run(bot, trigger, message) return trigger_cant_run(bot, trigger, botcom, message)
# don't run commands that are disabled for specific users # don't run commands that are disabled for specific users
nick_disabled_list = botcommands.get_commands_disabled(str(trigger.nick)) nick_disabled_list = botcommands.get_commands_disabled(str(trigger.nick))
if trigger.sb["realcomref"] in list(nick_disabled_list.keys()): if botcom.dict["realcomref"] in list(nick_disabled_list.keys()):
bywhom = nick_disabled_list[trigger.sb["realcomref"]]["disabledby"] bywhom = nick_disabled_list[botcom.dict["realcomref"]]["disabledby"]
if botusers.ID(bywhom) != botusers.ID(trigger.nick): if botusers.ID(bywhom) != botusers.ID(trigger.nick):
reason = nick_disabled_list[trigger.sb["realcomref"]]["reason"] reason = nick_disabled_list[botcom.dict["realcomref"]]["reason"]
timestamp = nick_disabled_list[trigger.sb["realcomref"]]["timestamp"] timestamp = nick_disabled_list[botcom.dict["realcomref"]]["timestamp"]
message = "The " + str(trigger.sb["comtext"]) + " command was disabled by " + bywhom + " for " + str(trigger.sender) + " at " + str(timestamp) + " for the following reason: " + str(reason) message = "The " + str(botcom.dict["comtext"]) + " command was disabled by " + bywhom + " for " + str(trigger.sender) + " at " + str(timestamp) + " for the following reason: " + str(reason)
return trigger_cant_run(bot, trigger, message) return trigger_cant_run(bot, trigger, botcom, message)
else: else:
botcommands.unset_command_disabled(trigger.sb["realcomref"], trigger.nick) botcommands.unset_command_disabled(botcom.dict["realcomref"], trigger.nick)
botmessagelog.messagelog_error(trigger.sb["log_id"], trigger.sb["comtext"] + " is now enabled for " + str(trigger.nick)) botmessagelog.messagelog_error(botcom.dict["log_id"], botcom.dict["comtext"] + " is now enabled for " + str(trigger.nick))
return True return True
def trigger_runstatus(bot, trigger): def trigger_runstatus(bot, trigger, botcom):
# Bots can't run commands # Bots can't run commands
if Identifier(trigger.nick) == bot.nick: if Identifier(trigger.nick) == bot.nick:
return False return False
# Allow permissions for enabling and disabling commands via hyphenargs # Allow permissions for enabling and disabling commands via hyphenargs
if trigger.sb["adminswitch"]: if botcom.dict["adminswitch"]:
if command_permissions_check(bot, trigger, ['admins', 'owner', 'OP', 'ADMIN', 'OWNER']): if command_permissions_check(bot, trigger, ['admins', 'owner', 'OP', 'ADMIN', 'OWNER']):
return True return True
else: else:
botmessagelog.messagelog_error(trigger.sb["log_id"], "The admin switch (-a) is for use by authorized nicks ONLY.") botmessagelog.messagelog_error(botcom.dict["log_id"], "The admin switch (-a) is for use by authorized nicks ONLY.")
return False return False
if trigger.sb["hyphen_arg"]: # if botcom.dict["hyphen_arg"]:
return False # return False
if trigger.sb["runcount"] > 1: if not trigger.is_privmsg:
if str(trigger.sender).lower() in [x.lower() for x in botcom.dict["dict"]["hardcoded_channel_block"]]:
botmessagelog.messagelog_error(botcom.dict["log_id"], "The " + str(botcom.dict["comtext"]) + " command cannot be used in " + str(trigger.sender) + " because it is hardcoded not to.")
if botcom.dict["runcount"] > 1:
# check channel multirun blocks # check channel multirun blocks
if not trigger.is_privmsg: if not trigger.is_privmsg:
channel_disabled_list = botcommands.get_commands_disabled(str(trigger.sender), "multirun") channel_disabled_list = botcommands.get_commands_disabled(str(trigger.sender), "multirun")
if trigger.sb["realcomref"] in list(channel_disabled_list.keys()): if botcom.dict["realcomref"] in list(channel_disabled_list.keys()):
reason = channel_disabled_list[trigger.sb["realcomref"]]["reason"] reason = channel_disabled_list[botcom.dict["realcomref"]]["reason"]
timestamp = channel_disabled_list[trigger.sb["realcomref"]]["timestamp"] timestamp = channel_disabled_list[botcom.dict["realcomref"]]["timestamp"]
bywhom = channel_disabled_list[trigger.sb["realcomref"]]["disabledby"] bywhom = channel_disabled_list[botcom.dict["realcomref"]]["disabledby"]
message = "The " + str(trigger.sb["comtext"]) + " command multirun usage was disabled by " + bywhom + " for " + str(trigger.sender) + " at " + str(timestamp) + " for the following reason: " + str(reason) message = "The " + str(botcom.dict["comtext"]) + " command multirun usage was disabled by " + bywhom + " for " + str(trigger.sender) + " at " + str(timestamp) + " for the following reason: " + str(reason)
return trigger_cant_run(bot, trigger, message) return trigger_cant_run(bot, trigger, botcom, message)
# don't run commands that are disabled for specific users # don't run commands that are disabled for specific users
nick_disabled_list = botcommands.get_commands_disabled(str(trigger.nick), "multirun") nick_disabled_list = botcommands.get_commands_disabled(str(trigger.nick), "multirun")
if trigger.sb["realcomref"] in list(nick_disabled_list.keys()): if botcom.dict["realcomref"] in list(nick_disabled_list.keys()):
bywhom = nick_disabled_list[trigger.sb["realcomref"]]["disabledby"] bywhom = nick_disabled_list[botcom.dict["realcomref"]]["disabledby"]
if botusers.ID(bywhom) != botusers.ID(trigger.nick): if botusers.ID(bywhom) != botusers.ID(trigger.nick):
reason = nick_disabled_list[trigger.sb["realcomref"]]["reason"] reason = nick_disabled_list[botcom.dict["realcomref"]]["reason"]
timestamp = nick_disabled_list[trigger.sb["realcomref"]]["timestamp"] timestamp = nick_disabled_list[botcom.dict["realcomref"]]["timestamp"]
message = "The " + str(trigger.sb["comtext"]) + " command was multirun unsage disabled by " + bywhom + " for " + str(trigger.sender) + " at " + str(timestamp) + " for the following reason: " + str(reason) message = "The " + str(botcom.dict["comtext"]) + " command was multirun unsage disabled by " + bywhom + " for " + str(trigger.sender) + " at " + str(timestamp) + " for the following reason: " + str(reason)
return trigger_cant_run(bot, trigger, message) return trigger_cant_run(bot, trigger, botcom, message)
else: else:
botcommands.unset_command_disabled(trigger.sb["realcomref"], trigger.nick, "multirun") botcommands.unset_command_disabled(botcom.dict["realcomref"], trigger.nick, "multirun")
botmessagelog.messagelog_error(trigger.sb["log_id"], trigger.sb["comtext"] + " multirun is now enabled for " + str(trigger.nick)) botmessagelog.messagelog_error(botcom.dict["log_id"], botcom.dict["comtext"] + " multirun is now enabled for " + str(trigger.nick))
# don't run commands that are disabled in channels # don't run commands that are disabled in channels
if not trigger.is_privmsg: if not trigger.is_privmsg:
channel_disabled_list = botcommands.get_commands_disabled(str(trigger.sender)) channel_disabled_list = botcommands.get_commands_disabled(str(trigger.sender))
if trigger.sb["realcomref"] in list(channel_disabled_list.keys()): if botcom.dict["realcomref"] in list(channel_disabled_list.keys()):
reason = channel_disabled_list[trigger.sb["realcomref"]]["reason"] reason = channel_disabled_list[botcom.dict["realcomref"]]["reason"]
timestamp = channel_disabled_list[trigger.sb["realcomref"]]["timestamp"] timestamp = channel_disabled_list[botcom.dict["realcomref"]]["timestamp"]
bywhom = channel_disabled_list[trigger.sb["realcomref"]]["disabledby"] bywhom = channel_disabled_list[botcom.dict["realcomref"]]["disabledby"]
message = "The " + str(trigger.sb["comtext"]) + " command was disabled by " + bywhom + " for " + str(trigger.sender) + " at " + str(timestamp) + " for the following reason: " + str(reason) message = "The " + str(botcom.dict["comtext"]) + " command was disabled by " + bywhom + " for " + str(trigger.sender) + " at " + str(timestamp) + " for the following reason: " + str(reason)
return trigger_cant_run(bot, trigger, message) return trigger_cant_run(bot, trigger, botcom, message)
# don't run commands that are disabled for specific users # don't run commands that are disabled for specific users
nick_disabled_list = botcommands.get_commands_disabled(str(trigger.nick)) nick_disabled_list = botcommands.get_commands_disabled(str(trigger.nick))
if trigger.sb["realcomref"] in list(nick_disabled_list.keys()): if botcom.dict["realcomref"] in list(nick_disabled_list.keys()):
bywhom = nick_disabled_list[trigger.sb["realcomref"]]["disabledby"] bywhom = nick_disabled_list[botcom.dict["realcomref"]]["disabledby"]
if botusers.ID(bywhom) != botusers.ID(trigger.nick): if botusers.ID(bywhom) != botusers.ID(trigger.nick):
reason = nick_disabled_list[trigger.sb["realcomref"]]["reason"] reason = nick_disabled_list[botcom.dict["realcomref"]]["reason"]
timestamp = nick_disabled_list[trigger.sb["realcomref"]]["timestamp"] timestamp = nick_disabled_list[botcom.dict["realcomref"]]["timestamp"]
message = "The " + str(trigger.sb["comtext"]) + " command was disabled by " + bywhom + " for " + str(trigger.sender) + " at " + str(timestamp) + " for the following reason: " + str(reason) message = "The " + str(botcom.dict["comtext"]) + " command was disabled by " + bywhom + " for " + str(trigger.sender) + " at " + str(timestamp) + " for the following reason: " + str(reason)
return trigger_cant_run(bot, trigger, message) return trigger_cant_run(bot, trigger, botcom, message)
else: else:
botcommands.unset_command_disabled(trigger.sb["realcomref"], trigger.nick) botcommands.unset_command_disabled(botcom.dict["realcomref"], trigger.nick)
botmessagelog.messagelog_error(trigger.sb["log_id"], trigger.sb["comtext"] + " is now enabled for " + str(trigger.nick)) botmessagelog.messagelog_error(botcom.dict["log_id"], botcom.dict["comtext"] + " is now enabled for " + str(trigger.nick))
return True return True
def trigger_cant_run(bot, trigger, message=None): def trigger_cant_run(bot, trigger, botcom, message=None):
if message: if message:
botmessagelog.messagelog_error(trigger.sb["log_id"], message) botmessagelog.messagelog_error(botcom.dict["log_id"], message)
if command_permissions_check(bot, trigger, ['admins', 'owner', 'OP', 'ADMIN', 'OWNER']): if command_permissions_check(bot, trigger, ['admins', 'owner', 'OP', 'ADMIN', 'OWNER']):
botmessagelog.messagelog_error(trigger.sb["log_id"], "You however are authorized to bypass this warning with the (-a) admin switch.") botmessagelog.messagelog_error(botcom.dict["log_id"], "You however are authorized to bypass this warning with the (-a) admin switch.")
return False return False
@ -401,155 +404,190 @@ def trigger_hyphen_args(trigger_args_part):
'contribs', 'contrib', "contributors", 'contribs', 'contrib', "contributors",
'alias', 'aliases' 'alias', 'aliases'
] ]
numdict = {
"last": -1
}
hyphen_args = [] hyphen_args = []
trigger_args_unhyphend = [] trigger_args_unhyphend = []
for worditem in trigger_args_part: for worditem in trigger_args_part:
if str(worditem).startswith("--") and worditem[2:] in valid_hyphen_args: if str(worditem).startswith("--"):
hyphen_args.append(worditem[2:]) clipped_word = str(worditem[2:]).lower()
# valid arg above
if clipped_word in valid_hyphen_args:
hyphen_args.append(clipped_word)
# numbered args
elif str(clipped_word).isdigit():
hyphen_args.append(int(clipped_word))
elif clipped_word in list(numdict.keys()):
hyphen_args.append(int(numdict[clipped_word]))
else:
# check if arg word is a number
try:
clipped_word = w2n.word_to_num(str(clipped_word))
hyphen_args.append(int(clipped_word))
# word is not a valid arg or number
except ValueError:
trigger_args_unhyphend.append(worditem)
else: else:
trigger_args_unhyphend.append(worditem) trigger_args_unhyphend.append(worditem)
# only one arg allowed per && split
if len(hyphen_args): if len(hyphen_args):
hyphenarg = hyphen_args[0] hyphenarg = hyphen_args[0]
else: else:
hyphenarg = None hyphenarg = None
return trigger_args_unhyphend, hyphenarg return trigger_args_unhyphend, hyphenarg
def trigger_hyphen_arg_handler(bot, trigger): def trigger_hyphen_arg_handler(bot, trigger, botcom):
# Commands that cannot run via privmsg # Commands that cannot run via privmsg
# TODO --check should work for commands that don't exist # TODO --check should work for commands that don't exist
if trigger.sb["hyphen_arg"] in ['check']:
if trigger.sb["com"].lower() != trigger.sb["realcom"]:
botmessagelog.messagelog(trigger.sb["log_id"], trigger.sb["comtext"] + " is a valid alias command for " + trigger.sb["realcomtext"])
else:
botmessagelog.messagelog(trigger.sb["log_id"], trigger.sb["comtext"] + " is a valid command")
return
elif trigger.sb["hyphen_arg"] in [ if not botcom.dict["hyphen_arg"]:
return True
# handle numbered args
if str(botcom.dict["hyphen_arg"]).isdigit() or botcom.dict["hyphen_arg"] in [-1, 'random']:
return True
elif botcom.dict["hyphen_arg"] in ['check']:
if botcom.dict["com"].lower() != botcom.dict["realcom"]:
botmessagelog.messagelog(botcom.dict["log_id"], botcom.dict["comtext"] + " is a valid alias command for " + botcom.dict["realcomtext"])
else:
botmessagelog.messagelog(botcom.dict["log_id"], botcom.dict["comtext"] + " is a valid command")
return False
elif botcom.dict["hyphen_arg"] in [
'enable', 'disable', 'enable', 'disable',
'block', 'unblock', 'block', 'unblock',
"activate", "deactivate", "activate", "deactivate",
"on", "off" "on", "off"
]: ]:
target = spicemanip.main(trigger.sb["args"], 1) or trigger.nick target = spicemanip(botcom.dict["args"], 1) or trigger.nick
if not target: if not target:
if trigger.sb["hyphen_arg"] in ['enable', 'unblock', "activate", "on"]: if botcom.dict["hyphen_arg"] in ['enable', 'unblock', "activate", "on"]:
botmessagelog.messagelog_error(trigger.sb["log_id"], "Who/Where am I enabling " + str(trigger.sb["comtext"]) + " usage for?") botmessagelog.messagelog_error(botcom.dict["log_id"], "Who/Where am I enabling " + str(botcom.dict["comtext"]) + " usage for?")
else: else:
botmessagelog.messagelog_error(trigger.sb["log_id"], "Who/Where am I disabling " + str(trigger.sb["comtext"]) + " usage for?") botmessagelog.messagelog_error(botcom.dict["log_id"], "Who/Where am I disabling " + str(botcom.dict["comtext"]) + " usage for?")
return return False
trigger.sb["args"] = spicemanip.main(trigger.sb["args"], "2+", "list") botcom.dict["args"] = spicemanip(botcom.dict["args"], "2+", "list")
if not botdb.check_nick_id(target) and not botchannels.check_channel_bot(target, True): if not botdb.check_nick_id(target) and not botchannels.check_channel_bot(target, True):
botmessagelog.messagelog_error(trigger.sb["log_id"], "I don't know who/what " + str(target) + " is.") botmessagelog.messagelog_error(botcom.dict["log_id"], "I don't know who/what " + str(target) + " is.")
return return False
if not command_permissions_check(bot, trigger, ['admins', 'owner', 'OP', 'ADMIN', 'OWNER']): if not command_permissions_check(bot, trigger, ['admins', 'owner', 'OP', 'ADMIN', 'OWNER']):
if target != trigger.nick: if target != trigger.nick:
if trigger.sb["hyphen_arg"] in ['enable', 'unblock', "activate", "on"]: if botcom.dict["hyphen_arg"] in ['enable', 'unblock', "activate", "on"]:
botmessagelog.messagelog_error(trigger.sb["log_id"], "I was unable to enable this command for " + str(target) + " due to privilege issues.") botmessagelog.messagelog_error(botcom.dict["log_id"], "I was unable to enable this command for " + str(target) + " due to privilege issues.")
else: else:
botmessagelog.messagelog_error(trigger.sb["log_id"], "I was unable to disable this command for " + str(target) + " due to privilege issues.") botmessagelog.messagelog_error(botcom.dict["log_id"], "I was unable to disable this command for " + str(target) + " due to privilege issues.")
return return False
if trigger.sb["hyphen_arg"] in ['enable', 'unblock', "activate", "on"]: if botcom.dict["hyphen_arg"] in ['enable', 'unblock', "activate", "on"]:
if not botcommands.check_commands_disabled(trigger.sb["realcomref"], target): if not botcommands.check_commands_disabled(botcom.dict["realcomref"], target):
botmessagelog.messagelog_error(trigger.sb["log_id"], trigger.sb["comtext"] + " is already enabled for " + str(target)) botmessagelog.messagelog_error(botcom.dict["log_id"], botcom.dict["comtext"] + " is already enabled for " + str(target))
return return False
botcommands.unset_command_disabled(trigger.sb["realcomref"], target) botcommands.unset_command_disabled(botcom.dict["realcomref"], target)
botmessagelog.messagelog(trigger.sb["log_id"], trigger.sb["comtext"] + " is now enabled for " + str(target)) botmessagelog.messagelog(botcom.dict["log_id"], botcom.dict["comtext"] + " is now enabled for " + str(target))
return return False
else: else:
if botcommands.check_commands_disabled(trigger.sb["realcomref"], target): if botcommands.check_commands_disabled(botcom.dict["realcomref"], target):
botmessagelog.messagelog_error(trigger.sb["log_id"], trigger.sb["comtext"] + " is already disabled for " + str(target)) botmessagelog.messagelog_error(botcom.dict["log_id"], botcom.dict["comtext"] + " is already disabled for " + str(target))
return return False
trailingmessage = spicemanip.main(trigger.sb["args"], 0) or "No reason given." trailingmessage = spicemanip(botcom.dict["args"], 0) or "No reason given."
timestamp = str(datetime.datetime.utcnow()) timestamp = str(datetime.datetime.utcnow())
botcommands.set_command_disabled(trigger.sb["realcomref"], target, timestamp, trailingmessage, trigger.nick) botcommands.set_command_disabled(botcom.dict["realcomref"], target, timestamp, trailingmessage, trigger.nick)
botmessagelog.messagelog(trigger.sb["log_id"], trigger.sb["comtext"] + " is now disabled for " + str(target)) botmessagelog.messagelog(botcom.dict["log_id"], botcom.dict["comtext"] + " is now disabled for " + str(target))
return return False
if trigger.sb["hyphen_arg"] in ['multirun', 'multiruns']: if botcom.dict["hyphen_arg"] in ['multirun', 'multiruns']:
onoff = spicemanip.main(trigger.sb["args"], 1) or None onoff = spicemanip(botcom.dict["args"], 1) or None
if not onoff or onoff not in ['enable', 'unblock', "activate", "on"]: if not onoff or onoff not in ['enable', 'unblock', "activate", "on"]:
botmessagelog.messagelog_error(trigger.sb["log_id"], "Do you want to enable or disable " + str(trigger.sb["comtext"]) + " multirun usage?") botmessagelog.messagelog_error(botcom.dict["log_id"], "Do you want to enable or disable " + str(botcom.dict["comtext"]) + " multirun usage?")
return return False
target = spicemanip.main(trigger.sb["args"], 1) or trigger.nick target = spicemanip(botcom.dict["args"], 1) or trigger.nick
if not target: if not target:
if onoff in ['enable', 'unblock', "activate", "on"]: if onoff in ['enable', 'unblock', "activate", "on"]:
botmessagelog.messagelog_error(trigger.sb["log_id"], "Who/Where am I enabling " + str(trigger.sb["comtext"]) + " multirun usage for?") botmessagelog.messagelog_error(botcom.dict["log_id"], "Who/Where am I enabling " + str(botcom.dict["comtext"]) + " multirun usage for?")
else: else:
botmessagelog.messagelog_error(trigger.sb["log_id"], "Who/Where am I disabling " + str(trigger.sb["comtext"]) + " multirun usage for?") botmessagelog.messagelog_error(botcom.dict["log_id"], "Who/Where am I disabling " + str(botcom.dict["comtext"]) + " multirun usage for?")
return return False
trigger.sb["args"] = spicemanip.main(trigger.sb["args"], "2+", "list") botcom.dict["args"] = spicemanip(botcom.dict["args"], "2+", "list")
if not botdb.check_nick_id(target) and not botchannels.check_channel_bot(target, True): if not botdb.check_nick_id(target) and not botchannels.check_channel_bot(target, True):
botmessagelog.messagelog_error(trigger.sb["log_id"], "I don't know who/what " + str(target) + " is.") botmessagelog.messagelog_error(botcom.dict["log_id"], "I don't know who/what " + str(target) + " is.")
return return False
if not command_permissions_check(bot, trigger, ['admins', 'owner', 'OP', 'ADMIN', 'OWNER']): if not command_permissions_check(bot, trigger, ['admins', 'owner', 'OP', 'ADMIN', 'OWNER']):
if target != trigger.nick: if target != trigger.nick:
if onoff in ['enable', 'unblock', "activate", "on"]: if onoff in ['enable', 'unblock', "activate", "on"]:
botmessagelog.messagelog_error(trigger.sb["log_id"], "I was unable to enable multirun usage on " + str(trigger.sb["comtext"]) + " for " + str(target) + " due to privilege issues.") botmessagelog.messagelog_error(botcom.dict["log_id"], "I was unable to enable multirun usage on " + str(botcom.dict["comtext"]) + " for " + str(target) + " due to privilege issues.")
else: else:
botmessagelog.messagelog_error(trigger.sb["log_id"], "I was unable to enable multirun usage on " + str(trigger.sb["comtext"]) + " for " + str(target) + " due to privilege issues.") botmessagelog.messagelog_error(botcom.dict["log_id"], "I was unable to enable multirun usage on " + str(botcom.dict["comtext"]) + " for " + str(target) + " due to privilege issues.")
return return False
if onoff in ['enable', 'unblock', "activate", "on"]: if onoff in ['enable', 'unblock', "activate", "on"]:
if not botcommands.check_commands_disabled(trigger.sb["realcomref"], target, "multirun"): if not botcommands.check_commands_disabled(botcom.dict["realcomref"], target, "multirun"):
botmessagelog.messagelog_error(trigger.sb["log_id"], trigger.sb["comtext"] + " multirun is already enabled for " + str(target)) botmessagelog.messagelog_error(botcom.dict["log_id"], botcom.dict["comtext"] + " multirun is already enabled for " + str(target))
return return False
botcommands.unset_command_disabled(trigger.sb["realcomref"], target, "multirun") botcommands.unset_command_disabled(botcom.dict["realcomref"], target, "multirun")
botmessagelog.messagelog(trigger.sb["log_id"], trigger.sb["comtext"] + " multirun is now enabled for " + str(target)) botmessagelog.messagelog(botcom.dict["log_id"], botcom.dict["comtext"] + " multirun is now enabled for " + str(target))
return return False
else: else:
if botcommands.check_commands_disabled(trigger.sb["realcomref"], target, "multirun"): if botcommands.check_commands_disabled(botcom.dict["realcomref"], target, "multirun"):
botmessagelog.messagelog_error(trigger.sb["log_id"], trigger.sb["comtext"] + " multirun is already disabled for " + str(target)) botmessagelog.messagelog_error(botcom.dict["log_id"], botcom.dict["comtext"] + " multirun is already disabled for " + str(target))
return return False
trailingmessage = spicemanip.main(trigger.sb["args"], 0) or "No reason given." trailingmessage = spicemanip(botcom.dict["args"], 0) or "No reason given."
timestamp = str(datetime.datetime.utcnow()) timestamp = str(datetime.datetime.utcnow())
botcommands.set_command_disabled(trigger.sb["realcomref"], target, timestamp, trailingmessage, trigger.nick, "multirun") botcommands.set_command_disabled(botcom.dict["realcomref"], target, timestamp, trailingmessage, trigger.nick, "multirun")
botmessagelog.messagelog(trigger.sb["log_id"], trigger.sb["comtext"] + " multirun is now disabled for " + str(target)) botmessagelog.messagelog(botcom.dict["log_id"], botcom.dict["comtext"] + " multirun is now disabled for " + str(target))
return return False
elif trigger.sb["hyphen_arg"] in ['example', 'usage']: elif botcom.dict["hyphen_arg"] in ['example', 'usage']:
botmessagelog.messagelog(trigger.sb["log_id"], trigger.sb["comtext"] + ": " + str(trigger.sb["dict"]["example"])) botmessagelog.messagelog(botcom.dict["log_id"], botcom.dict["comtext"] + ": " + str(botcom.dict["dict"]["example"]))
return return False
elif trigger.sb["hyphen_arg"] in ['filename', 'filepath']: elif botcom.dict["hyphen_arg"] in ['filename', 'filepath']:
botmessagelog.messagelog(trigger.sb["log_id"], "The " + str(trigger.sb["comtext"]) + " file is located at " + str(trigger.sb["dict"][trigger.sb["hyphen_arg"]])) botmessagelog.messagelog(botcom.dict["log_id"], "The " + str(botcom.dict["comtext"]) + " file is located at " + str(botcom.dict["dict"][botcom.dict["hyphen_arg"]]))
return return False
elif trigger.sb["hyphen_arg"] in ['foldername', 'folderpath']: elif botcom.dict["hyphen_arg"] in ['foldername', 'folderpath']:
botmessagelog.messagelog(trigger.sb["log_id"], "The " + str(trigger.sb["comtext"]) + " folder is located at " + str(trigger.sb["dict"][trigger.sb["hyphen_arg"]])) botmessagelog.messagelog(botcom.dict["log_id"], "The " + str(botcom.dict["comtext"]) + " folder is located at " + str(botcom.dict["dict"][botcom.dict["hyphen_arg"]]))
return return False
elif trigger.sb["hyphen_arg"] in ['author']: elif botcom.dict["hyphen_arg"] in ['author']:
botmessagelog.messagelog(trigger.sb["log_id"], "The author of the " + str(trigger.sb["comtext"]) + " command is " + trigger.sb["dict"]["author"] + ".") botmessagelog.messagelog(botcom.dict["log_id"], "The author of the " + str(botcom.dict["comtext"]) + " command is " + botcom.dict["dict"]["author"] + ".")
return return False
elif trigger.sb["hyphen_arg"] in ['contribs', 'contrib', "contributors"]: elif botcom.dict["hyphen_arg"] in ['contribs', 'contrib', "contributors"]:
botmessagelog.messagelog(trigger.sb["log_id"], "The contributors of the " + str(trigger.sb["comtext"]) + " command are " + spicemanip.main(trigger.sb["dict"]["contributors"], "andlist") + ".") botmessagelog.messagelog(botcom.dict["log_id"], "The contributors of the " + str(botcom.dict["comtext"]) + " command are " + spicemanip(botcom.dict["dict"]["contributors"], "andlist") + ".")
return return False
elif trigger.sb["hyphen_arg"] in ['alias', 'aliases']: elif botcom.dict["hyphen_arg"] in ['alias', 'aliases']:
botmessagelog.messagelog(trigger.sb["log_id"], "The alaises of the " + str(trigger.sb["comtext"]) + " command are " + spicemanip.main(trigger.sb["dict"]["validcoms"], "andlist") + ".") botmessagelog.messagelog(botcom.dict["log_id"], "The alaises of the " + str(botcom.dict["comtext"]) + " command are " + spicemanip(botcom.dict["dict"]["validcoms"], "andlist") + ".")
return return False
return return False

View File

@ -220,6 +220,9 @@ class BotRead():
if "privs" not in list(dict_from_file.keys()): if "privs" not in list(dict_from_file.keys()):
dict_from_file["privs"] = [] dict_from_file["privs"] = []
if "hardcoded_channel_block" not in list(dict_from_file.keys()):
dict_from_file["hardcoded_channel_block"] = []
return dict_from_file return dict_from_file

View File

@ -7,7 +7,7 @@ This is the SpiceBot Reddit system.
from sopel.config.types import StaticSection, ValidatedAttribute from sopel.config.types import StaticSection, ValidatedAttribute
from sopel.formatting import bold, color, colors from sopel.formatting import bold, color, colors
import spicemanip from sopel_modules.spicemanip import spicemanip
import datetime as dt import datetime as dt
import praw import praw
@ -56,7 +56,7 @@ class BotReddit():
def user_handler(self, trigger_argsdict): def user_handler(self, trigger_argsdict):
subcommand_valid = ['check'] subcommand_valid = ['check']
subcommand = spicemanip.main([x for x in trigger_argsdict["args"] if x in subcommand_valid], 1) or '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"]) userreal = self.reddit_user_exists(trigger_argsdict["command"])
if not userreal["exists"]: if not userreal["exists"]:
@ -97,7 +97,7 @@ class BotReddit():
def subreddit_handler(self, trigger_argsdict): def subreddit_handler(self, trigger_argsdict):
subcommand_valid = ['check', 'hot', 'new', 'top', 'random', 'controversial', 'gilded', 'rising', 'best'] subcommand_valid = ['check', 'hot', 'new', 'top', 'random', 'controversial', 'gilded', 'rising', 'best']
subcommand = spicemanip.main([x for x in trigger_argsdict["args"] if x in subcommand_valid], 1) or 'check' subcommand = spicemanip([x for x in trigger_argsdict["args"] if x in subcommand_valid], 1) or 'check'
fullrurul = str("https://www.reddit.com/" + trigger_argsdict["slashcomm"] + "/" + trigger_argsdict["command"]) fullrurul = str("https://www.reddit.com/" + trigger_argsdict["slashcomm"] + "/" + trigger_argsdict["command"])
@ -116,9 +116,9 @@ class BotReddit():
return dispmsg return dispmsg
if subcommand == 'random': if subcommand == 'random':
targnum = spicemanip.main([x for x in trigger_argsdict["args"] if str(x).isdigit()], 1) or 500 targnum = spicemanip([x for x in trigger_argsdict["args"] if str(x).isdigit()], 1) or 500
else: else:
targnum = spicemanip.main([x for x in trigger_argsdict["args"] if str(x).isdigit()], 1) or 1 targnum = spicemanip([x for x in trigger_argsdict["args"] if str(x).isdigit()], 1) or 1
targnum = int(targnum) targnum = int(targnum)
if subcommand == 'new': if subcommand == 'new':
@ -162,11 +162,11 @@ class BotReddit():
return dispmsg return dispmsg
def trigger_handler(self, trigger): def trigger_handler(self, trigger):
trigger_args = spicemanip.main(trigger.args[1], 'create') trigger_args = spicemanip(trigger.args[1], 'create')
trigger_argsdict = { trigger_argsdict = {
"slashcomm": spicemanip.main(trigger_args, 1).lower()[:1], "slashcomm": spicemanip(trigger_args, 1).lower()[:1],
"command": spicemanip.main(trigger_args, 1).lower()[2:], "command": spicemanip(trigger_args, 1).lower()[2:],
"args": spicemanip.main(trigger_args, "2+", 'list') "args": spicemanip(trigger_args, "2+", 'list')
} }
if trigger_argsdict["slashcomm"] == "u": if trigger_argsdict["slashcomm"] == "u":
trigger_argsdict["urltypetxt"] = "user" trigger_argsdict["urltypetxt"] = "user"

View File

@ -14,7 +14,7 @@ from operator import itemgetter
from collections import abc from collections import abc
from pygit2 import clone_repository from pygit2 import clone_repository
import spicemanip from sopel_modules.spicemanip import spicemanip
from .Logs import logs from .Logs import logs
from .Config import config as botconfig from .Config import config as botconfig
@ -231,7 +231,7 @@ def similar_list(searchitem, searchlist, matchcount=1, searchorder='reverse'):
sim_num, sim_listitems = (list(x) for x in zip(*sorted(zip(sim_num, sim_listitems), key=itemgetter(0)))) sim_num, sim_listitems = (list(x) for x in zip(*sorted(zip(sim_num, sim_listitems), key=itemgetter(0))))
if searchorder == 'reverse': if searchorder == 'reverse':
sim_listitems = spicemanip.main(sim_listitems, 'reverse', "list") sim_listitems = spicemanip(sim_listitems, 'reverse', "list")
sim_listitems[-matchcount:] sim_listitems[-matchcount:]

View File

@ -1,7 +1,7 @@
# coding=utf8 # coding=utf8
from __future__ import unicode_literals, absolute_import, division, print_function from __future__ import unicode_literals, absolute_import, division, print_function
import spicemanip from sopel_modules.spicemanip import spicemanip
import re import re
from num2words import num2words from num2words import num2words
@ -21,10 +21,10 @@ class Translate():
for translationtype in translationtypes: for translationtype in translationtypes:
if translationtype == "hyphen": if translationtype == "hyphen":
totranslate = spicemanip.main(totranslate, 0).replace(' ', '-') totranslate = spicemanip(totranslate, 0).replace(' ', '-')
elif translationtype == "underscore": elif translationtype == "underscore":
totranslate = spicemanip.main(totranslate, 0).replace(' ', '_') totranslate = spicemanip(totranslate, 0).replace(' ', '_')
elif translationtype == "ermahgerd": elif translationtype == "ermahgerd":
totranslate = self.trernslert(totranslate) totranslate = self.trernslert(totranslate)
@ -42,10 +42,10 @@ class Translate():
totranslate = self.text_one_to_zero_swap(totranslate) totranslate = self.text_one_to_zero_swap(totranslate)
elif translationtype == "upper": elif translationtype == "upper":
totranslate = spicemanip.main(totranslate, 0).upper() totranslate = spicemanip(totranslate, 0).upper()
elif translationtype == "lower": elif translationtype == "lower":
totranslate = spicemanip.main(totranslate, 0).lower() totranslate = spicemanip(totranslate, 0).lower()
return totranslate return totranslate
@ -66,7 +66,7 @@ class Translate():
else: else:
new_word = word[1:] + first + 'ay' new_word = word[1:] + first + 'ay'
rebuildarray.append(new_word) rebuildarray.append(new_word)
words = spicemanip.main(rebuildarray, 0) words = spicemanip(rebuildarray, 0)
return words return words
def trernslert(self, werds): def trernslert(self, werds):
@ -143,7 +143,7 @@ class Translate():
return "No input provided" return "No input provided"
if not isinstance(words, list): if not isinstance(words, list):
words = [words] words = [words]
words = spicemanip.main(words, 0).split(" ") words = spicemanip(words, 0).split(" ")
outputarray = [] outputarray = []
for word in words: for word in words:
if not self.isitbinary(word): if not self.isitbinary(word):
@ -152,7 +152,7 @@ class Translate():
word = str(word).replace('0', '1') word = str(word).replace('0', '1')
word = str(word).replace('2', '0') word = str(word).replace('2', '0')
outputarray.append(str(word)) outputarray.append(str(word))
outputarray = spicemanip.main(outputarray, 0) outputarray = spicemanip(outputarray, 0)
return outputarray return outputarray
def text_binary_swap(self, words): def text_binary_swap(self, words):
@ -160,16 +160,16 @@ class Translate():
return "No input provided" return "No input provided"
if not isinstance(words, list): if not isinstance(words, list):
words = [words] words = [words]
words = spicemanip.main(words, 0).split(" ") words = spicemanip(words, 0).split(" ")
outputarray = [] outputarray = []
for word in words: for word in words:
if self.isitbinary(word): if self.isitbinary(word):
word = self.bits2string(word) or 'error' word = self.bits2string(word) or 'error'
else: else:
word = self.string2bits(word) or 1 word = self.string2bits(word) or 1
word = spicemanip.main(word, 0) word = spicemanip(word, 0)
outputarray.append(str(word)) outputarray.append(str(word))
outputarray = spicemanip.main(outputarray, 0) outputarray = spicemanip(outputarray, 0)
return outputarray return outputarray
def unicode_string_cleanup(string): def unicode_string_cleanup(string):

View File

@ -8,7 +8,7 @@ from sopel.tools import Identifier
from .Database import db as botdb from .Database import db as botdb
from .Tools import is_number, inlist, similar, array_arrangesort from .Tools import is_number, inlist, similar, array_arrangesort
import spicemanip from sopel_modules.spicemanip import spicemanip
import threading import threading
import re import re
@ -393,13 +393,13 @@ class BotUsers():
sim_num.append(similarlevel) sim_num.append(similarlevel)
if sim_user != [] and sim_num != []: if sim_user != [] and sim_num != []:
sim_num, sim_user = array_arrangesort(bot, sim_num, sim_user) sim_num, sim_user = array_arrangesort(bot, sim_num, sim_user)
closestmatch = spicemanip.main(sim_user, 'reverse', "list") closestmatch = spicemanip(sim_user, 'reverse', "list")
listnumb, relist = 1, [] listnumb, relist = 1, []
for item in closestmatch: for item in closestmatch:
if listnumb <= 3: if listnumb <= 3:
relist.append(str(item)) relist.append(str(item))
listnumb += 1 listnumb += 1
closestmatches = spicemanip.main(relist, "andlist") closestmatches = spicemanip(relist, "andlist")
targetgooderror = "It looks like you're trying to target someone! Did you mean: " + str(closestmatches) + "?" targetgooderror = "It looks like you're trying to target someone! Did you mean: " + str(closestmatches) + "?"
else: else:
targetgooderror = "I am not sure who that is." targetgooderror = "I am not sure who that is."
@ -437,7 +437,7 @@ class BotUsers():
if outputtype == 'list': if outputtype == 'list':
return validtargs return validtargs
elif outputtype == 'random': elif outputtype == 'random':
return spicemanip.main(validtargs, 'random') return spicemanip(validtargs, 'random')
users = BotUsers() users = BotUsers()

View File

@ -6,7 +6,9 @@ import sopel.module
import sopel_modules.SpiceBot as SpiceBot import sopel_modules.SpiceBot as SpiceBot
import spicemanip from sopel_modules.spicemanip import spicemanip
# TODO split functionality for "no command"
@SpiceBot.prerun('nickname') @SpiceBot.prerun('nickname')
@ -59,7 +61,7 @@ def bot_command_rule_ai(bot, trigger):
command_type = 'nickname' command_type = 'nickname'
trigger_args, trigger_command, trigger_prefix = SpiceBot.make_trigger_args(message, 'nickname') trigger_args, trigger_command, trigger_prefix = SpiceBot.make_trigger_args(message, 'nickname')
trigger_args.insert(0, trigger_command) trigger_args.insert(0, trigger_command)
fulltrigger = bot.nick + " " + spicemanip.main(trigger_args, 0) fulltrigger = bot.nick + " " + spicemanip(trigger_args, 0)
if str(trigger_command).startswith(bot.config.SpiceBot_Commands.query_prefix): if str(trigger_command).startswith(bot.config.SpiceBot_Commands.query_prefix):
return return
if fulltrigger in SpiceBot.commands.dict['nickrules']: if fulltrigger in SpiceBot.commands.dict['nickrules']:
@ -73,7 +75,7 @@ def bot_command_rule_ai(bot, trigger):
command_type = 'module' command_type = 'module'
trigger_args, trigger_command, trigger_prefix = SpiceBot.make_trigger_args(message, 'module') trigger_args, trigger_command, trigger_prefix = SpiceBot.make_trigger_args(message, 'module')
trigger_args.insert(0, trigger_command) trigger_args.insert(0, trigger_command)
fulltrigger = spicemanip.main(trigger_args, 0) fulltrigger = spicemanip(trigger_args, 0)
# patch for people typing "...", maybe other stuff, but this verifies that there is still a command here # patch for people typing "...", maybe other stuff, but this verifies that there is still a command here
if trigger_command.startswith(tuple(bot.config.core.prefix_list)): if trigger_command.startswith(tuple(bot.config.core.prefix_list)):
return return
@ -82,11 +84,11 @@ def bot_command_rule_ai(bot, trigger):
return return
else: else:
command_type = 'other' command_type = 'other'
trigger_args = spicemanip.main(message, 'create') trigger_args = spicemanip(message, 'create')
if not len(trigger_args): if not len(trigger_args):
return return
trigger_command = trigger_args[0] trigger_command = trigger_args[0]
fulltrigger = spicemanip.main(trigger_args, 0) fulltrigger = spicemanip(trigger_args, 0)
returnmessage = SpiceBot.botai.on_message(bot, trigger, fulltrigger) returnmessage = SpiceBot.botai.on_message(bot, trigger, fulltrigger)
if returnmessage: if returnmessage:
@ -94,14 +96,13 @@ def bot_command_rule_ai(bot, trigger):
return return
if command_type == 'nickname': if command_type == 'nickname':
try_trigger = spicemanip.main(fulltrigger, "2+") try_trigger = spicemanip(fulltrigger, "2+")
returnmessage = SpiceBot.botai.on_message(bot, trigger, try_trigger) returnmessage = SpiceBot.botai.on_message(bot, trigger, try_trigger)
if returnmessage: if returnmessage:
bot.osd(str(returnmessage)) bot.osd(str(returnmessage))
return return
if command_type == 'module': if command_type == 'module':
return # TODO
if trigger_command not in commands_list: if trigger_command not in commands_list:
if not SpiceBot.letters_in_string(trigger_command): if not SpiceBot.letters_in_string(trigger_command):
return return
@ -116,7 +117,7 @@ def bot_command_rule_ai(bot, trigger):
if trigger_args[0].lower() in ["what", "where"] and trigger_args[1].lower() in ["is", "are"]: if trigger_args[0].lower() in ["what", "where"] and trigger_args[1].lower() in ["is", "are"]:
# TODO saved definitions # TODO saved definitions
searchterm = spicemanip.main(trigger_args, "3+") or None searchterm = spicemanip(trigger_args, "3+") or None
if searchterm: if searchterm:
if trigger_args[0].lower() == "where": if trigger_args[0].lower() == "where":
searchreturn = SpiceBot.google.search(searchterm, 'maps') searchreturn = SpiceBot.google.search(searchterm, 'maps')
@ -132,7 +133,7 @@ def bot_command_rule_ai(bot, trigger):
return return
elif trigger_args[0].lower() in ["can", "have"] and trigger_args[1].lower() in ["you"] and trigger_args[2].lower() in ["see", "seen"]: elif trigger_args[0].lower() in ["can", "have"] and trigger_args[1].lower() in ["you"] and trigger_args[2].lower() in ["see", "seen"]:
target = spicemanip.main(trigger_args, "4+") or None target = spicemanip(trigger_args, "4+") or None
if target: if target:
if SpiceBot.inlist(trigger.nick, bot.users): if SpiceBot.inlist(trigger.nick, bot.users):
realtarget = SpiceBot.inlist_match(target, bot.users) realtarget = SpiceBot.inlist_match(target, bot.users)
@ -141,7 +142,7 @@ def bot_command_rule_ai(bot, trigger):
for channel in list(bot.channels.keys()): for channel in list(bot.channels.keys()):
if SpiceBot.inlist(trigger.nick, list(bot.channels[channel].privileges.keys())): if SpiceBot.inlist(trigger.nick, list(bot.channels[channel].privileges.keys())):
targetchannels.append(channel) targetchannels.append(channel)
dispmsg.append(realtarget + " is in " + spicemanip.main(targetchannels, 'andlist')) dispmsg.append(realtarget + " is in " + spicemanip(targetchannels, 'andlist'))
bot.osd(dispmsg) bot.osd(dispmsg)
else: else:
bot.osd(trigger.nick + ", no. I cannot see " + target + " right now!") bot.osd(trigger.nick + ", no. I cannot see " + target + " right now!")
@ -164,7 +165,7 @@ def bot_command_rule_ai(bot, trigger):
for nonjedi in [bot.nick, trigger.nick]: for nonjedi in [bot.nick, trigger.nick]:
if nonjedi in jedilist: if nonjedi in jedilist:
jedilist.remove(nonjedi) jedilist.remove(nonjedi)
jedi = spicemanip.main(jedilist, 'random') jedi = spicemanip(jedilist, 'random')
if jedi: if jedi:
bot.osd("turns to " + jedi + " and shoots him.", trigger.sender, 'action') bot.osd("turns to " + jedi + " and shoots him.", trigger.sender, 'action')
@ -183,7 +184,7 @@ def bot_command_rule_ai(bot, trigger):
return return
elif fulltrigger.lower().startswith(tuple(["make me a", "beam me a"])): elif fulltrigger.lower().startswith(tuple(["make me a", "beam me a"])):
makemea = spicemanip.main(trigger_args, "4+") or None makemea = spicemanip(trigger_args, "4+") or None
if makemea: if makemea:
bot.osd("beams " + trigger.nick + " a " + makemea, trigger.sender, 'action') bot.osd("beams " + trigger.nick + " a " + makemea, trigger.sender, 'action')
else: else:
@ -191,7 +192,7 @@ def bot_command_rule_ai(bot, trigger):
return return
elif fulltrigger.lower().startswith("beam me to"): elif fulltrigger.lower().startswith("beam me to"):
location = spicemanip.main(trigger_args, "4+") or None location = spicemanip(trigger_args, "4+") or None
if location: if location:
bot.osd("locks onto " + trigger.nick + "s coordinates and transports them to " + location, 'action') bot.osd("locks onto " + trigger.nick + "s coordinates and transports them to " + location, 'action')
else: else:
@ -209,7 +210,7 @@ def bot_command_rule_ai(bot, trigger):
# TODO # TODO
# elif fulltrigger.lower().startswith(tuple(["have you seen"])): # elif fulltrigger.lower().startswith(tuple(["have you seen"])):
# posstarget = spicemanip.main(trigger_args, 4) or 0 # posstarget = spicemanip(trigger_args, 4) or 0
# message = seen_search(bot, trigger, posstarget) # message = seen_search(bot, trigger, posstarget)
# bot.osd(message) # bot.osd(message)
# return # return
@ -217,7 +218,7 @@ def bot_command_rule_ai(bot, trigger):
closestmatches = SpiceBot.similar_list(trigger_command, list(SpiceBot.commands.dict['commands']["nickname"].keys()), 3, 'reverse') closestmatches = SpiceBot.similar_list(trigger_command, list(SpiceBot.commands.dict['commands']["nickname"].keys()), 3, 'reverse')
if len(closestmatches): if len(closestmatches):
closestmatches = spicemanip.main(closestmatches, "andlist") closestmatches = spicemanip(closestmatches, "andlist")
bot.osd("I don't know what you are asking me to do! Did you mean: " + str(closestmatches) + "?") bot.osd("I don't know what you are asking me to do! Did you mean: " + str(closestmatches) + "?")
return return
else: else:

View File

@ -4,7 +4,7 @@ from __future__ import unicode_literals, absolute_import, division, print_functi
import sopel.module import sopel.module
import spicemanip from sopel_modules.spicemanip import spicemanip
import sopel_modules.SpiceBot as SpiceBot import sopel_modules.SpiceBot as SpiceBot
@ -12,19 +12,19 @@ import sopel_modules.SpiceBot as SpiceBot
@SpiceBot.prerun('nickname') @SpiceBot.prerun('nickname')
@sopel.module.nickname_commands('owners', 'owner') @sopel.module.nickname_commands('owners', 'owner')
def bot_command_owners(bot, trigger, botcom): def bot_command_owners(bot, trigger, botcom):
bot_command_process(bot, trigger) bot_command_process(bot, trigger, botcom)
@SpiceBot.prerun('nickname') @SpiceBot.prerun('nickname')
@sopel.module.nickname_commands('admins', 'admin') @sopel.module.nickname_commands('admins', 'admin')
def bot_command_admins(bot, trigger, botcom): def bot_command_admins(bot, trigger, botcom):
bot_command_process(bot, trigger) bot_command_process(bot, trigger, botcom)
def bot_command_process(bot, trigger): def bot_command_process(bot, trigger, botcom):
if not trigger.sb['com'].endswith("s"): if not botcom.dict['com'].endswith("s"):
trigger.sb['com'] = str(trigger.sb['com'] + "s") botcom.dict['com'] = str(botcom.dict['com'] + "s")
privlist = spicemanip.main(SpiceBot.bot_privs(trigger.sb['com']), 'andlist') privlist = spicemanip(SpiceBot.bot_privs(botcom.dict['com']), 'andlist')
bot.osd(str(bot.nick) + " " + trigger.sb['com'] + ": " + privlist) bot.osd(str(bot.nick) + " " + botcom.dict['com'] + ": " + privlist)

View File

@ -5,7 +5,7 @@ This is the SpiceBot Channels system.
""" """
import sopel import sopel
import spicemanip from sopel_modules.spicemanip import spicemanip
import sopel_modules.SpiceBot as SpiceBot import sopel_modules.SpiceBot as SpiceBot
@ -14,18 +14,18 @@ import sopel_modules.SpiceBot as SpiceBot
@sopel.module.nickname_commands('channels', 'channel') @sopel.module.nickname_commands('channels', 'channel')
def nickname_comand_channels(bot, trigger, botcom): def nickname_comand_channels(bot, trigger, botcom):
if not len(trigger.sb['args']): if not len(botcom.dict['args']):
commandused = 'list' commandused = 'list'
else: else:
commandused = spicemanip.main(trigger.sb['args'], 1).lower() commandused = spicemanip(botcom.dict['args'], 1).lower()
trigger.sb['args'] = spicemanip.main(trigger.sb['args'], '2+', 'list') botcom.dict['args'] = spicemanip(botcom.dict['args'], '2+', 'list')
if commandused == 'list': if commandused == 'list':
botcount = len(list(bot.channels.keys())) botcount = len(list(bot.channels.keys()))
servercount = len(list(SpiceBot.channels.dict['list'].keys())) servercount = len(list(SpiceBot.channels.dict['list'].keys()))
displayval = "I am in " + str(botcount) + " of " + str(servercount) + " channel(s) available on this server." displayval = "I am in " + str(botcount) + " of " + str(servercount) + " channel(s) available on this server."
chanlist = spicemanip.main(list(bot.channels.keys()), 'andlist') chanlist = spicemanip(list(bot.channels.keys()), 'andlist')
bot.osd([displayval, "You can find me in " + chanlist]) bot.osd([displayval, "You can find me in " + chanlist])
return return
@ -36,7 +36,7 @@ def nickname_comand_channels(bot, trigger, botcom):
return return
elif commandused == 'random': elif commandused == 'random':
channel = spicemanip.main(SpiceBot.channels.dict['list'], 'random') channel = spicemanip(SpiceBot.channels.dict['list'], 'random')
topic = SpiceBot.channels.dict['list'][channel]['topic'] topic = SpiceBot.channels.dict['list'][channel]['topic']
msg = ["Random channel for you: {}.".format(SpiceBot.channels.dict['list'][channel]['name'])] msg = ["Random channel for you: {}.".format(SpiceBot.channels.dict['list'][channel]['name'])]
if topic and not topic.isspace(): if topic and not topic.isspace():
@ -48,7 +48,7 @@ def nickname_comand_channels(bot, trigger, botcom):
elif commandused == 'update': elif commandused == 'update':
if not trigger.admin: if not trigger.admin:
SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], "You do not have permission to update the channel listing.") SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], "You do not have permission to update the channel listing.")
return return
SpiceBot.channels.bot_part_empty(bot) SpiceBot.channels.bot_part_empty(bot)
SpiceBot.channels.channel_list_request(bot) SpiceBot.channels.channel_list_request(bot)
@ -62,12 +62,12 @@ def nickname_comand_channels(bot, trigger, botcom):
return return
elif commandused == 'topic': elif commandused == 'topic':
if not len(trigger.sb['args']): if not len(botcom.dict['args']):
SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], "Channel name input missing.") SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], "Channel name input missing.")
return return
channel = spicemanip.main(trigger.sb['args'], 1) channel = spicemanip(botcom.dict['args'], 1)
if not SpiceBot.inlist(channel.lower(), list(SpiceBot.channels.dict['list'].keys())): if not SpiceBot.inlist(channel.lower(), list(SpiceBot.channels.dict['list'].keys())):
SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], "Channel name {} not valid.".format(channel)) SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], "Channel name {} not valid.".format(channel))
return return
topic = SpiceBot.channels.dict['list'][channel.lower()]['topic'] topic = SpiceBot.channels.dict['list'][channel.lower()]['topic']
channel = SpiceBot.channels.dict['list'][channel.lower()]['name'] channel = SpiceBot.channels.dict['list'][channel.lower()]['name']
@ -75,19 +75,19 @@ def nickname_comand_channels(bot, trigger, botcom):
return return
if commandused.upper() in ['OP', 'HOP', 'VOICE', 'OWNER', 'ADMIN']: if commandused.upper() in ['OP', 'HOP', 'VOICE', 'OWNER', 'ADMIN']:
if not len(trigger.sb['args']): if not len(botcom.dict['args']):
if trigger.is_privmsg: if trigger.is_privmsg:
SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], "Channel name required.") SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], "Channel name required.")
return return
else: else:
channel = trigger.sender channel = trigger.sender
else: else:
channel = spicemanip.main(trigger.sb['args'], 1) channel = spicemanip(botcom.dict['args'], 1)
if not SpiceBot.inlist(channel.lower(), list(SpiceBot.channels.dict['list'].keys())): if not SpiceBot.inlist(channel.lower(), list(SpiceBot.channels.dict['list'].keys())):
SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], "Channel name {} not valid.".format(channel)) SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], "Channel name {} not valid.".format(channel))
return return
if not SpiceBot.inlist(channel.lower(), list(bot.channels.keys())): if not SpiceBot.inlist(channel.lower(), list(bot.channels.keys())):
SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], "I need to be in {} to see nick privileges.".format(channel)) SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], "I need to be in {} to see nick privileges.".format(channel))
return return
privlist = SpiceBot.channel_privs(bot, channel, commandused.upper()) privlist = SpiceBot.channel_privs(bot, channel, commandused.upper())
@ -95,25 +95,25 @@ def nickname_comand_channels(bot, trigger, botcom):
if not len(privlist): if not len(privlist):
dispmsg.append("There are no Channel " + commandused.upper() + "s for " + str(channel)) dispmsg.append("There are no Channel " + commandused.upper() + "s for " + str(channel))
else: else:
oplist = spicemanip.main(privlist, 'andlist') oplist = spicemanip(privlist, 'andlist')
dispmsg.append("Channel " + commandused.upper() + "s for " + str(channel) + " are: " + oplist) dispmsg.append("Channel " + commandused.upper() + "s for " + str(channel) + " are: " + oplist)
bot.osd(dispmsg, trigger.nick, 'notice') bot.osd(dispmsg, trigger.nick, 'notice')
return return
# Users List # Users List
if commandused == 'users': if commandused == 'users':
channel = spicemanip.main(trigger.sb['args'], 1) channel = spicemanip(botcom.dict['args'], 1)
if not SpiceBot.inlist(channel.lower(), list(SpiceBot.channels.dict['list'].keys())): if not SpiceBot.inlist(channel.lower(), list(SpiceBot.channels.dict['list'].keys())):
SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], "Channel name {} not valid.".format(channel)) SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], "Channel name {} not valid.".format(channel))
return return
if not SpiceBot.inlist(channel.lower(), list(bot.channels.keys())): if not SpiceBot.inlist(channel.lower(), list(bot.channels.keys())):
SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], "I need to be in {} to see user list.".format(channel)) SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], "I need to be in {} to see user list.".format(channel))
return return
dispmsg = [] dispmsg = []
if not len(list(bot.channels[channel].privileges.keys())): if not len(list(bot.channels[channel].privileges.keys())):
dispmsg.append("There are no Channel users for " + str(channel)) dispmsg.append("There are no Channel users for " + str(channel))
else: else:
userslist = spicemanip.main(list(bot.channels[channel].privileges.keys()), 'andlist') userslist = spicemanip(list(bot.channels[channel].privileges.keys()), 'andlist')
dispmsg.append("Channel users for " + str(channel) + " are: " + userslist) dispmsg.append("Channel users for " + str(channel) + " are: " + userslist)
bot.osd(dispmsg, trigger.nick, 'notice') bot.osd(dispmsg, trigger.nick, 'notice')
return return

View File

@ -7,7 +7,7 @@ This Class stores commands in an easy to access manner
""" """
import sopel import sopel
import spicemanip from sopel_modules.spicemanip import spicemanip
import sopel_modules.SpiceBot as SpiceBot import sopel_modules.SpiceBot as SpiceBot
@ -18,10 +18,10 @@ import sopel_modules.SpiceBot as SpiceBot
@sopel.module.nickname_commands('commands', 'command') @sopel.module.nickname_commands('commands', 'command')
def nickname_comand_commands(bot, trigger, botcom): def nickname_comand_commands(bot, trigger, botcom):
if not len(trigger.sb['args']): if not len(botcom.dict['args']):
commandused = 'list' commandused = 'list'
else: else:
commandused = spicemanip.main(trigger.sb['args'], 1).lower() commandused = spicemanip(botcom.dict['args'], 1).lower()
if commandused == 'list': if commandused == 'list':
availablecomsnum, availablecomsfiles = 0, [] availablecomsnum, availablecomsfiles = 0, []
@ -52,5 +52,5 @@ def nickname_comand_commands(bot, trigger, botcom):
return return
if commandused == 'random': if commandused == 'random':
bot.osd(["Here's a random command for you:", spicemanip.main(commands_list, 'random')]) bot.osd(["Here's a random command for you:", spicemanip(commands_list, 'random')])
return return

View File

@ -7,7 +7,7 @@ This Class stores commands in an easy to access manner
""" """
import sopel import sopel
import spicemanip from sopel_modules.spicemanip import spicemanip
import sopel_modules.SpiceBot as SpiceBot import sopel_modules.SpiceBot as SpiceBot
@ -23,14 +23,14 @@ def query_trigger(bot, trigger, botcom):
def query_detection_nick(bot, trigger, botcom): def query_detection_nick(bot, trigger, botcom):
# command issued, check if valid # command issued, check if valid
if not trigger.sb['com'] or not len(trigger.sb['com']): if not botcom.dict['com'] or not len(botcom.dict['com']):
return return
if not trigger.sb['com'][0] == bot.config.SpiceBot_Commands.query_prefix: if not botcom.dict['com'][0] == bot.config.SpiceBot_Commands.query_prefix:
return return
trigger.sb['com'] = trigger.sb['com'][1:] botcom.dict['com'] = botcom.dict['com'][1:]
if not SpiceBot.letters_in_string(trigger.sb['com']): if not SpiceBot.letters_in_string(botcom.dict['com']):
return return
commands_list = dict() commands_list = dict()
@ -38,49 +38,49 @@ def query_detection_nick(bot, trigger, botcom):
if com not in list(commands_list.keys()): if com not in list(commands_list.keys()):
commands_list[com] = SpiceBot.commands.dict['commands']['nickname'][com] commands_list[com] = SpiceBot.commands.dict['commands']['nickname'][com]
if trigger.sb['com'].endswith("+"): if botcom.dict['com'].endswith("+"):
trigger.sb['com'] = trigger.sb['com'][:-1] botcom.dict['com'] = botcom.dict['com'][:-1]
if not trigger.sb['com'] or not len(trigger.sb['com']): if not botcom.dict['com'] or not len(botcom.dict['com']):
return return
if trigger.sb['com'].lower() not in list(commands_list.keys()): if botcom.dict['com'].lower() not in list(commands_list.keys()):
dispmsg = ["Cannot find any alias " + bot.nick + " commands: No valid commands match " + str(trigger.sb['com']) + "."] dispmsg = ["Cannot find any alias " + bot.nick + " commands: No valid commands match " + str(botcom.dict['com']) + "."]
closestmatches = SpiceBot.similar_list(trigger.sb['com'], list(commands_list.keys()), 10, 'reverse') closestmatches = SpiceBot.similar_list(botcom.dict['com'], list(commands_list.keys()), 10, 'reverse')
if len(closestmatches): if len(closestmatches):
dispmsg.append("The following " + bot.nick + " commands match " + str(trigger.sb['com']) + ": " + spicemanip.main(closestmatches, 'andlist') + ".") dispmsg.append("The following " + bot.nick + " commands match " + str(botcom.dict['com']) + ": " + spicemanip(closestmatches, 'andlist') + ".")
bot.osd(dispmsg, trigger.nick, 'notice') bot.osd(dispmsg, trigger.nick, 'notice')
return return
realcom = trigger.sb['com'] realcom = botcom.dict['com']
if "aliasfor" in list(commands_list[trigger.sb['com']].keys()): if "aliasfor" in list(commands_list[botcom.dict['com']].keys()):
realcom = commands_list[trigger.sb['com']]["aliasfor"] realcom = commands_list[botcom.dict['com']]["aliasfor"]
validcomlist = commands_list[realcom]["validcoms"] validcomlist = commands_list[realcom]["validcoms"]
bot.osd("The following " + bot.nick + " commands match " + str(trigger.sb['com']) + ": " + spicemanip.main(validcomlist, 'andlist') + ".", trigger.nick, 'notice') bot.osd("The following " + bot.nick + " commands match " + str(botcom.dict['com']) + ": " + spicemanip(validcomlist, 'andlist') + ".", trigger.nick, 'notice')
return return
if trigger.sb['com'].endswith(bot.config.SpiceBot_Commands.query_prefix): if botcom.dict['com'].endswith(bot.config.SpiceBot_Commands.query_prefix):
trigger.sb['com'] = trigger.sb['com'][:-1] botcom.dict['com'] = botcom.dict['com'][:-1]
if not trigger.sb['com'] or not len(trigger.sb['com']): if not botcom.dict['com'] or not len(botcom.dict['com']):
return return
closestmatches = SpiceBot.similar_list(trigger.sb['com'], list(commands_list.keys()), 10, 'reverse') closestmatches = SpiceBot.similar_list(botcom.dict['com'], list(commands_list.keys()), 10, 'reverse')
if not len(closestmatches): if not len(closestmatches):
bot.osd("Cannot find any similar " + bot.nick + " commands for " + str(trigger.sb['com']) + ".", trigger.nick, 'notice') bot.osd("Cannot find any similar " + bot.nick + " commands for " + str(botcom.dict['com']) + ".", trigger.nick, 'notice')
else: else:
bot.osd("The following " + bot.nick + " commands may match " + str(trigger.sb['com']) + ": " + spicemanip.main(closestmatches, 'andlist') + ".", trigger.nick, 'notice') bot.osd("The following " + bot.nick + " commands may match " + str(botcom.dict['com']) + ": " + spicemanip(closestmatches, 'andlist') + ".", trigger.nick, 'notice')
return return
commandlist = [] commandlist = []
for command in list(commands_list.keys()): for command in list(commands_list.keys()):
if command.lower().startswith(str(trigger.sb['com']).lower()): if command.lower().startswith(str(botcom.dict['com']).lower()):
commandlist.append(command) commandlist.append(command)
if not len(commandlist): if not len(commandlist):
bot.osd("No " + bot.nick + " commands start with " + str(trigger.sb['com']) + ".", trigger.nick, 'notice') bot.osd("No " + bot.nick + " commands start with " + str(botcom.dict['com']) + ".", trigger.nick, 'notice')
else: else:
bot.osd("The following " + bot.nick + " commands start with " + str(trigger.sb['com']) + ": " + spicemanip.main(commandlist, 'andlist') + ".", trigger.nick, 'notice') bot.osd("The following " + bot.nick + " commands start with " + str(botcom.dict['com']) + ": " + spicemanip(commandlist, 'andlist') + ".", trigger.nick, 'notice')
@SpiceBot.prerun_query('module', 'module') @SpiceBot.prerun_query('module', 'module')
@ -88,10 +88,10 @@ def query_detection_nick(bot, trigger, botcom):
def query_detection(bot, trigger, botcom): def query_detection(bot, trigger, botcom):
# command issued, check if valid # command issued, check if valid
if not trigger.sb['com'] or not len(trigger.sb['com']): if not botcom.dict['com'] or not len(botcom.dict['com']):
return return
if not SpiceBot.letters_in_string(trigger.sb['com']): if not SpiceBot.letters_in_string(botcom.dict['com']):
return return
commands_list = dict() commands_list = dict()
@ -101,46 +101,46 @@ def query_detection(bot, trigger, botcom):
if com not in list(commands_list.keys()): if com not in list(commands_list.keys()):
commands_list[com] = SpiceBot.commands.dict['commands'][commandstype][com] commands_list[com] = SpiceBot.commands.dict['commands'][commandstype][com]
if trigger.sb['com'][:-1] == "+": if botcom.dict['com'][:-1] == "+":
trigger.sb['com'] = trigger.sb['com'][:-1] botcom.dict['com'] = botcom.dict['com'][:-1]
if not trigger.sb['com'] or not len(trigger.sb['com']): if not botcom.dict['com'] or not len(botcom.dict['com']):
return return
if trigger.sb['com'].lower() not in list(commands_list.keys()): if botcom.dict['com'].lower() not in list(commands_list.keys()):
dispmsg = ["Cannot find any alias commands: No valid commands match " + str(trigger.sb['com']) + "."] dispmsg = ["Cannot find any alias commands: No valid commands match " + str(botcom.dict['com']) + "."]
closestmatches = SpiceBot.similar_list(trigger.sb['com'], list(commands_list.keys()), 10, 'reverse') closestmatches = SpiceBot.similar_list(botcom.dict['com'], list(commands_list.keys()), 10, 'reverse')
if len(closestmatches): if len(closestmatches):
dispmsg.append("The following commands match " + str(trigger.sb['com']) + ": " + spicemanip.main(closestmatches, 'andlist') + ".") dispmsg.append("The following commands match " + str(botcom.dict['com']) + ": " + spicemanip(closestmatches, 'andlist') + ".")
bot.osd(dispmsg, trigger.nick, 'notice') bot.osd(dispmsg, trigger.nick, 'notice')
return return
realcom = trigger.sb['com'] realcom = botcom.dict['com']
if "aliasfor" in list(commands_list[trigger.sb['com']].keys()): if "aliasfor" in list(commands_list[botcom.dict['com']].keys()):
realcom = commands_list[trigger.sb['com']]["aliasfor"] realcom = commands_list[botcom.dict['com']]["aliasfor"]
validcomlist = commands_list[realcom]["validcoms"] validcomlist = commands_list[realcom]["validcoms"]
bot.osd("The following commands match " + str(trigger.sb['com']) + ": " + spicemanip.main(validcomlist, 'andlist') + ".", trigger.nick, 'notice') bot.osd("The following commands match " + str(botcom.dict['com']) + ": " + spicemanip(validcomlist, 'andlist') + ".", trigger.nick, 'notice')
return return
if trigger.sb['com'][:-1] == "?": if botcom.dict['com'][:-1] == "?":
trigger.sb['com'] = trigger.sb['com'][:-1] botcom.dict['com'] = botcom.dict['com'][:-1]
if not trigger.sb['com'] or not len(trigger.sb['com']): if not botcom.dict['com'] or not len(botcom.dict['com']):
return return
closestmatches = SpiceBot.similar_list(trigger.sb['com'], list(commands_list.keys()), 10, 'reverse') closestmatches = SpiceBot.similar_list(botcom.dict['com'], list(commands_list.keys()), 10, 'reverse')
if not len(closestmatches): if not len(closestmatches):
bot.osd("Cannot find any similar commands for " + str(trigger.sb['com']) + ".", trigger.nick, 'notice') bot.osd("Cannot find any similar commands for " + str(botcom.dict['com']) + ".", trigger.nick, 'notice')
else: else:
bot.osd("The following commands may match " + str(trigger.sb['com']) + ": " + spicemanip.main(closestmatches, 'andlist') + ".", trigger.nick, 'notice') bot.osd("The following commands may match " + str(botcom.dict['com']) + ": " + spicemanip(closestmatches, 'andlist') + ".", trigger.nick, 'notice')
return return
commandlist = [] commandlist = []
for command in list(commands_list.keys()): for command in list(commands_list.keys()):
if command.lower().startswith(str(trigger.sb['com']).lower()): if command.lower().startswith(str(botcom.dict['com']).lower()):
commandlist.append(command) commandlist.append(command)
if not len(commandlist): if not len(commandlist):
bot.osd("No commands start with " + str(trigger.sb['com']) + ".", trigger.nick, 'notice') bot.osd("No commands start with " + str(botcom.dict['com']) + ".", trigger.nick, 'notice')
else: else:
bot.osd("The following commands start with " + str(trigger.sb['com']) + ": " + spicemanip.main(commandlist, 'andlist') + ".", trigger.nick, 'notice') bot.osd("The following commands start with " + str(botcom.dict['com']) + ": " + spicemanip(commandlist, 'andlist') + ".", trigger.nick, 'notice')

View File

@ -9,7 +9,7 @@ import sopel.module
import sopel_modules.SpiceBot as SpiceBot import sopel_modules.SpiceBot as SpiceBot
import spicemanip from sopel_modules.spicemanip import spicemanip
from word2number import w2n from word2number import w2n
from random import randint from random import randint
@ -20,78 +20,78 @@ import time
@sopel.module.commands('(.*)') @sopel.module.commands('(.*)')
def command_dictcom(bot, trigger, botcom): def command_dictcom(bot, trigger, botcom):
if trigger.sb['com'] not in list(SpiceBot.commands.dict['commands']["dictcom"].keys()): if botcom.dict['com'] not in list(SpiceBot.commands.dict['commands']["dictcom"].keys()):
return return
bot_dictcom_process(bot, trigger) bot_dictcom_process(bot, trigger, botcom)
return return
time.time() time.time()
def bot_dictcom_process(bot, trigger): def bot_dictcom_process(bot, trigger, botcom):
# use the default key, unless otherwise specified # use the default key, unless otherwise specified
trigger.sb["responsekey"] = "?default" botcom.dict["responsekey"] = "?default"
# handling for special cases # handling for special cases
posscom = spicemanip.main(trigger.sb['args'], 1) posscom = spicemanip(botcom.dict['args'], 1)
if posscom.lower() in [command.lower() for command in trigger.sb["dict"].keys()]: if posscom.lower() in [command.lower() for command in list(botcom.dict["dict"].keys())]:
for command in trigger.sb["dict"].keys(): for command in botcom.dict["dict"].keys():
if command.lower() == posscom.lower(): if command.lower() == posscom.lower():
posscom = command posscom = command
trigger.sb["responsekey"] = posscom botcom.dict["responsekey"] = posscom
trigger.sb['args'] = spicemanip.main(trigger.sb['args'], '2+', 'list') botcom.dict['args'] = spicemanip(botcom.dict['args'], '2+', 'list')
trigger.sb["dict"][trigger.sb["responsekey"]]["type"] = trigger.sb["dict"][trigger.sb["responsekey"]]["type"] botcom.dict["dict"][botcom.dict["responsekey"]]["type"] = botcom.dict["dict"][botcom.dict["responsekey"]]["type"]
trigger.sb["nonstockoptions"] = [] botcom.dict["nonstockoptions"] = []
for command in trigger.sb["dict"].keys(): for command in list(botcom.dict["dict"].keys()):
if command not in ["?default", "validcoms", "type", "hardcoded_channel_block"]: if command not in ["?default", "validcoms", "type", "hardcoded_channel_block"]:
trigger.sb["nonstockoptions"].append(command) botcom.dict["nonstockoptions"].append(command)
# This allows users to specify which reply by number by using an ! and a digit (first or last in string) # This allows users to specify which reply by number by using an ! and a digit (first or last in string)
validspecifides = ['last', 'random', 'count', 'view', 'add', 'del', 'remove', 'special'] validspecifides = ['last', 'random', 'count', 'view', 'add', 'del', 'remove', 'special']
trigger.sb["specified"] = None botcom.dict["specified"] = None
argone = spicemanip.main(trigger.sb['args'], 1) argone = spicemanip(botcom.dict['args'], 1)
if str(argone).startswith("--") and len(str(argone)) > 2: if str(argone).startswith("--") and len(str(argone)) > 2:
if str(argone[2:]).isdigit(): if str(argone[2:]).isdigit():
trigger.sb["specified"] = int(argone[2:]) botcom.dict["specified"] = int(argone[2:])
elif SpiceBot.inlist(str(argone[2:]), validspecifides): elif SpiceBot.inlist(str(argone[2:]), validspecifides):
trigger.sb["specified"] = str(argone[2:]).lower() botcom.dict["specified"] = str(argone[2:]).lower()
elif SpiceBot.inlist(str(argone[2:]), trigger.sb["nonstockoptions"]): elif SpiceBot.inlist(str(argone[2:]), botcom.dict["nonstockoptions"]):
trigger.sb["specified"] = str(argone[2:]).lower() botcom.dict["specified"] = str(argone[2:]).lower()
trigger.sb["responsekey"] = trigger.sb["specified"] botcom.dict["responsekey"] = botcom.dict["specified"]
else: else:
try: try:
trigger.sb["specified"] = w2n.word_to_num(str(argone[1:])) botcom.dict["specified"] = w2n.word_to_num(str(argone[1:]))
trigger.sb["specified"] = int(trigger.sb["specified"]) botcom.dict["specified"] = int(botcom.dict["specified"])
except ValueError: except ValueError:
trigger.sb["specified"] = None botcom.dict["specified"] = None
if trigger.sb["specified"]: if botcom.dict["specified"]:
trigger.sb['args'] = spicemanip.main(trigger.sb['args'], '2+', 'list') botcom.dict['args'] = spicemanip(botcom.dict['args'], '2+', 'list')
# commands that can be updated # commands that can be updated
if trigger.sb["dict"][trigger.sb["responsekey"]]["updates_enabled"]: if botcom.dict["dict"][botcom.dict["responsekey"]]["updates_enabled"]:
if trigger.sb["dict"][trigger.sb["responsekey"]]["updates_enabled"] == "shared": if botcom.dict["dict"][botcom.dict["responsekey"]]["updates_enabled"] == "shared":
SpiceBot.dictcoms.adjust_nick_array(str(SpiceBot.config.nick), 'sayings', trigger.sb["realcom"] + "_" + str(trigger.sb["responsekey"]), trigger.sb["dict"][trigger.sb["responsekey"]]["responses"], 'startup') SpiceBot.dictcoms.adjust_nick_array(str(SpiceBot.config.nick), 'sayings', botcom.dict["realcom"] + "_" + str(botcom.dict["responsekey"]), botcom.dict["dict"][botcom.dict["responsekey"]]["responses"], 'startup')
trigger.sb["dict"][trigger.sb["responsekey"]]["responses"] = SpiceBot.db.get_nick_value(str(bot.nick), trigger.sb["dict"]["validcoms"][0] + "_" + str(trigger.sb["responsekey"]), 'sayings') or [] botcom.dict["dict"][botcom.dict["responsekey"]]["responses"] = SpiceBot.db.get_nick_value(str(bot.nick), botcom.dict["dict"]["validcoms"][0] + "_" + str(botcom.dict["responsekey"]), 'sayings') or []
elif trigger.sb["dict"][trigger.sb["responsekey"]]["updates_enabled"] == "user": elif botcom.dict["dict"][botcom.dict["responsekey"]]["updates_enabled"] == "user":
SpiceBot.dictcoms.adjust_nick_array(str(trigger.nick), 'sayings', trigger.sb["realcom"] + "_" + str(trigger.sb["responsekey"]), trigger.sb["dict"][trigger.sb["responsekey"]]["responses"], 'startup') SpiceBot.dictcoms.adjust_nick_array(str(trigger.nick), 'sayings', botcom.dict["realcom"] + "_" + str(botcom.dict["responsekey"]), botcom.dict["dict"][botcom.dict["responsekey"]]["responses"], 'startup')
trigger.sb["dict"][trigger.sb["responsekey"]]["responses"] = SpiceBot.db.get_nick_value(str(trigger.nick), trigger.sb["dict"]["validcoms"][0] + "_" + str(trigger.sb["responsekey"]), 'sayings') or [] botcom.dict["dict"][botcom.dict["responsekey"]]["responses"] = SpiceBot.db.get_nick_value(str(trigger.nick), botcom.dict["dict"]["validcoms"][0] + "_" + str(botcom.dict["responsekey"]), 'sayings') or []
if trigger.sb["specified"] == 'special': if botcom.dict["specified"] == 'special':
nonstockoptions = spicemanip.main(trigger.sb["nonstockoptions"], "andlist") nonstockoptions = spicemanip(botcom.dict["nonstockoptions"], "andlist")
return bot.osd("The special options for " + str(trigger.sb["realcom"]) + " command include: " + str(nonstockoptions) + ".") return bot.osd("The special options for " + str(botcom.dict["realcom"]) + " command include: " + str(nonstockoptions) + ".")
elif trigger.sb["specified"] == 'count': elif botcom.dict["specified"] == 'count':
return bot.osd("The " + str(trigger.sb["realcom"]) + " " + str(trigger.sb["responsekey"] or '') + " command has " + str(len(trigger.sb["dict"][trigger.sb["responsekey"]]["responses"])) + " entries.") return bot.osd("The " + str(botcom.dict["realcom"]) + " " + str(botcom.dict["responsekey"] or '') + " command has " + str(len(botcom.dict["dict"][botcom.dict["responsekey"]]["responses"])) + " entries.")
elif trigger.sb["specified"] == 'view': elif botcom.dict["specified"] == 'view':
if trigger.sb["dict"][trigger.sb["responsekey"]]["responses"] == []: if botcom.dict["dict"][botcom.dict["responsekey"]]["responses"] == []:
return bot.osd("The " + str(trigger.sb["realcom"]) + " " + str(trigger.sb["responsekey"] or '') + " command appears to have no entries!") return bot.osd("The " + str(botcom.dict["realcom"]) + " " + str(botcom.dict["responsekey"] or '') + " command appears to have no entries!")
else: else:
bot.osd("The " + str(trigger.sb["realcom"]) + " " + str(trigger.sb["responsekey"] or '') + " command contains:", trigger.nick, 'notice') bot.osd("The " + str(botcom.dict["realcom"]) + " " + str(botcom.dict["responsekey"] or '') + " command contains:", trigger.nick, 'notice')
listnumb, relist = 1, [] listnumb, relist = 1, []
for item in trigger.sb["dict"][trigger.sb["responsekey"]]["responses"]: for item in botcom.dict["dict"][botcom.dict["responsekey"]]["responses"]:
if isinstance(item, dict): if isinstance(item, dict):
relist.append(str("[#" + str(listnumb) + "] COMPLEX dict Entry")) relist.append(str("[#" + str(listnumb) + "] COMPLEX dict Entry"))
elif isinstance(item, list): elif isinstance(item, list):
@ -101,143 +101,143 @@ def bot_dictcom_process(bot, trigger):
bot.osd(relist, trigger.nick) bot.osd(relist, trigger.nick)
return return
elif trigger.sb["specified"] == 'add': elif botcom.dict["specified"] == 'add':
if not trigger.sb["dict"][trigger.sb["responsekey"]]["updates_enabled"]: if not botcom.dict["dict"][botcom.dict["responsekey"]]["updates_enabled"]:
return bot.osd("The " + str(trigger.sb["realcom"]) + " " + str(trigger.sb["responsekey"] or '') + " entry list cannot be updated.") return bot.osd("The " + str(botcom.dict["realcom"]) + " " + str(botcom.dict["responsekey"] or '') + " entry list cannot be updated.")
fulltext = spicemanip.main(trigger.sb['args'], 0) fulltext = spicemanip(botcom.dict['args'], 0)
if not fulltext: if not fulltext:
return bot.osd("What would you like to add to the " + str(trigger.sb["realcom"]) + " " + str(trigger.sb["responsekey"] or '') + " entry list?") return bot.osd("What would you like to add to the " + str(botcom.dict["realcom"]) + " " + str(botcom.dict["responsekey"] or '') + " entry list?")
if fulltext in trigger.sb["dict"][trigger.sb["responsekey"]]["responses"]: if fulltext in botcom.dict["dict"][botcom.dict["responsekey"]]["responses"]:
return bot.osd("The following was already in the " + str(trigger.sb["realcom"]) + " " + str(trigger.sb["responsekey"] or '') + " entry list: '" + str(fulltext) + "'") return bot.osd("The following was already in the " + str(botcom.dict["realcom"]) + " " + str(botcom.dict["responsekey"] or '') + " entry list: '" + str(fulltext) + "'")
if trigger.sb["dict"][trigger.sb["responsekey"]]["updates_enabled"] == "shared": if botcom.dict["dict"][botcom.dict["responsekey"]]["updates_enabled"] == "shared":
SpiceBot.dictcoms.adjust_nick_array(str(bot.nick), 'sayings', trigger.sb["realcom"] + "_" + str(trigger.sb["responsekey"]), fulltext, trigger.sb["specified"]) SpiceBot.dictcoms.adjust_nick_array(str(bot.nick), 'sayings', botcom.dict["realcom"] + "_" + str(botcom.dict["responsekey"]), fulltext, botcom.dict["specified"])
elif trigger.sb["dict"][trigger.sb["responsekey"]]["updates_enabled"] == "user": elif botcom.dict["dict"][botcom.dict["responsekey"]]["updates_enabled"] == "user":
SpiceBot.dictcoms.adjust_nick_array(str(trigger.nick), 'sayings', trigger.sb["realcom"] + "_" + str(trigger.sb["responsekey"]), fulltext, trigger.sb["specified"]) SpiceBot.dictcoms.adjust_nick_array(str(trigger.nick), 'sayings', botcom.dict["realcom"] + "_" + str(botcom.dict["responsekey"]), fulltext, botcom.dict["specified"])
return bot.osd("The following was added to the " + str(trigger.sb["realcom"]) + " " + str(trigger.sb["responsekey"] or '') + " entry list: '" + str(fulltext) + "'") return bot.osd("The following was added to the " + str(botcom.dict["realcom"]) + " " + str(botcom.dict["responsekey"] or '') + " entry list: '" + str(fulltext) + "'")
elif trigger.sb["specified"] in ['del', 'remove']: elif botcom.dict["specified"] in ['del', 'remove']:
if not trigger.sb["dict"][trigger.sb["responsekey"]]["updates_enabled"]: if not botcom.dict["dict"][botcom.dict["responsekey"]]["updates_enabled"]:
return bot.osd("The " + str(trigger.sb["realcom"]) + " " + str(trigger.sb["responsekey"] or '') + " entry list cannot be updated.") return bot.osd("The " + str(botcom.dict["realcom"]) + " " + str(botcom.dict["responsekey"] or '') + " entry list cannot be updated.")
fulltext = spicemanip.main(trigger.sb['args'], 0) fulltext = spicemanip(botcom.dict['args'], 0)
if not fulltext: if not fulltext:
return bot.osd("What would you like to remove from the " + str(trigger.sb["realcom"]) + " " + str(trigger.sb["responsekey"] or '') + " entry list?") return bot.osd("What would you like to remove from the " + str(botcom.dict["realcom"]) + " " + str(botcom.dict["responsekey"] or '') + " entry list?")
if fulltext not in trigger.sb["dict"][trigger.sb["responsekey"]]["responses"]: if fulltext not in botcom.dict["dict"][botcom.dict["responsekey"]]["responses"]:
return bot.osd("The following was already not in the " + str(trigger.sb["realcom"]) + " " + str(trigger.sb["responsekey"] or '') + " entry list: '" + str(fulltext) + "'") return bot.osd("The following was already not in the " + str(botcom.dict["realcom"]) + " " + str(botcom.dict["responsekey"] or '') + " entry list: '" + str(fulltext) + "'")
if trigger.sb["dict"][trigger.sb["responsekey"]]["updates_enabled"] == "shared": if botcom.dict["dict"][botcom.dict["responsekey"]]["updates_enabled"] == "shared":
SpiceBot.dictcoms.adjust_nick_array(str(bot.nick), 'sayings', trigger.sb["realcom"] + "_" + str(trigger.sb["responsekey"]), fulltext, trigger.sb["specified"]) SpiceBot.dictcoms.adjust_nick_array(str(bot.nick), 'sayings', botcom.dict["realcom"] + "_" + str(botcom.dict["responsekey"]), fulltext, botcom.dict["specified"])
elif trigger.sb["dict"][trigger.sb["responsekey"]]["updates_enabled"] == "user": elif botcom.dict["dict"][botcom.dict["responsekey"]]["updates_enabled"] == "user":
SpiceBot.dictcoms.adjust_nick_array(str(trigger.nick), 'sayings', trigger.sb["realcom"] + "_" + str(trigger.sb["responsekey"]), fulltext, trigger.sb["specified"]) SpiceBot.dictcoms.adjust_nick_array(str(trigger.nick), 'sayings', botcom.dict["realcom"] + "_" + str(botcom.dict["responsekey"]), fulltext, botcom.dict["specified"])
return bot.osd("The following was removed from the " + str(trigger.sb["realcom"]) + " " + str(trigger.sb["responsekey"] or '') + " entry list: '" + str(fulltext) + "'") return bot.osd("The following was removed from the " + str(botcom.dict["realcom"]) + " " + str(botcom.dict["responsekey"] or '') + " entry list: '" + str(fulltext) + "'")
elif trigger.sb["specified"] and not trigger.sb["dict"][trigger.sb["responsekey"]]["selection_allowed"]: elif botcom.dict["specified"] and not botcom.dict["dict"][botcom.dict["responsekey"]]["selection_allowed"]:
return bot.osd("The " + str(trigger.sb["realcom"]) + " " + str(trigger.sb["responsekey"] or '') + " response list cannot be specified.") return bot.osd("The " + str(botcom.dict["realcom"]) + " " + str(botcom.dict["responsekey"] or '') + " response list cannot be specified.")
trigger.sb["target"] = False botcom.dict["target"] = False
trigger.sb["success"] = True botcom.dict["success"] = True
if trigger.sb["dict"][trigger.sb["responsekey"]]["type"] in ['simple', 'fillintheblank', "target", 'targetplusreason', 'sayings', "readfromfile", "readfromurl", "ascii_art", "translate", "responses"]: if botcom.dict["dict"][botcom.dict["responsekey"]]["type"] in ['simple', 'fillintheblank', "target", 'targetplusreason', 'sayings', "readfromfile", "readfromurl", "ascii_art", "translate", "responses"]:
return bot_dictcom_responses(bot, trigger) return bot_dictcom_responses(bot, trigger, botcom)
else: else:
command_function_run = str('bot_dictcom_' + trigger.sb["dict"][trigger.sb["responsekey"]]["type"] + '(bot, trigger)') command_function_run = str('bot_dictcom_' + botcom.dict["dict"][botcom.dict["responsekey"]]["type"] + '(bot, trigger, botcom)')
eval(command_function_run) eval(command_function_run)
def bot_dictcom_responses(bot, trigger): def bot_dictcom_responses(bot, trigger, botcom):
commandrunconsensus = [] commandrunconsensus = []
reaction = False reaction = False
# A target is required # A target is required
if trigger.sb["dict"][trigger.sb["responsekey"]]["target_required"]: if botcom.dict["dict"][botcom.dict["responsekey"]]["target_required"]:
# try first term as a target # try first term as a target
posstarget = spicemanip.main(trigger.sb['args'], 1) or 0 posstarget = spicemanip(botcom.dict['args'], 1) or 0
targetbypass = trigger.sb["dict"][trigger.sb["responsekey"]]["target_bypass"] targetbypass = botcom.dict["dict"][botcom.dict["responsekey"]]["target_bypass"]
targetchecking = SpiceBot.users.target_check(bot, trigger, posstarget, targetbypass) targetchecking = SpiceBot.users.target_check(bot, trigger, posstarget, targetbypass)
if not targetchecking["targetgood"]: if not targetchecking["targetgood"]:
if trigger.sb["dict"][trigger.sb["responsekey"]]["target_backup"]: if botcom.dict["dict"][botcom.dict["responsekey"]]["target_backup"]:
trigger.sb["target"] = trigger.sb["dict"][trigger.sb["responsekey"]]["target_backup"] botcom.dict["target"] = botcom.dict["dict"][botcom.dict["responsekey"]]["target_backup"]
if trigger.sb["target"] == 'instigator': if botcom.dict["target"] == 'instigator':
trigger.sb["target"] = trigger.nick botcom.dict["target"] = trigger.nick
elif trigger.sb["target"] == 'random': elif botcom.dict["target"] == 'random':
trigger.sb["target"] = SpiceBot.users.random_valid_target(bot, trigger, 'random') botcom.dict["target"] = SpiceBot.users.random_valid_target(bot, trigger, 'random')
else: else:
for reason in ['self', 'bot', 'bots', 'offline', 'unknown', 'privmsg', 'diffchannel', 'diffbot']: for reason in ['self', 'bot', 'bots', 'offline', 'unknown', 'privmsg', 'diffchannel', 'diffbot']:
if targetchecking["reason"] == reason and trigger.sb["dict"][trigger.sb["responsekey"]]["react_"+reason]: if targetchecking["reason"] == reason and botcom.dict["dict"][botcom.dict["responsekey"]]["react_"+reason]:
reaction = True reaction = True
commandrunconsensus.append(trigger.sb["dict"][trigger.sb["responsekey"]]["react_"+reason]) commandrunconsensus.append(botcom.dict["dict"][botcom.dict["responsekey"]]["react_"+reason])
if not reaction: if not reaction:
commandrunconsensus.append([targetchecking["error"]]) commandrunconsensus.append([targetchecking["error"]])
else: else:
trigger.sb["target"] = spicemanip.main(trigger.sb['args'], 1) botcom.dict["target"] = spicemanip(botcom.dict['args'], 1)
trigger.sb['args'] = spicemanip.main(trigger.sb['args'], '2+', 'list') botcom.dict['args'] = spicemanip(botcom.dict['args'], '2+', 'list')
# $blank input # $blank input
trigger.sb["completestring"] = spicemanip.main(trigger.sb['args'], 0) or '' botcom.dict["completestring"] = spicemanip(botcom.dict['args'], 0) or ''
if trigger.sb["dict"][trigger.sb["responsekey"]]["blank_required"]: if botcom.dict["dict"][botcom.dict["responsekey"]]["blank_required"]:
if trigger.sb["completestring"] == '' or not trigger.sb["completestring"]: if botcom.dict["completestring"] == '' or not botcom.dict["completestring"]:
if trigger.sb["dict"][trigger.sb["responsekey"]]["blank_backup"]: if botcom.dict["dict"][botcom.dict["responsekey"]]["blank_backup"]:
trigger.sb["completestring"] = trigger.sb["dict"][trigger.sb["responsekey"]]["blank_backup"] botcom.dict["completestring"] = botcom.dict["dict"][botcom.dict["responsekey"]]["blank_backup"]
else: else:
commandrunconsensus.append(trigger.sb["dict"][trigger.sb["responsekey"]]["blank_fail"]) commandrunconsensus.append(botcom.dict["dict"][botcom.dict["responsekey"]]["blank_fail"])
if trigger.sb["dict"][trigger.sb["responsekey"]]["blank_phrasehandle"]: if botcom.dict["dict"][botcom.dict["responsekey"]]["blank_phrasehandle"]:
if trigger.sb["dict"][trigger.sb["responsekey"]]["blank_phrasehandle"] != []: if botcom.dict["dict"][botcom.dict["responsekey"]]["blank_phrasehandle"] != []:
if spicemanip.main(trigger.sb["completestring"], 1).lower() not in trigger.sb["dict"][trigger.sb["responsekey"]]["blank_phrasehandle"]: if spicemanip(botcom.dict["completestring"], 1).lower() not in botcom.dict["dict"][botcom.dict["responsekey"]]["blank_phrasehandle"]:
trigger.sb["completestring"] = trigger.sb["dict"][trigger.sb["responsekey"]]["blank_phrasehandle"][0] + " " + trigger.sb["completestring"] botcom.dict["completestring"] = botcom.dict["dict"][botcom.dict["responsekey"]]["blank_phrasehandle"][0] + " " + botcom.dict["completestring"]
elif spicemanip.main(trigger.sb["completestring"], 1).lower() in trigger.sb["dict"][trigger.sb["responsekey"]]["blank_phrasehandle"]: elif spicemanip(botcom.dict["completestring"], 1).lower() in botcom.dict["dict"][botcom.dict["responsekey"]]["blank_phrasehandle"]:
if spicemanip.main(trigger.sb["completestring"], 1).lower() != trigger.sb["dict"][trigger.sb["responsekey"]]["blank_phrasehandle"][0]: if spicemanip(botcom.dict["completestring"], 1).lower() != botcom.dict["dict"][botcom.dict["responsekey"]]["blank_phrasehandle"][0]:
trigger.sb['args'] = spicemanip.main(trigger.sb['args'], '2+', 'list') botcom.dict['args'] = spicemanip(botcom.dict['args'], '2+', 'list')
if trigger.sb['args'] != []: if botcom.dict['args'] != []:
trigger.sb["completestring"] = trigger.sb["dict"][trigger.sb["responsekey"]]["blank_phrasehandle"][0] + " " + spicemanip.main(trigger.sb['args'], 0) botcom.dict["completestring"] = botcom.dict["dict"][botcom.dict["responsekey"]]["blank_phrasehandle"][0] + " " + spicemanip(botcom.dict['args'], 0)
if commandrunconsensus != []: if commandrunconsensus != []:
trigger.sb["success"] = False botcom.dict["success"] = False
if trigger.sb["dict"][trigger.sb["responsekey"]]["response_fail"] and not reaction: if botcom.dict["dict"][botcom.dict["responsekey"]]["response_fail"] and not reaction:
trigger.sb["dict"][trigger.sb["responsekey"]]["responses"] = trigger.sb["dict"][trigger.sb["responsekey"]]["response_fail"] botcom.dict["dict"][botcom.dict["responsekey"]]["responses"] = botcom.dict["dict"][botcom.dict["responsekey"]]["response_fail"]
else: else:
trigger.sb["dict"][trigger.sb["responsekey"]]["responses"] = commandrunconsensus[0] botcom.dict["dict"][botcom.dict["responsekey"]]["responses"] = commandrunconsensus[0]
bot_dictcom_reply_shared(bot, trigger) bot_dictcom_reply_shared(bot, trigger, botcom)
def bot_dictcom_reply_shared(bot, trigger): def bot_dictcom_reply_shared(bot, trigger, botcom):
if trigger.sb["specified"]: if botcom.dict["specified"]:
if trigger.sb["specified"] > len(trigger.sb["dict"][trigger.sb["responsekey"]]["responses"]): if botcom.dict["specified"] > len(botcom.dict["dict"][botcom.dict["responsekey"]]["responses"]):
currentspecified = len(trigger.sb["dict"][trigger.sb["responsekey"]]["responses"]) currentspecified = len(botcom.dict["dict"][botcom.dict["responsekey"]]["responses"])
else: else:
currentspecified = trigger.sb["specified"] currentspecified = botcom.dict["specified"]
trigger.sb["replies"] = spicemanip.main(trigger.sb["dict"][trigger.sb["responsekey"]]["responses"], currentspecified, 'return') botcom.dict["replies"] = spicemanip(botcom.dict["dict"][botcom.dict["responsekey"]]["responses"], currentspecified, 'return')
trigger.sb["replynum"] = currentspecified botcom.dict["replynum"] = currentspecified
else: else:
trigger.sb["replies"] = spicemanip.main(trigger.sb["dict"][trigger.sb["responsekey"]]["responses"], 'random', 'return') botcom.dict["replies"] = spicemanip(botcom.dict["dict"][botcom.dict["responsekey"]]["responses"], 'random', 'return')
try: try:
trigger.sb["replynum"] = trigger.sb["dict"][trigger.sb["responsekey"]]["responses"].index(trigger.sb["replies"]) botcom.dict["replynum"] = botcom.dict["dict"][botcom.dict["responsekey"]]["responses"].index(botcom.dict["replies"])
except Exception as e: except Exception as e:
trigger.sb["replynum"] = e botcom.dict["replynum"] = e
trigger.sb["replynum"] = 0 botcom.dict["replynum"] = 0
trigger.sb["replynum"] += 1 botcom.dict["replynum"] += 1
trigger.sb["totalreplies"] = len(trigger.sb["dict"][trigger.sb["responsekey"]]["responses"]) botcom.dict["totalreplies"] = len(botcom.dict["dict"][botcom.dict["responsekey"]]["responses"])
# This handles responses in list form # This handles responses in list form
if not isinstance(trigger.sb["replies"], list): if not isinstance(botcom.dict["replies"], list):
trigger.sb["replies"] = [trigger.sb["replies"]] botcom.dict["replies"] = [botcom.dict["replies"]]
for rply in trigger.sb["replies"]: for rply in botcom.dict["replies"]:
# replies that can be evaluated as code # replies that can be evaluated as code
if rply.startswith("time.sleep"): if rply.startswith("time.sleep"):
@ -246,31 +246,31 @@ def bot_dictcom_reply_shared(bot, trigger):
# random number # random number
if "$randnum" in rply: if "$randnum" in rply:
if trigger.sb["dict"][trigger.sb["responsekey"]]["randnum"]: if botcom.dict["dict"][botcom.dict["responsekey"]]["randnum"]:
randno = randint(trigger.sb["dict"][trigger.sb["responsekey"]]["randnum"][0], trigger.sb["dict"][trigger.sb["responsekey"]]["randnum"][1]) randno = randint(botcom.dict["dict"][botcom.dict["responsekey"]]["randnum"][0], botcom.dict["dict"][botcom.dict["responsekey"]]["randnum"][1])
else: else:
randno = randint(0, 50) randno = randint(0, 50)
rply = rply.replace("$randnum", str(randno)) rply = rply.replace("$randnum", str(randno))
# blank # blank
if "$blank" in rply: if "$blank" in rply:
rply = rply.replace("$blank", trigger.sb["completestring"] or '') rply = rply.replace("$blank", botcom.dict["completestring"] or '')
# the remaining input # the remaining input
if "$input" in rply: if "$input" in rply:
rply = rply.replace("$input", spicemanip.main(trigger.sb['args'], 0) or trigger.sb["realcom"]) rply = rply.replace("$input", spicemanip(botcom.dict['args'], 0) or botcom.dict["realcom"])
# translation # translation
if trigger.sb["dict"][trigger.sb["responsekey"]]["translations"]: if botcom.dict["dict"][botcom.dict["responsekey"]]["translations"]:
rply = SpiceBot.translate.bot_translate_process(rply, trigger.sb["dict"][trigger.sb["responsekey"]]["translations"]) rply = SpiceBot.translate.bot_translate_process(rply, botcom.dict["dict"][botcom.dict["responsekey"]]["translations"])
# text to precede the output # text to precede the output
if trigger.sb["dict"][trigger.sb["responsekey"]]["prefixtext"] and trigger.sb["success"]: if botcom.dict["dict"][botcom.dict["responsekey"]]["prefixtext"] and botcom.dict["success"]:
rply = spicemanip.main(trigger.sb["dict"][trigger.sb["responsekey"]]["prefixtext"], 'random') + rply rply = spicemanip(botcom.dict["dict"][botcom.dict["responsekey"]]["prefixtext"], 'random') + rply
# text to follow the output # text to follow the output
if trigger.sb["dict"][trigger.sb["responsekey"]]["suffixtext"] and trigger.sb["success"]: if botcom.dict["dict"][botcom.dict["responsekey"]]["suffixtext"] and botcom.dict["success"]:
rply = rply + spicemanip.main(trigger.sb["dict"][trigger.sb["responsekey"]]["suffixtext"], 'random') rply = rply + spicemanip(botcom.dict["dict"][botcom.dict["responsekey"]]["suffixtext"], 'random')
# trigger.nick # trigger.nick
if "$instigator" in rply: if "$instigator" in rply:
@ -279,7 +279,7 @@ def bot_dictcom_reply_shared(bot, trigger):
# random user # random user
if "$randuser" in rply: if "$randuser" in rply:
if not trigger.is_privmsg: if not trigger.is_privmsg:
randuser = spicemanip.main(SpiceBot.users.random_valid_target(trigger, 'random')) randuser = spicemanip(SpiceBot.users.random_valid_target(trigger, 'random'))
else: else:
randuser = trigger.nick randuser = trigger.nick
rply = rply.replace("$randuser", randuser) rply = rply.replace("$randuser", randuser)
@ -294,7 +294,7 @@ def bot_dictcom_reply_shared(bot, trigger):
# target # target
if "$target" in rply: if "$target" in rply:
targetnames = trigger.sb["target"] or '' targetnames = botcom.dict["target"] or ''
if "$targets" in rply: if "$targets" in rply:
if targetnames.lower() == "your": if targetnames.lower() == "your":
targetnames = targetnames targetnames = targetnames
@ -309,26 +309,26 @@ def bot_dictcom_reply_shared(bot, trigger):
# smaller variations for the text # smaller variations for the text
if "$replyvariation" in rply: if "$replyvariation" in rply:
if trigger.sb["dict"][trigger.sb["responsekey"]]["replyvariation"] != []: if botcom.dict["dict"][botcom.dict["responsekey"]]["replyvariation"] != []:
variation = spicemanip.main(trigger.sb["dict"][trigger.sb["responsekey"]]["replyvariation"], 'random') variation = spicemanip(botcom.dict["dict"][botcom.dict["responsekey"]]["replyvariation"], 'random')
rply = rply.replace("$replyvariation", variation) rply = rply.replace("$replyvariation", variation)
else: else:
rply = rply.replace("$replyvariation", '') rply = rply.replace("$replyvariation", '')
# smaller variations for the text # smaller variations for the text
if "$responsekey" in rply: if "$responsekey" in rply:
rply = rply.replace("$responsekey", str(trigger.sb["responsekey"])) rply = rply.replace("$responsekey", str(botcom.dict["responsekey"]))
if "$index" in rply: if "$index" in rply:
rply = rply.replace("$index", str(str(trigger.sb["replynum"]) + "/" + str(trigger.sb["totalreplies"]))) rply = rply.replace("$index", str(str(botcom.dict["replynum"]) + "/" + str(botcom.dict["totalreplies"])))
# display special options for this command # display special options for this command
if "$specialoptions" in rply: if "$specialoptions" in rply:
nonstockoptions = [] nonstockoptions = []
for command in trigger.sb["dict"].keys(): for command in list(botcom.dict["dict"].keys()):
if command not in ["?default", "validcoms", "contributors", "author", "type", "filepath", "filename", "hardcoded_channel_block", "description", "exampleresponse", "example", "usage", "privs"]: if command not in ["?default", "validcoms", "contributors", "author", "type", "filepath", "filename", "hardcoded_channel_block", "description", "exampleresponse", "example", "usage", "privs"]:
nonstockoptions.append(command) nonstockoptions.append(command)
nonstockoptions = spicemanip.main(nonstockoptions, "andlist") nonstockoptions = spicemanip(nonstockoptions, "andlist")
rply = rply.replace("$specialoptions", nonstockoptions) rply = rply.replace("$specialoptions", nonstockoptions)
# saying, or action? # saying, or action?
@ -341,28 +341,28 @@ def bot_dictcom_reply_shared(bot, trigger):
bot.osd(rply, trigger.sender, rplytype) bot.osd(rply, trigger.sender, rplytype)
def bot_dictcom_gif(bot, trigger): def bot_dictcom_gif(bot, trigger, botcom):
if trigger.sb["dict"][trigger.sb["responsekey"]]["blank_required"] and not trigger.sb["completestring"]: if botcom.dict["dict"][botcom.dict["responsekey"]]["blank_required"] and not botcom.dict["completestring"]:
trigger.sb["dict"][trigger.sb["responsekey"]]["responses"] = trigger.sb["dict"][trigger.sb["responsekey"]]["blank_fail"] botcom.dict["dict"][botcom.dict["responsekey"]]["responses"] = botcom.dict["dict"][botcom.dict["responsekey"]]["blank_fail"]
return bot_dictcom_reply_shared(bot, trigger) return bot_dictcom_reply_shared(bot, trigger, botcom)
elif trigger.sb["dict"][trigger.sb["responsekey"]]["blank_required"] and trigger.sb["completestring"]: elif botcom.dict["dict"][botcom.dict["responsekey"]]["blank_required"] and botcom.dict["completestring"]:
queries = [trigger.sb["completestring"]] queries = [botcom.dict["completestring"]]
else: else:
queries = trigger.sb["dict"][trigger.sb["responsekey"]]["responses"] queries = botcom.dict["dict"][botcom.dict["responsekey"]]["responses"]
# which api's are we using to search # which api's are we using to search
if "queryapi" in trigger.sb["dict"].keys(): if "queryapi" in list(botcom.dict["dict"].keys()):
searchapis = trigger.sb["dict"][trigger.sb["responsekey"]]["queryapi"] searchapis = botcom.dict["dict"][botcom.dict["responsekey"]]["queryapi"]
else: else:
searchapis = list(SpiceBot.gif.valid_api.keys()) searchapis = list(SpiceBot.gif.valid_api.keys())
if trigger.sb["specified"]: if botcom.dict["specified"]:
if trigger.sb["specified"] > len(queries): if botcom.dict["specified"] > len(queries):
trigger.sb["specified"] = len(queries) botcom.dict["specified"] = len(queries)
query = spicemanip.main(queries, trigger.sb["specified"], 'return') query = spicemanip(queries, botcom.dict["specified"], 'return')
else: else:
query = spicemanip.main(queries, 'random', 'return') query = spicemanip(queries, 'random', 'return')
searchdict = {"query": query, "gifsearch": searchapis} searchdict = {"query": query, "gifsearch": searchapis}
@ -374,18 +374,18 @@ def bot_dictcom_gif(bot, trigger):
gifdict = SpiceBot.gif.get_gif(searchdict) gifdict = SpiceBot.gif.get_gif(searchdict)
if gifdict["error"]: if gifdict["error"]:
trigger.sb["success"] = False botcom.dict["success"] = False
if trigger.sb["dict"][trigger.sb["responsekey"]]["search_fail"]: if botcom.dict["dict"][botcom.dict["responsekey"]]["search_fail"]:
gifdict["error"] = trigger.sb["dict"][trigger.sb["responsekey"]]["search_fail"] gifdict["error"] = botcom.dict["dict"][botcom.dict["responsekey"]]["search_fail"]
trigger.sb["dict"][trigger.sb["responsekey"]]["responses"] = [gifdict["error"]] botcom.dict["dict"][botcom.dict["responsekey"]]["responses"] = [gifdict["error"]]
else: else:
trigger.sb["dict"][trigger.sb["responsekey"]]["responses"] = [str(gifdict['gifapi'].title() + " Result (" + str(query) + " #" + str(gifdict["returnnum"]) + "): " + str(gifdict["returnurl"]))] botcom.dict["dict"][botcom.dict["responsekey"]]["responses"] = [str(gifdict['gifapi'].title() + " Result (" + str(query) + " #" + str(gifdict["returnnum"]) + "): " + str(gifdict["returnurl"]))]
trigger.sb["specified"] = False botcom.dict["specified"] = False
bot_dictcom_reply_shared(bot, trigger) bot_dictcom_reply_shared(bot, trigger, botcom)
def bot_dictcom_feeds(bot, trigger): def bot_dictcom_feeds(bot, trigger, botcom):
return bot.osd("WIP") return bot.osd("WIP")
""" """
@ -394,7 +394,7 @@ def bot_dictcom_feeds(bot, trigger):
bot_startup_requirements_set(bot, "feeds") bot_startup_requirements_set(bot, "feeds")
feed = trigger.sb["dict"][trigger.sb["responsekey"]]["responses"][0] feed = botcom.dict["dict"][botcom.dict["responsekey"]]["responses"][0]
if feed not in bot.memory['feeds'].keys(): if feed not in bot.memory['feeds'].keys():
return bot.osd(feed + " does not appear to be a valid feed.") return bot.osd(feed + " does not appear to be a valid feed.")
@ -407,5 +407,5 @@ def bot_dictcom_feeds(bot, trigger):
""" """
def bot_dictcom_search(bot, trigger): def bot_dictcom_search(bot, trigger, botcom):
bot.say("testing done") bot.say("testing done")

View File

@ -7,7 +7,7 @@ This is the SpiceBot Logs System
# sopel imports # sopel imports
import sopel.module import sopel.module
import spicemanip from sopel_modules.spicemanip import spicemanip
import sopel_modules.SpiceBot as SpiceBot import sopel_modules.SpiceBot as SpiceBot
@ -17,20 +17,20 @@ import sopel_modules.SpiceBot as SpiceBot
def bot_command_logs(bot, trigger, botcom): def bot_command_logs(bot, trigger, botcom):
if not SpiceBot.command_permissions_check(bot, trigger, ['admins', 'owner', 'OP', 'ADMIN', 'OWNER']): if not SpiceBot.command_permissions_check(bot, trigger, ['admins', 'owner', 'OP', 'ADMIN', 'OWNER']):
SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], "I was unable to process this Bot Nick command due to privilege issues.") SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], "I was unable to process this Bot Nick command due to privilege issues.")
return return
logtype = spicemanip.main(trigger.sb['args'], 1) or None logtype = spicemanip(botcom.dict['args'], 1) or None
if not logtype: if not logtype:
bot.osd("Current valid log(s) include: " + spicemanip.main(list(SpiceBot.logs.dict["list"].keys()), 'andlist'), trigger.sender, 'action') bot.osd("Current valid log(s) include: " + spicemanip(list(SpiceBot.logs.dict["list"].keys()), 'andlist'), trigger.sender, 'action')
return return
if not SpiceBot.inlist(logtype, list(SpiceBot.logs.dict["list"].keys())): if not SpiceBot.inlist(logtype, list(SpiceBot.logs.dict["list"].keys())):
closestmatches = SpiceBot.similar_list(logtype, list(SpiceBot.logs.dict["list"].keys()), 10, 'reverse') closestmatches = SpiceBot.similar_list(logtype, list(SpiceBot.logs.dict["list"].keys()), 10, 'reverse')
if not len(closestmatches): if not len(closestmatches):
SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], "No valid logs match " + str(logtype) + ".", trigger.nick, 'notice') SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], "No valid logs match " + str(logtype) + ".", trigger.nick, 'notice')
else: else:
SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], "The following commands may match " + str(logtype) + ": " + spicemanip.main(closestmatches, 'andlist') + ".", trigger.nick, 'notice') SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], "The following commands may match " + str(logtype) + ": " + spicemanip(closestmatches, 'andlist') + ".", trigger.nick, 'notice')
return return
@ -39,7 +39,7 @@ def bot_command_logs(bot, trigger, botcom):
logindex = SpiceBot.logs.get_logs(logtype) logindex = SpiceBot.logs.get_logs(logtype)
if not len(logindex): if not len(logindex):
SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], "No logs found for " + str(logtype) + ".") SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], "No logs found for " + str(logtype) + ".")
return return
bot.osd("Is Examining " + str(logtype) + " log(s).") bot.osd("Is Examining " + str(logtype) + " log(s).")

View File

@ -4,7 +4,7 @@ from __future__ import unicode_literals, absolute_import, division, print_functi
import sopel.module import sopel.module
import spicemanip from sopel_modules.spicemanip import spicemanip
import sopel_modules.SpiceBot as SpiceBot import sopel_modules.SpiceBot as SpiceBot
@ -12,42 +12,42 @@ import sopel_modules.SpiceBot as SpiceBot
@SpiceBot.prerun('nickname') @SpiceBot.prerun('nickname')
@sopel.module.nickname_commands('action') @sopel.module.nickname_commands('action')
def bot_command_action(bot, trigger, botcom): def bot_command_action(bot, trigger, botcom):
bot_command_process(bot, trigger) bot_command_process(bot, trigger, botcom)
@SpiceBot.prerun('nickname') @SpiceBot.prerun('nickname')
@sopel.module.nickname_commands('notice') @sopel.module.nickname_commands('notice')
def bot_command_notice(bot, trigger, botcom): def bot_command_notice(bot, trigger, botcom):
bot_command_process(bot, trigger) bot_command_process(bot, trigger, botcom)
@SpiceBot.prerun('nickname') @SpiceBot.prerun('nickname')
@sopel.module.nickname_commands('privmsg', 'say', 'msg') @sopel.module.nickname_commands('privmsg', 'say', 'msg')
def bot_command_privmsg(bot, trigger, botcom): def bot_command_privmsg(bot, trigger, botcom):
bot_command_process(bot, trigger) bot_command_process(bot, trigger, botcom)
def bot_command_process(bot, trigger): def bot_command_process(bot, trigger, botcom):
if not SpiceBot.command_permissions_check(bot, trigger, ['admins', 'owner']): if not SpiceBot.command_permissions_check(bot, trigger, ['admins', 'owner']):
SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], "I was unable to process this Bot Nick command due to privilege issues.") SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], "I was unable to process this Bot Nick command due to privilege issues.")
return return
if trigger.sb['com'] in ['say', 'msg']: if botcom.dict['com'] in ['say', 'msg']:
trigger.sb['com'] = 'privmsg' botcom.dict['com'] = 'privmsg'
if not len(trigger.sb['args']): if not len(botcom.dict['args']):
SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], "You must specify a channel or nick.") SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], "You must specify a channel or nick.")
return return
target = spicemanip.main(trigger.sb['args'], 1) target = spicemanip(botcom.dict['args'], 1)
if (target not in ['allchans', 'allnicks'] if (target not in ['allchans', 'allnicks']
and not SpiceBot.inlist(target.lower(), list(SpiceBot.channels.dict['list'].keys())) and not SpiceBot.inlist(target.lower(), list(SpiceBot.channels.dict['list'].keys()))
and not SpiceBot.inlist(target.lower(), bot.users)): and not SpiceBot.inlist(target.lower(), bot.users)):
SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], "Channel/nick name {} not valid.".format(target)) SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], "Channel/nick name {} not valid.".format(target))
return return
trigger.sb['args'] = spicemanip.main(trigger.sb['args'], '2+', 'list') botcom.dict['args'] = spicemanip(botcom.dict['args'], '2+', 'list')
if target == 'allchans': if target == 'allchans':
targetsendlist = list(bot.channels.keys()) targetsendlist = list(bot.channels.keys())
@ -56,9 +56,9 @@ def bot_command_process(bot, trigger):
else: else:
targetsendlist = [target] targetsendlist = [target]
botmessage = spicemanip.main(trigger.sb['args'], 0) botmessage = spicemanip(botcom.dict['args'], 0)
if not botmessage: if not botmessage:
SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], "You must specify a message to send.") SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], "You must specify a message to send.")
return return
bot.osd(botmessage, targetsendlist, trigger.sb['com'].upper()) bot.osd(botmessage, targetsendlist, botcom.dict['com'].upper())

View File

@ -4,7 +4,7 @@ from __future__ import unicode_literals, absolute_import, division, print_functi
import sopel.module import sopel.module
import spicemanip from sopel_modules.spicemanip import spicemanip
import sopel_modules.SpiceBot as SpiceBot import sopel_modules.SpiceBot as SpiceBot
@ -14,19 +14,19 @@ import sopel_modules.SpiceBot as SpiceBot
def nickname_comand_update(bot, trigger, botcom): def nickname_comand_update(bot, trigger, botcom):
if not SpiceBot.command_permissions_check(bot, trigger, ['admins', 'owner', 'OP', 'ADMIN', 'OWNER']): if not SpiceBot.command_permissions_check(bot, trigger, ['admins', 'owner', 'OP', 'ADMIN', 'OWNER']):
SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], "I was unable to process this Bot Nick command due to privilege issues.") SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], "I was unable to process this Bot Nick command due to privilege issues.")
return return
if not len(trigger.sb['args']): if not len(botcom.dict['args']):
commandused = 'nodeps' commandused = 'nodeps'
else: else:
commandused = spicemanip.main(trigger.sb['args'], 1).lower() commandused = spicemanip(botcom.dict['args'], 1).lower()
if commandused not in ['deps', 'nodeps']: if commandused not in ['deps', 'nodeps']:
SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], "Please specify deps or nodeps") SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], "Please specify deps or nodeps")
return return
trigger.sb['args'] = spicemanip.main(trigger.sb['args'], '2+', 'list') botcom.dict['args'] = spicemanip(botcom.dict['args'], '2+', 'list')
quitmessage = "Received command from " + trigger.nick + " to update from Github and restart" quitmessage = "Received command from " + trigger.nick + " to update from Github and restart"
SpiceBot.logs.log('SpiceBot_Update', quitmessage) SpiceBot.logs.log('SpiceBot_Update', quitmessage)
@ -46,7 +46,7 @@ def nickname_comand_update(bot, trigger, botcom):
def nickname_comand_restart(bot, trigger, botcom): def nickname_comand_restart(bot, trigger, botcom):
if not trigger.admin: if not trigger.admin:
SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], "You are not authorized to perform this function.") SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], "You are not authorized to perform this function.")
quitmessage = "Received command from " + trigger.nick + " to restart. Be Back Soon!" quitmessage = "Received command from " + trigger.nick + " to restart. Be Back Soon!"
SpiceBot.logs.log('SpiceBot_Restart', quitmessage) SpiceBot.logs.log('SpiceBot_Restart', quitmessage)

View File

@ -0,0 +1,16 @@
# coding=utf8
from __future__ import unicode_literals, absolute_import, division, print_function
"""
This is the SpiceBot Users system.
"""
import sopel
import sopel_modules.SpiceBot as SpiceBot
from sopel_modules.spicemanip import spicemanip
@SpiceBot.prerun('nickname')
@sopel.module.nickname_commands('todo')
def nickname_comand_users(bot, trigger, botcom):
todo_task = spicemanip(SpiceBot.commands.todo_list, 'random')
bot.osd(["Random TODO task for you: {}.".format(todo_task)])

View File

@ -19,12 +19,9 @@ from .Runtime_Controls import *
from .Messaging import * from .Messaging import *
from .Docs import * from .Docs import *
from .BotPrivs import * from .BotPrivs import *
from .Search import *
from .AI import * from .AI import *
from .Gif import *
from .Sherlock import *
from .Reddit import *
from .DictComs import * from .DictComs import *
from .TODO import *
__author__ = 'Sam Zick' __author__ = 'Sam Zick'
__email__ = 'sam@deathbybandaid.net' __email__ = 'sam@deathbybandaid.net'

View File

@ -0,0 +1,9 @@
# coding=utf8
from __future__ import unicode_literals, absolute_import, division, print_function
# pylama:ignore=W0401,W0611
from .flip import *
__author__ = 'Sam Zick'
__email__ = 'sam@deathbybandaid.net'
__version__ = '0.1.1'

View File

@ -0,0 +1,34 @@
# coding=utf-8
from __future__ import unicode_literals, absolute_import, division, print_function
import sopel.module
# import sopel_modules.SpiceBot as SpiceBot
# from sopel_modules.spicemanip import spicemanip
from upsidedown import transform
# TODO add upsidedown to spicemanip
@sopel.module.rule('^flips (.+)')
@sopel.module.intent('ACTION')
def flips(bot, trigger):
target = trigger.group(1).strip()
if target == 'a table':
bot.say("(╯°□°)╯︵ ┻━┻")
else:
bot.say("(╯°□°)╯︵ %s" % transform(target))
@sopel.module.rule('^rolls (.+)')
@sopel.module.intent('ACTION')
def roll(bot, trigger):
target = trigger.group(1).strip()
if target.endswith(' down a hill'):
target = target[:-12]
tegrat = transform(target)
bot.say("(╮°-°)╯︵ %s %s %s %s %s (@_@;)" % (tegrat, target, tegrat, target, tegrat))
else:
bot.say("(╮°-°)╯︵ %s" % transform(target))

View File

@ -7,7 +7,7 @@ import sopel
import time import time
import spicemanip from sopel_modules.spicemanip import spicemanip
import sopel_modules.SpiceBot as SpiceBot import sopel_modules.SpiceBot as SpiceBot
@ -86,7 +86,7 @@ def trigger_channel_list_recurring(bot, trigger):
if "*" in newlist: if "*" in newlist:
newlist.remove("*") newlist.remove("*")
if len(newlist) and SpiceBot.config.SpiceBot_Channels.announcenew: if len(newlist) and SpiceBot.config.SpiceBot_Channels.announcenew:
bot.osd(["The Following channel(s) are new:", spicemanip.main(newlist, 'andlist')], list(bot.channels.keys())) bot.osd(["The Following channel(s) are new:", spicemanip(newlist, 'andlist')], list(bot.channels.keys()))
SpiceBot.channels.join_all_channels(bot) SpiceBot.channels.join_all_channels(bot)

View File

@ -6,7 +6,7 @@ import sopel.module
import sopel_modules.SpiceBot as SpiceBot import sopel_modules.SpiceBot as SpiceBot
import spicemanip from sopel_modules.spicemanip import spicemanip
# TODO custom gif shortcut commands # TODO custom gif shortcut commands
@ -15,17 +15,17 @@ import spicemanip
@sopel.module.commands('gif') @sopel.module.commands('gif')
def gif_trigger(bot, trigger, botcom): def gif_trigger(bot, trigger, botcom):
if not len(trigger.sb['args']): if not len(botcom.dict['args']):
return SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], "Please present a query to search.") return SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], "Please present a query to search.")
query = spicemanip.main(trigger.sb['args'], 0) query = spicemanip(botcom.dict['args'], 0)
searchapis = list(SpiceBot.gif.valid_api.keys()) searchapis = list(SpiceBot.gif.valid_api.keys())
searchdict = {"query": query, "gifsearch": searchapis} searchdict = {"query": query, "gifsearch": searchapis}
gifdict = SpiceBot.gif.get_gif(searchdict) gifdict = SpiceBot.gif.get_gif(searchdict)
if gifdict["error"]: if gifdict["error"]:
SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], gifdict["error"]) SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], gifdict["error"])
else: else:
bot.osd(str(gifdict['gifapi'].title() + " Result (" + str(query) + " #" + str(gifdict["returnnum"]) + "): " + str(gifdict["returnurl"]))) bot.osd(str(gifdict['gifapi'].title() + " Result (" + str(query) + " #" + str(gifdict["returnnum"]) + "): " + str(gifdict["returnurl"])))
@ -34,18 +34,18 @@ def gif_trigger(bot, trigger, botcom):
@sopel.module.commands('(.*)') @sopel.module.commands('(.*)')
def gifapi_triggers(bot, trigger, botcom): def gifapi_triggers(bot, trigger, botcom):
if trigger.sb['com'] not in list(SpiceBot.gif.valid_api.keys()): if botcom.dict['com'] not in list(SpiceBot.gif.valid_api.keys()):
return return
if not len(trigger.sb['args']): if not len(botcom.dict['args']):
return SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], "Please present a query to search.") return SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], "Please present a query to search.")
query = spicemanip.main(trigger.sb['args'], 0) query = spicemanip(botcom.dict['args'], 0)
searchdict = {"query": query, "gifsearch": trigger.sb['com']} searchdict = {"query": query, "gifsearch": botcom.dict['com']}
gifdict = SpiceBot.gif.get_gif(searchdict) gifdict = SpiceBot.gif.get_gif(searchdict)
if gifdict["error"]: if gifdict["error"]:
SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], gifdict["error"]) SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], gifdict["error"])
else: else:
bot.osd(str(gifdict['gifapi'].title() + " Result (" + str(query) + " #" + str(gifdict["returnnum"]) + "): " + str(gifdict["returnurl"]))) bot.osd(str(gifdict['gifapi'].title() + " Result (" + str(query) + " #" + str(gifdict["returnnum"]) + "): " + str(gifdict["returnurl"])))

View File

@ -5,7 +5,7 @@ This is the SpiceBot search system.
""" """
import sopel import sopel
import spicemanip from sopel_modules.spicemanip import spicemanip
import sopel_modules.SpiceBot as SpiceBot import sopel_modules.SpiceBot as SpiceBot
@ -14,14 +14,14 @@ import sopel_modules.SpiceBot as SpiceBot
@sopel.module.commands('search', 'find', 'google', 'lookup') @sopel.module.commands('search', 'find', 'google', 'lookup')
def search_main(bot, trigger, botcom): def search_main(bot, trigger, botcom):
searchterm = spicemanip.main(trigger.sb['args'], 0) or None searchterm = spicemanip(botcom.dict['args'], 0) or None
if not searchterm: if not searchterm:
SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], "Not sure what you want me to look for.") SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], "Not sure what you want me to look for.")
return return
searchreturn = SpiceBot.google.search(searchterm) searchreturn = SpiceBot.google.search(searchterm)
if not searchreturn: if not searchreturn:
SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], 'I cannot find anything about that') SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], 'I cannot find anything about that')
else: else:
bot.osd(["[Information search for '" + str(searchterm) + "']", str(searchreturn)]) bot.osd(["[Information search for '" + str(searchterm) + "']", str(searchreturn)])
@ -30,14 +30,14 @@ def search_main(bot, trigger, botcom):
@sopel.module.commands("where", "whereis") @sopel.module.commands("where", "whereis")
def search_where(bot, trigger, botcom): def search_where(bot, trigger, botcom):
searchterm = spicemanip.main(trigger.sb['args'], 0) or None searchterm = spicemanip(botcom.dict['args'], 0) or None
if not searchterm: if not searchterm:
SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], "Not sure what you want me to look for.") SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], "Not sure what you want me to look for.")
return return
searchreturn = SpiceBot.google.search(searchterm, 'maps') searchreturn = SpiceBot.google.search(searchterm, 'maps')
if not searchreturn: if not searchreturn:
SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], 'I cannot find anything about that') SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], 'I cannot find anything about that')
else: else:
bot.osd(["[Location search for " + str(searchterm) + "]", str(searchreturn)]) bot.osd(["[Location search for " + str(searchterm) + "]", str(searchreturn)])
@ -46,14 +46,14 @@ def search_where(bot, trigger, botcom):
@sopel.module.commands("what", "whatis") @sopel.module.commands("what", "whatis")
def search_what(bot, trigger, botcom): def search_what(bot, trigger, botcom):
searchterm = spicemanip.main(trigger.sb['args'], 0) or None searchterm = spicemanip(botcom.dict['args'], 0) or None
if not searchterm: if not searchterm:
SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], "Not sure what you want me to look for.") SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], "Not sure what you want me to look for.")
return return
searchreturn = SpiceBot.google.search(searchterm) searchreturn = SpiceBot.google.search(searchterm)
if not searchreturn: if not searchreturn:
SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], 'I cannot find anything about that') SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], 'I cannot find anything about that')
else: else:
bot.osd(["[Information search for '" + str(searchterm) + "']", str(searchreturn)]) bot.osd(["[Information search for '" + str(searchterm) + "']", str(searchreturn)])
@ -62,13 +62,13 @@ def search_what(bot, trigger, botcom):
@sopel.module.commands("youtube", "video") @sopel.module.commands("youtube", "video")
def search_video(bot, trigger, botcom): def search_video(bot, trigger, botcom):
searchterm = spicemanip.main(trigger.sb['args'], 0) or None searchterm = spicemanip(botcom.dict['args'], 0) or None
if not searchterm: if not searchterm:
SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], "Not sure what you want me to look for.") SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], "Not sure what you want me to look for.")
return return
searchreturn = SpiceBot.google.search(searchterm, 'youtube') searchreturn = SpiceBot.google.search(searchterm, 'youtube')
if not searchreturn: if not searchreturn:
SpiceBot.messagelog.messagelog_error(trigger.sb["log_id"], 'I cannot find anything about that') SpiceBot.messagelog.messagelog_error(botcom.dict["log_id"], 'I cannot find anything about that')
else: else:
bot.osd(["[Youtube search for '" + str(searchterm) + "']", str(searchreturn)]) bot.osd(["[Youtube search for '" + str(searchterm) + "']", str(searchreturn)])

View File

@ -4,7 +4,7 @@ from __future__ import unicode_literals, absolute_import, division, print_functi
# sopel imports # sopel imports
import sopel.module import sopel.module
import spicemanip from sopel_modules.spicemanip import spicemanip
import sopel_modules.SpiceBot as SpiceBot import sopel_modules.SpiceBot as SpiceBot
@ -15,15 +15,15 @@ def bot_command_sherlock(bot, trigger, botcom):
netlist = list(SpiceBot.sherlock.dict.keys()) netlist = list(SpiceBot.sherlock.dict.keys())
username = spicemanip.main(trigger.sb["args"], 1) or trigger.nick username = spicemanip(botcom.dict["args"], 1) or trigger.nick
trigger.sb["args"] = spicemanip.main(trigger.sb["args"], "2+", 'list') botcom.dict["args"] = spicemanip(botcom.dict["args"], "2+", 'list')
checklist = netlist checklist = netlist
checklistname = 'all' checklistname = 'all'
if SpiceBot.inlist(username, netlist): if SpiceBot.inlist(username, netlist):
checklistname = SpiceBot.inlist_match(username, netlist) checklistname = SpiceBot.inlist_match(username, netlist)
checklist = [checklistname] checklist = [checklistname]
username = spicemanip.main(trigger.sb["args"], 1) or trigger.nick username = spicemanip(botcom.dict["args"], 1) or trigger.nick
bot.osd("Checking username " + username + " in " + checklistname + " network.") bot.osd("Checking username " + username + " in " + checklistname + " network.")
@ -41,9 +41,9 @@ def bot_command_sherlock(bot, trigger, botcom):
if checklistname != 'all': if checklistname != 'all':
bot.osd(["The username " + username + " is in " + checklist[0], SpiceBot.sherlock.dict.get(social_network).get("url").format(username)]) bot.osd(["The username " + username + " is in " + checklist[0], SpiceBot.sherlock.dict.get(social_network).get("url").format(username)])
else: else:
bot.osd(["The username " + username + " is in the following:", spicemanip.main(inlist, "andlist")], trigger.nick, 'NOTICE') bot.osd(["The username " + username + " is in the following:", spicemanip(inlist, "andlist")], trigger.nick, 'NOTICE')
if len(notinlist): if len(notinlist):
if checklistname != 'all': if checklistname != 'all':
bot.osd(["The username " + username + " is NOT in the following:", spicemanip.main(notinlist, "andlist")]) bot.osd(["The username " + username + " is NOT in the following:", spicemanip(notinlist, "andlist")])
else: else:
bot.osd(["The username " + username + " is NOT in the following:", spicemanip.main(notinlist, "andlist")], trigger.nick, 'NOTICE') bot.osd(["The username " + username + " is NOT in the following:", spicemanip(notinlist, "andlist")], trigger.nick, 'NOTICE')

View File

@ -0,0 +1,12 @@
# coding=utf8
from __future__ import unicode_literals, absolute_import, division, print_function
# pylama:ignore=W0401,W0611
from .Gif import *
from .Sherlock import *
from .Reddit import *
from .Search import *
__author__ = 'Sam Zick'
__email__ = 'sam@deathbybandaid.net'
__version__ = '0.1.1'

View File

@ -0,0 +1,684 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Top-level package for spicemanip."""
__author__ = """Sam Zick"""
__email__ = 'sam@deathbybandaid.net'
__version__ = '0.1.8'
import random
import collections
# TODO 'this*that' or '1*that' replace either all strings matching, or an index value
# TODO reverse sort z.sort(reverse = True)
# list.extend adds lists to eachother
class Spicemanip():
def __init__(self):
pass
def __call__(self, inputs, outputtask, output_type='default'):
mainoutputtask, suboutputtask = None, None
# Input needs to be a list, but don't split a word into letters
if not inputs:
inputs = []
if isinstance(inputs, collections.abc.KeysView):
inputs = list(inputs)
elif isinstance(inputs, dict):
inputs = list(inputs.keys())
if not isinstance(inputs, list):
inputs = list(inputs.split(" "))
inputs = [x for x in inputs if x and x not in ['', ' ']]
inputs = [inputspart.strip() for inputspart in inputs]
# Create return
if outputtask == 'create':
return inputs
# Make temparray to preserve original order
temparray = []
for inputpart in inputs:
temparray.append(inputpart)
inputs = temparray
# Convert outputtask to standard
if outputtask in [0, 'complete']:
outputtask = 'string'
elif outputtask == 'index':
mainoutputtask = inputs[1]
suboutputtask = inputs[2]
inputs = inputs[0]
elif str(outputtask).isdigit():
mainoutputtask, outputtask = int(outputtask), 'number'
elif "^" in str(outputtask):
mainoutputtask = str(outputtask).split("^", 1)[0]
suboutputtask = str(outputtask).split("^", 1)[1]
outputtask = 'rangebetween'
if int(suboutputtask) < int(mainoutputtask):
mainoutputtask, suboutputtask = suboutputtask, mainoutputtask
elif str(outputtask).startswith("split_"):
mainoutputtask = str(outputtask).replace("split_", "")
outputtask = 'split'
elif str(outputtask).endswith(tuple(["!", "+", "-", "<", ">"])):
mainoutputtask = str(outputtask)
if str(outputtask).endswith("!"):
outputtask = 'exclude'
if str(outputtask).endswith("+"):
outputtask = 'incrange_plus'
if str(outputtask).endswith("-"):
outputtask = 'incrange_minus'
if str(outputtask).endswith(">"):
outputtask = 'excrange_plus'
if str(outputtask).endswith("<"):
outputtask = 'excrange_minus'
for r in (("!", ""), ("+", ""), ("-", ""), ("<", ""), (">", "")):
mainoutputtask = mainoutputtask.replace(*r)
if mainoutputtask == 'last':
mainoutputtask = len(inputs)
if outputtask == 'string':
returnvalue = inputs
else:
returnvalue = eval(
'self.' + outputtask +
'(inputs, outputtask, mainoutputtask, suboutputtask)')
# default return if not specified
if output_type == 'default':
if outputtask in [
'string', 'number', 'rangebetween', 'exclude', 'random',
'incrange_plus', 'incrange_minus', 'excrange_plus',
'excrange_minus'
]:
output_type = 'string'
elif outputtask in ['count']:
output_type = 'dict'
# verify output is correct
if output_type == 'return':
return returnvalue
if output_type == 'string':
if isinstance(returnvalue, list):
returnvalue = ' '.join(returnvalue)
elif output_type in ['list', 'array']:
if not isinstance(returnvalue, list):
returnvalue = list(returnvalue.split(" "))
returnvalue = [x for x in returnvalue if x and x not in ['', ' ']]
returnvalue = [inputspart.strip() for inputspart in returnvalue]
return returnvalue
# compare 2 lists, based on the location of an index item, passthrough needs to be [indexitem, arraytoindex, arraytocompare]
def index(self, indexitem, outputtask, arraytoindex, arraytocompare):
item = ''
for x, y in zip(arraytoindex, arraytocompare):
if x == indexitem:
item = y
return item
# split list by string
def split(self, inputs, outputtask, mainoutputtask, suboutputtask):
split_array = []
restring = ' '.join(inputs)
if mainoutputtask not in inputs:
split_array = [restring]
else:
split_array = restring.split(mainoutputtask)
split_array = [x for x in split_array if x and x not in ['', ' ']]
split_array = [inputspart.strip() for inputspart in split_array]
if split_array == []:
split_array = [[]]
return split_array
# dedupe list
def dedupe(self, inputs, outputtask, mainoutputtask, suboutputtask):
newlist = []
for inputspart in inputs:
if inputspart not in newlist:
newlist.append(inputspart)
return newlist
# Sort list
def sort(self, inputs, outputtask, mainoutputtask, suboutputtask):
return sorted(inputs)
# reverse sort list
def rsort(self, inputs, outputtask, mainoutputtask, suboutputtask):
return sorted(inputs)[::-1]
# count items in list, return dictionary
def count(self, inputs, outputtask, mainoutputtask, suboutputtask):
returndict = dict()
if not len(inputs):
return returndict
uniqueinputitems, uniquecount = [], []
for inputspart in inputs:
if inputspart not in uniqueinputitems:
uniqueinputitems.append(inputspart)
for uniqueinputspart in uniqueinputitems:
count = 0
for ele in inputs:
if (ele == uniqueinputspart):
count += 1
uniquecount.append(count)
for inputsitem, unumber in zip(uniqueinputitems, uniquecount):
returndict[inputsitem] = unumber
return returndict
# random item from list
def random(self, inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
randomselectlist = []
for temppart in inputs:
randomselectlist.append(temppart)
while len(randomselectlist) > 1:
random.shuffle(randomselectlist)
randomselect = randomselectlist[random.randint(
0,
len(randomselectlist) - 1)]
randomselectlist.remove(randomselect)
randomselect = randomselectlist[0]
return randomselect
# remove random item from list
def exrandom(self, inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return []
randremove = self.random(inputs, outputtask, mainoutputtask, suboutputtask)
inputs.remove(randremove)
return inputs
# Convert list into lowercase
def lower(self, inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
return [inputspart.lower() for inputspart in inputs]
# Convert list to uppercase
def upper(self, inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
return [inputspart.upper() for inputspart in inputs]
# Convert list to uppercase
def title(self, inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
return [inputspart.title() for inputspart in inputs]
# Reverse List Order
def reverse(self, inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return []
return inputs[::-1]
# comma seperated list
def list(self, inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
return ', '.join(str(x) for x in inputs)
def list_nospace(self, inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
return ','.join(str(x) for x in inputs)
# comma seperated list with and
def andlist(self, inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
if len(inputs) < 2:
return ' '.join(inputs)
lastentry = str("and " + str(inputs[len(inputs) - 1]))
del inputs[-1]
inputs.append(lastentry)
if len(inputs) == 2:
return ' '.join(inputs)
return ', '.join(str(x) for x in inputs)
# comma seperated list with or
def orlist(self, inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
if len(inputs) < 2:
return ' '.join(inputs)
lastentry = str("or " + str(inputs[len(inputs) - 1]))
del inputs[-1]
inputs.append(lastentry)
if len(inputs) == 2:
return ' '.join(inputs)
return ', '.join(str(x) for x in inputs)
# exclude number
def exclude(self, inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
del inputs[int(mainoutputtask) - 1]
return ' '.join(inputs)
# Convert list to string
def string(self, inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
return ' '.join(inputs)
# Get number item from list
def number(self, inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
elif len(inputs) == 1:
return inputs[0]
elif int(mainoutputtask) > len(inputs) or int(mainoutputtask) < 0:
return ''
else:
return inputs[int(mainoutputtask) - 1]
# Get Last item from list
def last(self, inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
return inputs[len(inputs) - 1]
# range between items in list
def rangebetween(self, inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
if not str(mainoutputtask).isdigit() or not str(
suboutputtask).isdigit():
return ''
mainoutputtask, suboutputtask = int(mainoutputtask), int(suboutputtask)
if suboutputtask == mainoutputtask:
return self.number(inputs, outputtask, mainoutputtask, suboutputtask)
if suboutputtask < mainoutputtask:
return []
if mainoutputtask < 0:
mainoutputtask = 1
if suboutputtask > len(inputs):
suboutputtask = len(inputs)
newlist = []
for i in range(mainoutputtask, suboutputtask + 1):
newlist.append(
str(
self.number(inputs, outputtask, i, suboutputtask)))
if newlist == []:
return ''
return ' '.join(newlist)
# Forward Range includes index number
def incrange_plus(self, inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
return self.rangebetween(inputs, outputtask, int(mainoutputtask), len(inputs))
# Reverse Range includes index number
def incrange_minus(self, inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
return self.rangebetween(inputs, outputtask, 1, int(mainoutputtask))
# Forward Range excludes index number
def excrange_plus(self, inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
return self.rangebetween(inputs, outputtask, int(mainoutputtask) + 1, len(inputs))
# Reverse Range excludes index number
def excrange_minus(self, inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
return self.rangebetween(inputs, outputtask, 1, int(mainoutputtask) - 1)
spicemanip = Spicemanip()
"""
# Hub
def spicemanip(inputs, outputtask, output_type='default'):
mainoutputtask, suboutputtask = None, None
# Input needs to be a list, but don't split a word into letters
if not inputs:
inputs = []
if isinstance(inputs, collections.abc.KeysView):
inputs = list(inputs)
elif isinstance(inputs, dict):
inputs = list(inputs.keys())
if not isinstance(inputs, list):
inputs = list(inputs.split(" "))
inputs = [x for x in inputs if x and x not in ['', ' ']]
inputs = [inputspart.strip() for inputspart in inputs]
# Create return
if outputtask == 'create':
return inputs
# Make temparray to preserve original order
temparray = []
for inputpart in inputs:
temparray.append(inputpart)
inputs = temparray
# Convert outputtask to standard
if outputtask in [0, 'complete']:
outputtask = 'string'
elif outputtask == 'index':
mainoutputtask = inputs[1]
suboutputtask = inputs[2]
inputs = inputs[0]
elif str(outputtask).isdigit():
mainoutputtask, outputtask = int(outputtask), 'number'
elif "^" in str(outputtask):
mainoutputtask = str(outputtask).split("^", 1)[0]
suboutputtask = str(outputtask).split("^", 1)[1]
outputtask = 'rangebetween'
if int(suboutputtask) < int(mainoutputtask):
mainoutputtask, suboutputtask = suboutputtask, mainoutputtask
elif str(outputtask).startswith("split_"):
mainoutputtask = str(outputtask).replace("split_", "")
outputtask = 'split'
elif str(outputtask).endswith(tuple(["!", "+", "-", "<", ">"])):
mainoutputtask = str(outputtask)
if str(outputtask).endswith("!"):
outputtask = 'exclude'
if str(outputtask).endswith("+"):
outputtask = 'incrange_plus'
if str(outputtask).endswith("-"):
outputtask = 'incrange_minus'
if str(outputtask).endswith(">"):
outputtask = 'excrange_plus'
if str(outputtask).endswith("<"):
outputtask = 'excrange_minus'
for r in (("!", ""), ("+", ""), ("-", ""), ("<", ""), (">", "")):
mainoutputtask = mainoutputtask.replace(*r)
if mainoutputtask == 'last':
mainoutputtask = len(inputs)
if outputtask == 'string':
returnvalue = inputs
else:
returnvalue = eval(
'spicemanip_' + outputtask +
'(inputs, outputtask, mainoutputtask, suboutputtask)')
# default return if not specified
if output_type == 'default':
if outputtask in [
'string', 'number', 'rangebetween', 'exclude', 'random',
'incrange_plus', 'incrange_minus', 'excrange_plus',
'excrange_minus'
]:
output_type = 'string'
elif outputtask in ['count']:
output_type = 'dict'
# verify output is correct
if output_type == 'return':
return returnvalue
if output_type == 'string':
if isinstance(returnvalue, list):
returnvalue = ' '.join(returnvalue)
elif output_type in ['list', 'array']:
if not isinstance(returnvalue, list):
returnvalue = list(returnvalue.split(" "))
returnvalue = [x for x in returnvalue if x and x not in ['', ' ']]
returnvalue = [inputspart.strip() for inputspart in returnvalue]
return returnvalue
# compare 2 lists, based on the location of an index item, passthrough needs to be [indexitem, arraytoindex, arraytocompare]
def spicemanip_index(indexitem, outputtask, arraytoindex, arraytocompare):
item = ''
for x, y in zip(arraytoindex, arraytocompare):
if x == indexitem:
item = y
return item
# split list by string
def spicemanip_split(inputs, outputtask, mainoutputtask, suboutputtask):
split_array = []
restring = ' '.join(inputs)
if mainoutputtask not in inputs:
split_array = [restring]
else:
split_array = restring.split(mainoutputtask)
split_array = [x for x in split_array if x and x not in ['', ' ']]
split_array = [inputspart.strip() for inputspart in split_array]
if split_array == []:
split_array = [[]]
return split_array
# dedupe list
def spicemanip_dedupe(inputs, outputtask, mainoutputtask, suboutputtask):
newlist = []
for inputspart in inputs:
if inputspart not in newlist:
newlist.append(inputspart)
return newlist
# Sort list
def spicemanip_sort(inputs, outputtask, mainoutputtask, suboutputtask):
return sorted(inputs)
# reverse sort list
def spicemanip_rsort(inputs, outputtask, mainoutputtask, suboutputtask):
return sorted(inputs)[::-1]
# count items in list, return dictionary
def spicemanip_count(inputs, outputtask, mainoutputtask, suboutputtask):
returndict = dict()
if not len(inputs):
return returndict
uniqueinputitems, uniquecount = [], []
for inputspart in inputs:
if inputspart not in uniqueinputitems:
uniqueinputitems.append(inputspart)
for uniqueinputspart in uniqueinputitems:
count = 0
for ele in inputs:
if (ele == uniqueinputspart):
count += 1
uniquecount.append(count)
for inputsitem, unumber in zip(uniqueinputitems, uniquecount):
returndict[inputsitem] = unumber
return returndict
# random item from list
def spicemanip_random(inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
randomselectlist = []
for temppart in inputs:
randomselectlist.append(temppart)
while len(randomselectlist) > 1:
random.shuffle(randomselectlist)
randomselect = randomselectlist[random.randint(
0,
len(randomselectlist) - 1)]
randomselectlist.remove(randomselect)
randomselect = randomselectlist[0]
return randomselect
# remove random item from list
def spicemanip_exrandom(inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return []
randremove = spicemanip_random(inputs, outputtask, mainoutputtask,
suboutputtask)
inputs.remove(randremove)
return inputs
# Convert list into lowercase
def spicemanip_lower(inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
return [inputspart.lower() for inputspart in inputs]
# Convert list to uppercase
def spicemanip_upper(inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
return [inputspart.upper() for inputspart in inputs]
# Convert list to uppercase
def spicemanip_title(inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
return [inputspart.title() for inputspart in inputs]
# Reverse List Order
def spicemanip_reverse(inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return []
return inputs[::-1]
# comma seperated list
def spicemanip_list(inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
return ', '.join(str(x) for x in inputs)
def spicemanip_list_nospace(inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
return ','.join(str(x) for x in inputs)
# comma seperated list with and
def spicemanip_andlist(inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
if len(inputs) < 2:
return ' '.join(inputs)
lastentry = str("and " + str(inputs[len(inputs) - 1]))
del inputs[-1]
inputs.append(lastentry)
if len(inputs) == 2:
return ' '.join(inputs)
return ', '.join(str(x) for x in inputs)
# comma seperated list with or
def spicemanip_orlist(inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
if len(inputs) < 2:
return ' '.join(inputs)
lastentry = str("or " + str(inputs[len(inputs) - 1]))
del inputs[-1]
inputs.append(lastentry)
if len(inputs) == 2:
return ' '.join(inputs)
return ', '.join(str(x) for x in inputs)
# exclude number
def spicemanip_exclude(inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
del inputs[int(mainoutputtask) - 1]
return ' '.join(inputs)
# Convert list to string
def spicemanip_string(inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
return ' '.join(inputs)
# Get number item from list
def spicemanip_number(inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
elif len(inputs) == 1:
return inputs[0]
elif int(mainoutputtask) > len(inputs) or int(mainoutputtask) < 0:
return ''
else:
return inputs[int(mainoutputtask) - 1]
# Get Last item from list
def spicemanip_last(inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
return inputs[len(inputs) - 1]
# range between items in list
def spicemanip_rangebetween(inputs, outputtask, mainoutputtask, suboutputtask):
if not len(inputs):
return ''
if not str(mainoutputtask).isdigit() or not str(suboutputtask).isdigit():
return ''
mainoutputtask, suboutputtask = int(mainoutputtask), int(suboutputtask)
if suboutputtask == mainoutputtask:
return spicemanip_number(inputs, outputtask, mainoutputtask,
suboutputtask)
if suboutputtask < mainoutputtask:
return []
if mainoutputtask < 0:
mainoutputtask = 1
if suboutputtask > len(inputs):
suboutputtask = len(inputs)
newlist = []
for i in range(mainoutputtask, suboutputtask + 1):
newlist.append(
str(spicemanip_number(inputs, outputtask, i, suboutputtask)))
if newlist == []:
return ''
return ' '.join(newlist)
# Forward Range includes index number
def spicemanip_incrange_plus(inputs, outputtask, mainoutputtask,
suboutputtask):
if not len(inputs):
return ''
return spicemanip_rangebetween(inputs, outputtask, int(mainoutputtask),
len(inputs))
# Reverse Range includes index number
def spicemanip_incrange_minus(inputs, outputtask, mainoutputtask,
suboutputtask):
if not len(inputs):
return ''
return spicemanip_rangebetween(inputs, outputtask, 1, int(mainoutputtask))
# Forward Range excludes index number
def spicemanip_excrange_plus(inputs, outputtask, mainoutputtask,
suboutputtask):
if not len(inputs):
return ''
return spicemanip_rangebetween(inputs, outputtask,
int(mainoutputtask) + 1, len(inputs))
# Reverse Range excludes index number
def spicemanip_excrange_minus(inputs, outputtask, mainoutputtask,
suboutputtask):
if not len(inputs):
return ''
return spicemanip_rangebetween(inputs, outputtask, 1,
int(mainoutputtask) - 1)
"""