From eff28605a0801004c17e4f17aa967a43c56a1fce Mon Sep 17 00:00:00 2001 From: deathbybandaid Date: Thu, 2 May 2019 19:32:52 -0400 Subject: [PATCH 1/4] CommandsQuery/BotEvents --- sopel_modules/SpiceBot_Botevents/BotEvents.py | 69 +++++ sopel_modules/SpiceBot_Botevents/Connected.py | 24 ++ .../SpiceBot_Botevents/Startup_Complete.py | 19 ++ sopel_modules/SpiceBot_Botevents/__init__.py | 15 + .../SpiceBot_CommandsQuery/CommandsQuery.py | 268 ++++++++++++++++++ .../SpiceBot_CommandsQuery/__init__.py | 12 + 6 files changed, 407 insertions(+) create mode 100644 sopel_modules/SpiceBot_Botevents/BotEvents.py create mode 100644 sopel_modules/SpiceBot_Botevents/Connected.py create mode 100644 sopel_modules/SpiceBot_Botevents/Startup_Complete.py create mode 100644 sopel_modules/SpiceBot_Botevents/__init__.py create mode 100644 sopel_modules/SpiceBot_CommandsQuery/CommandsQuery.py create mode 100644 sopel_modules/SpiceBot_CommandsQuery/__init__.py diff --git a/sopel_modules/SpiceBot_Botevents/BotEvents.py b/sopel_modules/SpiceBot_Botevents/BotEvents.py new file mode 100644 index 0000000..6f831d5 --- /dev/null +++ b/sopel_modules/SpiceBot_Botevents/BotEvents.py @@ -0,0 +1,69 @@ +# coding=utf8 +"""Sopel_BotEvents + +Sopel BotEvents is a poor mans way to create module load order dependencies +""" +from __future__ import unicode_literals, absolute_import, division, print_function + +import sopel.module +from sopel.tools import stderr +import threading + + +def configure(config): + pass + + +def setup(bot): + stderr("[Sopel_BotEvents] Starting Module Events Logging") + + threading.Thread(target=setup_thread, args=(bot,)).start() + + +def setup_thread(bot): + if "Sopel_BotEvents" not in bot.memory: + bot.memory["Sopel_BotEvents"] = {"loaded": [], "startup": []} + + +def list_bot_events(bot, list_type): + if "Sopel_BotEvents" not in bot.memory: + bot.memory["Sopel_BotEvents"] = {"loaded": [], "startup": []} + return bot.memory["Sopel_BotEvents"][list_type] + + +def check_bot_events(bot, listreq): + if "Sopel_BotEvents" not in bot.memory: + bot.memory["Sopel_BotEvents"] = {"loaded": [], "startup": []} + if not isinstance(listreq, list): + listreq = [str(listreq)] + for requirement in listreq: + if requirement not in bot.memory["Sopel_BotEvents"]["loaded"]: + return False + return True + + +def set_bot_event(bot, addonreq): + if "Sopel_BotEvents" not in bot.memory: + bot.memory["Sopel_BotEvents"] = {"loaded": [], "startup": []} + if not isinstance(addonreq, list): + addonreq = [str(addonreq)] + + bot.memory["Sopel_BotEvents"]["loaded"].extend(addonreq) + + +def startup_bot_event(bot, addonreq): + if "Sopel_BotEvents" not in bot.memory: + bot.memory["Sopel_BotEvents"] = {"loaded": [], "startup": []} + if not isinstance(addonreq, list): + addonreq = [str(addonreq)] + + bot.memory["Sopel_BotEvents"]["startup"].extend(addonreq) + + +def check_bot_startup(bot): + if "Sopel_BotEvents" not in bot.memory: + bot.memory["Sopel_BotEvents"] = {"loaded": [], "startup": []} + for startupitem in bot.memory["Sopel_BotEvents"]["startup"]: + if startupitem not in bot.memory["Sopel_BotEvents"]["loaded"]: + return False + return True diff --git a/sopel_modules/SpiceBot_Botevents/Connected.py b/sopel_modules/SpiceBot_Botevents/Connected.py new file mode 100644 index 0000000..fe93a79 --- /dev/null +++ b/sopel_modules/SpiceBot_Botevents/Connected.py @@ -0,0 +1,24 @@ +# coding=utf-8 + +from __future__ import unicode_literals, absolute_import, division, print_function + +from sopel import module +from sopel.tools import stderr +from .BotEvents import check_bot_events, startup_bot_event, set_bot_event + +import time + + +@module.event('001') +@module.rule('.*') +def bot_startup_connection(bot, trigger): + + if check_bot_events(bot, ["startup_complete"]): + return + startup_bot_event(bot, "connected") + + while not len(bot.channels.keys()) > 0: + pass + time.sleep(1) + + set_bot_event(bot, "connected") diff --git a/sopel_modules/SpiceBot_Botevents/Startup_Complete.py b/sopel_modules/SpiceBot_Botevents/Startup_Complete.py new file mode 100644 index 0000000..aa84ef3 --- /dev/null +++ b/sopel_modules/SpiceBot_Botevents/Startup_Complete.py @@ -0,0 +1,19 @@ +# coding=utf-8 + +from __future__ import unicode_literals, absolute_import, division, print_function + +from sopel import module +from sopel.tools import stderr + +from .BotEvents import set_bot_event, check_bot_startup + + +@module.event('001') +@module.rule('.*') +def bot_startup_complete(bot, trigger): + + while not check_bot_startup(bot): + pass + + set_bot_event(bot, "startup_complete") + stderr("[Sopel_BotEvents] Module Events Logging Complete") diff --git a/sopel_modules/SpiceBot_Botevents/__init__.py b/sopel_modules/SpiceBot_Botevents/__init__.py new file mode 100644 index 0000000..e4dc160 --- /dev/null +++ b/sopel_modules/SpiceBot_Botevents/__init__.py @@ -0,0 +1,15 @@ +# coding=utf8 +"""Sopel_BotEvents + +Sopel BotEvents is a poor mans way to create module load order dependencies +""" +from __future__ import unicode_literals, absolute_import, division, print_function + +from .BotEvents import * +from .Connected import * +from .Startup_Complete import * + + +__author__ = 'Sam Zick' +__email__ = 'sam@deathbybandaid.net' +__version__ = '0.1.0' diff --git a/sopel_modules/SpiceBot_CommandsQuery/CommandsQuery.py b/sopel_modules/SpiceBot_CommandsQuery/CommandsQuery.py new file mode 100644 index 0000000..20cb960 --- /dev/null +++ b/sopel_modules/SpiceBot_CommandsQuery/CommandsQuery.py @@ -0,0 +1,268 @@ +# coding=utf-8 + +from __future__ import unicode_literals, absolute_import, division, print_function + +import sopel +from sopel import module +from sopel.tools import stderr + +import os +from difflib import SequenceMatcher +from operator import itemgetter +import threading + + +from sopel_modules.SpiceBot_SBTools.BotEvents import set_bot_event + + +import spicemanip + + +def configure(config): + pass + + +def setup(bot): + stderr("[Sopel-CommandsQuery] Evaluating Core Commands List") + + threading.Thread(target=setup_thread, args=(bot,)).start() + + +def setup_thread(bot): + + bot.memory['Sopel-CommandsQuery'] = dict() + for comtype in ['module', 'nickname', 'rule']: + bot.memory['Sopel-CommandsQuery'][comtype + "_commands"] = dict() + bot.memory['Sopel-CommandsQuery'][comtype + "_commands_count"] = 0 + + filepathlisting = [] + + # main Modules directory + main_dir = os.path.dirname(os.path.abspath(sopel.__file__)) + modules_dir = os.path.join(main_dir, 'modules') + filepathlisting.append(modules_dir) + + # Home Directory + home_modules_dir = os.path.join(bot.config.homedir, 'modules') + if os.path.isdir(home_modules_dir): + filepathlisting.append(home_modules_dir) + + # pypi installed + try: + import sopel_modules + pypi_modules = os.path.dirname(os.path.abspath(sopel_modules.__file__)) + pypi_modules_dir = os.path.join(pypi_modules, 'modules') + filepathlisting.append(pypi_modules_dir) + except Exception: + pass + + # Extra directories + filepathlist = [] + for directory in bot.config.core.extra: + filepathlisting.append(directory) + + for directory in filepathlisting: + for pathname in os.listdir(directory): + path = os.path.join(directory, pathname) + if (os.path.isfile(path) and path.endswith('.py') and not path.startswith('_')): + filepathlist.append(str(path)) + + # CoreTasks + ct_path = os.path.join(main_dir, 'coretasks.py') + filepathlist.append(ct_path) + + for modulefile in filepathlist: + module_file_lines = [] + module_file = open(modulefile, 'r') + lines = module_file.readlines() + for line in lines: + module_file_lines.append(line) + module_file.close() + + dict_from_file = dict() + filelinelist = [] + + for line in module_file_lines: + + if str(line).startswith("@"): + line = str(line)[1:] + + # Commands + if str(line).startswith(tuple(["commands", "module.commands", "sopel.module.commands"])): + comtype = "module" + line = str(line).split("commands(")[-1] + line = str("(" + line) + validcoms = eval(str(line)) + if isinstance(validcoms, tuple): + validcoms = list(validcoms) + else: + validcoms = [validcoms] + validcomdict = {"comtype": comtype, "validcoms": validcoms} + filelinelist.append(validcomdict) + elif str(line).startswith(tuple(["nickname_commands", "module.nickname_commands", "sopel.module.nickname_commands"])): + comtype = "nickname" + line = str(line).split("commands(")[-1] + line = str("(" + line) + validcoms = eval(str(line)) + if isinstance(validcoms, tuple): + validcoms = list(validcoms) + else: + validcoms = [validcoms] + nickified = [] + for nickcom in validcoms: + nickified.append(str(bot.nick) + " " + nickcom) + validcomdict = {"comtype": comtype, "validcoms": nickified} + filelinelist.append(validcomdict) + elif str(line).startswith(tuple(["rule", "module.rule", "sopel.module.rule"])): + comtype = "rule" + line = str(line).split("rule(")[-1] + validcoms = [str("(" + line)] + validcomdict = {"comtype": comtype, "validcoms": validcoms} + filelinelist.append(validcomdict) + + for atlinefound in filelinelist: + + comtype = atlinefound["comtype"] + validcoms = atlinefound["validcoms"] + + comtypedict = str(comtype + "_commands") + + bot.memory['Sopel-CommandsQuery'][comtypedict + "_count"] += 1 + + # default command to filename + if "validcoms" not in dict_from_file.keys(): + dict_from_file["validcoms"] = validcoms + + maincom = dict_from_file["validcoms"][0] + if len(dict_from_file["validcoms"]) > 1: + comaliases = spicemanip.main(dict_from_file["validcoms"], '2+', 'list') + else: + comaliases = [] + + bot.memory['Sopel-CommandsQuery'][comtypedict][maincom] = dict_from_file + for comalias in comaliases: + if comalias not in bot.memory['Sopel-CommandsQuery'][comtypedict].keys(): + bot.memory['Sopel-CommandsQuery'][comtypedict][comalias] = {"aliasfor": maincom} + + for comtype in ['module_commands', 'nickname_commands', 'rule_commands']: + stderr("[Sopel-CommandsQuery] Found " + str(len(bot.memory['Sopel-CommandsQuery'][comtype].keys())) + " " + comtype + " commands.") + + set_bot_event(bot, "Sopel-CommandsQuery") + + +@module.rule('^\?(.*)') +def query_detection(bot, trigger): + + while "Sopel-CommandsQuery" not in bot.memory: + pass + + # command must start with + if not str(trigger).startswith(tuple(['?'])): + return + stderr(trigger.args) + + commands_list = dict() + for commandstype in bot.memory['Sopel-CommandsQuery'].keys(): + if not commandstype.endswith("_count"): + for com in bot.memory['Sopel-CommandsQuery'][commandstype].keys(): + if com not in commands_list.keys(): + commands_list[com] = bot.memory['Sopel-CommandsQuery'][commandstype][com] + + triggerargsarray = spicemanip.main(trigger, 'create') + + # command issued, check if valid + querycommand = spicemanip.main(triggerargsarray, 1).lower()[1:] + if len(querycommand) == 1: + commandlist = [] + for command in commands_list.keys(): + if command.lower().startswith(querycommand): + commandlist.append(command) + if commandlist == []: + bot.notice("No commands match " + str(querycommand) + ".", trigger.nick) + return + else: + bot.notice("The following commands match " + str(querycommand) + ": " + spicemanip.main(commandlist, 'andlist') + ".", trigger.nick) + return + + elif querycommand.endswith(tuple(["+"])): + querycommand = querycommand[:-1] + if querycommand not in commands_list.keys(): + bot.notice("The " + str(querycommand) + " does not appear to be valid.") + return + realcom = querycommand + if "aliasfor" in commands_list[querycommand].keys(): + realcom = commands_list[querycommand]["aliasfor"] + validcomlist = commands_list[realcom]["validcoms"] + bot.notice("The following commands match " + str(querycommand) + ": " + spicemanip.main(validcomlist, 'andlist') + ".", trigger.nick) + return + + elif querycommand.endswith(tuple(['?'])): + querycommand = querycommand[:-1] + sim_com, sim_num = [], [] + for com in commands_list.keys(): + similarlevel = SequenceMatcher(None, querycommand.lower(), com.lower()).ratio() + sim_com.append(com) + sim_num.append(similarlevel) + sim_num, sim_com = (list(x) for x in zip(*sorted(zip(sim_num, sim_com), key=itemgetter(0)))) + closestmatch = spicemanip.main(sim_com, 'reverse', "list") + listnumb, relist = 1, [] + for item in closestmatch: + if listnumb <= 10: + relist.append(str(item)) + listnumb += 1 + bot.notice("The following commands may match " + str(querycommand) + ": " + spicemanip.main(relist, 'andlist') + ".", trigger.nick) + return + + elif querycommand in commands_list.keys(): + bot.notice("The following commands match " + str(querycommand) + ": " + str(querycommand) + ".", trigger.nick) + return + + elif not querycommand: + return + + else: + commandlist = [] + for command in commands_list.keys(): + if command.lower().startswith(querycommand): + commandlist.append(command) + if commandlist == []: + bot.notice("No commands match " + str(querycommand) + ".", trigger.nick) + return + else: + bot.notice("The following commands match " + str(querycommand) + ": " + spicemanip.main(commandlist, 'andlist') + ".", trigger.nick) + return + + +def commandsquery_register(bot, command_type, validcoms, aliasfor=None): + + if not isinstance(validcoms, list): + validcoms = [validcoms] + + if 'Sopel-CommandsQuery' not in bot.memory: + bot.memory['Sopel-CommandsQuery'] = dict() + + if command_type not in bot.memory['Sopel-CommandsQuery'].keys(): + bot.memory['Sopel-CommandsQuery'][command_type] = dict() + bot.memory['Sopel-CommandsQuery'][command_type + "_count"] = 0 + bot.memory['Sopel-CommandsQuery'][command_type + "_count"] += 1 + + dict_from_file = dict() + + # default command to filename + if "validcoms" not in dict_from_file.keys(): + dict_from_file["validcoms"] = validcoms + + if not aliasfor: + + maincom = dict_from_file["validcoms"][0] + if len(dict_from_file["validcoms"]) > 1: + comaliases = spicemanip.main(dict_from_file["validcoms"], '2+', 'list') + else: + comaliases = [] + bot.memory['Sopel-CommandsQuery'][command_type][maincom] = dict_from_file + else: + comaliases = validcoms + + for comalias in comaliases: + if comalias not in bot.memory['Sopel-CommandsQuery'][command_type].keys(): + bot.memory['Sopel-CommandsQuery'][command_type][comalias] = {"aliasfor": aliasfor} diff --git a/sopel_modules/SpiceBot_CommandsQuery/__init__.py b/sopel_modules/SpiceBot_CommandsQuery/__init__.py new file mode 100644 index 0000000..4cd2977 --- /dev/null +++ b/sopel_modules/SpiceBot_CommandsQuery/__init__.py @@ -0,0 +1,12 @@ +# coding=utf8 +"""Sopel Commands Query + +Sopel Commands Query responds to ? to display commands matching patterns +""" +from __future__ import unicode_literals, absolute_import, division, print_function + +from .commandsquery import * + +__author__ = 'Sam Zick' +__email__ = 'sam@deathbybandaid.net' +__version__ = '0.1.0' From 1604924a48115ed21d54016343a3173e039f6ec7 Mon Sep 17 00:00:00 2001 From: deathbybandaid Date: Thu, 2 May 2019 19:42:15 -0400 Subject: [PATCH 2/4] CommandsQuery/BotEvents adjustments for consistancy --- sopel_modules/SpiceBot_Botevents/Connected.py | 6 +++--- sopel_modules/SpiceBot_Botevents/Startup_Complete.py | 6 +++--- sopel_modules/SpiceBot_CommandsQuery/CommandsQuery.py | 4 ++-- sopel_modules/SpiceBot_CommandsQuery/__init__.py | 2 +- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/sopel_modules/SpiceBot_Botevents/Connected.py b/sopel_modules/SpiceBot_Botevents/Connected.py index fe93a79..a027c66 100644 --- a/sopel_modules/SpiceBot_Botevents/Connected.py +++ b/sopel_modules/SpiceBot_Botevents/Connected.py @@ -2,15 +2,15 @@ from __future__ import unicode_literals, absolute_import, division, print_function -from sopel import module +import sopel.module from sopel.tools import stderr from .BotEvents import check_bot_events, startup_bot_event, set_bot_event import time -@module.event('001') -@module.rule('.*') +@sopel.module.event('001') +@sopel.module.rule('.*') def bot_startup_connection(bot, trigger): if check_bot_events(bot, ["startup_complete"]): diff --git a/sopel_modules/SpiceBot_Botevents/Startup_Complete.py b/sopel_modules/SpiceBot_Botevents/Startup_Complete.py index aa84ef3..6891b79 100644 --- a/sopel_modules/SpiceBot_Botevents/Startup_Complete.py +++ b/sopel_modules/SpiceBot_Botevents/Startup_Complete.py @@ -2,14 +2,14 @@ from __future__ import unicode_literals, absolute_import, division, print_function -from sopel import module +import sopel.module from sopel.tools import stderr from .BotEvents import set_bot_event, check_bot_startup -@module.event('001') -@module.rule('.*') +@sopel.module.event('001') +@sopel.module.rule('.*') def bot_startup_complete(bot, trigger): while not check_bot_startup(bot): diff --git a/sopel_modules/SpiceBot_CommandsQuery/CommandsQuery.py b/sopel_modules/SpiceBot_CommandsQuery/CommandsQuery.py index 20cb960..c8bafaa 100644 --- a/sopel_modules/SpiceBot_CommandsQuery/CommandsQuery.py +++ b/sopel_modules/SpiceBot_CommandsQuery/CommandsQuery.py @@ -3,7 +3,7 @@ from __future__ import unicode_literals, absolute_import, division, print_function import sopel -from sopel import module +import sopel.module from sopel.tools import stderr import os @@ -150,7 +150,7 @@ def setup_thread(bot): set_bot_event(bot, "Sopel-CommandsQuery") -@module.rule('^\?(.*)') +@sopel.module.rule('^\?(.*)') def query_detection(bot, trigger): while "Sopel-CommandsQuery" not in bot.memory: diff --git a/sopel_modules/SpiceBot_CommandsQuery/__init__.py b/sopel_modules/SpiceBot_CommandsQuery/__init__.py index 4cd2977..a169d76 100644 --- a/sopel_modules/SpiceBot_CommandsQuery/__init__.py +++ b/sopel_modules/SpiceBot_CommandsQuery/__init__.py @@ -5,7 +5,7 @@ Sopel Commands Query responds to ? to display commands matching patterns """ from __future__ import unicode_literals, absolute_import, division, print_function -from .commandsquery import * +from .CommandsQuery import * __author__ = 'Sam Zick' __email__ = 'sam@deathbybandaid.net' From 0dc6858e5ee81bffc5efa8fbcc05a33d26f65705 Mon Sep 17 00:00:00 2001 From: deathbybandaid Date: Thu, 2 May 2019 19:32:52 -0400 Subject: [PATCH 3/4] CommandsQuery/BotEvents CommandsQuery/BotEvents adjustments for consistancy --- sopel_modules/SpiceBot_Botevents/BotEvents.py | 69 +++++ sopel_modules/SpiceBot_Botevents/Connected.py | 24 ++ .../SpiceBot_Botevents/Startup_Complete.py | 19 ++ sopel_modules/SpiceBot_Botevents/__init__.py | 15 + .../SpiceBot_CommandsQuery/CommandsQuery.py | 268 ++++++++++++++++++ .../SpiceBot_CommandsQuery/__init__.py | 12 + 6 files changed, 407 insertions(+) create mode 100644 sopel_modules/SpiceBot_Botevents/BotEvents.py create mode 100644 sopel_modules/SpiceBot_Botevents/Connected.py create mode 100644 sopel_modules/SpiceBot_Botevents/Startup_Complete.py create mode 100644 sopel_modules/SpiceBot_Botevents/__init__.py create mode 100644 sopel_modules/SpiceBot_CommandsQuery/CommandsQuery.py create mode 100644 sopel_modules/SpiceBot_CommandsQuery/__init__.py diff --git a/sopel_modules/SpiceBot_Botevents/BotEvents.py b/sopel_modules/SpiceBot_Botevents/BotEvents.py new file mode 100644 index 0000000..6f831d5 --- /dev/null +++ b/sopel_modules/SpiceBot_Botevents/BotEvents.py @@ -0,0 +1,69 @@ +# coding=utf8 +"""Sopel_BotEvents + +Sopel BotEvents is a poor mans way to create module load order dependencies +""" +from __future__ import unicode_literals, absolute_import, division, print_function + +import sopel.module +from sopel.tools import stderr +import threading + + +def configure(config): + pass + + +def setup(bot): + stderr("[Sopel_BotEvents] Starting Module Events Logging") + + threading.Thread(target=setup_thread, args=(bot,)).start() + + +def setup_thread(bot): + if "Sopel_BotEvents" not in bot.memory: + bot.memory["Sopel_BotEvents"] = {"loaded": [], "startup": []} + + +def list_bot_events(bot, list_type): + if "Sopel_BotEvents" not in bot.memory: + bot.memory["Sopel_BotEvents"] = {"loaded": [], "startup": []} + return bot.memory["Sopel_BotEvents"][list_type] + + +def check_bot_events(bot, listreq): + if "Sopel_BotEvents" not in bot.memory: + bot.memory["Sopel_BotEvents"] = {"loaded": [], "startup": []} + if not isinstance(listreq, list): + listreq = [str(listreq)] + for requirement in listreq: + if requirement not in bot.memory["Sopel_BotEvents"]["loaded"]: + return False + return True + + +def set_bot_event(bot, addonreq): + if "Sopel_BotEvents" not in bot.memory: + bot.memory["Sopel_BotEvents"] = {"loaded": [], "startup": []} + if not isinstance(addonreq, list): + addonreq = [str(addonreq)] + + bot.memory["Sopel_BotEvents"]["loaded"].extend(addonreq) + + +def startup_bot_event(bot, addonreq): + if "Sopel_BotEvents" not in bot.memory: + bot.memory["Sopel_BotEvents"] = {"loaded": [], "startup": []} + if not isinstance(addonreq, list): + addonreq = [str(addonreq)] + + bot.memory["Sopel_BotEvents"]["startup"].extend(addonreq) + + +def check_bot_startup(bot): + if "Sopel_BotEvents" not in bot.memory: + bot.memory["Sopel_BotEvents"] = {"loaded": [], "startup": []} + for startupitem in bot.memory["Sopel_BotEvents"]["startup"]: + if startupitem not in bot.memory["Sopel_BotEvents"]["loaded"]: + return False + return True diff --git a/sopel_modules/SpiceBot_Botevents/Connected.py b/sopel_modules/SpiceBot_Botevents/Connected.py new file mode 100644 index 0000000..a027c66 --- /dev/null +++ b/sopel_modules/SpiceBot_Botevents/Connected.py @@ -0,0 +1,24 @@ +# coding=utf-8 + +from __future__ import unicode_literals, absolute_import, division, print_function + +import sopel.module +from sopel.tools import stderr +from .BotEvents import check_bot_events, startup_bot_event, set_bot_event + +import time + + +@sopel.module.event('001') +@sopel.module.rule('.*') +def bot_startup_connection(bot, trigger): + + if check_bot_events(bot, ["startup_complete"]): + return + startup_bot_event(bot, "connected") + + while not len(bot.channels.keys()) > 0: + pass + time.sleep(1) + + set_bot_event(bot, "connected") diff --git a/sopel_modules/SpiceBot_Botevents/Startup_Complete.py b/sopel_modules/SpiceBot_Botevents/Startup_Complete.py new file mode 100644 index 0000000..6891b79 --- /dev/null +++ b/sopel_modules/SpiceBot_Botevents/Startup_Complete.py @@ -0,0 +1,19 @@ +# coding=utf-8 + +from __future__ import unicode_literals, absolute_import, division, print_function + +import sopel.module +from sopel.tools import stderr + +from .BotEvents import set_bot_event, check_bot_startup + + +@sopel.module.event('001') +@sopel.module.rule('.*') +def bot_startup_complete(bot, trigger): + + while not check_bot_startup(bot): + pass + + set_bot_event(bot, "startup_complete") + stderr("[Sopel_BotEvents] Module Events Logging Complete") diff --git a/sopel_modules/SpiceBot_Botevents/__init__.py b/sopel_modules/SpiceBot_Botevents/__init__.py new file mode 100644 index 0000000..e4dc160 --- /dev/null +++ b/sopel_modules/SpiceBot_Botevents/__init__.py @@ -0,0 +1,15 @@ +# coding=utf8 +"""Sopel_BotEvents + +Sopel BotEvents is a poor mans way to create module load order dependencies +""" +from __future__ import unicode_literals, absolute_import, division, print_function + +from .BotEvents import * +from .Connected import * +from .Startup_Complete import * + + +__author__ = 'Sam Zick' +__email__ = 'sam@deathbybandaid.net' +__version__ = '0.1.0' diff --git a/sopel_modules/SpiceBot_CommandsQuery/CommandsQuery.py b/sopel_modules/SpiceBot_CommandsQuery/CommandsQuery.py new file mode 100644 index 0000000..3996216 --- /dev/null +++ b/sopel_modules/SpiceBot_CommandsQuery/CommandsQuery.py @@ -0,0 +1,268 @@ +# coding=utf-8 + +from __future__ import unicode_literals, absolute_import, division, print_function + +import sopel +import sopel.module +from sopel.tools import stderr + +import os +from difflib import SequenceMatcher +from operator import itemgetter +import threading + + +from sopel_modules.SpiceBot_Botevents.BotEvents import set_bot_event + + +import spicemanip + + +def configure(config): + pass + + +def setup(bot): + stderr("[Sopel-CommandsQuery] Evaluating Core Commands List") + + threading.Thread(target=setup_thread, args=(bot,)).start() + + +def setup_thread(bot): + + bot.memory['Sopel-CommandsQuery'] = dict() + for comtype in ['module', 'nickname', 'rule']: + bot.memory['Sopel-CommandsQuery'][comtype + "_commands"] = dict() + bot.memory['Sopel-CommandsQuery'][comtype + "_commands_count"] = 0 + + filepathlisting = [] + + # main Modules directory + main_dir = os.path.dirname(os.path.abspath(sopel.__file__)) + modules_dir = os.path.join(main_dir, 'modules') + filepathlisting.append(modules_dir) + + # Home Directory + home_modules_dir = os.path.join(bot.config.homedir, 'modules') + if os.path.isdir(home_modules_dir): + filepathlisting.append(home_modules_dir) + + # pypi installed + try: + import sopel_modules + pypi_modules = os.path.dirname(os.path.abspath(sopel_modules.__file__)) + pypi_modules_dir = os.path.join(pypi_modules, 'modules') + filepathlisting.append(pypi_modules_dir) + except Exception as e: + stderr("[Sopel-CommandsQuery] sopel_modules not found:" + str(e)) + + # Extra directories + filepathlist = [] + for directory in bot.config.core.extra: + filepathlisting.append(directory) + + for directory in filepathlisting: + for pathname in os.listdir(directory): + path = os.path.join(directory, pathname) + if (os.path.isfile(path) and path.endswith('.py') and not path.startswith('_')): + filepathlist.append(str(path)) + + # CoreTasks + ct_path = os.path.join(main_dir, 'coretasks.py') + filepathlist.append(ct_path) + + for modulefile in filepathlist: + module_file_lines = [] + module_file = open(modulefile, 'r') + lines = module_file.readlines() + for line in lines: + module_file_lines.append(line) + module_file.close() + + dict_from_file = dict() + filelinelist = [] + + for line in module_file_lines: + + if str(line).startswith("@"): + line = str(line)[1:] + + # Commands + if str(line).startswith(tuple(["commands", "module.commands", "sopel.module.commands"])): + comtype = "module" + line = str(line).split("commands(")[-1] + line = str("(" + line) + validcoms = eval(str(line)) + if isinstance(validcoms, tuple): + validcoms = list(validcoms) + else: + validcoms = [validcoms] + validcomdict = {"comtype": comtype, "validcoms": validcoms} + filelinelist.append(validcomdict) + elif str(line).startswith(tuple(["nickname_commands", "module.nickname_commands", "sopel.module.nickname_commands"])): + comtype = "nickname" + line = str(line).split("commands(")[-1] + line = str("(" + line) + validcoms = eval(str(line)) + if isinstance(validcoms, tuple): + validcoms = list(validcoms) + else: + validcoms = [validcoms] + nickified = [] + for nickcom in validcoms: + nickified.append(str(bot.nick) + " " + nickcom) + validcomdict = {"comtype": comtype, "validcoms": nickified} + filelinelist.append(validcomdict) + elif str(line).startswith(tuple(["rule", "module.rule", "sopel.module.rule"])): + comtype = "rule" + line = str(line).split("rule(")[-1] + validcoms = [str("(" + line)] + validcomdict = {"comtype": comtype, "validcoms": validcoms} + filelinelist.append(validcomdict) + + for atlinefound in filelinelist: + + comtype = atlinefound["comtype"] + validcoms = atlinefound["validcoms"] + + comtypedict = str(comtype + "_commands") + + bot.memory['Sopel-CommandsQuery'][comtypedict + "_count"] += 1 + + # default command to filename + if "validcoms" not in dict_from_file.keys(): + dict_from_file["validcoms"] = validcoms + + maincom = dict_from_file["validcoms"][0] + if len(dict_from_file["validcoms"]) > 1: + comaliases = spicemanip.main(dict_from_file["validcoms"], '2+', 'list') + else: + comaliases = [] + + bot.memory['Sopel-CommandsQuery'][comtypedict][maincom] = dict_from_file + for comalias in comaliases: + if comalias not in bot.memory['Sopel-CommandsQuery'][comtypedict].keys(): + bot.memory['Sopel-CommandsQuery'][comtypedict][comalias] = {"aliasfor": maincom} + + for comtype in ['module_commands', 'nickname_commands', 'rule_commands']: + stderr("[Sopel-CommandsQuery] Found " + str(len(bot.memory['Sopel-CommandsQuery'][comtype].keys())) + " " + comtype + " commands.") + + set_bot_event(bot, "Sopel-CommandsQuery") + + +@sopel.module.rule('^\?(.*)') +def query_detection(bot, trigger): + + while "Sopel-CommandsQuery" not in bot.memory: + pass + + # command must start with + if not str(trigger).startswith(tuple(['?'])): + return + stderr(trigger.args) + + commands_list = dict() + for commandstype in bot.memory['Sopel-CommandsQuery'].keys(): + if not commandstype.endswith("_count"): + for com in bot.memory['Sopel-CommandsQuery'][commandstype].keys(): + if com not in commands_list.keys(): + commands_list[com] = bot.memory['Sopel-CommandsQuery'][commandstype][com] + + triggerargsarray = spicemanip.main(trigger, 'create') + + # command issued, check if valid + querycommand = spicemanip.main(triggerargsarray, 1).lower()[1:] + if len(querycommand) == 1: + commandlist = [] + for command in commands_list.keys(): + if command.lower().startswith(querycommand): + commandlist.append(command) + if commandlist == []: + bot.notice("No commands match " + str(querycommand) + ".", trigger.nick) + return + else: + bot.notice("The following commands match " + str(querycommand) + ": " + spicemanip.main(commandlist, 'andlist') + ".", trigger.nick) + return + + elif querycommand.endswith(tuple(["+"])): + querycommand = querycommand[:-1] + if querycommand not in commands_list.keys(): + bot.notice("The " + str(querycommand) + " does not appear to be valid.") + return + realcom = querycommand + if "aliasfor" in commands_list[querycommand].keys(): + realcom = commands_list[querycommand]["aliasfor"] + validcomlist = commands_list[realcom]["validcoms"] + bot.notice("The following commands match " + str(querycommand) + ": " + spicemanip.main(validcomlist, 'andlist') + ".", trigger.nick) + return + + elif querycommand.endswith(tuple(['?'])): + querycommand = querycommand[:-1] + sim_com, sim_num = [], [] + for com in commands_list.keys(): + similarlevel = SequenceMatcher(None, querycommand.lower(), com.lower()).ratio() + sim_com.append(com) + sim_num.append(similarlevel) + sim_num, sim_com = (list(x) for x in zip(*sorted(zip(sim_num, sim_com), key=itemgetter(0)))) + closestmatch = spicemanip.main(sim_com, 'reverse', "list") + listnumb, relist = 1, [] + for item in closestmatch: + if listnumb <= 10: + relist.append(str(item)) + listnumb += 1 + bot.notice("The following commands may match " + str(querycommand) + ": " + spicemanip.main(relist, 'andlist') + ".", trigger.nick) + return + + elif querycommand in commands_list.keys(): + bot.notice("The following commands match " + str(querycommand) + ": " + str(querycommand) + ".", trigger.nick) + return + + elif not querycommand: + return + + else: + commandlist = [] + for command in commands_list.keys(): + if command.lower().startswith(querycommand): + commandlist.append(command) + if commandlist == []: + bot.notice("No commands match " + str(querycommand) + ".", trigger.nick) + return + else: + bot.notice("The following commands match " + str(querycommand) + ": " + spicemanip.main(commandlist, 'andlist') + ".", trigger.nick) + return + + +def commandsquery_register(bot, command_type, validcoms, aliasfor=None): + + if not isinstance(validcoms, list): + validcoms = [validcoms] + + if 'Sopel-CommandsQuery' not in bot.memory: + bot.memory['Sopel-CommandsQuery'] = dict() + + if command_type not in bot.memory['Sopel-CommandsQuery'].keys(): + bot.memory['Sopel-CommandsQuery'][command_type] = dict() + bot.memory['Sopel-CommandsQuery'][command_type + "_count"] = 0 + bot.memory['Sopel-CommandsQuery'][command_type + "_count"] += 1 + + dict_from_file = dict() + + # default command to filename + if "validcoms" not in dict_from_file.keys(): + dict_from_file["validcoms"] = validcoms + + if not aliasfor: + + maincom = dict_from_file["validcoms"][0] + if len(dict_from_file["validcoms"]) > 1: + comaliases = spicemanip.main(dict_from_file["validcoms"], '2+', 'list') + else: + comaliases = [] + bot.memory['Sopel-CommandsQuery'][command_type][maincom] = dict_from_file + else: + comaliases = validcoms + + for comalias in comaliases: + if comalias not in bot.memory['Sopel-CommandsQuery'][command_type].keys(): + bot.memory['Sopel-CommandsQuery'][command_type][comalias] = {"aliasfor": aliasfor} diff --git a/sopel_modules/SpiceBot_CommandsQuery/__init__.py b/sopel_modules/SpiceBot_CommandsQuery/__init__.py new file mode 100644 index 0000000..a169d76 --- /dev/null +++ b/sopel_modules/SpiceBot_CommandsQuery/__init__.py @@ -0,0 +1,12 @@ +# coding=utf8 +"""Sopel Commands Query + +Sopel Commands Query responds to ? to display commands matching patterns +""" +from __future__ import unicode_literals, absolute_import, division, print_function + +from .CommandsQuery import * + +__author__ = 'Sam Zick' +__email__ = 'sam@deathbybandaid.net' +__version__ = '0.1.0' From cb9ef6c436e8db871daf7cbd80480bf897d63681 Mon Sep 17 00:00:00 2001 From: deathbybandaid Date: Thu, 2 May 2019 20:04:22 -0400 Subject: [PATCH 4/4] CommandsQuery: Update Logic for sopel_modules --- sopel_modules/SpiceBot_CommandsQuery/CommandsQuery.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/sopel_modules/SpiceBot_CommandsQuery/CommandsQuery.py b/sopel_modules/SpiceBot_CommandsQuery/CommandsQuery.py index 3996216..c1b6cf1 100644 --- a/sopel_modules/SpiceBot_CommandsQuery/CommandsQuery.py +++ b/sopel_modules/SpiceBot_CommandsQuery/CommandsQuery.py @@ -50,11 +50,12 @@ def setup_thread(bot): # pypi installed try: import sopel_modules - pypi_modules = os.path.dirname(os.path.abspath(sopel_modules.__file__)) - pypi_modules_dir = os.path.join(pypi_modules, 'modules') - filepathlisting.append(pypi_modules_dir) + for plugin_dir in set(sopel_modules.__path__): + for pathname in os.listdir(plugin_dir): + pypi_modules_dir = os.path.join(plugin_dir, pathname) + filepathlisting.append(pypi_modules_dir) except Exception as e: - stderr("[Sopel-CommandsQuery] sopel_modules not found:" + str(e)) + stderr("[Sopel-CommandsQuery] sopel_modules not loaded :" + str(e)) # Extra directories filepathlist = [] @@ -159,7 +160,6 @@ def query_detection(bot, trigger): # command must start with if not str(trigger).startswith(tuple(['?'])): return - stderr(trigger.args) commands_list = dict() for commandstype in bot.memory['Sopel-CommandsQuery'].keys():