How to use Mattermost to create Microsoft Sharepoint sites and others

Some of my prospects have a fairly large Sharepoint implementation and usage. This is why some of them ask if it’s possible to run a task in Sharepoint or other tools from Mattermost. Because Mattermost supports so called WebSocket connections it’s fairly easy to integrate Mattermost events with different other tools. In a case the question was: “How can I create a Sharepoint site every time a channel in Mattermost ist created?”

Let me give you a bit background first… The Mattermost WebSocket API allows you to capture events based on a secure (if enabled) WebSocket connection and has different drivers already available: https://api.mattermost.com/

After you managed the authentication challenge you can use the token to authenticate against your Mattermost installation. I just started the script on my Mac and connect to my Mattermost server using a websocket (ws) driver. My websocket.js script is written in JavaScript as it seemed to be a natural way to connect to a React.js based frontend.

const WebSocket = require('ws');

var ws = new WebSocket("ws://192.168.0.15:8065/api/v4/websocket");

ws.on('open', function open(){
  var msg = {
  "seq": 1,
  "action": "authentication_challenge",
  "data": {
    "token": "YOUR TOKEN HERE"
    }
  };
  ws.send(JSON.stringify(msg));
});

ws.onmessage = function (event) {
  var sortedKeys = Object.keys(event).sort();;
  var obj = JSON.parse(event.data);
  console.log(event.data);
  if(obj.event == "channel_created"){
    console.log("New channel created...")
    ExternalCall();
  }
  else if (obj.event == "channel_viewed") {
    console.log("Channel was viewed...")
  }
}

function ExternalCall() {
  var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    console.log("State: " + this.readyState);
    if (this.readyState === 4) {
      console.log("Complete.\nBody length: " + this.responseText.length);
      console.log("Body:\n" + this.responseText);
      }
    };
  xhttp.open("POST", "https://httpbin.org/post");
  xhttp.send();
}

As you can see the script is very easy. It opens a new WebSocket connection and uses the token to authenticate against the Mattermost server. Now the script listens to the events happening on the server and parses them as JSON. As soon as an event matches `channel_created` or `channel_viewed` a log output is created.

While this output is just informal you can add the creation call for Sharepoint or some other tools or APIs right here. I added a small REST API call (ExternalCall) to a public API to demonstrate the use-case a bit better. You can easily use the information like team_id or user_id that was provided when creating the channel to gather more information to send to the external system.

 

 

Leave a Reply