From 5f5f96a35ea3c675f0494ed376b10ed5e6f1542f Mon Sep 17 00:00:00 2001 From: Knut Ahlers Date: Sun, 20 Feb 2022 13:52:40 +0100 Subject: [PATCH] [overlays] Add helper function to render template strings Signed-off-by: Knut Ahlers --- .../apimodules/overlays/default/debug.html | 2 +- .../overlays/default/eventclient.mjs | 27 +++++++++++++++++-- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/internal/apimodules/overlays/default/debug.html b/internal/apimodules/overlays/default/debug.html index b9cb107..3539f68 100644 --- a/internal/apimodules/overlays/default/debug.html +++ b/internal/apimodules/overlays/default/debug.html @@ -71,7 +71,7 @@ }, mounted() { - new EventClient({ + window.botClient = new EventClient({ handlers: { _: (evt, data, time, live) => { this.events = [ diff --git a/internal/apimodules/overlays/default/eventclient.mjs b/internal/apimodules/overlays/default/eventclient.mjs index b48e5d9..f73ed23 100644 --- a/internal/apimodules/overlays/default/eventclient.mjs +++ b/internal/apimodules/overlays/default/eventclient.mjs @@ -36,6 +36,15 @@ export default class EventClient { this.connect() } + /** + * Returns the API base URL without trailing slash + * + * @returns {string} API base URL + */ + apiBase() { + return window.location.href.substr(0, window.location.href.indexOf('/overlays/')) + } + /** * Connects the EventClient to the socket * @@ -104,6 +113,21 @@ export default class EventClient { return this.params.get(key) || this.options[key] || fallback } + /** + * Renders a given template using the bots msgformat API (supports all templating you can use in bot messages) + * + * @params {string} template The template to render + * @returns {Promise} Promise resolving to the rendered output of the template + */ + renderTemplate(template) { + return fetch(`${this.apiBase()}/msgformat/format?template=${encodeURIComponent(template)}`, { + headers: { + authorization: this.paramOptionFallback('token'), + }, + }) + .then(resp => resp.text()) + } + /** * Modifies the overlay address to the websocket address the bot listens to * @@ -111,7 +135,6 @@ export default class EventClient { * @returns {string} Websocket address in form ws://... or wss://... */ socketAddr() { - const base = window.location.href.substr(0, window.location.href.indexOf('/overlays/') + '/overlays/'.length) - return `${base.replace(/^http/, 'ws')}events.sock` + return `${this.apiBase().replace(/^http/, 'ws')}/overlays/events.sock` } }