diff --git a/MANIFEST.in b/MANIFEST.in index 60ca266..5e2e278 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -6,3 +6,4 @@ include *requirements.txt recursive-include tests * recursive-exclude * __pycache__ recursive-exclude * *.py[co] +recursive-include sopel_modules/SpiceBot_GifSearch/gifapi * diff --git a/requirements.txt b/requirements.txt index 25327ab..b8b4d4e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,3 +2,4 @@ sopel>=6.0,<7 spicemanip>=0.1.6 gitpython sopel-modules.osd +fake-useragent diff --git a/sopel_modules/SpiceBot_CommandsQuery/CommandsQuery.py b/sopel_modules/SpiceBot_CommandsQuery/CommandsQuery.py index 27d1fe6..81080b5 100644 --- a/sopel_modules/SpiceBot_CommandsQuery/CommandsQuery.py +++ b/sopel_modules/SpiceBot_CommandsQuery/CommandsQuery.py @@ -22,17 +22,17 @@ def configure(config): def setup(bot): - stderr("[Sopel-CommandsQuery] Evaluating Core Commands List") + stderr("[SpiceBot_CommandsQuery] Evaluating Core Commands List") threading.Thread(target=setup_thread, args=(bot,)).start() def setup_thread(bot): - bot.memory['Sopel-CommandsQuery'] = dict() + bot.memory['SpiceBot_CommandsQuery'] = dict() for comtype in ['module', 'nickname', 'rule']: - bot.memory['Sopel-CommandsQuery'][comtype + "_commands"] = dict() - bot.memory['Sopel-CommandsQuery'][comtype + "_commands_count"] = 0 + bot.memory['SpiceBot_CommandsQuery'][comtype + "_commands"] = dict() + bot.memory['SpiceBot_CommandsQuery'][comtype + "_commands_count"] = 0 filepathlisting = [] @@ -54,7 +54,7 @@ def setup_thread(bot): pypi_modules_dir = os.path.join(plugin_dir, pathname) filepathlisting.append(pypi_modules_dir) except Exception as e: - stderr("[Sopel-CommandsQuery] sopel_modules not loaded :" + str(e)) + stderr("[SpiceBot_CommandsQuery] sopel_modules not loaded :" + str(e)) # Extra directories filepathlist = [] @@ -127,7 +127,7 @@ def setup_thread(bot): comtypedict = str(comtype + "_commands") - bot.memory['Sopel-CommandsQuery'][comtypedict + "_count"] += 1 + bot.memory['SpiceBot_CommandsQuery'][comtypedict + "_count"] += 1 # default command to filename if "validcoms" not in dict_from_file.keys(): @@ -139,21 +139,21 @@ def setup_thread(bot): else: comaliases = [] - bot.memory['Sopel-CommandsQuery'][comtypedict][maincom] = dict_from_file + bot.memory['SpiceBot_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} + if comalias not in bot.memory['SpiceBot_CommandsQuery'][comtypedict].keys(): + bot.memory['SpiceBot_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.") + stderr("[SpiceBot_CommandsQuery] Found " + str(len(bot.memory['SpiceBot_CommandsQuery'][comtype].keys())) + " " + comtype + " commands.") - set_bot_event(bot, "Sopel-CommandsQuery") + set_bot_event(bot, "SpiceBot_CommandsQuery") @sopel.module.rule('^\?(.*)') def query_detection(bot, trigger): - while "Sopel-CommandsQuery" not in bot.memory: + while "SpiceBot_CommandsQuery" not in bot.memory: pass # command must start with @@ -161,11 +161,11 @@ def query_detection(bot, trigger): return commands_list = dict() - for commandstype in bot.memory['Sopel-CommandsQuery'].keys(): + for commandstype in bot.memory['SpiceBot_CommandsQuery'].keys(): if not commandstype.endswith("_count"): - for com in bot.memory['Sopel-CommandsQuery'][commandstype].keys(): + for com in bot.memory['SpiceBot_CommandsQuery'][commandstype].keys(): if com not in commands_list.keys(): - commands_list[com] = bot.memory['Sopel-CommandsQuery'][commandstype][com] + commands_list[com] = bot.memory['SpiceBot_CommandsQuery'][commandstype][com] triggerargsarray = spicemanip.main(trigger, 'create') @@ -232,18 +232,28 @@ def query_detection(bot, trigger): return +def commandsquery_register_type(bot, command_type): + if 'SpiceBot_CommandsQuery' not in bot.memory: + bot.memory['SpiceBot_CommandsQuery'] = dict() + + if command_type not in bot.memory['SpiceBot_CommandsQuery'].keys(): + bot.memory['SpiceBot_CommandsQuery'][command_type] = dict() + bot.memory['SpiceBot_CommandsQuery'][command_type + "_count"] = 0 + bot.memory['SpiceBot_CommandsQuery'][command_type + "_count"] += 1 + + 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 'SpiceBot_CommandsQuery' not in bot.memory: + bot.memory['SpiceBot_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 + if command_type not in bot.memory['SpiceBot_CommandsQuery'].keys(): + bot.memory['SpiceBot_CommandsQuery'][command_type] = dict() + bot.memory['SpiceBot_CommandsQuery'][command_type + "_count"] = 0 + bot.memory['SpiceBot_CommandsQuery'][command_type + "_count"] += 1 dict_from_file = dict() @@ -258,10 +268,10 @@ def commandsquery_register(bot, command_type, validcoms, aliasfor=None): comaliases = spicemanip.main(dict_from_file["validcoms"], '2+', 'list') else: comaliases = [] - bot.memory['Sopel-CommandsQuery'][command_type][maincom] = dict_from_file + bot.memory['SpiceBot_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} + if comalias not in bot.memory['SpiceBot_CommandsQuery'][command_type].keys(): + bot.memory['SpiceBot_CommandsQuery'][command_type][comalias] = {"aliasfor": aliasfor} diff --git a/sopel_modules/SpiceBot_GifSearch/__init__.py b/sopel_modules/SpiceBot_GifSearch/__init__.py new file mode 100644 index 0000000..3aee2ea --- /dev/null +++ b/sopel_modules/SpiceBot_GifSearch/__init__.py @@ -0,0 +1,14 @@ +# coding=utf8 +"""Sopel Gif Search + +Sopel Gif Search builds a convenient framework for searching for Gifs +""" +from __future__ import unicode_literals, absolute_import, division, print_function + +from .gif import * +from .gifapi import * +from .gifsearch import * + +__author__ = 'Sam Zick' +__email__ = 'sam@deathbybandaid.net' +__version__ = '0.1.0' diff --git a/sopel_modules/SpiceBot_GifSearch/gif.py b/sopel_modules/SpiceBot_GifSearch/gif.py new file mode 100644 index 0000000..a5f4724 --- /dev/null +++ b/sopel_modules/SpiceBot_GifSearch/gif.py @@ -0,0 +1,35 @@ +# coding=utf-8 + +from __future__ import unicode_literals, absolute_import, division, print_function + +from sopel import module + +from .gifsearch import getGif + +import sopel_modules.osd + +from sopel_modules.SpiceBot_SBTools import sopel_triggerargs + +import spicemanip + + +@module.commands('gif') +def gif_trigger(bot, trigger): + + while "SpiceBot_GifSearch" not in bot.memory: + pass + + triggerargs = sopel_triggerargs(bot, trigger) + if triggerargs == []: + return bot.osd("Please present a query to search.") + + query = spicemanip.main(triggerargs, 0) + searchapis = bot.memory["SpiceBot_GifSearch"]['valid_gif_api_dict'].keys() + searchdict = {"query": query, "gifsearch": searchapis} + + gifdict = getGif(bot, searchdict) + + if gifdict["error"]: + bot.osd(gifdict["error"]) + else: + bot.osd(str(gifdict['gifapi'].title() + " Result (" + str(query) + " #" + str(gifdict["returnnum"]) + "): " + str(gifdict["returnurl"]))) diff --git a/sopel_modules/SpiceBot_GifSearch/gifapi.py b/sopel_modules/SpiceBot_GifSearch/gifapi.py new file mode 100644 index 0000000..36e0b87 --- /dev/null +++ b/sopel_modules/SpiceBot_GifSearch/gifapi.py @@ -0,0 +1,38 @@ +# coding=utf-8 + +from __future__ import unicode_literals, absolute_import, division, print_function + +from .gifsearch import getGif + +import sopel.module + +import sopel_modules.osd + +import spicemanip + +from sopel_modules.SpiceBot_SBTools import sopel_triggerargs + + +@sopel.module.commands('(.*)') +def gifapi_triggers(bot, trigger): + + while "SpiceBot_GifSearch" not in bot.memory: + pass + + triggerargs, prefixcommand = sopel_triggerargs(bot, trigger, 'prefix_command') + + if prefixcommand not in bot.memory["SpiceBot_GifSearch"]['valid_gif_api_dict'].keys(): + return + + if triggerargs == []: + return bot.osd("Please present a query to search.") + + query = spicemanip.main(triggerargs, 0) + searchdict = {"query": query, "gifsearch": prefixcommand} + + gifdict = getGif(bot, searchdict) + + if gifdict["error"]: + bot.osd(gifdict["error"]) + else: + bot.osd(str(gifdict['gifapi'].title() + " Result (" + str(query) + " #" + str(gifdict["returnnum"]) + "): " + str(gifdict["returnurl"]))) diff --git a/sopel_modules/SpiceBot_GifSearch/gifapi/gfycat b/sopel_modules/SpiceBot_GifSearch/gifapi/gfycat new file mode 100644 index 0000000..81da56d --- /dev/null +++ b/sopel_modules/SpiceBot_GifSearch/gifapi/gfycat @@ -0,0 +1,12 @@ +{ +"url": "https://api.gfycat.com/v1/gfycats/search?", +"query": 'search_text=', +"limit": '&count=', +"id": None, +"api_id": None, +"key": None, +"nsfw": '&nsfw=3', +"sfw": '&nsfw=1', +"results": 'gfycats', +"cururl": 'gifUrl', +} diff --git a/sopel_modules/SpiceBot_GifSearch/gifapi/gifme b/sopel_modules/SpiceBot_GifSearch/gifapi/gifme new file mode 100644 index 0000000..7839724 --- /dev/null +++ b/sopel_modules/SpiceBot_GifSearch/gifapi/gifme @@ -0,0 +1,12 @@ +{ +"url": "http://api.gifme.io/v1/search?", +"query": 'query=', +"limit": '&limit=', +"id": None, +"api_id": None, +"key": "&key=", +"nsfw": '&sfw=false', +"sfw": '&sfw=true', +"results": 'data', +"cururl": 'link', +} diff --git a/sopel_modules/SpiceBot_GifSearch/gifapi/giphy b/sopel_modules/SpiceBot_GifSearch/gifapi/giphy new file mode 100644 index 0000000..d1c7dcf --- /dev/null +++ b/sopel_modules/SpiceBot_GifSearch/gifapi/giphy @@ -0,0 +1,12 @@ +{ +"url": "http://api.giphy.com/v1/gifs/search?", +"query": 'q=', +"limit": '&limit=', +"id": None, +"api_id": None, +"key": "&api_key=", +"nsfw": None, +"sfw": 'rating=R', +"results": 'data', +"cururl": 'url', +} diff --git a/sopel_modules/SpiceBot_GifSearch/gifapi/tenor b/sopel_modules/SpiceBot_GifSearch/gifapi/tenor new file mode 100644 index 0000000..bf36873 --- /dev/null +++ b/sopel_modules/SpiceBot_GifSearch/gifapi/tenor @@ -0,0 +1,12 @@ +{ +"url": "https://api.tenor.com/v1/search?", +"query": 'q=', +"limit": '&limit=', +"id": None, +"api_id": None, +"key": "&key=", +"nsfw": '&contentfilter=off', +"sfw": '&contentfilter=low', +"results": 'results', +"cururl": 'url', +} diff --git a/sopel_modules/SpiceBot_GifSearch/gifsearch.py b/sopel_modules/SpiceBot_GifSearch/gifsearch.py new file mode 100644 index 0000000..6922d29 --- /dev/null +++ b/sopel_modules/SpiceBot_GifSearch/gifsearch.py @@ -0,0 +1,278 @@ +# coding=utf-8 + +from __future__ import unicode_literals, absolute_import, division, print_function + +import sopel.module +from sopel.tools import stderr +from sopel.config.types import StaticSection, ValidatedAttribute + +import sopel_modules.osd + +from sopel_modules.SpiceBot_Botevents.BotEvents import set_bot_event, check_bot_events, startup_bot_event + +from sopel_modules.SpiceBot_CommandsQuery.CommandsQuery import commandsquery_register, commandsquery_register_type + +from sopel_modules.SpiceBot_SBTools import read_directory_json_to_dict, sopel_triggerargs + +import spicemanip + +import os +import urllib +import requests +import json +from fake_useragent import UserAgent +import random +import threading + +# user agent and header +ua = UserAgent() +header = {'User-Agent': str(ua.chrome)} + + +class GifAPIMainSection(StaticSection): + extra = ValidatedAttribute('extra', default=None) + nsfw = ValidatedAttribute('nsfw', default=False) + + +class GifAPISection(StaticSection): + apikey = ValidatedAttribute('apikey', default=None) + + +def configure(config): + moduledir = os.path.dirname(os.path.abspath(__file__)) + api_dir = os.path.join(moduledir, 'gifapi') + valid_gif_api_dict = read_directory_json_to_dict([api_dir], "Gif API", "[SpiceBot_GifSearch] ") + + config.define_section("SopelGifSearch", GifAPIMainSection, validate=False) + config.SopelGifSearch.configure_setting('extra', 'SpiceBot_GifSearch API Extra directory') + config.SopelGifSearch.configure_setting('nsfw', 'SpiceBot_GifSearch API nsfw content') + + for gif_api in valid_gif_api_dict.keys(): + config.define_section(gif_api, GifAPISection, validate=False) + gif_api_config = eval("config." + gif_api) + gif_api_config.configure_setting('apikey', 'GIF API Client ID-' + gif_api) + + +def setup(bot): + + stderr("[SpiceBot_GifSearch] Starting Setup Procedure") + + threading.Thread(target=setup_thread, args=(bot,)).start() + + +def setup_thread(bot): + + startup_bot_event(bot, "SpiceBot_GifSearch") + + bot.memory["SpiceBot_GifSearch"] = {"cache": {}, "badgiflinks": [], 'valid_gif_api_dict': {}} + + dir_to_scan = [] + + moduledir = os.path.dirname(os.path.abspath(__file__)) + api_dir = os.path.join(moduledir, 'gifapi') + dir_to_scan.append(api_dir) + + bot.config.define_section("SopelGifSearch", GifAPIMainSection, validate=False) + if bot.config.SopelGifSearch.extra: + dir_to_scan.append(bot.config.SopelGifSearch.extra) + + valid_gif_api_dict = read_directory_json_to_dict(dir_to_scan, "Gif API", "[SpiceBot_GifSearch] ") + + for gif_api in valid_gif_api_dict.keys(): + bot.config.define_section(gif_api, GifAPISection, validate=False) + apikey = eval("bot.config." + gif_api + ".apikey") + if apikey: + valid_gif_api_dict[gif_api]["apikey"] = apikey + else: + valid_gif_api_dict[gif_api]["apikey"] = None + bot.memory["SpiceBot_GifSearch"]['valid_gif_api_dict'][gif_api] = valid_gif_api_dict[gif_api] + + while not check_bot_events(bot, ["SpiceBot_CommandsQuery"]): + pass + + commandsquery_register_type(bot, "prefix_command") + for prefix_command in bot.memory["SpiceBot_GifSearch"]['valid_gif_api_dict'].keys(): + commandsquery_register(bot, "prefix_command", prefix_command) + + stderr("[SpiceBot_CommandsQuery] Found " + str(len(bot.memory['SpiceBot_CommandsQuery']["prefix_command"].keys())) + " " + "prefix_command" + " commands.") + + set_bot_event(bot, "SpiceBot_GifSearch") + + +@sopel.module.commands('gif') +def gif_trigger(bot, trigger): + triggerargs = sopel_triggerargs(bot, trigger) + if triggerargs == []: + return bot.osd("Please present a query to search.") + + query = spicemanip.main(trigger.args[1], 0) + searchapis = bot.memory["SpiceBot_GifSearch"]['valid_gif_api_dict'].keys() + searchdict = {"query": query, "gifsearch": searchapis} + + gifdict = getGif(bot, searchdict) + + if gifdict["error"]: + bot.osd(gifdict["error"]) + else: + bot.osd(str(gifdict['gifapi'].title() + " Result (" + str(query) + " #" + str(gifdict["returnnum"]) + "): " + str(gifdict["returnurl"]))) + + +def getGif(bot, searchdict): + + # list of defaults + query_defaults = { + "query": None, + "searchnum": 'random', + "gifsearch": bot.memory["SpiceBot_GifSearch"]['valid_gif_api_dict'].keys(), + "gifsearchremove": ['gifme'], + "searchlimit": 'default', + "nsfw": False, + } + + if bot.config.SopelGifSearch.nsfw: + query_defaults["nsfw"] = True + + # set defaults if they don't exist + for key in query_defaults: + if key not in searchdict.keys(): + searchdict[key] = query_defaults[key] + if key == "gifsearch": + for remx in query_defaults["gifsearchremove"]: + searchdict["gifsearch"].remove(remx) + + # Replace spaces in search query + if not searchdict["query"]: + return {"error": 'No Query to Search'} + # searchdict["searchquery"] = searchdict["query"].replace(' ', '%20') + searchdict["searchquery"] = urllib.request.pathname2url(searchdict["query"]) + + # set api usage + if not isinstance(searchdict['gifsearch'], list): + if str(searchdict['gifsearch']) in bot.memory["SpiceBot_GifSearch"]['valid_gif_api_dict'].keys(): + searchdict['gifsearch'] = [searchdict['gifsearch']] + else: + searchdict['gifsearch'] = bot.memory["SpiceBot_GifSearch"]['valid_gif_api_dict'].keys() + else: + for apis in searchdict['gifsearch']: + if apis not in bot.memory["SpiceBot_GifSearch"]['valid_gif_api_dict'].keys(): + searchdict['gifsearch'].remove(apis) + + # Verify search limit + if searchdict['searchlimit'] == 'default' or not isinstance(searchdict['searchlimit'], int): + searchdict['searchlimit'] = 50 + + # Random handling for searchnum + if searchdict["searchnum"] == 'random': + searchdict["searchnum"] = random.randint(0, searchdict['searchlimit']) + + # Make sure there is a valid input of query and search number + if not searchdict["query"]: + return {"error": 'No Query to Search'} + + if not str(searchdict["searchnum"]).isdigit(): + return {"error": 'No Search Number or Random Specified'} + + gifapiresults = [] + for currentapi in searchdict['gifsearch']: + + # url base + url = str(bot.memory["SpiceBot_GifSearch"]['valid_gif_api_dict'][currentapi]['url']) + # query + url += str(bot.memory["SpiceBot_GifSearch"]['valid_gif_api_dict'][currentapi]['query']) + str(searchdict["searchquery"]) + # limit + url += str(bot.memory["SpiceBot_GifSearch"]['valid_gif_api_dict'][currentapi]['limit']) + str(searchdict["searchlimit"]) + # nsfw search? + if searchdict['nsfw']: + url += str(bot.memory["SpiceBot_GifSearch"]['valid_gif_api_dict'][currentapi]['nsfw']) + else: + url += str(bot.memory["SpiceBot_GifSearch"]['valid_gif_api_dict'][currentapi]['sfw']) + # api key + url += str(bot.memory["SpiceBot_GifSearch"]['valid_gif_api_dict'][currentapi]['key']) + str(bot.memory["SpiceBot_GifSearch"]['valid_gif_api_dict'][currentapi]['apikey']) + + if currentapi not in bot.memory["SpiceBot_GifSearch"]['cache'].keys(): + bot.memory["SpiceBot_GifSearch"]['cache'][currentapi] = dict() + + if str(searchdict["searchquery"]) not in bot.memory["SpiceBot_GifSearch"]['cache'][currentapi].keys(): + bot.memory["SpiceBot_GifSearch"]['cache'][currentapi][str(searchdict["searchquery"])] = [] + + if bot.memory["SpiceBot_GifSearch"]['cache'][currentapi][str(searchdict["searchquery"])] == []: + + try: + page = requests.get(url, headers=header) + except Exception as e: + page = None + + if page and not str(page.status_code).startswith(tuple(["4", "5"])): + + data = json.loads(urllib.request.urlopen(url).read().decode('utf-8')) + + results = data[bot.memory["SpiceBot_GifSearch"]['valid_gif_api_dict'][currentapi]['results']] + resultsarray = [] + for result in results: + appendresult = False + cururl = result[bot.memory["SpiceBot_GifSearch"]['valid_gif_api_dict'][currentapi]['cururl']] + slashsplit = str(cururl).split("/") + fileextension = slashsplit[-1] + if not fileextension or fileextension == '': + appendresult = True + elif str(fileextension).endswith(".gif"): + appendresult = True + elif "." not in str(fileextension): + appendresult = True + if appendresult: + resultsarray.append(cururl) + + # make sure there are results + if resultsarray != []: + + # Create Temp dict for every result + tempresultnum = 0 + for tempresult in resultsarray: + if tempresult not in bot.memory["SpiceBot_GifSearch"]["badgiflinks"]: + tempresultnum += 1 + tempdict = dict() + tempdict["returnnum"] = tempresultnum + tempdict["returnurl"] = tempresult + tempdict["gifapi"] = currentapi + bot.memory["SpiceBot_GifSearch"]['cache'][currentapi][str(searchdict["searchquery"])].append(tempdict) + + else: + verifygoodlinks = [] + for gifresult in bot.memory["SpiceBot_GifSearch"]['cache'][currentapi][str(searchdict["searchquery"])]: + if gifresult["returnurl"] not in bot.memory["SpiceBot_GifSearch"]["badgiflinks"]: + verifygoodlinks.append(gifresult) + bot.memory["SpiceBot_GifSearch"]['cache'][currentapi][str(searchdict["searchquery"])] = verifygoodlinks + + if bot.memory["SpiceBot_GifSearch"]['cache'][currentapi][str(searchdict["searchquery"])] != []: + gifapiresults.extend(bot.memory["SpiceBot_GifSearch"]['cache'][currentapi][str(searchdict["searchquery"])]) + + if gifapiresults == []: + return {"error": "No Results were found for '" + searchdict["query"] + "' in the " + str(spicemanip.main(searchdict['gifsearch'], 'orlist')) + " api(s)"} + + random.shuffle(gifapiresults) + random.shuffle(gifapiresults) + randombad = True + while randombad: + gifdict = spicemanip.main(gifapiresults, "random") + + try: + gifpage = requests.get(gifdict["returnurl"], headers=None) + except Exception as e: + gifpage = None + + if gifpage and not str(gifpage.status_code).startswith(tuple(["4", "5"])): + randombad = False + else: + bot.memory["SpiceBot_GifSearch"]["badgiflinks"].append(gifdict["returnurl"]) + newlist = [] + for tempdict in gifapiresults: + if tempdict["returnurl"] != gifdict["returnurl"]: + newlist.append(tempdict) + gifapiresults = newlist + + if gifapiresults == []: + return {"error": "No Results were found for '" + searchdict["query"] + "' in the " + str(spicemanip.main(searchdict['gifsearch'], 'orlist')) + " api(s)"} + + # return dict + gifdict['error'] = None + return gifdict diff --git a/sopel_modules/SpiceBot_SBTools/__init__.py b/sopel_modules/SpiceBot_SBTools/__init__.py index c055092..3596aaa 100644 --- a/sopel_modules/SpiceBot_SBTools/__init__.py +++ b/sopel_modules/SpiceBot_SBTools/__init__.py @@ -11,6 +11,7 @@ HOP = HALFOP import collections import re import os +import codecs import spicemanip @@ -18,7 +19,7 @@ import spicemanip """Sopel Wrapping Tools""" -def sopel_triggerargs(bot, trigger, command_type): +def sopel_triggerargs(bot, trigger, command_type='module_command'): triggerargs = [] if len(trigger.args) > 1: @@ -29,6 +30,10 @@ def sopel_triggerargs(bot, trigger, command_type): triggerargs = spicemanip.main(triggerargs, '2+', 'list') elif command_type in ['nickname_command']: triggerargs = spicemanip.main(triggerargs, '3+', 'list') + elif command_type in ['prefix_command']: + prefixcommand = spicemanip.main(triggerargs, 1).lower()[1:] + triggerargs = spicemanip.main(triggerargs, '2+', 'list') + return triggerargs, prefixcommand return triggerargs @@ -148,3 +153,55 @@ def spicebot_update(bot, deps="False"): path = os.path.join(modules_dir, pathname) if (os.path.isfile(path) and path.endswith('.py') and not path.startswith('_')): os.system("sudo mv " + path + " " + stockdir) + + +"""Config Reading Functions""" + + +def read_directory_json_to_dict(directories, configtypename="Config File", stderrname=''): + + if not isinstance(directories, list): + directories = [directories] + + configs_dict = {} + filesprocess, fileopenfail, filecount = [], 0, 0 + for directory in directories: + if os.path.exists(directory) and os.path.isdir(directory): + if len(os.listdir(directory)) > 0: + for file in os.listdir(directory): + filepath = os.path.join(directory, file) + if os.path.isfile(filepath): + filesprocess.append(filepath) + else: + stderr(stderrname + directory) + + for filepath in filesprocess: + + # Read dictionary from file, if not, enable an empty dict + filereadgood = True + inf = codecs.open(filepath, "r", encoding='utf-8') + infread = inf.read() + try: + dict_from_file = eval(infread) + except Exception as e: + filereadgood = False + stderr(stderrname + "Error loading %s: %s (%s)" % (configtypename, e, filepath)) + dict_from_file = dict() + # Close File + inf.close() + + if filereadgood and isinstance(dict_from_file, dict): + filecount += 1 + slashsplit = str(filepath).split("/") + filename = slashsplit[-1] + configs_dict[filename] = dict_from_file + else: + fileopenfail += 1 + + if filecount: + stderr(stderrname + 'Registered %d %s files,' % (filecount, configtypename)) + stderr(stderrname + '%d %s files failed to load' % (fileopenfail, configtypename)) + else: + stderr(stderrname + "Warning: Couldn't load any %s files" % (configtypename)) + + return configs_dict diff --git a/sopel_modules/SpiceBot_StartupMonologue/StartupMonologue.py b/sopel_modules/SpiceBot_StartupMonologue/StartupMonologue.py new file mode 100644 index 0000000..7817ca6 --- /dev/null +++ b/sopel_modules/SpiceBot_StartupMonologue/StartupMonologue.py @@ -0,0 +1,74 @@ +# coding=utf-8 + +from __future__ import unicode_literals, absolute_import, division, print_function + +from sopel import module +from sopel.tools import stderr + +import sopel_modules.osd + + +from sopel_modules.SpiceBot_Botevents.BotEvents import set_bot_event, check_bot_events + +from sopel_modules.SpiceBot_CommandsQuery.CommandsQuery import commandsquery_register + + +def configure(config): + pass + + +def setup(bot): + pass + + +@module.event('001') +@module.rule('.*') +@module.thread(True) +def bot_startup_monologue(bot, trigger): + + while not check_bot_events(bot, ["connected"]): + pass + + if check_bot_events(bot, ["SpiceBot_StartupMonologue"]): + startup_reconnect(bot, trigger) + else: + startup_fresh(bot, trigger) + + +def startup_fresh(bot, trigger): + + # Startup + stderr("[SpiceBot_StartupMonologue] " + bot.nick + " is now starting. Please wait while I load my configuration.") + bot.osd(" is now starting. Please wait while I load my configuration.", bot.channels.keys(), 'ACTION') + + startupcomplete = [bot.nick + " startup complete"] + + while not check_bot_events(bot, ["SpiceBot_CommandsQuery"]): + pass + + availablecomsnum, availablecomsfiles = 0, 0 + + for commandstype in bot.memory['SpiceBot_CommandsQuery'].keys(): + if commandstype.endswith("_count"): + availablecomsfiles += bot.memory['SpiceBot_CommandsQuery'][commandstype] + else: + availablecomsnum += len(bot.memory['SpiceBot_CommandsQuery'][commandstype].keys()) + + startupcomplete.append("There are " + str(availablecomsnum) + " commands available in " + str(availablecomsfiles) + " files.") + stderr("[SpiceBot_StartupMonologue] " + "There are " + str(availablecomsnum) + " commands available in " + str(availablecomsfiles) + " files.") + + while not check_bot_events(bot, ["startup_complete"]): + pass + + # Announce to chan, then handle some closing stuff + bot.osd(startupcomplete, bot.channels.keys()) + stderr("[SpiceBot_StartupMonologue] " + bot.nick + " startup complete") + + set_bot_event(bot, "SpiceBot_StartupMonologue") + + +def startup_reconnect(bot, trigger): + + # Startup + stderr("[SpiceBot_StartupMonologue] " + bot.nick + " has reconnected.") + bot.osd(" has reconnected.", bot.channels.keys(), 'ACTION') diff --git a/sopel_modules/SpiceBot_StartupMonologue/__init__.py b/sopel_modules/SpiceBot_StartupMonologue/__init__.py new file mode 100644 index 0000000..70dd200 --- /dev/null +++ b/sopel_modules/SpiceBot_StartupMonologue/__init__.py @@ -0,0 +1,12 @@ +# coding=utf8 +"""Sopel Startup Monologue + +Sopel Startup Monologue displays to all channels that the bot is online +""" +from __future__ import unicode_literals, absolute_import, division, print_function + +from .StartupMonologue import * + +__author__ = 'Sam Zick' +__email__ = 'sam@deathbybandaid.net' +__version__ = '0.1.0'