-
Notifications
You must be signed in to change notification settings - Fork 104
/
norrisbot.js
199 lines (175 loc) · 5.57 KB
/
norrisbot.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
'use strict';
var util = require('util');
var path = require('path');
var fs = require('fs');
var SQLite = require('sqlite3').verbose();
var Bot = require('slackbots');
/**
* Constructor function. It accepts a settings object which should contain the following keys:
* token : the API token of the bot (mandatory)
* name : the name of the bot (will default to "norrisbot")
* dbPath : the path to access the database (will default to "data/norrisbot.db")
*
* @param {object} settings
* @constructor
*
* @author Luciano Mammino <lucianomammino@gmail.com>
*/
var NorrisBot = function Constructor(settings) {
this.settings = settings;
this.settings.name = this.settings.name || 'norrisbot';
this.dbPath = settings.dbPath || path.resolve(__dirname, '..', 'data', 'norrisbot.db');
this.user = null;
this.db = null;
};
// inherits methods and properties from the Bot constructor
util.inherits(NorrisBot, Bot);
/**
* Run the bot
* @public
*/
NorrisBot.prototype.run = function () {
NorrisBot.super_.call(this, this.settings);
this.on('start', this._onStart);
this.on('message', this._onMessage);
};
/**
* On Start callback, called when the bot connects to the Slack server and access the channel
* @private
*/
NorrisBot.prototype._onStart = function () {
this._loadBotUser();
this._connectDb();
this._firstRunCheck();
};
/**
* On message callback, called when a message (of any type) is detected with the real time messaging API
* @param {object} message
* @private
*/
NorrisBot.prototype._onMessage = function (message) {
if (this._isChatMessage(message) &&
this._isChannelConversation(message) &&
!this._isFromNorrisBot(message) &&
this._isMentioningChuckNorris(message)
) {
this._replyWithRandomJoke(message);
}
};
/**
* Replyes to a message with a random Joke
* @param {object} originalMessage
* @private
*/
NorrisBot.prototype._replyWithRandomJoke = function (originalMessage) {
var self = this;
self.db.get('SELECT id, joke FROM jokes ORDER BY used ASC, RANDOM() LIMIT 1', function (err, record) {
if (err) {
return console.error('DATABASE ERROR:', err);
}
var channel = self._getChannelById(originalMessage.channel);
self.postMessageToChannel(channel.name, record.joke, {as_user: true});
self.db.run('UPDATE jokes SET used = used + 1 WHERE id = ?', record.id);
});
};
/**
* Loads the user object representing the bot
* @private
*/
NorrisBot.prototype._loadBotUser = function () {
var self = this;
this.user = this.users.filter(function (user) {
return user.name === self.name;
})[0];
};
/**
* Open connection to the db
* @private
*/
NorrisBot.prototype._connectDb = function () {
if (!fs.existsSync(this.dbPath)) {
console.error('Database path ' + '"' + this.dbPath + '" does not exists or it\'s not readable.');
process.exit(1);
}
this.db = new SQLite.Database(this.dbPath);
};
/**
* Check if the first time the bot is run. It's used to send a welcome message into the channel
* @private
*/
NorrisBot.prototype._firstRunCheck = function () {
var self = this;
self.db.get('SELECT val FROM info WHERE name = "lastrun" LIMIT 1', function (err, record) {
if (err) {
return console.error('DATABASE ERROR:', err);
}
var currentTime = (new Date()).toJSON();
// this is a first run
if (!record) {
self._welcomeMessage();
return self.db.run('INSERT INTO info(name, val) VALUES("lastrun", ?)', currentTime);
}
// updates with new last running time
self.db.run('UPDATE info SET val = ? WHERE name = "lastrun"', currentTime);
});
};
/**
* Sends a welcome message in the channel
* @private
*/
NorrisBot.prototype._welcomeMessage = function () {
this.postMessageToChannel(this.channels[0].name, 'Hi guys, roundhouse-kick anyone?' +
'\n I can tell jokes, but very honest ones. Just say `Chuck Norris` or `' + this.name + '` to invoke me!',
{as_user: true});
};
/**
* Util function to check if a given real time message object represents a chat message
* @param {object} message
* @returns {boolean}
* @private
*/
NorrisBot.prototype._isChatMessage = function (message) {
return message.type === 'message' && Boolean(message.text);
};
/**
* Util function to check if a given real time message object is directed to a channel
* @param {object} message
* @returns {boolean}
* @private
*/
NorrisBot.prototype._isChannelConversation = function (message) {
return typeof message.channel === 'string' &&
message.channel[0] === 'C'
;
};
/**
* Util function to check if a given real time message is mentioning Chuck Norris or the norrisbot
* @param {object} message
* @returns {boolean}
* @private
*/
NorrisBot.prototype._isMentioningChuckNorris = function (message) {
return message.text.toLowerCase().indexOf('chuck norris') > -1 ||
message.text.toLowerCase().indexOf(this.name) > -1;
};
/**
* Util function to check if a given real time message has ben sent by the norrisbot
* @param {object} message
* @returns {boolean}
* @private
*/
NorrisBot.prototype._isFromNorrisBot = function (message) {
return message.user === this.user.id;
};
/**
* Util function to get the name of a channel given its id
* @param {string} channelId
* @returns {Object}
* @private
*/
NorrisBot.prototype._getChannelById = function (channelId) {
return this.channels.filter(function (item) {
return item.id === channelId;
})[0];
};
module.exports = NorrisBot;