From 240745a4046878bf362e035078adbc497ef5099a Mon Sep 17 00:00:00 2001 From: Midgard Date: Thu, 9 Jun 2022 00:29:24 +0200 Subject: [PATCH] Add support for slash commands --- js/controller.js | 40 +++++++++++++++++++++++++++++++++++----- js/mm_client.js | 4 ++++ js/util.js | 5 +++++ 3 files changed, 44 insertions(+), 5 deletions(-) diff --git a/js/controller.js b/js/controller.js index 2896cf8..864160d 100644 --- a/js/controller.js +++ b/js/controller.js @@ -164,6 +164,25 @@ function sendMessage(endpoint, channel_id, message) { //}); } +async function executeSlashCommand(endpoint, channel_id, command) { + const client = mm_client.get(endpoint); + const response = await client.executeSlashCommand(channel_id, command); + + if ( + response.responseJson && + response.responseJson.text && + response.responseJson.response_type !== "in_channel" + ) { + pubsub.publish("MESSAGES_NEW", { + endpoint, + channel_id, + create_at: (new Date()).getTime(), + user_id: client.me.id, + message: "(only visible to you) " + response.responseJson.text + }); + } +} + function markChannelAsRead(client, channel) { return client.markChannelRead(channel.id); } @@ -172,11 +191,22 @@ function checkKeyPress(event) { // Battle tested for many years in several browsers if ((event.keyCode === event.DOM_VK_RETURN || event.keyCode === 13 || event.keyCode === 10 || event.key === "Enter" || event.keyIdentifier === "U+000A") && !event.shiftKey && !event.ctrlKey) { if (byId("compose").value.length > 0) { - sendMessage( - byId("channel_contents").dataset["server"], - byId("channel_contents").dataset["id"], - byId("compose").value - ); + let message = byId("compose").value; + + if (message[0] === "/") { + executeSlashCommand( + byId("channel_contents").dataset["server"], + byId("channel_contents").dataset["id"], + message + ); + } else { + sendMessage( + byId("channel_contents").dataset["server"], + byId("channel_contents").dataset["id"], + message + ); + } + byId("compose").value = ""; } return true; diff --git a/js/mm_client.js b/js/mm_client.js index a0dda4e..02f9eea 100644 --- a/js/mm_client.js +++ b/js/mm_client.js @@ -155,6 +155,10 @@ class MattermostClient { }); } + executeSlashCommand(channel_id, command) { + return this.post("/commands/execute", {channel_id, command}); + } + getUsers() { if (!this.users) { this.users = this.paginatedGet("/users", {}).then(users => { diff --git a/js/util.js b/js/util.js index 749d90a..39e5c77 100644 --- a/js/util.js +++ b/js/util.js @@ -72,6 +72,11 @@ function arrayToHashmap(array, key) { } +function startsWith(string, start) { + return string.slice(0, start.length) == start; +} + + function padLeft(input, width, padding=" ") { text = input + ""; while (text.length < width) {