-
Notifications
You must be signed in to change notification settings - Fork 331
Expand file tree
/
Copy pathbot.js
More file actions
1586 lines (1299 loc) · 53.2 KB
/
Copy pathbot.js
File metadata and controls
1586 lines (1299 loc) · 53.2 KB
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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// =====================================
// 🎎 WAIFU DEAL SNIPER - PRODUCTION BOT
// =====================================
// "Protect the waifu. Save the laifu. Snipe the deal."
//
// A hosted Discord bot for anime figure collectors
// Users just DM the bot - no setup required!
const fs = require('fs');
const path = require('path');
const dotenv = require('dotenv');
// Load `.env`, then override with `.env.local` when present (local dev).
dotenv.config({ path: path.join(__dirname, '.env') });
if (fs.existsSync(path.join(__dirname, '.env.local'))) {
dotenv.config({ path: path.join(__dirname, '.env.local'), override: true });
}
const { Client, GatewayIntentBits, EmbedBuilder, ActivityType, Partials } = require('discord.js');
const { TEMPLATES, SPICY_KEYWORDS, HUSBANDO_KEYWORDS, FIGURE_TYPE_KEYWORDS, GACHA_TEMPLATES, ROAST_TEMPLATES, COPIUM_TEMPLATES } = require('./templates');
const db = require('./database');
// TinyFish SDK is ESM; this app is CommonJS. Use a lazy dynamic import.
let tinyFishClientPromise = null;
async function getTinyFishClient() {
if (!tinyFishClientPromise) {
tinyFishClientPromise = import('@tiny-fish/sdk').then(({ TinyFish }) => new TinyFish());
}
return tinyFishClientPromise;
}
/**
* Wait for a TinyFish scrape using the SSE stream (`/v1/automation/run-sse`).
* This matches the pre-migration HTTP integration, which only parsed items from the final COMPLETE event.
*
* `agent.run()` (`/v1/automation/run`) can return while the run is still in progress with `result: null`,
* which produced empty searches even though progress logs (e.g. BACKGROUND) showed work continuing.
*/
async function runTinyFishSearch(client, searchUrl, goal) {
const { RunStatus, EventType } = await import('@tiny-fish/sdk');
const stream = await client.agent.stream({ url: searchUrl, goal });
for await (const event of stream) {
if (event.type !== EventType.COMPLETE) continue;
if (event.status === RunStatus.FAILED || event.status === RunStatus.CANCELLED) {
const msg = event.error?.message || `Run ${event.status}`;
return { error: msg };
}
if (event.status === RunStatus.COMPLETED) {
return { result: event.result };
}
return { error: `Unexpected run status: ${event.status}` };
}
return { error: 'Stream ended before completion' };
}
// Store last search results per user for gacha/roast
const lastSearchResults = new Map();
// Cleanup old search results every 15 minutes to prevent memory leak
setInterval(() => {
const now = Date.now();
const maxAge = 15 * 60 * 1000; // 15 minutes
for (const [userId, data] of lastSearchResults.entries()) {
if (now - data.timestamp > maxAge) {
lastSearchResults.delete(userId);
}
}
}, 15 * 60 * 1000);
// =====================================
// ⚙️ CONFIG
// =====================================
const CONFIG = {
DISCORD_TOKEN: process.env.DISCORD_TOKEN,
TINYFISH_API_KEY: process.env.TINYFISH_API_KEY,
WATCH_INTERVAL: 5 * 60 * 1000, // 5 minutes
RATE_LIMIT_WINDOW: 60000, // 1 minute
RATE_LIMIT_MAX: 10, // 10 searches per minute
MAX_WATCHES_PER_USER: 20,
};
// =====================================
// 🎲 HELPERS
// =====================================
function pick(arr) {
if (!arr || arr.length === 0) return '';
return arr[Math.floor(Math.random() * arr.length)];
}
function fill(template, vars) {
if (!template) return '';
let result = template;
for (const [key, val] of Object.entries(vars)) {
const safeVal = sanitizeForDisplay(String(val));
result = result.replace(new RegExp(`\\{${key}\\}`, 'g'), safeVal);
}
return result;
}
// =====================================
// 🔒 SECURITY HELPERS
// =====================================
// Sanitize for Discord display (prevent markdown injection)
function sanitizeForDisplay(str) {
if (!str) return '';
return str
.replace(/`/g, '\\`')
.replace(/@/g, '@') // Full-width @ to prevent mentions
.replace(/#/g, '#') // Full-width # to prevent channel mentions
.slice(0, 200);
}
// Validate search query
function sanitizeQuery(query) {
if (!query || typeof query !== 'string') return null;
let clean = query.trim().replace(/\s+/g, ' ');
if (clean.length > 100) clean = clean.slice(0, 100);
if (clean.length < 2) return null;
return clean;
}
// Validate price
function sanitizePrice(price) {
if (price === null || price === undefined) return null;
const num = parseInt(price, 10);
if (isNaN(num) || num < 0) return null;
if (num > 10000000) return 10000000;
return num;
}
// Rate limiting
const rateLimits = new Map();
function checkRateLimit(userId) {
const now = Date.now();
const userLimits = rateLimits.get(userId) || { count: 0, resetAt: now + CONFIG.RATE_LIMIT_WINDOW };
if (now > userLimits.resetAt) {
userLimits.count = 0;
userLimits.resetAt = now + CONFIG.RATE_LIMIT_WINDOW;
}
userLimits.count++;
rateLimits.set(userId, userLimits);
return userLimits.count <= CONFIG.RATE_LIMIT_MAX;
}
// Cleanup old rate limits every 10 minutes to prevent memory leak
setInterval(() => {
const now = Date.now();
for (const [userId, limits] of rateLimits.entries()) {
if (now > limits.resetAt + 60000) {
rateLimits.delete(userId);
}
}
}, 10 * 60 * 1000);
// =====================================
// 🎭 PERSONALITY DETECTION
// =====================================
function isSpicy(query) {
const q = query.toLowerCase();
return SPICY_KEYWORDS.some(kw => q.includes(kw));
}
function isHusbando(query) {
const q = query.toLowerCase();
return HUSBANDO_KEYWORDS.some(kw => q.includes(kw));
}
function getFigureType(query) {
const q = query.toLowerCase();
for (const [type, keywords] of Object.entries(FIGURE_TYPE_KEYWORDS)) {
if (keywords.some(kw => q.includes(kw))) return type;
}
return null;
}
function getCharacterReaction(query) {
const q = query.toLowerCase();
for (const [char, reactions] of Object.entries(TEMPLATES.characters)) {
if (q.includes(char)) return pick(reactions);
}
return null;
}
function getPriceReaction(price) {
if (price < 3000) return pick(TEMPLATES.prices.budget);
if (price < 10000) return pick(TEMPLATES.prices.mid);
if (price < 25000) return pick(TEMPLATES.prices.expensive);
return pick(TEMPLATES.prices.whale);
}
function getConditionComment(itemGrade, boxGrade) {
const item = (itemGrade || '').toUpperCase();
const box = (boxGrade || '').toUpperCase();
if ((item === 'A' || item === 'A-') && (box === 'B' || box === 'B-' || box === 'C')) {
return pick(TEMPLATES.condition.mint_box_damaged);
}
if (item === 'A' && box === 'A') {
return pick(TEMPLATES.condition.mint_mint);
}
if (item === 'A-' || item === 'B+') {
return pick(TEMPLATES.condition.good);
}
return pick(TEMPLATES.condition.used);
}
function isDeal(item) {
const itemGrade = (item.item_grade || '').toUpperCase();
const boxGrade = (item.box_grade || '').toUpperCase();
return (itemGrade === 'A' || itemGrade === 'A-') &&
(boxGrade === 'B' || boxGrade === 'B-' || boxGrade === 'C');
}
// =====================================
// 🔍 SMART PARSER - Find items in any response format
// =====================================
function findItemsArray(obj) {
if (!obj) return null;
// If it's a string, try to parse as JSON
if (typeof obj === 'string') {
try {
obj = JSON.parse(obj.replace(/```json\n?/g, '').replace(/```\n?/g, '').trim());
} catch (e) {
return null;
}
}
// If it's already an array of objects with url/price, return it
if (Array.isArray(obj) && obj.length > 0 && typeof obj[0] === 'object' && (obj[0].url || obj[0].price)) {
return obj;
}
// Search through all properties for an array of items
if (typeof obj === 'object') {
for (const key of Object.keys(obj)) {
const value = obj[key];
// Check if this property is an array of objects with url or price
if (Array.isArray(value) && value.length > 0 && typeof value[0] === 'object') {
if (value[0].url || value[0].price || value[0].name || value[0].raw_title) {
console.log(`Found items in field: "${key}" (${value.length} items)`);
return value;
}
}
// Recursively check nested objects (but not arrays)
if (typeof value === 'object' && !Array.isArray(value)) {
const nested = findItemsArray(value);
if (nested) return nested;
}
}
}
return null;
}
// =====================================
// 🔍 TINYFISH SDK - Multi-Site Search
// =====================================
// Site configurations
const SITES = {
amiami: {
name: 'AmiAmi',
emoji: '🇯🇵',
currency: 'JPY',
searchUrl: (query) => `https://www.amiami.com/eng/search/list/?s_keywords=${encodeURIComponent(query)}&s_st_condition_flg=1`,
goal: `Scrape pre-owned figure listings from this AmiAmi page.
The title contains condition grades like "(Pre-owned ITEM:A/BOX:B)".
For each product (max 8), extract:
- raw_title: FULL title text including "(Pre-owned ITEM:X/BOX:Y)"
- price: Price in JPY (number only)
- url: Product link
- image: Image URL
- in_stock: true/false
- scale: Figure scale if shown (e.g., "1/4", "1/7", "1/8") or null
- manufacturer: Company name (e.g., "Good Smile Company", "FREEing", "Alter", "Kotobukiya", "SEGA", "Banpresto")
- line: Product line if shown (e.g., "B-Style", "POP UP PARADE", "Nendoroid", "figma", "Prize Figure")
- exclusive: true if exclusive (contains "Exclusive", "Limited", "Event"), false otherwise
Return JSON array.`,
},
mercari: {
name: 'Mercari US',
emoji: '🇺🇸',
currency: 'USD',
searchUrl: (query) => `https://www.mercari.com/search/?keyword=${encodeURIComponent(query + ' figure')}&status=sold_out%3Afalse`,
goal: `Scrape figure listings from this Mercari search page.
For each product (max 8), extract:
- raw_title: Full product title
- price: Price in USD (number only, no $)
- url: Product link
- image: Image URL
- in_stock: true if available, false if sold
- condition: Item condition (e.g., "New", "Like new", "Good")
- seller: Seller name if visible
Return JSON array.`,
},
solaris: {
name: 'Solaris Japan',
emoji: '☀️',
currency: 'USD',
searchUrl: (query) => `https://solarisjapan.com/search?q=${encodeURIComponent(query)}&filter.category=Figures`,
goal: `Scrape figure listings from this Solaris Japan search page.
For each product (max 8), extract:
- raw_title: Full product name
- price: Price in USD (number only, no $)
- url: Product link
- image: Image URL
- in_stock: true if "Add to Cart" visible, false if "Sold Out" or "Notify Me"
- condition: Condition text (e.g., "BRAND NEW", "PRE ORDER", "Pre-owned")
- manufacturer: Company name if visible in title (e.g., "Good Smile Company", "Taito")
Return JSON array.`,
},
};
// Rarity scoring based on actual figure attributes
function calculateRarity(item) {
let score = 0;
const name = (item.raw_title || item.name || '').toLowerCase();
const manufacturer = (item.manufacturer || '').toLowerCase();
const line = (item.line || '').toLowerCase();
const scale = item.scale || '';
const price = parseInt(item.price) || 0;
// === SCALE SCORING ===
if (scale.includes('1/4')) score += 30;
else if (scale.includes('1/6')) score += 20;
else if (scale.includes('1/7')) score += 15;
else if (scale.includes('1/8')) score += 10;
else if (name.includes('1/4')) score += 30;
else if (name.includes('1/6')) score += 20;
else if (name.includes('1/7')) score += 15;
else if (name.includes('1/8')) score += 10;
// === MANUFACTURER SCORING ===
const premiumMakers = ['alter', 'freeing', 'native', 'orchid seed', 'vertex', 'b\'full', 'binding'];
const goodMakers = ['good smile', 'kotobukiya', 'max factory', 'megahouse', 'phat', 'aquamarine', 'ques q', 'wing'];
const budgetMakers = ['sega', 'banpresto', 'taito', 'furyu', 'bandai spirits', 'prize'];
if (premiumMakers.some(m => manufacturer.includes(m) || name.includes(m))) score += 25;
else if (goodMakers.some(m => manufacturer.includes(m) || name.includes(m))) score += 15;
else if (budgetMakers.some(m => manufacturer.includes(m) || name.includes(m))) score -= 10;
// === LINE SCORING ===
if (line.includes('b-style') || name.includes('b-style')) score += 25;
if (line.includes('native') || name.includes('native')) score += 20;
if (name.includes('bunny') && (name.includes('1/4') || price > 20000)) score += 20;
if (line.includes('pop up parade') || name.includes('pop up parade')) score -= 5;
if (name.includes('prize') || name.includes('game-prize') || name.includes('ichiban kuji')) score -= 15;
if (line.includes('nendoroid') || name.includes('nendoroid')) score += 5;
if (line.includes('figma') || name.includes('figma')) score += 10;
// === EXCLUSIVE SCORING ===
if (item.exclusive || name.includes('exclusive') || name.includes('limited')) score += 15;
if (name.includes('event') || name.includes('wf ') || name.includes('wonder festival')) score += 20;
// === CONDITION SCORING ===
const itemGrade = (item.item_grade || '').toUpperCase();
const boxGrade = (item.box_grade || '').toUpperCase();
if (itemGrade === 'A' && boxGrade === 'A') score += 10;
if (itemGrade === 'A' && (boxGrade === 'B' || boxGrade === 'C')) score += 5; // Deal!
// === PRICE SANITY CHECK ===
if (price > 30000) score += 10;
else if (price > 20000) score += 5;
else if (price < 2000) score -= 10;
// Determine rarity tier
if (score >= 50) return { tier: 'ssr', score, label: '🌈 SSR - LEGENDARY' };
if (score >= 30) return { tier: 'sr', score, label: '⭐ SR - RARE' };
if (score >= 10) return { tier: 'r', score, label: '📦 R - COMMON' };
return { tier: 'salt', score, label: '🧂 N - BUDGET' };
}
// Get rarity details for display
function getRarityDetails(item) {
const details = [];
const name = (item.raw_title || item.name || '').toLowerCase();
// Scale
const scaleMatch = name.match(/1\/[4-8]/);
if (scaleMatch) details.push(`📏 ${scaleMatch[0]} Scale`);
// Manufacturer
if (item.manufacturer) details.push(`🏭 ${item.manufacturer}`);
// Line
if (item.line) details.push(`📦 ${item.line}`);
// Special tags
if (name.includes('exclusive') || name.includes('limited') || item.exclusive) details.push(`✨ Limited/Exclusive`);
if (name.includes('b-style') || name.includes('bunny')) details.push(`🐰 Bunny`);
if (name.includes('native')) details.push(`🔞 Native`);
if (name.includes('prize') || name.includes('game-prize')) details.push(`🎮 Prize Figure`);
return details;
}
async function searchSite(siteKey, query, maxPrice = null) {
const site = SITES[siteKey];
if (!site) return { success: false, error: 'Unknown site' };
const searchUrl = site.searchUrl(query);
const goal = site.goal + (maxPrice ? `\n\nOnly items under ${maxPrice} JPY.` : '');
try {
const client = await getTinyFishClient();
const { result, error: tinyfishError } = await runTinyFishSearch(client, searchUrl, goal);
if (tinyfishError) {
console.error(`${site.name} TinyFish error:`, tinyfishError);
return { success: false, error: String(tinyfishError) };
}
let foundItems = findItemsArray(result);
if (foundItems && foundItems.length > 0) {
// Post-process items
foundItems = foundItems.map(item => {
// Parse grades from title
const title = item.raw_title || item.full_title || item.name || '';
const gradeMatch = title.match(/ITEM:\s*([A-C][+-]?)\s*[\/\s]*BOX:\s*([A-C][+-]?)/i);
if (gradeMatch) {
item.item_grade = gradeMatch[1].toUpperCase();
item.box_grade = gradeMatch[2].toUpperCase();
item.name = title.replace(/^\(Pre-owned\s+ITEM:[A-C][+-]?\s*[\/\s]*BOX:[A-C][+-]?\)\s*/i, '').trim() || item.name;
} else {
item.item_grade = item.item_grade || null;
item.box_grade = item.box_grade || null;
item.name = item.name || title;
}
// Calculate rarity
item.rarity = calculateRarity(item);
item.rarityDetails = getRarityDetails(item);
item.site = siteKey;
item.siteName = site.name;
item.siteEmoji = site.emoji;
console.log(` → ${(item.name || 'Unknown').slice(0, 40)}... | ${item.rarity.label}`);
return item;
});
console.log(`✅ ${site.name} found ${foundItems.length} items`);
return { success: true, items: foundItems, site: siteKey };
}
console.error(`❌ No items found from ${site.name}`);
return { success: false, error: 'No results found' };
} catch (error) {
console.error(`${site.name} search error:`, error.message);
return { success: false, error: error.message };
}
}
// Main search function - defaults to AmiAmi, can specify site
async function searchAmiAmi(query, maxPrice = null, siteKey = 'amiami') {
return searchSite(siteKey, query, maxPrice);
}
// Search multiple sites at once
async function searchAllSites(query, maxPrice = null) {
const siteKeys = ['amiami', 'mercari', 'solaris'];
const results = await Promise.allSettled(
siteKeys.map(site => searchSite(site, query, maxPrice))
);
const allItems = [];
const siteResults = {};
results.forEach((result, index) => {
const siteKey = siteKeys[index];
if (result.status === 'fulfilled' && result.value.success) {
siteResults[siteKey] = result.value;
allItems.push(...result.value.items);
} else {
console.log(`${siteKey} failed:`, result.reason?.message || result.value?.error);
}
});
// Sort by rarity score
allItems.sort((a, b) => (b.rarity?.score || 0) - (a.rarity?.score || 0));
return {
success: allItems.length > 0,
items: allItems,
siteResults,
sitesSearched: siteKeys,
};
}
// =====================================
// 🎨 DISCORD EMBEDS
// =====================================
function createFigureEmbed(item) {
const isGoodDeal = isDeal(item);
const price = parseInt(item.price) || 0;
const rarity = item.rarity?.tier || 'r';
const rarityLabel = item.rarity?.label || '';
// Color based on rarity or deal status
const rarityColors = {
ssr: 0xFFD700, // Gold
sr: 0xA855F7, // Purple
r: 0x3B82F6, // Blue
salt: 0x6B7280, // Gray
};
const embedColor = isGoodDeal ? 0xFF6B6B : (rarityColors[rarity] || 0x6C5CE7);
// Title prefix based on rarity
const rarityPrefix = rarity === 'ssr' ? '🌈 ' : rarity === 'sr' ? '⭐ ' : '';
const embed = new EmbedBuilder()
.setColor(embedColor)
.setTitle(`${isGoodDeal ? '🔥 ' : rarityPrefix}${(item.name || 'Figure').slice(0, 250)}`)
.setURL(item.url || 'https://www.amiami.com');
// Only set thumbnail if it's a valid URL
if (item.image && item.image.startsWith('http')) {
embed.setThumbnail(item.image);
}
let desc = '';
if (isGoodDeal) {
desc += `**${pick(TEMPLATES.deal_alert)}**\n\n`;
} else if (rarity === 'ssr') {
desc += `**${rarityLabel}**\n\n`;
}
desc += `💴 **¥${price.toLocaleString()}**\n`;
desc += `✨ Figure: **${item.item_grade || '?'}** | 📦 Box: **${item.box_grade || '?'}**\n`;
desc += `${item.in_stock !== false ? '✅ In Stock' : '❌ Sold Out'}`;
// Add rarity tags if present
if (item.rarityDetails && item.rarityDetails.length > 0) {
desc += `\n\n🏷️ ${item.rarityDetails.slice(0, 3).join(' • ')}`;
}
desc += `\n\n*${getConditionComment(item.item_grade, item.box_grade)}*`;
embed.setDescription(desc);
// Footer with site info if multi-site
const siteInfo = item.siteEmoji ? `${item.siteEmoji} ${item.siteName} • ` : '';
embed.setFooter({ text: `${siteInfo}${getPriceReaction(price)} • Click title to buy!` });
return embed;
}
function createResultsSummaryEmbed(items, query, spicy) {
const deals = items.filter(isDeal);
const templates = spicy ? TEMPLATES.found.spicy : TEMPLATES.found.normal;
const embed = new EmbedBuilder()
.setColor(spicy ? 0xE91E63 : 0x6C5CE7)
.setTitle(`🎯 Results for "${sanitizeForDisplay(query)}"`)
.setDescription(fill(pick(templates), { count: items.length, query }));
if (deals.length > 0) {
embed.addFields({
name: '🔥 Deals Found!',
value: `${deals.length} item(s) with mint figure + damaged box discount!`
});
}
embed.setFooter({ text: `Say "watch ${query}" to get alerts! 🔔` });
return embed;
}
// =====================================
// 🗣️ NATURAL LANGUAGE PARSER
// =====================================
function parseMessage(content) {
const lower = content.toLowerCase().trim();
// Help
if (/^(help|commands|how|what can you do)/i.test(lower)) {
return { intent: 'help' };
}
// Greetings
if (/^(hey|hi|hello|yo|sup|henlo|hii+|hewwo|ohayo)(!|\?)?$/i.test(lower)) {
return { intent: 'greeting' };
}
// Watchlist
if (/^(my )?(watchlist|watches|alerts|list|hunting)$/i.test(lower)) {
return { intent: 'watchlist' };
}
// Stop watching
const unwatchMatch = lower.match(/^(stop watching|unwatch|remove|cancel|delete)\s+(.+)/i);
if (unwatchMatch) {
return { intent: 'unwatch', query: unwatchMatch[2].trim() };
}
// === NEW FEATURES ===
// Gacha mode
const gachaMatch = lower.match(/^(?:gacha|roll|spin|gamble|yolo)\s+(.+)/i);
if (gachaMatch) {
return { intent: 'gacha', query: gachaMatch[1].trim() };
}
if (/^(?:gacha|roll|spin)$/i.test(lower)) {
return { intent: 'gacha_last' };
}
// Roast mode
if (/^(?:roast|roast me|roast this|judge|judge me|flame)$/i.test(lower)) {
return { intent: 'roast' };
}
const roastMatch = lower.match(/^(?:roast|judge|flame)\s+(.+)/i);
if (roastMatch) {
return { intent: 'roast_query', query: roastMatch[1].trim() };
}
// Copium mode
if (/^(?:copium|cope|copium mode|inhale|sad|pain)$/i.test(lower)) {
return { intent: 'copium' };
}
// === MULTI-SITE SEARCH ===
// Search all sites
const allSitesMatch = lower.match(/^(?:all|everywhere|all sites)\s+(.+?)(?:\s+under\s+|\s*<\s*)?(\d+)?$/i);
if (allSitesMatch) {
const query = allSitesMatch[1].replace(/\s*(figures?|deals?)\s*/gi, ' ').trim();
const price = allSitesMatch[2] ? parseInt(allSitesMatch[2]) : null;
if (query.length > 2) {
return { intent: 'search_all', query, maxPrice: price };
}
}
// Site-specific search: mercari <query>, solaris <query>, amiami <query>
const siteMatch = lower.match(/^(mercari|solaris|amiami)\s+(.+?)(?:\s+under\s+|\s*<\s*)?(\d+)?$/i);
if (siteMatch) {
const site = siteMatch[1].toLowerCase();
const query = siteMatch[2].replace(/\s*(figures?|deals?)\s*/gi, ' ').trim();
const price = siteMatch[3] ? parseInt(siteMatch[3]) : null;
if (query.length > 2) {
return { intent: 'search_site', site, query, maxPrice: price };
}
}
// Watch/alert
const watchPatterns = [
/^(?:watch|alert|notify|ping|dm|tell)\s+(?:me\s+)?(?:for\s+|when\s+|if\s+)?(.+?)(?:\s+under\s+|\s*<\s*|\s+max\s+)?(\d+)?$/i,
/^(.+?)\s+(?:alert|notify|watch)(?:\s+under\s+|\s*<\s*)?(\d+)?$/i,
];
for (const pattern of watchPatterns) {
const match = lower.match(pattern);
if (match) {
const query = match[1].replace(/^(for|when|if)\s+/i, '').replace(/\s+(appears?|drops?|available|shows? up).*$/i, '').trim();
const price = match[2] ? parseInt(match[2]) : null;
if (query.length > 2) {
return { intent: 'watch', query, maxPrice: price || 999999 };
}
}
}
// Search patterns - extract query and optional price
// First, detect if price is in USD (need to convert to JPY for AmiAmi)
const usdPattern = /[\$](\d+)|(\d+)\s*[\$]|(\d+)\s*(dollars?|bucks?|usd)/i;
const usdMatch = lower.match(usdPattern);
const isUSD = !!usdMatch;
const USD_TO_JPY = 150; // Approximate conversion rate
// Clean the input of conversational fluff
let cleanedInput = lower
.replace(/^(yo|hey|hi|hello|sup|bro|dude|man|guys?),?\s*/gi, '') // Remove greetings
.replace(/^bro,?\s*/gi, '') // Remove "bro" again if still there
.replace(/,?\s*(anything\s+)?(under|below|max|less than)\s*[\$¥]?(\d+)[\$¥]?\s*(works|dollars?|bucks?|usd|jpy|yen)?.*$/i, ' under $3') // Normalize price
.trim();
const searchPatterns = [
// "find me some figure of ganyu from genshin impact under 500"
/^(?:looking for|find|search|hunt|show|got any|get me|i want|i need)\s+(?:me\s+)?(?:some\s+)?(?:figure[s]?\s+of\s+)?(.+?)(?:\s+under\s+)?(\d+)?$/i,
// "any ganyu figures under 500"
/^(?:any\s+)?(.+?)\s+(?:figures?|deals?)(?:\s+under\s+)?(\d+)?$/i,
// "ganyu under 500"
/^(.+?)\s+under\s+(\d+)$/i,
];
for (const pattern of searchPatterns) {
const match = cleanedInput.match(pattern);
if (match) {
let query = match[1]
.replace(/\s*(figures?|deals?|please|pls|thx|thanks)\s*/gi, ' ')
.replace(/\s+/g, ' ')
.trim();
// Extract "X from Y" → "X Y" (e.g., "ganyu from genshin" → "ganyu genshin")
const fromMatch = query.match(/(.+?)\s+from\s+(.+)/i);
if (fromMatch) {
query = fromMatch[1].trim() + ' ' + fromMatch[2].trim();
}
let price = match[2] ? parseInt(match[2]) : null;
// Convert USD to JPY if detected
if (price && isUSD) {
price = Math.round(price * USD_TO_JPY);
}
if (query.length > 2) {
return { intent: 'search', query, maxPrice: price, isUSD };
}
}
}
// Stats
if (/^(stats|statistics|my stats|status)$/i.test(lower)) {
return { intent: 'stats' };
}
// Default: treat short text as search
if (lower.length > 3 && lower.length < 50 && !lower.includes('?')) {
return { intent: 'search', query: lower };
}
return { intent: 'unknown' };
}
// =====================================
// 🤖 MESSAGE HANDLERS
// =====================================
async function handleMessage(message, content) {
const username = message.author.username;
const discordId = message.author.id;
console.log(` → handleMessage called with: "${content}"`);
// Get or create user
const user = db.getOrCreateUser(discordId, username);
console.log(` → User: ${user ? 'found/created' : 'NULL'}`);
db.updateUserActivity(discordId);
const isNew = db.isNewUser(discordId);
const parsed = parseMessage(content);
console.log(` → Parsed intent: ${parsed.intent}, query: ${parsed.query || 'none'}`);
try {
switch (parsed.intent) {
case 'help':
await message.reply(TEMPLATES.help[0]);
break;
case 'greeting':
if (isNew) {
await message.reply(fill(TEMPLATES.welcome[0], { user: username }));
} else {
await message.reply(fill(pick(TEMPLATES.greetings.returning), { user: username }));
}
break;
case 'search':
await handleSearch(message, user, parsed.query, parsed.maxPrice, parsed.isUSD);
break;
case 'watch':
await handleWatch(message, user, parsed.query, parsed.maxPrice);
break;
case 'watchlist':
await handleWatchlist(message, user);
break;
case 'unwatch':
await handleUnwatch(message, user, parsed.query);
break;
case 'stats':
await handleStats(message, user);
break;
// === NEW FEATURES ===
case 'gacha':
await handleGacha(message, user, parsed.query);
break;
case 'gacha_last':
await handleGachaLast(message, user);
break;
case 'roast':
await handleRoast(message, user);
break;
case 'roast_query':
await handleRoastQuery(message, user, parsed.query);
break;
case 'copium':
await handleCopium(message, user);
break;
// === MULTI-SITE SEARCH ===
case 'search_site':
await handleSearchSite(message, user, parsed.site, parsed.query, parsed.maxPrice);
break;
case 'search_all':
await handleSearchAll(message, user, parsed.query, parsed.maxPrice);
break;
default:
if (!message.guild) { // DM
const response = isNew
? fill(TEMPLATES.welcome[0], { user: username })
: `🤔 Not sure what you mean! Try:\n• \`looking for rem figures\`\n• \`watch marin under 15000\`\n• \`help\``;
await message.reply(response);
}
}
} catch (error) {
console.error('Handler error:', error);
await message.reply(pick(TEMPLATES.errors.search_failed)).catch(() => {});
}
}
async function handleSearch(message, user, query, maxPrice, isUSD = false) {
// Validate inputs
const cleanQuery = sanitizeQuery(query);
if (!cleanQuery) {
await message.reply("🤔 That search doesn't look right. Try: `looking for rem figures`");
return;
}
const cleanPrice = sanitizePrice(maxPrice);
// Rate limit check
if (!checkRateLimit(user.discord_id)) {
await message.reply("⏳ Slow down! Too many searches. Try again in a minute~");
return;
}
const spicy = isSpicy(cleanQuery);
const husbando = isHusbando(cleanQuery);
const figureType = getFigureType(cleanQuery);
const charReaction = getCharacterReaction(cleanQuery);
// Build response
let searchMsg = '';
// Show USD conversion notice
if (isUSD && cleanPrice) {
const originalUSD = Math.round(cleanPrice / 150);
searchMsg += `💱 *$${originalUSD} USD → ¥${cleanPrice.toLocaleString()} JPY*\n\n`;
}
if (charReaction) {
searchMsg += charReaction + '\n\n';
} else if (figureType && TEMPLATES.figure_types[figureType]) {
searchMsg += pick(TEMPLATES.figure_types[figureType]) + '\n\n';
}
const templates = husbando ? TEMPLATES.searching.husbando :
spicy ? TEMPLATES.searching.spicy :
TEMPLATES.searching.normal;
searchMsg += fill(pick(templates), { query: cleanQuery });
const statusMsg = await message.reply(searchMsg);
// Search!
const result = await searchAmiAmi(cleanQuery, cleanPrice);
db.incrementSearchCount(user.id);
if (!result.success) {
await statusMsg.edit(searchMsg + '\n\n' + pick(TEMPLATES.errors.search_failed));
return;
}
if (!result.items || result.items.length === 0) {
const noResult = fill(
pick(spicy ? TEMPLATES.no_results.spicy : TEMPLATES.no_results.normal),
{ query: cleanQuery }
);
await statusMsg.edit(searchMsg + '\n\n' + noResult);
return;
}
// Log & count deals
db.logSearch(user.id, cleanQuery, result.items.length);
const deals = result.items.filter(isDeal);
if (deals.length > 0) {
db.incrementDealsFound(user.id, deals.length);
}
// Send results
const summaryEmbed = createResultsSummaryEmbed(result.items, cleanQuery, spicy);
await statusMsg.edit({ content: searchMsg, embeds: [summaryEmbed] });
const toShow = result.items.slice(0, 5);
for (const item of toShow) {
await message.channel.send({ embeds: [createFigureEmbed(item)] });
}
if (result.items.length > 5) {
await message.channel.send(`*...and ${result.items.length - 5} more! Say \`watch ${sanitizeForDisplay(cleanQuery)}\` to get alerts~*`);
}
}
// =====================================
// 🌐 MULTI-SITE SEARCH HANDLERS
// =====================================
async function handleSearchSite(message, user, siteKey, query, maxPrice) {
const site = SITES[siteKey];
if (!site) {
await message.reply(`🤔 Unknown site! Try: \`mercari rem\`, \`solaris miku\`, or \`amiami power\``);
return;
}
const cleanQuery = sanitizeQuery(query);
if (!cleanQuery) {
await message.reply(`🤔 What should I search on ${site.name}? Try: \`${siteKey} rem figures\``);
return;
}
const cleanPrice = sanitizePrice(maxPrice);
// Rate limit
if (!checkRateLimit(user.discord_id)) {
await message.reply("⏳ Slow down! Too many searches. Try again in a minute~");
return;
}
// Send searching message
const searchMsg = `${site.emoji} Searching **${site.name}** for **${sanitizeForDisplay(cleanQuery)}**...`;
const statusMsg = await message.reply(searchMsg);
// Search
const result = await searchSite(siteKey, cleanQuery, cleanPrice);
db.incrementSearchCount(user.id);
if (!result.success) {
await statusMsg.edit(searchMsg + `\n\n💀 ${site.name} search failed... Try again?`);
return;
}
if (!result.items || result.items.length === 0) {
await statusMsg.edit(searchMsg + `\n\n😢 No results on ${site.name}! Try a different search.`);
return;
}
// Store for gacha/roast
lastSearchResults.set(user.discord_id, { query: cleanQuery, items: result.items, timestamp: Date.now() });
// Log
db.logSearch(user.id, `${siteKey}:${cleanQuery}`, result.items.length);
// Build summary
const currency = site.currency === 'USD' ? '$' : '¥';
const avgPrice = result.items.reduce((sum, i) => sum + (parseInt(i.price) || 0), 0) / result.items.length;
const summaryEmbed = new EmbedBuilder()
.setColor(siteKey === 'mercari' ? 0xE53935 : siteKey === 'solaris' ? 0xFFA726 : 0x6C5CE7)
.setTitle(`${site.emoji} ${site.name} Results`)
.setDescription(`Found **${result.items.length}** results for **${sanitizeForDisplay(cleanQuery)}**\n\nAverage price: **${currency}${Math.round(avgPrice).toLocaleString()}**`);
await statusMsg.edit({ content: null, embeds: [summaryEmbed] });
// Show items
const toShow = result.items.slice(0, 5);
for (const item of toShow) {
const embed = createSiteEmbed(item, site);
await message.channel.send({ embeds: [embed] });
}
if (result.items.length > 5) {
await message.channel.send(`*...and ${result.items.length - 5} more on ${site.name}!*`);
}
}
async function handleSearchAll(message, user, query, maxPrice) {
const cleanQuery = sanitizeQuery(query);
if (!cleanQuery) {
await message.reply("🤔 What should I search? Try: `all rem figures`");
return;
}