From fe76b23b09b2c043fe64e0af9450194185575ba4 Mon Sep 17 00:00:00 2001 From: Knut Ahlers Date: Thu, 20 Jan 2022 02:03:52 +0100 Subject: [PATCH] [msgformat] Add module to retrieve filled template through API Signed-off-by: Knut Ahlers --- internal/apimodules/msgformat/msgformat.go | 51 ++++++++++++++++++++++ plugins_core.go | 4 ++ 2 files changed, 55 insertions(+) create mode 100644 internal/apimodules/msgformat/msgformat.go diff --git a/internal/apimodules/msgformat/msgformat.go b/internal/apimodules/msgformat/msgformat.go new file mode 100644 index 0000000..e8d010d --- /dev/null +++ b/internal/apimodules/msgformat/msgformat.go @@ -0,0 +1,51 @@ +package msgformat + +import ( + "fmt" + "net/http" + + "github.com/pkg/errors" + + "github.com/Luzifer/twitch-bot/plugins" +) + +var formatMessage plugins.MsgFormatter + +func Register(args plugins.RegistrationArguments) error { + formatMessage = args.FormatMessage + + args.RegisterAPIRoute(plugins.HTTPRouteRegistrationArgs{ + HandlerFunc: handleFormattedMessage, + Method: http.MethodGet, + Module: "msgformat", + Path: "/format", + QueryParams: []plugins.HTTPRouteParamDocumentation{ + { + Description: "The template to execute", + Name: "template", + Required: true, + Type: "string", + }, + }, + RequiresWriteAuth: true, // This module can potentially be used to harvest data / read internal variables so it is handled as a write-module + ResponseType: plugins.HTTPRouteResponseTypeTextPlain, + }) + + return nil +} + +func handleFormattedMessage(w http.ResponseWriter, r *http.Request) { + tpl := r.FormValue("template") + if tpl == "" { + w.WriteHeader(http.StatusNoContent) + return + } + + msg, err := formatMessage(tpl, nil, nil, nil) + if err != nil { + http.Error(w, errors.Wrap(err, "executing template").Error(), http.StatusInternalServerError) + return + } + + fmt.Fprint(w, msg) +} diff --git a/plugins_core.go b/plugins_core.go index 0f3384d..a8025b5 100644 --- a/plugins_core.go +++ b/plugins_core.go @@ -21,6 +21,7 @@ import ( "github.com/Luzifer/twitch-bot/internal/actors/respond" "github.com/Luzifer/twitch-bot/internal/actors/timeout" "github.com/Luzifer/twitch-bot/internal/actors/whisper" + "github.com/Luzifer/twitch-bot/internal/apimodules/msgformat" "github.com/Luzifer/twitch-bot/internal/template/numeric" "github.com/Luzifer/twitch-bot/internal/template/random" "github.com/Luzifer/twitch-bot/plugins" @@ -47,6 +48,9 @@ var ( // Template functions numeric.Register, random.Register, + + // API-only modules + msgformat.Register, } knownModules []string )