-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
355 lines (305 loc) · 9.43 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
const sqlite = require('better-sqlite3');
const Discord = require('discord.js');
const moment = require('moment-timezone');
const predictions = require('./predictions.js');
const CONFIG = require('./config.json');
const db = new sqlite('.data/data.db');
const client = new Discord.Client();
// MUST be US, because ACNH weeks start on Sunday.
moment.locale('en-US');
moment.tz.setDefault(CONFIG.tz);
/**
* DB setup.
*/
db.prepare(`CREATE TABLE IF NOT EXISTS sell_price (
user_id INTEGER NOT NULL,
week INTEGER NOT NULL,
price INTEGER NOT NULL,
PRIMARY KEY(user_id, week) ON CONFLICT REPLACE
);`).run();
db.prepare(`CREATE TABLE IF NOT EXISTS buy_price (
user_id INTEGER NOT NULL,
week INTEGER NOT NULL,
day INTEGER NOT NULL,
night INTEGER NOT NULL,
price INTEGER NOT NULL,
PRIMARY KEY(user_id, week, day, night) ON CONFLICT REPLACE
);`).run();
db.prepare(`CREATE TABLE IF NOT EXISTS pattern (
user_id INTEGER NOT NULL,
week INTEGER NOT NULL,
pattern INTEGER NOT NULL,
PRIMARY KEY(user_id, week) ON CONFLICT REPLACE
);`).run();
/**
* Turnip Prophet
*/
function turnipProphetLink(prices, pattern) {
return 'https://turnipprophet.io/?prices=' +
prices.slice(1).join('.').replace('undefined', '') +
'&pattern=' + pattern;
}
/**
* Handle all response types, so the command functions don't need to know about the Discord API.
*/
function respond(msg, results) {
if (results['react']) {
msg.react(results['react']);
}
if (results['reply']) {
msg.reply(results['reply']);
}
if (results['send']) {
msg.channel.send(results['send']);
}
}
/**
* Command Functions
*/
// args: PRICE
function sellPrice(user, args) {
// Validate price.
const price = parseInt(args[0]);
if (!price) {
return {
'reply': 'what was Daisy Mae\'s sell price?'
};
} else if (price < 90 || price > 110) {
return {
'reply': `invalid sell price, did you mean \`!buy ${price}\`?`
};
}
// Store the price in the DB.
const stmt = db.prepare('INSERT INTO sell_price VALUES (?, ?, ?)');
stmt.run(user, moment().week(), price)
return {
'react': '🔔'
};
}
// args: PRICE [morning|night [DAY_OF_WEEK]]
function buyPrice(user, args) {
// Validate price.
const price = parseInt(args[0]);
if (!price || price < 1 || price > 660) {
return {
'reply': 'must give a valid buy price'
};
}
// Validate morning|night.
var night = moment().hour() >= 12 ? 1 : 0;
if (args[1]) {
const timeOfDay = args[1].toLowerCase();
if (timeOfDay === 'morning') {
night = 0;
} else if (timeOfDay === 'night') {
night = 1;
} else {
return {
'reply': `${args[1]} isn't \`morning\` or \`night\``
}
}
}
// Validate day of week.
var day = moment().day();
var week = moment().week();
if (args[2]) {
const dayOfWeek = moment(args[2].toLowerCase(), ['ddd', 'dddd']).day();
if (!dayOfWeek) {
return {
'reply': `${args[2]} isn't a day`
};
}
if (dayOfWeek > day) {
// Note: breaks on year rollover, but who cares.
week--;
}
day = dayOfWeek;
}
// Can't buy on Sundays.
if (day == 0) {
return {
'reply': `there is no buy price on Sundays, did you mean \`!sell\`?`
};
}
// Store the price in the DB.
const stmt = db.prepare('INSERT INTO buy_price VALUES (?, ?, ?, ?, ?)');
stmt.run(user, week, day, night, price)
return {
'react': '🔔'
};
}
// args: largespike|smallspike|fluctuating|decreasing
function lastPattern(user, args) {
const patterns = {
'fluctuating': 0,
'largespike': 1,
'decreasing': 2,
'smallspike': 3,
};
if (!args[0] || !Object.keys(patterns).includes(args[0].toLowerCase())) {
return {
'reply': `pick your last week's pattern from: ${patterns.join(' ')}`
};
}
const pattern = patterns[args[0].toLowerCase()];
// Store the pattern in the DB.
const stmt = db.prepare('INSERT INTO pattern VALUES (?, ?, ?)');
// Note: breaks on year rollover, but who cares.
stmt.run(user, moment().week()-1, pattern);
return {
'react': args[0].toLowerCase() === 'decreasing' ? '📉' : '📈'
};
}
// args: [@mention]
function predict(user, args, mentions) {
var user_id = user;
if (mentions && mentions.first()) {
user_id = mentions.first().id;
}
// Get data from the DB.
const week = moment().week();
const patternRow = db.prepare('SELECT pattern FROM pattern WHERE user_id = ? AND week = ?').get(user_id, week - 1);
const sellPriceRow = db.prepare('SELECT price FROM sell_price WHERE user_id = ? AND week = ?').get(user_id, week);
const buyPriceRows = db.prepare('SELECT day, night, price FROM buy_price WHERE user_id = ? AND week = ?').all(user_id, week);
if (!sellPriceRow && !buyPriceRows.length) {
return {
'send': 'no data yet this week. try !sell, !buy, !lastpattern'
};
}
// Unpack db row objeccts and convert to epected formats.
const pattern = patternRow ? patternRow.pattern : undefined;
const sellPrice = sellPriceRow ? sellPriceRow.price : undefined;
var buyPriceList = Array(6 * 2);
buyPriceRows.forEach(row => {
buyPriceList[row.day * 2 - 2 + row.night] = row.price;
});
const prices = [sellPrice, sellPrice, ...buyPriceList]
// Predict!
const predictor = new predictions.Predictor(prices, false, pattern);
const generatedPossibilities = predictor.analyze_possibilities();
const getPatternPercent = (poss, id) => {
const filtered = poss.filter(x=>x.pattern_number===id);
if (filtered.length) {
return (filtered[0].category_total_probability*100).toPrecision(3) + '%';
}
};
const indexToDayTime = [
false,
false,
'Monday morning',
'Monday night',
'Tuesday morning',
'Tuesday night',
'Wednesday morning',
'Wednesday night',
'Thursday morning',
'Thursday night',
'Friday morning',
'Friday night',
'Saturday morning',
'Saturday night',
];
const getPatternPeak = (poss, id) => {
const filtered = poss.filter(x=>x.pattern_number===id);
if (filtered.length == 1) {
return ' (potential peak **' +
filtered[0].prices.flatMap((x, i) => x.max === filtered[0].weekMax ? i : []).map(x => indexToDayTime[x]).join(', ') +
'** up to **' + filtered[0].weekMax + '**🔔)';
} else {
return '';
}
};
const patternWeights = [
['Fluctuating', getPatternPercent(generatedPossibilities, 0), getPatternPeak(generatedPossibilities, 0)],
['Large Spike', getPatternPercent(generatedPossibilities, 1), getPatternPeak(generatedPossibilities, 1)],
['Decreasing', getPatternPercent(generatedPossibilities, 2), ''],
['Small Spike', getPatternPercent(generatedPossibilities, 3), getPatternPeak(generatedPossibilities, 3)],
].filter(t=>t[1]);
const reply = patternWeights.sort((x,y)=>parseInt(y[1])-parseInt(x[1])).map(x=>x.slice(0, 2).join(': ')+x[2]).join('\n') +
'\nGuaranteed min: ' + Math.min(...generatedPossibilities.map(x=>x.weekGuaranteedMinimum)) +
'\nPotential max: ' + Math.max(...generatedPossibilities.map(x=>x.weekMax)) +
'\nTurnip Prophet: ' + turnipProphetLink(prices, pattern);
return {
'send': reply
};
}
function link(user, args, mentions) {
var user_id = user;
if (mentions && mentions.first()) {
user_id = mentions.first().id;
}
// Get data from the DB.
const week = moment().week();
const patternRow = db.prepare('SELECT pattern FROM pattern WHERE user_id = ? AND week = ?').get(user_id, week - 1);
const sellPriceRow = db.prepare('SELECT price FROM sell_price WHERE user_id = ? AND week = ?').get(user_id, week);
const buyPriceRows = db.prepare('SELECT day, night, price FROM buy_price WHERE user_id = ? AND week = ?').all(user_id, week);
if (!sellPriceRow && !buyPriceRows.length) {
return {
'send': 'no data yet this week. try !sell, !buy, !lastpattern'
};
}
// Unpack db row objeccts and convert to epected formats.
const pattern = patternRow ? patternRow.pattern : undefined;
const sellPrice = sellPriceRow ? sellPriceRow.price : undefined;
var buyPriceList = Array(6 * 2);
buyPriceRows.forEach(row => {
buyPriceList[row.day * 2 - 2 + row.night] = row.price;
});
const prices = [sellPrice, sellPrice, ...buyPriceList]
return {
send: turnipProphetLink(prices, pattern)
};
}
function help() {
return {
send: Object.keys(commands).map(x=>'!'+x).join(', ')
};
}
/**
* Command Map
*/
commands = {
'help': help,
'sell': sellPrice,
'buy': buyPrice,
'lastpattern': lastPattern,
'predict': predict,
'link': link,
'code': ()=>({send:'https://github.com/rshipp/tornps'}),
}
/**
* Bot Main
*/
function setPresence() {
client.user.setPresence({ activity: { name: 'the stalk market' }, status: 'invisible' })
}
client.on('ready', () => {
setPresence();
console.log(`Logged in as ${client.user.tag}!`);
});
// Handle shard events cleanly, so the bot doesn't reconnect as "online" constantly.
client.on('shardResume', () => {
setPresence();
});
client.on('shardReady', () => {
setPresence();
});
client.on('message', msg => {
// Ignore bot messages.
if (msg.author.bot) return;
// Process !commands.
if (msg.content.startsWith('!')) {
const command = commands[msg.content.slice(1).split(' ')[0]];
if (command) {
try {
respond(msg, command(msg.author.id, msg.content.split(' ').slice(1), msg.mentions.users));
} catch (e) {
msg.reply(e.message);
console.error(e);
}
} else {
msg.reply('WHAT');
}
}
});
client.login(CONFIG.key);