forked from ggauravr/slack-terminalize
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dispatcher.js
84 lines (67 loc) · 2.15 KB
/
dispatcher.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
'use strict';
var logger = require('winston'),
MemoryDataStore = require('@slack/client').MemoryDataStore,
dataStore = new MemoryDataStore(),
util = {
config: require('./util/config'),
command: require('./util/command')
},
path = require('path'),
handlers,
commands,
slackClient;
/**
* Get dispatcher status
*
* @return boolean
*/
var isInitialized = function() {
return handlers !== undefined && handlers.length > 0;
}
/**
* Reads commands.json from CONFIG_DIR and sets up handlers.
* Handlers are expected to have the same name as the command, i.e.
* of the pattern {command-name}.js
*
* @param { object } Slack client
* @return { none }
*
*/
var init = function (client) {
slackClient = client;
handlers = {};
util.command.init();
commands = require(path.resolve(util.config.get('CONFIG_DIR'), 'commands'));
Object.keys(commands).forEach(function (command) {
handlers[command] = require(path.resolve(util.config.get('COMMAND_DIR'), command));
});
logger.info('Command dispatcher initialized');
};
/**
* Processes, using helpers, the user message posted and calls the appropriate command,
* passing it an object with four parameters: the channel posted, the user posting,
* the command entered by the user and the additional text as an array of tokens(args).
* If no matching command is found, looks for and calls file named after the ERROR_COMMAND
* config parameter set on initialization.
*
* @param { string } message posted by a user in Slack channel
* @return { none }
*/
var handle = function (msg) {
var data;
// gets command and args parameters
data = util.command.parse(msg);
data.user = msg.user;
data.channel = msg.channel;
data.commandConfig = commands[data.command];
// respond only for non-bot user messages
if (data.user && !slackClient.dataStore.getUserById(data.user).is_bot) {
if (!handlers[data.command]) {
throw new Error('Command ' + data.command + ' not found in ' + util.config.get('COMMAND_DIR') + ' directory');
}
handlers[data.command](data);
}
};
exports.init = init;
exports.handle = handle;
exports.isInitialized = isInitialized;