-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.js
286 lines (224 loc) · 9.67 KB
/
bot.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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
______ ______ ______ __ __ __ ______
/\ == \ /\ __ \ /\__ _\ /\ \/ / /\ \ /\__ _\
\ \ __< \ \ \/\ \ \/_/\ \/ \ \ _"-. \ \ \ \/_/\ \/
\ \_____\ \ \_____\ \ \_\ \ \_\ \_\ \ \_\ \ \_\
\/_____/ \/_____/ \/_/ \/_/\/_/ \/_/ \/_/
This is a sample Slack bot built with Botkit.
This bot demonstrates many of the core features of Botkit:
* Connect to Slack using the real time API
* Receive messages based on "spoken" patterns
* Reply to messages
* Use the conversation system to ask questions
* Use the built in storage system to store and retrieve information
for a user.
# RUN THE BOT:
Create a new app via the Slack Developer site:
-> http://api.slack.com
Run your bot from the command line:
clientId=<MY SLACK TOKEN> clientSecret=<my client secret> PORT=<3000> node bot.js
# USE THE BOT:
Navigate to the built-in login page:
https://<myhost.com>/login
This will authenticate you with Slack.
If successful, your bot will come online and greet you.
# EXTEND THE BOT:
Botkit has many features for building cool and useful bots!
Read all about it here:
-> http://howdy.ai/botkit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
var env = require('node-env-file');
env(__dirname + '/.env');
if (!process.env.clientId || !process.env.clientSecret || !process.env.PORT) {
usage_tip();
// process.exit(1);
}
var Botkit = require('botkit');
var debug = require('debug')('botkit:main');
var request = require('request');
var bot_options = {
clientId: process.env.clientId,
clientSecret: process.env.clientSecret,
clientSigningSecret: process.env.clientSigningSecret,
debug: true,
scopes: ['bot'],
studio_token: process.env.studio_token,
studio_command_uri: process.env.studio_command_uri
};
// Use a mongo database if specified, otherwise store in a JSON file local to the app.
// Mongo is automatically configured when deploying to Heroku
if (process.env.MONGO_URI) {
var mongoStorage = require('botkit-storage-mongo')({mongoUri: process.env.MONGO_URI});
bot_options.storage = mongoStorage;
} else {
bot_options.json_file_store = __dirname + '/.data/db/'; // store user data in a simple JSON format
}
// Create the Botkit controller, which controls all instances of the bot.
var controller = Botkit.slackbot(bot_options);
// Add Wit.ai middleware using middleware
var wit = require('botkit-witai')({
accessToken: process.env.wit_ai_token,
minConfidence: 0.1,
logLevel: 'error'
});
controller.middleware.receive.use(wit.receive);
// Define Wit.ai custom listeners
let incomingEvent = 'direct_message,direct_mention,mention,ambient';
controller.hears(['hi'], incomingEvent, function(bot, message) {
bot.reply(message, 'Hi ... I heard a message.')
});
controller.hears(['hello'], incomingEvent, function(bot, message) {
bot.reply(message, 'Hello? Hello? Hello?. Is there anybody in there?')
});
controller.hears(['hola', 'que tal'], incomingEvent, function(bot, message) {
bot.reply(message, 'Hola que tal.')
});
controller.hears(['Open the pod bay doors'], incomingEvent, function(bot, message) {
bot.reply(message, '...');
bot.reply(message, {
attachments:[
{
"title": "I’m sorry, Dave, I’m afraid I can’t do that.",
"image_url": "https://i.ytimg.com/vi/NJ-CcFcM9Hw/maxresdefault.jpg",
"color": "#ff0000"
}
]
});
});
controller.hears(['show crypto prices'], incomingEvent, function(bot, message) {
bot.reply(message, 'fetching information ...');
request({
method: 'get',
uri: 'https://api.bitso.com/v3/ticker',
json: true,
}, function (err, response, json) {
let colors = [ 'good', 'warning', 'danger'];
controller.log(JSON.stringify(json));
for (var i = 0; i < json.payload.length; i++) {
bot.reply(message, {
attachments: [
{
"title": json.payload[i].book,
"text": JSON.stringify(json.payload[i], undefined, 2),
"color": colors[Math.floor(Math.random() * colors.length)]
}
]
});
}
});
});
controller.hears(['.*'], incomingEvent, function (bot, message) {
controller.log( JSON.stringify(message) );
if (message != undefined && message.entities != undefined) {
var intent =
('intent' in message.entities && message.entities.intent[0].value) ||
false;
var itemTypeKey =
(intent && `${intent}_type`)
|| false;
var intentType =
(itemTypeKey in message.entities && message.entities[itemTypeKey][0].value)
|| false;
controller.log( `intent: ${intent}, itemTypeKey: ${itemTypeKey}, type: ${intentType}`);
if (intent === 'wiki' && intent && itemTypeKey) {
bot.reply(message, '🧐 please wait a moment while I think...');
const total = (Math.floor(Math.random() * (1 - 5 + 1)) + 5);
controller.log( `results: ${total}` );
request({
method: 'get',
uri: 'https://jsonplaceholder.typicode.com/posts',
json: true,
}, function (err, response, json) {
controller.log(JSON.stringify(json));
for (var i = 0; i <= total; i++) {
bot.reply(message, {
attachments: [
{
"title": json[i].title,
"title_link": `https://jsonplaceholder.typicode.com/posts/${json[i].id}`,
"text": json[i].body,
}
]
});
}
});
} else {
controller.log(`I couldn't understand the request`);
}
}
});
controller.startTicking();
// Set up an Express-powered webserver to expose oauth and webhook endpoints
var webserver = require(__dirname + '/components/express_webserver.js')(controller);
if (!process.env.clientId || !process.env.clientSecret) {
// Load in some helpers that make running Botkit on Glitch.com better
require(__dirname + '/components/plugin_glitch.js')(controller);
webserver.get('/', function(req, res){
res.render('installation', {
domain: req.get('host'),
protocol: req.protocol,
glitch_domain: process.env.PROJECT_DOMAIN,
layout: 'layouts/default'
});
})
var where_its_at = 'http://' + (process.env.PROJECT_DOMAIN ? process.env.PROJECT_DOMAIN+ '.glitch.me/' : 'localhost:' + process.env.PORT || 3000);
console.log('WARNING: This application is not fully configured to work with Slack. Please see instructions at ' + where_its_at);
} else {
webserver.get('/', function(req, res){
res.render('index', {
domain: req.get('host'),
protocol: req.protocol,
glitch_domain: process.env.PROJECT_DOMAIN,
layout: 'layouts/default'
});
})
// Set up a simple storage backend for keeping a record of customers
// who sign up for the app via the oauth
require(__dirname + '/components/user_registration.js')(controller);
// Send an onboarding message when a new team joins
require(__dirname + '/components/onboarding.js')(controller);
// Load in some helpers that make running Botkit on Glitch.com better
require(__dirname + '/components/plugin_glitch.js')(controller);
var normalizedPath = require("path").join(__dirname, "skills");
require("fs").readdirSync(normalizedPath).forEach(function(file) {
require("./skills/" + file)(controller);
});
// This captures and evaluates any message sent to the bot as a DM
// or sent to the bot in the form "@bot message" and passes it to
// Botkit CMS to evaluate for trigger words and patterns.
// If a trigger is matched, the conversation will automatically fire!
// You can tie into the execution of the script using the functions
// controller.studio.before, controller.studio.after and controller.studio.validate
if (process.env.studio_token) {
controller.on('direct_message,direct_mention,mention', function(bot, message) {
controller.studio.runTrigger(bot, message.text, message.user, message.channel, message).then(function(convo) {
if (!convo) {
// no trigger was matched
// If you want your bot to respond to every message,
// define a 'fallback' script in Botkit CMS
// and uncomment the line below.
// controller.studio.run(bot, 'fallback', message.user, message.channel);
} else {
// set variables here that are needed for EVERY script
// use controller.studio.before('script') to set variables specific to a script
convo.setVar('current_time', new Date());
}
}).catch(function(err) {
bot.reply(message, 'I experienced an error with a request to Botkit CMS: ' + err);
debug('Botkit CMS: ', err);
});
});
} else {
console.log('~~~~~~~~~~');
console.log('NOTE: Botkit CMS functionality has not been enabled');
console.log('Learn mode https://github.com/howdyai/botkit-cms');
}
}
function usage_tip() {
console.log('~~~~~~~~~~');
console.log('Botkit Starter Kit');
console.log('Execute your bot application like this:');
console.log('clientId=<MY SLACK CLIENT ID> clientSecret=<MY CLIENT SECRET> PORT=3000 node bot.js');
console.log('Get Slack app credentials here: https://api.slack.com/apps')
console.log('~~~~~~~~~~');
}