Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Help plugin #16

Merged
merged 9 commits into from
Jun 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions bench/FINDINGS.txt
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,11 @@ averaging 210 words per record

STRING.SPLIT IDENTICAL TO :binary.split()
GIVING STRING.SPLIT A PRECOMPILED PATTERN HELPS THE SPEED

BINARY MATCHING FROM PREMADE LIST IS FASTER THAN REGEX
##### With input 128 prefixed strings #####
Name ips average deviation median 99th %
Single-case Binary match split 79.90 K 12.52 μs ±408.49% 9.52 μs 27.70 μs
Binary match split 25.46 K 39.28 μs ±177.42% 32.96 μs 143.95 μs
Single-case Regex split 5.94 K 168.27 μs ±213.75% 152.29 μs 198.49 μs
Regex split 3.32 K 300.76 μs ±76.96% 286.42 μs 340.08 μs
87 changes: 87 additions & 0 deletions bench/prefix_checking.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
alias Stampede, as: S
require Stampede.MsgReceived
require Aja

defmodule T do
require Plugin
require Aja

def split_prefix_re(text, prefix) when is_struct(prefix, Regex) and is_binary(text) do
case Regex.split(prefix, text, include_captures: true, capture: :first, trim: true) do
[p, b] ->
{p, b}

[^text] ->
{false, text}

[] ->
{false, text}
end
end

def split_prefix(text, prefix) when is_binary(prefix) and is_binary(text) do
case text do
<<^prefix::binary-size(floor(bit_size(prefix) / 8)), _::binary>> ->
{
binary_part(text, 0, byte_size(prefix)),
binary_part(text, byte_size(prefix), byte_size(text) - byte_size(prefix))
}

not_prefixed ->
{false, not_prefixed}
end
end

def split_prefix(text, prefixes) when is_list(prefixes) and is_binary(text) do
prefixes
|> Enum.reduce(nil, fn
_, {s, b} ->
{s, b}

p, nil ->
{s, b} = split_prefix(text, p)
if s, do: {s, b}, else: nil
end)
|> then(fn
nil ->
{false, text}

{s, b} ->
{s, b}
end)
end

def make_input(pref, number) do
for n <- 0..(number - 1) do
Enum.at(pref, Integer.mod(n, length(pref))) <> String.duplicate("x", 16)
end
end
end

r = ~r/^[ab][cd]/
bl = ["ac", "bc", "ad", "bd"]
r2 = ~r/\!/
bl2 = ["!"]

inputs = %{
"128 prefixed strings" => T.make_input(bl, 128),
"128 non-prefixed" => Enum.map(0..127, fn _ -> String.duplicate("x", 18) end)
}

suites = %{
"Regex split" => &Enum.map(&1, fn x -> T.split_prefix_re(x, r) end),
"Binary match split" => &Enum.map(&1, fn x -> T.split_prefix(x, bl) end),
"Single-case Regex split" => &Enum.map(&1, fn x -> T.split_prefix_re(x, r2) end),
"Single-case Binary match split" => &Enum.map(&1, fn x -> T.split_prefix(x, bl2) end)
}

Benchee.run(
suites,
inputs: inputs,
time: 30,
memory_time: 5,
# profile_after: true,
# profile_after: :fprof
measure_function_call_overhead: true,
pre_check: true
)
1 change: 1 addition & 0 deletions config/config.exs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ config :logger, :console,
metadata: stampede_metadata ++ [:mfa]

config :logger,
truncate: :infinity,
handle_otp_reports: true,
# this will spam a lot of messages
handle_sasl_reports: false,
Expand Down
32 changes: 26 additions & 6 deletions lib/plugin.ex
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ defmodule Plugin do

@callback usage() :: usage_tuples()
@callback description() :: TxtBlock.t()
@callback description_long() :: TxtBlock.t()

defguard is_bot_invoked(msg)
when msg.at_bot? or msg.dm? or msg.prefix != false
Expand All @@ -59,7 +60,12 @@ defmodule Plugin do

defmacro __using__(_opts \\ []) do
quote do
@behaviour unquote(__MODULE__)
@behaviour Plugin

@impl Plugin
def description_long(), do: description()

defoverridable description_long: 0
end
end

Expand All @@ -77,11 +83,7 @@ defmodule Plugin do
S.find_submodules(Plugins)
|> Enum.reduce(MapSet.new(), fn
mod, acc ->
b =
mod.__info__(:attributes)
|> Keyword.get(:behaviour, [])

if Plugin in b do
if valid?(mod) do
MapSet.put(acc, mod)
else
acc
Expand Down Expand Up @@ -523,4 +525,22 @@ defmodule Plugin do
)
)
end

