Commit 967331e2 authored by Anastasios Kalogeropoulos's avatar Anastasios Kalogeropoulos
Browse files

Initial commit

parents
Pipeline #13659 failed with stages
in 1 minute and 12 seconds
PORT=the-port-of-the-server
BOT_OATH_TOKEN=your-bot-use-oauth-access-token
OATH_TOKEN=your-oath-access-token
CHANNEL=the-channel-id, e.g. C012AB3CD for a general channel
\ No newline at end of file
# Dependency directories
node_modules/
# dotenv environment variables file
.env
# custom scripts
delete-channel-messages.js
\ No newline at end of file
# README
## Websocket Server for Slack App
A Websocket server for communication between slack app and web-plugin.
## Getting Started
This project requires a slack app installed on a workspace and a running web-plugin version (can be found here: [webplugin](https://git.fortiss.org/civitas-digitalis/CivDig-DigitalAssisstant/webplugin))
To create a slack app:
1) Go to https://api.slack.com/apps
2) Click "Create New App"
3) Write App Name, choose workspace and click "Create App"
4) On the redirected page click Bot User from the left column and select "Add a Bot User", then click "Add bot User"
5) click "Basic Information" from the left column and then "Install your app to your workspace"
6) Click "Install App to Workspace" and Authorize
7) Now both "Add features and functionality" & "Install your app to your workspace" should be checked and you can find your app in Slack under "Apps"
8) You can find your workspace tokens under "OAth & Permissions" in the left column. Only the "Bot User OAuth Access Token" is needed.
Create a ***.env*** file similar to the ***.env.example***. This is the basic configuration and contains all the necessary variables that are used by the server.
To communicate with your slack app, you need to replace the ***BOT_OATH_TOKEN*** with your "Bot User OAuth Access Token".
The ***CHANNEL*** id can be found on the URL if you open slack from a browser and click on the slack app. (e.g. https://your-slack-workspace.slack.com/messages/DXXXXXXXX)
### Prerequisites
Node.js (version 8.15.1)
### Installing
Clone the project and run
```sh
npm install
```
to install the dependencies.
## Deployment
Run ```npm start``` to start the server.
## Built With
* [Node.js](https://nodejs.org/en/) - The JavaScript runtime
## Authors
* **Anastasios Kalogeropoulos**
module.exports = {
port: process.env.PORT,
botOathToken: process.env.BOT_OATH_TOKEN,
oathToken: process.env.OATH_TOKEN,
channel: process.env.CHANNEL
};
\ No newline at end of file
This diff is collapsed.
{
"name": "slackbot",
"version": "1.0.0",
"description": "",
"main": "slack-server.js",
"scripts": {
"start": "node -r dotenv/config slack-server.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"dependencies": {
"@slack/client": "^4.10.0",
"express": "^4.16.4",
"uuid": "^3.3.2",
"ws": "^6.1.4"
},
"devDependencies": {
"dotenv": "^6.2.0"
}
}
const { RTMClient } = require('@slack/client');
const express = require('express')
const WebSocket = require('ws');
const http = require('http');
const uuidv4 = require('uuid/v4');
const {port, botOathToken, channel} = require('./config');
const app = express();
//initialize a simple http server
const server = http.createServer(app);
const wss = new WebSocket.Server({ server, path: '/webplugin' }); // Accept only connections matching this path
class Client {
constructor(ws, uuid) {
this.ws = ws;
this.uuid = uuid;
}
}
// store client's info to distinguish between different connections
let connectedClients = []
// An access token (from your Slack app or custom integration - usually xoxb)
const rtm = new RTMClient(botOathToken);
rtm.start();
let currentClient = "";
wss.on('connection', (ws) => {
let uuid = uuidv4();
connectedClients.push(new Client(ws, uuid))
console.log("Connection established")
ws.on('message', (wsMessage) => {
let incomingMessage = JSON.parse(wsMessage);
console.log('-------------------');
console.log(incomingMessage);
console.log('-------------------');
// refuse empty messages
if (typeof incomingMessage !== 'object') {
ws.send("404");
return;
}
// refuse bad requests
if (!incomingMessage['recipient'] || !incomingMessage['recipient']['id']) {
ws.send("400");
return;
}
currentClient = connectedClients.find(obj => {
return obj.uuid === incomingMessage['sender']['id'];
});
//Send the incoming message to slack bot
if (incomingMessage['message']) {
console.log("Incoming message: ", incomingMessage['message']['text']);
rtm.sendMessage(incomingMessage['message']['text'], channel)
.then((res) => {
// `res` contains information about the posted message
console.log('Message sent: ', res.ts);
})
.catch(console.error);
}
});
let conversationStatus = getConversationStatus(ws, uuid);
ws.send(JSON.stringify(conversationStatus));
});
rtm.on('message', (message) => {
// Skip messages that are from a bot or my own user ID
if ((message.subtype && message.subtype === 'bot_message') ||
(!message.subtype && message.user === rtm.activeUserId)) {
return;
}
console.log(`(channel:${message.channel}) ${message.user} says: ${message.text}`);
//Get text from slack bot and send it to web-plugin
let outgoingMessage = createOutgoingMessage(message.text, currentClient.uuid);
currentClient.ws.send(JSON.stringify(outgoingMessage));
});
function createOutgoingMessage(text, uuid) {
let outgoingMessage = {
"statusCode": 200,
"connected": true,
"type": "new_message",
"payload": {
"messaging_type": "RESPONSE",
"recipient": {
"id": uuid
},
"message": {
"type": "text",
"text": text,
"quick_replies": []
},
"timestamp": Date.now
}
}
return outgoingMessage;
}
function getConversationStatus(ws, uuid) {
if (ws.readyState === WebSocket.OPEN) {
return { statusCode: 202, connected: true, type: "user_found", payload: uuid };
} else {
return { statusCode: 400, connected: false, type: "connection_rejected", payload: "" };
}
}
//start our server
server.listen(port || 3999, () => {
const { port } = server.address();
console.log(`Server started on port ${port} :)`);
});
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment