forked from hackclub/banker-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
592 lines (508 loc) · 15.3 KB
/
index.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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
var Botkit = require('botkit');
var Airtable = require('airtable');
var Bottleneck = require('bottleneck');
var _ = require('lodash');
var fs = require('fs');
var fetch = require('node-fetch');
var rawData = fs.readFileSync('data.json');
var data = JSON.parse(rawData);
var base = new Airtable({
apiKey: process.env.AIRTABLE_KEY,
}).base(process.env.AIRTABLE_BASE);
var redisConfig = {
url: process.env.REDISCLOUD_URL,
};
var redisStorage = require('botkit-storage-redis')(redisConfig);
var startBalance = 0;
var invoiceReplies = {};
console.log('Booting bank bot');
function createBalance(user, cb = () => {}) {
console.log(`Creating balance for User ${user}`);
base('bank').create(
{
User: user,
Balance: startBalance,
},
function (err, record) {
if (err) {
console.error(err);
return;
}
console.log(`New balance created for User ${user}`);
// console.log(record)
cb(startBalance, record);
}
);
}
function setBalance(id, amount, user, cb = () => {}) {
console.log(`Changing balance for Record ${id} by ${amount}`);
getBalance(user, (bal) => {
base('bank').update(
id,
{
Balance: bal + amount,
},
(err, record) => {
if (err) {
console.error(err);
return;
}
console.log(`Balance for Record ${id} set to ${bal + amount}`);
cb(bal + amount, record);
}
);
});
}
function getBalance(user, cb = () => {}) {
console.log(`Retrieving balance for User ${user}`);
base('bank')
.select({
filterByFormula: `User = "${user}"`,
})
.firstPage(function page(err, records) {
if (err) {
console.error(err);
return;
}
if (records.length == 0) {
console.log(`No balance found for User ${user}.`);
createBalance(user, cb);
} else {
var record = records[0];
var fields = record.fields;
var balance = fields['Balance'];
console.log(`Balance for User ${user} is ${balance}`);
console.log(fields);
cb(balance, record);
}
});
}
function getInvoice(id) {
return new Promise((resolve, reject) => {
base('invoices').find(id, (err, record) => {
if (err) {
console.error(err);
reject(err);
}
resolve(record);
});
});
}
console.log('Booting banker bot');
var controller = Botkit.slackbot({
clientId: process.env.SLACK_CLIENT_ID,
clientSecret: process.env.SLACK_CLIENT_SECRET,
clientSigningSecret: process.env.SLACK_CLIENT_SIGNING_SECRET,
scopes: ['bot', 'chat:write:bot'],
storage: redisStorage,
});
controller.setupWebserver(process.env.PORT, function (err, webserver) {
controller.createWebhookEndpoints(controller.webserver);
controller.createOauthEndpoints(controller.webserver);
});
function matchData(str, pattern, keys, obj = {}) {
var match = pattern.exec(str);
if (match) {
var text = _.head(match);
var vals = _.tail(match);
var zip = _.zipObject(keys, vals);
_.defaults(obj, zip);
return obj;
}
return null;
}
// @bot balance --> Returns my balance
// @bot balance @zrl --> Returns zrl's balance
var balancePattern = /^balance(?:\s+<@([A-z|0-9]+)>)?/i;
controller.hears(
balancePattern.source,
'direct_mention,direct_message,bot_message',
async (bot, message) => {
var { text, user } = message;
var captures = balancePattern.exec(text);
var target = captures[1] || user;
const verifyResult = await verifyPayload(text);
if (verifyResult[0] != 204) {
bot.replyInThread(message, JSON.parse(verifyResult[1])['text']);
} else {
console.log(
`Received balance request from User ${user} for User ${target}`
);
console.log(message);
getBalance(target, (balance) => {
var reply =
user == target
? `You have ${balance}gp in your account, hackalacker.`
: `Ah yes, User <@${target}> (${target})—they have ${balance}gp.`;
bot.replyInThread(message, reply);
});
}
}
);
var invoice = async (
bot,
channelType,
sender,
recipient,
amount,
note,
replyCallback,
ts,
channelid
) => {
if (sender == recipient) {
console.log(`${sender} attempting to invoice theirself`);
replyCallback(`What are you trying to pull here, <@${sender}>?`);
return;
}
if (amount === 0) {
console.log(`${sender} attempting to send 0gp`);
replyCallback(`no`);
return;
}
var replyNote = note ? ` for "${note}".` : '.';
replyCallback(`I shall invoice <@${recipient}> ${amount}gp` + replyNote);
var invRecord = await createInvoice(sender, recipient, amount, replyNote);
var isPrivate = false;
invoiceReplies[invRecord.id] = replyCallback;
bot.say({
user: '@' + recipient,
channel: '@' + recipient,
text: `Good morrow hackalacker. <@${sender}> has just sent you an invoice of ${amount}gp${replyNote}
Reply with "@banker pay ${invRecord.id}".`,
});
};
var txLimiter = new Bottleneck({
maxConcurrent: 1,
});
var transfer = (args, cb) => txLimiter.submit(transferJob, args, cb);
var transferJob = (
{ bot, channelType, user, target, amount, note, ts, channelid },
replyCallback
) => {
if (user == target) {
console.log(`${user} attempting to transfer to theirself`);
replyCallback(`What are you trying to pull here, <@${user}>?`);
logTransaction(user, target, amount, note, false, 'Self transfer');
return;
}
getBalance(user, (userBalance, userRecord) => {
if (userBalance < amount) {
console.log(`User has insufficient funds`);
replyCallback(
`Regrettably, you only have ${userBalance}gp in your account.`,
false
);
logTransaction(user, target, amount, note, false, 'Insufficient funds');
} else {
getBalance(target, (targetBalance, targetRecord) => {
setBalance(userRecord.id, -amount, user);
// Treats targetBalance+amount as a string concatenation. WHY???
setBalance(targetRecord.id, -(-amount), target);
var replyNote = note ? ` for "${note}".` : '.';
replyCallback(
`I shall transfer ${amount}gp to <@${target}> immediately` +
replyNote,
true
);
var isPrivate = false;
if (channelType == 'im') {
bot.say({
user: '@' + target,
channel: '@' + target,
text: `Good morrow hackalacker. <@${user}> has just transferred ${amount}gp to your account${replyNote}`,
});
isPrivate = true;
} else if (data.bots.includes(target)) {
// send clean, splittable data string
bot.say({
user: '@' + target,
channel: '@' + target,
text: `$$$ | <@${user}> | ${amount} | ${replyNote} | ${channelid} | ${ts}`,
});
}
logTransaction(user, target, amount, note, true, '', isPrivate);
});
}
});
};
// log transactions in ledger
// parameters: user, target, amount, note, success, log message, private
function logTransaction(u, t, a, n, s, m, p) {
if (p === undefined) p = false;
console.log(parseInt(a));
base('ledger').create(
{
From: u,
To: t,
Amount: parseInt(a),
Note: n,
Success: s,
'Admin Note': m,
Timestamp: Date.now(),
Private: p,
},
function (err, record) {
if (err) {
console.error(err);
return;
}
console.log('New ledger transaction logged: ' + record.getId());
}
);
}
// log invoice on airtable
function createInvoice(sender, recipient, amount, note) {
return new Promise((resolve, reject) => {
base('invoices').create(
{
From: sender,
To: recipient,
Amount: parseInt(amount),
Reason: note,
},
function (err, record) {
if (err) {
console.error(err);
reject(err);
}
console.log('New invoice created:', record.getId());
resolve(record);
}
);
});
}
// @bot give @zrl 100 --> Gives 100gp from my account to zrl's
controller.hears(
/give\s+<@([A-z|0-9]+)>\s+([0-9]+)(?:gp)?(?:\s+for\s+(.+))?/i,
'direct_mention,direct_message,bot_message',
async (bot, message) => {
// console.log(message)
var { text, user, event, ts, channel } = message;
const verifyResult = await verifyPayload(text);
if (verifyResult[0] != 204) {
bot.replyInThread(message, JSON.parse(verifyResult[1])['text']);
} else {
if (message.thread_ts) {
ts = message.thread_ts;
}
if (message.type == 'bot_message' && !data.bots.includes(user)) return;
console.log(`Processing give request from ${user}`);
console.log(message);
var target = message.match[1];
var amount = message.match[2];
var note = message.match[3] || '';
var replyCallback = (text) => bot.replyInThread(message, text);
transfer(
{
bot,
channelType: event['channel_type'],
user,
target,
amount,
note,
ts,
channelid: channel,
},
replyCallback
);
}
}
);
// @bot invoice @zrl 100 for stickers --> Creates invoice for 100gp & notifies @zrl
controller.hears(
/invoice\s+<@([A-z|0-9]+)>\s+([0-9]+)(?:gp)?(?:\s+for\s+(.+))?/i,
'direct_mention,direct_message,bot_message',
async (bot, message) => {
var { text, user, event, ts, channel } = message;
const verifyResult = await verifyPayload(text);
if (verifyResult[0] != 204) {
bot.replyInThread(message, JSON.parse(verifyResult[1])['text']);
} else {
if (message.thread_ts) {
ts = message.thread_ts;
}
if (message.type == 'bot_message' && !data.bots.includes(user)) return;
console.log(`Processing invoice request from ${user}`);
var target = message.match[1];
var amount = message.match[2];
var note = message.match[3] || '';
var replyCallback = (text) => bot.replyInThread(message, text);
invoice(
bot,
event['channel_type'],
user,
target,
amount,
note,
replyCallback,
ts,
channel
);
}
}
);
// @bot pay rec182yhe902 --> pays an invoice
controller.hears(
/pay\s+([A-z|0-9]+)/i,
'direct_mention,direct_message,bot_message',
async (bot, message) => {
var { text, user, event, ts, channel } = message;
const verifyResult = await verifyPayload(text);
if (message.thread_ts) {
ts = message.thread_ts;
}
if (message.type == 'bot_message' && !data.bots.includes(user)) return;
console.log(`Processing invoice payment from ${user}`);
var id = message.match[1];
var invRecord = await getInvoice(id);
if (invRecord.fields['Paid']) {
bot.replyInThread(message, "You've already paid this invoice!");
}
var amount = invRecord.fields['Amount'];
var target = invRecord.fields['From'];
var note = `for invoice ${invRecord.id}`;
var replyCallback = (text, wentThrough) => {
bot.replyInThread(message, text);
if (typeof invoiceReplies[id] == 'function' && wentThrough) {
invoiceReplies[id](
`<@${user}> paid their invoice of ${amount} gp from <@${target}>${invRecord.fields['Reason']}`
);
}
};
transfer(
{
bot,
channelType: channel.type,
user,
target,
amount,
note,
ts,
channelid: channel,
},
replyCallback
);
}
);
controller.on('slash_command', async (bot, message) => {
var { command, text, user_id, ts, channel } = message;
var user = user_id;
console.log(`Slash command received from ${user_id}: ${text}`);
console.log(message);
bot.replyAcknowledge();
const verifyResult = await verifyPayload(text);
if (verifyResult[0] != 204) {
bot.replyPrivateDelayed(message, JSON.parse(verifyResult[1])['text']);
} else {
if (message.channel_id == process.env.SLACK_SELF_ID) {
bot.replyPublicDelayed(
message,
"Just fyi... You're talking to me already... no need for slash commands to summon me!"
);
} else {
if (command == '/give') {
var pattern = /<@([A-z|0-9]+)\|.+>\s+([0-9]+)(?:gp)?(?:\s+for\s+(.+))?/;
var match = pattern.exec(text);
if (match) {
var target = match[1];
var amount = match[2];
var note = match[3] || '';
var replyCallback = (text) =>
bot.replyPublicDelayed(message, {
blocks: [
{
type: 'section',
text: {
type: 'mrkdwn',
text: text,
},
},
{
type: 'context',
elements: [
{
type: 'mrkdwn',
text: `Transferred by <@${user_id}>`,
},
],
},
],
});
transfer(
{
bot,
channelType: 'public',
user: user_id,
target,
amount,
note,
ts,
channel,
},
replyCallback
);
} else {
bot.replyPrivateDelayed(
message,
'I do not understand! Please type your message as `/give @user [positive-amount]gp for [reason]`'
);
}
}
if (command == '/balance') {
var pattern = /(?:<@([A-z|0-9]+)\|.+>)?/i;
var match = pattern.exec(text);
if (match) {
var target = match[1] || user;
console.log(
`Received balance request from User ${user} for User ${target}`
);
getBalance(target, (balance) => {
var reply =
user == target
? `Ah yes, <@${target}> (${target}). You have ${balance}gp in your account, hackalacker.`
: `Ah yes, <@${target}> (${target})—they have ${balance}gp.`;
bot.replyPrivateDelayed(message, {
blocks: [
{
type: 'section',
text: {
type: 'mrkdwn',
text: reply,
},
},
{
type: 'context',
elements: [
{
type: 'mrkdwn',
text: `Requested by <@${user}>`,
},
],
},
],
});
});
}
}
}
}
});
controller.hears('.*', 'direct_mention,direct_message', (bot, message) => {
var { text, user } = message;
console.log(`Received unhandled message from User ${user}:\n${text}`);
// Ignore if reply is in a thread. Hack to work around infinite bot loops.
if (_.has(message.event, 'parent_user_id')) return;
bot.replyInThread(message, 'Pardon me, but I do not understand.');
});
let verifyPayload = async (data) => {
const response = await fetch('https://slack.hosted.hackclub.com', {
method: 'post',
body: data
});
const responseData = await response.text();
const status = await response.status;
console.log("Data: " + responseData);
console.log("Status: " + status)
return [status, responseData];
};