from spanky.hook2 import ( Hook, Command, ComplexCommand, ActionCommand, EventType, MiddlewareResult, ) from nextcord import AllowedMentions from spanky.utils import discord_utils as dutils no_mention = AllowedMentions.none() # TODO: storage might be unsafe? hook = Hook("cmd_owner_hook", storage_name="plugins_admin.json") @hook.global_middleware(priority=15) def check_cmd_owner(action: ActionCommand, hooklet: Command): if action.is_pm: return # If not already admin, we should add that he is "technically" an admin for the owner. cmd = CmdPerms(hook.server_storage(action.server_id), action.triggered_command) if "admin" not in action.context["perms"]["creds"]: allowed_roles = set(cmd.owners) user_roles = set([i.id for i in action.author.roles]) if user_roles & allowed_roles: action.context["perms"]["creds"].append("admin")
Created By: - Luke Rogers <https://github.com/lukeroge> License: GPL v3 """ import codecs import json import os from spanky.utils import formatting, textgen from spanky.hook2 import Hook hook = Hook("name_generator") def get_generator(_json): data = json.loads(_json) return textgen.TextGenerator(data["templates"], data["parts"], default_templates=data["default_templates"]) @hook.command(autohelp=False) def namegen(text, bot): """[generator|list] - generates some names using the chosen generator, or lists all generators if 'list' is specified :type bot: cloudbot.bot.CloudBot """
from spanky.hook2 import ( Hook, ActionCommand, Command, ComplexCommand, MiddlewareResult, ) hook = Hook("permission_hook", storage_name="plugins_admin") # Permission context creation and validation @hook.global_middleware(priority=0) def setup_perm_ctx(action: ActionCommand, hooklet: Command): action.context["perms"] = {"creds": []} @hook.global_middleware(priority=100) def finalize_perm_filter(action: ActionCommand, hooklet: Command): perms = hooklet.args.get("permissions", []) if not isinstance(perms, list): perms = [perms] new_perms = [] for perm in perms: if hasattr(perm, "value"): new_perms.append(perm.value) else: new_perms.append(perm) perms = set(new_perms) if perms == set():
import itertools import praw import random import spanky.utils.time_utils as tutils from spanky.plugin.permissions import Permission from spanky.hook2 import Hook, EventType, Command hook = Hook("image_generator", storage_name="plugins_image_generator") RODDIT_ID = "287285563118190592" TESTOSTERON = "611894947024470027" ROBYTE = "464089471806210049" BEN_SRV = "484640057764872193" DISO_SRV = "423964901128536065" TZ_SRV = "754550072955371620" TZ_SRV2 = "426392328429633542" TZ_SRV3 = "881138853765865493" TZ_SRV4 = "905470387717021696" DRUNKBOYZ_SRV = "418705572511219723" CNC_TEST_SRV = "648937029433950218" SERVERS = [ RODDIT_ID, TESTOSTERON, ROBYTE, BEN_SRV, DISO_SRV, TZ_SRV, TZ_SRV2,
import re from spanky.hook2 import Hook, EventType, ComplexCommand from spanky.plugin.permissions import Permission hook = Hook("log_events", storage_name="plugins_log_events") @hook.event(EventType.on_ready) def log_prepare(storage): if "chan_filter_list" not in storage.keys(): storage["chan_filter_list"] = [] if "evt_chan" not in storage.keys(): storage["evt_chan"] = None @hook.command(permissions=Permission.admin, format="chan") def set_event_log_chan(text, storage, str_to_id): """ <channel> - Activate event logging and log to channel. Logged events: user join, user leave, message edit, message delete, member update, member ban, member unban. """ storage["evt_chan"] = str_to_id(text) return "Done." @hook.command(permissions=Permission.admin) def clear_event_log_chan(storage): """ <channel> - Clear logging channel and deactivate logging. """
import os import datetime import spanky.utils.discord_utils as dutils import plugins.paged_content as paged import io import nextcord import csv from spanky.hook2 import Hook, Command, ComplexCommand from spanky.utils import time_utils from spanky.utils.volatile import set_vdata, get_vdata from collections import OrderedDict from spanky.plugin.permissions import Permission from spanky.hook2 import Hook, EventType, Command hook = Hook("temp_role", storage_name="plugins_temp_role") time_tokens = ["s", "m", "h", "d"] SEC_IN_MIN = 60 SEC_IN_HOUR = SEC_IN_MIN * 60 SEC_IN_DAY = SEC_IN_HOUR * 24 def log_action(storage, ret_val, send_embed, title): # If the command is set to log the action onto a channel if "modlog_chan" in storage: # Compose the reply log_text = "" for k, v in ret_val.items(): log_text += "**%s:** %s\n" % (k, v)
import codecs import os import random from spanky.hook2 import Hook, EventType hook = Hook("jokes") def load_joke_data(): global yo_momma, do_it, pun, confucious, one_liner, wisdom, book_puns, lawyerjoke, kero_sayings with codecs.open(os.path.join("plugin_data/yo_momma.txt"), encoding="utf-8") as f: yo_momma = [ line.strip() for line in f.readlines() if not line.startswith("//") ] with codecs.open(os.path.join("plugin_data/do_it.txt"), encoding="utf-8") as f: do_it = [ line.strip() for line in f.readlines() if not line.startswith("//") ] with codecs.open(os.path.join("plugin_data/puns.txt"), encoding="utf-8") as f: pun = [ line.strip() for line in f.readlines() if not line.startswith("//") ] with codecs.open(os.path.join("plugin_data/confucious.txt"),
import os import plugins.selector as selector import spanky.utils.carousel as carousel import spanky.utils.discord_utils as dutils from spanky.plugin.permissions import Permission from spanky.utils.volatile import set_vdata, get_vdata from spanky.hook2 import Hook, EventType, Command hook = Hook("role_selector", storage_name="plugins_role_selector") # selector.py is the generic implementation of the selector # role_selector.py is the plugin that manages the selectors # # Selector registration # # register_cmd(storage["selectors"][cmd], server) def register_cmd(cmd, server): """Register a user defined command""" cmd_name = cmd["name"] async def do_cmd(text, server, storage, event, send_embed, reply): print(f"Got selector {cmd_name}") if storage["selectors"][cmd_name]["roles"] == []: # TODO: For some reason, `return "No roles in selector"` does not work here reply("No roles in selector") return
from spanky.hook2 import Hook hook = Hook("debug_cmds") @hook.command(permissions="bot_owner") def inspect_hook(hook: Hook, text: str): if text == "": text = "bot_hook" hk = hook.root.find_hook(text) if not hk: return "Hook doesn't exist" info = f""" Name: {hk.hook_id} Children ({len(hk.children)}): {', '.join([child.hook_id for child in hk.children])} Comands ({len(hk.commands)}): {', '.join([cmd.name for cmd in hk.commands.values()])} Event Handlers ({len(hk.events)}): {', '.join([' '.join((name, hklt.event_type.name)) for name, hklt in hk.events.items()])} Periodics ({len(hk.periodics)}): {', '.join(hk.periodics.keys())} """ return info
from spanky.hook2 import Hook, ActionCommand, Command from spanky.hook2.hooklet import MiddlewareResult from spanky.plugin.hook_parameters import map_params, extract_params hook = Hook("legacy_compat_hook") @hook.global_middleware(priority=4) def check_format(action: ActionCommand, hooklet: Command): cmd_format = hooklet.args.get("format", None) if cmd_format == None: return MiddlewareResult.CONTINUE if len(cmd_format.split()) != len(action.text.split()): msg = "Invalid format" if hooklet.get_doc(no_format=True): msg += ": " + "\n`" + hooklet.get_doc().strip() + "`" return MiddlewareResult.DENY, msg # cmd_args are used for image-related stuff @hook.global_middleware(priority=4) def command_args(action: ActionCommand, hooklet: Command): param_list = hooklet.args.get("params", None) if param_list == None: return param_list = extract_params(param_list) action.context["cmd_args"] = map_params(action.text, param_list)
import random from spanky.hook2 import Hook hook = Hook("lurve") @hook.command() def lurve(text, event): """lurves all over <user>""" target = text.strip() # Use {N} to represent the person's nickname who is performing the action # Use {T} to represent the person's nickname who is the target of the action loving = [ "{N} wraps arms around {T} and clings forever", "{N} cuddles {T} in the fluffiest blanket ever", "{N} lays their head on the lap of {T} and goes to sleep, dreaming da best sweet dreams", "{N} caresses {T}'s hair", "{N} caresses {T}'s cheek", "{N} plants a shy kiss on {T}'s cheek", "{N} gives {T} a BIIIIIIIIG hug!!!", "{N} lovingly tackles {T} into a pit of the softest pillows ever", "{N} cheers happily for {T}!!", "{N} pulls {T} back into bed for more cuddles ♥~", "{N} snuggles {T} for Netflix and chili popcorn", "{N} happily kisses {T} on the cheek", "{N} shares a milkshake with {T}", ] out = "{}".format(random.choice(loving))
from spanky.hook2 import Hook, EventType, ComplexCommand # Așa creem un hook pentru acest plugin hook = Hook("hook2_example_plugin") """ Un mic ghid pentru schimbarile mai mari: @hook.on_connection_ready -> @hook.event(EventType.on_conn_ready) @hook.on_ready -> @hook.event(EventType.on_ready) @hook.on_start -> @hook.event(EventType.on_start) """ @hook.command() def test_hook2(reply): reply("COMMAND EXECUTED WITH HOOK2") # test_cmd se ataseaza la hook și definim ulterior subcomenzile (și help-ul, care e fallback pentru nicio comandă și subcomandă invalidă) test_cmd = ComplexCommand(hook, "test_cmd") @test_cmd.subcommand() def subcmd(): return "Cf" @test_cmd.subcommand() def subcmd2(): return "Subcomandă"
import asyncpraw import time from spanky.hook2 import Hook, EventType from spanky.plugin.permissions import Permission storages = {} servers = {} hook = Hook("watcher", storage_name="plugins_watch") def set_crt_timestamp(storage): epoch = int(time.time()) if not storage["subs"]: storage["subs"] = {} for sub in storage["subs"].keys(): storage["subs"][sub]["timestamp"] = epoch storage.sync() @hook.event(EventType.on_ready) def ready(server, storage): storages[server.id] = storage servers[server.id] = server # Set the current time for each subreddit set_crt_timestamp(storage)
import subprocess from oslo_concurrency import lockutils from wand.image import Image as wand_img from spanky.hook2 import Hook, EventType hook = Hook("img_manip") @lockutils.synchronized("not_thread_safe") def make_df(frame): frame.transform(resize="800x800>") frame.contrast_stretch(black_point=0.4, white_point=0.5) frame.modulate(saturation=800) frame.compression_quality = 2 return frame @hook.command() def df(event, send_file, send_message): """ Deepfry image """ for img in event.image: img.proc_each_wand_frame(make_df, send_file, send_message) @lockutils.synchronized("not_thread_safe") def make_flip(frame): frame.flip()
return requests.get(API_URL.format(quote_plus(currency))) def alias_wrapper(alias): def func(text, reply): return crypto_command(" ".join((alias.name, text)), reply) func.__doc__ = """- Returns the current {} value""".format(alias.name) func.__name__ = alias.name + "_alias" return func from spanky.hook2 import Hook, EventType, Command hook = Hook("crypto") @hook.event(EventType.on_start) def init_aliases(): for alias in ALIASES: if alias.nocmd: continue hook.command(name=alias.cmds)(alias_wrapper(alias)) @hook.command() def serak(): msg = "\n" for cur in ALIASES: msg += crypto_command(cur.name, None) + "\n"
# -*- coding: utf-8 -*- import math import random import time from collections import deque from spanky.hook2 import Hook, EventType LARROW = u"⬅" RARROW = u"➡" RANDOM = u"🔢" TIMEOUT = 5 elements = deque(maxlen=10) hook = Hook("paged_content") class element: def __init__( self, text_list, send_func, description="", max_lines=10, max_line_len=200, no_timeout=False, with_quotes=True, ): self.max_lines = max_lines self.crt_idx = 0 self.description = description
from spanky.hook2 import Hook, ActionCommand, Command from spanky.hook2.hooklet import MiddlewareResult hook = Hook("serverid_hook") @hook.global_middleware(priority=1) def check_server_id(action: ActionCommand, hooklet: Command): good_server = True server_id = hooklet.args.get("server_id", None) if server_id == None: return MiddlewareResult.CONTINUE if isinstance(server_id, int): server_id = str(server_id) if action.is_pm: return MiddlewareResult.DENY, "" if type(server_id) == str: good_server = action.server_id == server_id elif type(server_id) == list: good_server = action.server_id in server_id else: print(f"Unknown server_id type for hooklet {hooklet.hooklet_id}") good_server = False if not good_server: return MiddlewareResult.DENY, ""
from spanky.hook2 import Hook, ActionCommand, Command from spanky.hook2.hooklet import MiddlewareResult hook = Hook("pm_hook") @hook.global_middleware(priority=5) def handle_pm(action: ActionCommand, hooklet: Command): can_pm = hooklet.args.get("can_pm", False) pm_only = hooklet.args.get("pm_only", False) if pm_only: can_pm = True if action.is_pm and not can_pm: return MiddlewareResult.DENY, "Command cannot be run in DM" if not action.is_pm and pm_only: return MiddlewareResult.DENY, "Command can only be run in DM"