@spec! decorate_usage(SiteConfig.t(), module()) :: TxtBlock.t()
def decorate_usage(cfg, plugin) do
{{:list, :dotted},
Enum.map(plugin.usage(), fn
{prompt, response} ->
[
{:source, SiteConfig.example_prefix(cfg) <> prompt},
" ",
{:bold, "<>"},
" ",
{:source, response}
]

other ->
TypeCheck.conforms!(other, TxtBlock.t())
end)}
end
end
110 changes: 110 additions & 0 deletions lib/plugins/help.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
defmodule Plugins.Help do
@moduledoc false
require Logger
use TypeCheck
alias Stampede, as: S
require S.ResponseToPost
use Plugin

# TODO: make all except ping only respond to admins

@impl Plugin
def usage() do
[
{"help", "(main help)"},
{"help [plugin]", "(describes plugin)"}
]
end

@impl Plugin
def description() do
"Describes how the bot can be used. You're using it right now!"
end

@impl Plugin
@spec! respond(SiteConfig.t(), S.MsgReceived.t()) :: nil | S.ResponseToPost.t()
def respond(_cfg, msg) when not Plugin.is_bot_invoked(msg), do: nil

def respond(cfg, msg) when Plugin.is_bot_invoked(msg) do
plugs =
SiteConfig.get_plugs(cfg)

case summon_type(msg.body) do
:list_plugins ->
txt =
[
"Here are the available plugins! Learn about any of them with ",
{:source, "help [plugin]"},
"\n\n",
{{:list, :dotted},
plugs
|> Enum.map(fn
plug ->
s = SiteConfig.trim_plugin_name(plug)

[
{:bold, s},
": ",
plug.description()
]
|> List.flatten()
end)}
]

S.ResponseToPost.new(
confidence: 10,
text: txt,
origin_msg_id: msg.id,
why: ["They pinged so I ponged!"]
)

{:specific, requested_name} ->
downcase = requested_name |> String.downcase()

Enum.find(plugs, nil, fn full_atom ->
downcase == full_atom |> SiteConfig.trim_plugin_name() |> String.downcase()
end)
|> case do
nil ->
S.ResponseToPost.new(
confidence: 10,
text: [
"Couldn't find a module named #{requested_name}. Possible modules: ",
Enum.map(Plugin.ls(), &inspect/1) |> Enum.intersperse(", ")
],
origin_msg_id: msg.id,
why: ["They asked for a module that didn't exist."]
)

found ->
S.ResponseToPost.new(
confidence: 10,
text: [
found.description_long(),
"\n\nUsage:\n",
Plugin.decorate_usage(cfg, found)
],
origin_msg_id: msg.id,
why: ["They asked for help with a module."]
)
end

nil ->
nil
end
end

def summon_type(body) do
if Regex.match?(~r/^(help$|list plugin(s)?)/, body) do
:list_plugins
else
case Regex.run(~r/^help (\w+)/, body, capture: :all_but_first) do
[plug] ->
{:specific, plug}

nil ->
nil
end
end
end
end
10 changes: 8 additions & 2 deletions lib/plugins/why.ex
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,17 @@ defmodule Plugins.Why do
def description() do
"""
Explains the bot's reasoning for posting a particular message, if it remembers it. Summoned with "why did you say that?" for a short summary. Remember to identify the message you want; on Discord, this is the "reply" function. If you want a full traceback, ask with "specifically".

Full regex: #{at_module_regex() |> Regex.source()}
"""
end

def description_long() do
[
description(),
"Full regex: ",
{:source, at_module_regex() |> Regex.source()}
]
end

@impl Plugin
@spec! respond(SiteConfig.t(), S.MsgReceived.t()) :: nil | S.ResponseToPost.t()
def respond(_cfg, msg) when not Plugin.is_bot_invoked(msg), do: nil
Expand Down
3 changes: 2 additions & 1 deletion lib/service/discord.ex
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,8 @@ defmodule Service.Discord do
" in plugin ",
inspect(p),
":\n\n",
{:source_block, [S.pp(e), "\n", S.pp(st)]}
{:source_block, [Exception.format(t, e, st)]}
# BUG: can't handle colored text like TypeCheck failures
]
end

Expand Down
7 changes: 2 additions & 5 deletions lib/service/dummy.ex
Original file line number Diff line number Diff line change
Expand Up @@ -94,10 +94,6 @@ defmodule Service.Dummy do
default: :error,
type: :atom
],
prefix: [
default: "!",
type: S.ntc(Regex.t() | String.t())
],
plugs: [
default: ["Test", "Sentience"],
type: {:custom, SiteConfig, :real_plugins, []}
Expand Down Expand Up @@ -197,7 +193,8 @@ defmodule Service.Dummy do
" in plugin ",
inspect(p),
":\n\n",
{:source_block, [S.pp(e), "\n", S.pp(st)]}
{:source_block, [Exception.format(t, e, st)]}
# BUG: can't handle colored text like TypeCheck failures
]
end

Expand Down
Loading
Loading