-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
355 lines (267 loc) · 10.6 KB
/
server.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/*
Earfish
This Slack bot translates Slack messages from German to English
v0.1 - 20 June 2017
created by Eric Mueller, [email protected]
For use on BeepBoop platfom
*/
'use strict'
const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')
const unirest = require('unirest');
const slack = require('slack')
const jsonfile = require('jsonfile')
const CONFIG = require('config.json')('./conf.json');
// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000
var slapp = Slapp({
// Beep Boop sets the SLACK_VERIFY_TOKEN env var
verify_token: process.env.SLACK_VERIFY_TOKEN,
convo_store: ConvoStore({ debug: true }),
context: Context(),
log: true
})
//* ********************************************
// Setup different handlers for messages
//* ********************************************
// translate the most recent x messages
slapp.command('/tron', /(.*)/, (msg, text, match) => {
if(CONFIG) var token = CONFIG.slack_token; // msg.meta.app_token
if(!token) var token = process.env.slack_token;
// let channel = msg.body.event.channel;
let channel = msg.body.channel_id;
var v = 0;
// want to use https://api.slack.com/methods/channels.history/test API call here
slack.channels.history({token, channel}, (err, data) => {
// walk through each message and translate it
for (let s of data.messages) {
// console.log("\n\n------------------");
// console.log(s);
// add the translation as a reply to this individual message
var reply_thread = s.ts;
// console.log("reply thread is "+s.ts)
// avoid bot messages from ourselves
if (s.subtype != 'bot_message') {
var m = JSON.stringify(s.text)
// translate it with Yandex - not as good as Google Translate, but it's free!
// see https://tech.yandex.com/translate/doc/dg/reference/translate-docpage/
// TODO let the user specify source and target languages
if(CONFIG) var ykey = CONFIG.yandex_api_key ; // msg.meta.app_token
if(!ykey) var ykey = process.env.yandex_api_key;
var headers = {'accept' : "json"};
var post = 'https://translate.yandex.net/api/v1.5/tr.json/translate?lang=en&key=' + ykey + '&text=' + encodeURIComponent(m);
unirest.get(post, headers, function(res) {
// console.log("\n\n\n result body is:");
// console.log(res.body);
// now we have translated message - pull it out and remove quotes around it that stringify adds
var translated = JSON.stringify( res.body.text[0] ).replace(/^"(.+)"$/,'$1');
// console.log("\n\n\n translated 1 = "+translated);
// unescape double quotes and remove from start and end of string
translated = translated.replace(/\\\"/g, "\"");
// console.log("\n\n\n translated 2 = "+translated);
// remove double slash to single slash
translated = translated.replace(/\\\\/g, "\\");
// console.log("\n\n\n translated 3 = "+translated);
// and finally remove any other double quotes enclosing the whole thing
translated = translated.replace(/^"(.+)"$/, '$1')
// console.log("\n\n\n translated LAST = "+translated);
translated = translated.replace(/\\n/g, '\n')
// console.log("\n\n\n translated LAST = "+translated);
// console.log("\n\n\n");
// console.log(translated);
// post it to slack
// TODO - see if translation was already posted and if so, don't post it again
// translated = "Kartoffel\nGross Kartoffel"
// console.log(translated);
// set up correct emoji flag to show source lang
var langcode = res.body.lang.substring(0,2); // get source language like "de" or "en"
var flag = langcode;
if(flag == 'en') flag = 'us';
msg.say({
text: translated + "\n_(from " + langcode.toUpperCase() + " :flag-" + flag + ":)_",
thread_ts: reply_thread,
})
} )
// did we get enough valid messages?
v++;
if (v == parseInt(match)) break; // yes - get out of the loop
}
}
})
})
slapp.message('(.*)', (msg) => {
/*
Message {
type: 'event',
body: {
token: 'XXXXXXXXXXXXXXXXXXXXX',
team_id: 'XXXXXXX',
api_app_id: 'XXXXXXXXX',
event: {
type: 'message',
user: 'XXXXXXX',
text: 'blargp',
ts: 'XXXXXXXXXXXXX.XXXXXXXX',
channel: 'XXXXXX',
event_ts: 'XXXXXXXXXXXX.XXXXXXXX'
},
type: 'event_callback',
authed_users: [ 'XXXXXXXXX' ],
event_id: 'XXXXXXXXX',
event_time: 1497971718
},
meta: {
verify_token: 'XXXXXXXXXXXXXXXXXXXXXXXX',
user_id: 'XXXXXXXXX',
bot_id: undefined,
channel_id: 'XXXXXX',
team_id: 'XXXXXX',
app_token: 'xoxp-XXXXXXXXX [removed] xxxxxxx',
app_user_id: 'XXXXXXXX',
app_bot_id: 'XXXXXXXXX',
bot_token: 'xoxb-XXXXXXXXX [removed] XXXXXXXX',
bot_user_id: 'XXXXXX',
bot_user_name: 'translateotron',
team_name: 'XXXXXX',
team_domain: 'XXXXXX',
team_resource_id: 'XXXXXXXXXXXXXXXXX',
incoming_webhook_url: '',
incoming_webhook_channel: '',
error: undefined,
config: {}
}
}
*/
// console.log("\n\n------------------");
// console.log(msg);
console.log(msg.meta);
if(msg.body.event.type == 'message') {
var m = JSON.stringify(msg.body.event.text)
var reply_thread = msg.body.event.event_ts;
console.log(process.env);
// TODO let the user specify source and target languages
if (typeof CONFIG !== 'undefined') var ykey = CONFIG.yandex_api_key; // msg.meta.app_token
if(!ykey) var ykey = process.env.yandex_api_key;
var headers = {'accept' : "json"};
var post = 'https://translate.yandex.net/api/v1.5/tr.json/translate?lang=en&key=' + ykey + '&text=' + encodeURIComponent(m);
unirest.get(post, headers, function (res) {
// console.log("\n\n\n result body is:");
// console.log(res.body);
// now we have translated message - pull it out and remove quotes around it that stringify adds
var translated = JSON.stringify(res.body.text[0]).replace(/^"(.+)"$/, '$1');
// console.log("\n\n\n translated 1 = "+translated);
// unescape double quotes and remove from start and end of string
translated = translated.replace(/\\\"/g, "\"");
// console.log("\n\n\n translated 2 = "+translated);
// remove double slash to single slash
translated = translated.replace(/\\\\/g, "\\");
// console.log("\n\n\n translated 3 = "+translated);
// and finally remove any other double quotes enclosing the whole thing
translated = translated.replace(/^"(.+)"$/, '$1')
// console.log("\n\n\n translated LAST = "+translated);
// fix tabs
translated = translated.replace(/\\t/g, '\t');
// fix newlines
translated = translated.replace(/\\n/g, '\n')
// post it to slack
// TODO - see if translation was already posted and if so, don't post it again
console.log(translated);
// set up correct emoji flag to show source lang
var langcode = res.body.lang.substring(0, 2); // get source language like "de" or "en"
var flag = langcode;
if (flag != 'en') {
msg.say({
text: translated + "\n_(from " + langcode.toUpperCase() + " :flag-" + flag + ":)_",
thread_ts: reply_thread,
})
}
})
}
})
/*
// response to the user typing "help"
slapp.message('help', ['mention', 'direct_message'], (msg) => {
msg.say(`TESTING ${HELP_TEXT}`)
})
// "Conversation" flow that tracks state - kicks off when user says hi, hello or hey
slapp
.message('^(hi|hello|hey)$', ['direct_mention', 'direct_message'], (msg, text) => {
msg
.say(`${text}, how are you?`)
// sends next event from user to this route, passing along state
.route('how-are-you', { greeting: text })
})
.route('how-are-you', (msg, state) => {
let text = (msg.body.event && msg.body.event.text) || ''
// user may not have typed text as their next action, ask again and re-route
if (!text) {
return msg
.say("Whoops, I'm still waiting to hear how you're doing.")
.say('How are you?')
.route('how-are-you', state)
}
// add their response to state
state.status = text
msg
.say(`Ok then. What's your favorite color?`)
.route('color', state)
})
.route('color', (msg, state) => {
var text = (msg.body.event && msg.body.event.text) || ''
// user may not have typed text as their next action, ask again and re-route
if (!text) {
return msg
.say("I'm eagerly awaiting to hear your favorite color.")
.route('color', state)
}
// add their response to state
state.color = text
msg
.say('Thanks for sharing.')
.say(`Here's what you've told me so far: \`\`\`${JSON.stringify(state)}\`\`\``)
// At this point, since we don't route anywhere, the "conversation" is over
})
// Can use a regex as well
slapp.message(/^(thanks|thank you)/i, ['mention', 'direct_message'], (msg) => {
// You can provide a list of responses, and a random one will be chosen
// You can also include slack emoji in your responses
msg.say([
"You're welcome :smile:",
'You bet',
':+1: Of course',
'Anytime :sun_with_face: :full_moon_with_face:'
])
})
// demonstrate returning an attachment...
slapp.message('attachment', ['mention', 'direct_message'], (msg) => {
msg.say({
text: 'Check out this amazing attachment! :confetti_ball: ',
attachments: [{
text: 'Slapp is a robust open source library that sits on top of the Slack APIs',
title: 'Slapp Library - Open Source',
image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
title_link: 'https://beepboophq.com/',
color: '#7CD197'
}]
})
})
// Catch-all for any other responses not handled above
slapp.message('.*', ['direct_mention', 'direct_message'], (msg) => {
msg.say(`You said ${JSON.stringify(msg)}`)
// respond only 40% of the time
if (Math.random() < 0.4) {
msg.say([':wave:', ':pray:', ':raised_hands:'])
}
})
*/
// attach Slapp to express server
var server = slapp.attachToExpress(express())
// start http server
server.listen(port, (err) => {
if (err) {
return console.error(err)
}
console.log(`Listening on port ${port} - local`)
})