-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathArtIndexerBot.ts
More file actions
1119 lines (1005 loc) · 34.7 KB
/
ArtIndexerBot.ts
File metadata and controls
1119 lines (1005 loc) · 34.7 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
/* eslint-disable no-case-declarations */
import { Channel, Collection, EmbedBuilder, Message } from 'discord.js'
import * as dotenv from 'dotenv'
import { ProjectBot } from './ProjectBot'
import {
getAllProjects,
getArtblocksOpenProjects,
getAllTokensInWallet,
getMostRecentMintedTokenByContracts,
getAllContracts,
getMostRecentMintedFlagshipToken,
getArtblocksNextUpcomingProject,
getEntryByTag,
getEntryByVertical,
getAllSets,
getSetByName,
} from '../Data/queryGraphQL'
import { projectConfig, triviaBot } from '..'
import {
Categories_Enum,
ContractDetailFragment,
ProjectDetailFragment,
ProjectTokenDetailFragment,
TokenDetailFragment,
} from '../../generated/graphql'
import {
getVerticalName,
isVerticalName,
resolveEnsName,
getProjectUrl,
getProjectSlugUrl,
} from './APIBots/utils'
import { ProjectConfig } from '../ProjectConfig/projectConfig'
import { randomColor } from '../Utils/smartBotResponse'
dotenv.config()
const deburr = require('lodash.deburr')
const PROJECT_ALIASES = require('../ProjectConfig/project_aliases.json')
const CONTRACT_ALIASES: {
aliases: string[]
named_contracts: string[]
}[] = require('../ProjectConfig/contract_aliases.json')
const { isWallet } = require('./APIBots/utils')
const METADATA_REFRESH_INTERVAL_MINUTES =
process.env.METADATA_REFRESH_INTERVAL_MINUTES ?? '480' // 8 hours
const ONE_MINUTE_IN_MS = 60000
export enum MessageTypes {
RANDOM = 'random',
RANDOM_ALL = 'random_all',
ARTIST = 'artist',
COLLECTION = 'collection',
TAG = 'tag',
PROJECT = 'project',
OPEN = 'open',
WALLET = 'wallet',
RECENT = 'recent',
ENTRY = 'entry',
SET = 'set',
PLATFORM = 'platform',
UPCOMING = 'upcoming',
UNKNOWN = 'unknown',
}
type ProjectBotAndToken = {
projectBot: ProjectBot
tokenId: string
}
export class ArtIndexerBot {
projectFetch: () => Promise<ProjectDetailFragment[]>
projects: { [id: string]: ProjectBot } = {}
artists: { [id: string]: ProjectBot[] } = {}
birthdays: { [id: string]: ProjectBot[] } = {}
collections: { [id: string]: ProjectBot[] } = {}
tags: { [id: string]: ProjectBot[] } = {}
projectsById: { [id: string]: ProjectBot } = {}
contracts: { [id: string]: ContractDetailFragment } = {}
walletTokens: { [id: string]: TokenDetailFragment[] } = {}
sets: { [id: string]: string } = {}
initialized = false
platforms: { [id: string]: ProjectBot[] } = {}
flagship: { [id: string]: ProjectBot } = {}
constructor(projectFetch = getAllProjects) {
this.projectFetch = projectFetch
this.init()
}
/**
* Initialize async aspects of the FactoryBot
*/
async init() {
await this.buildProjectBots()
if (this.projectFetch === getAllProjects) {
await this.buildContracts()
await this.buildSets()
projectConfig.initializeProjectBots()
}
setInterval(async () => {
this.logDictionarySizes()
await this.buildProjectBots()
if (this.projectFetch === getAllProjects) {
projectConfig.initializeProjectBots()
}
}, parseInt(METADATA_REFRESH_INTERVAL_MINUTES) * ONE_MINUTE_IN_MS)
}
private logDictionarySizes() {
console.log('ArtIndexerBot Dictionary Sizes:')
console.log(`projects: ${Object.keys(this.projects).length}`)
console.log(`artists: ${Object.keys(this.artists).length}`)
console.log(`birthdays: ${Object.keys(this.birthdays).length}`)
console.log(`collections: ${Object.keys(this.collections).length}`)
console.log(`tags: ${Object.keys(this.tags).length}`)
console.log(`projectsById: ${Object.keys(this.projectsById).length}`)
console.log(`contracts: ${Object.keys(this.contracts).length}`)
console.log(`walletTokens: ${Object.keys(this.walletTokens).length}`)
console.log(`sets: ${Object.keys(this.sets).length}`)
console.log(`platforms: ${Object.keys(this.platforms).length}`)
console.log(`flagship: ${Object.keys(this.flagship).length}`)
}
async buildContracts() {
try {
const arbContractsArr = await getAllContracts(true)
for (let i = 0; i < arbContractsArr.length; i++) {
const name = arbContractsArr[i].name
if (typeof name === 'string') {
this.contracts[name.toLowerCase()] = arbContractsArr[i]
}
}
const ethContractsArr = await getAllContracts(false)
for (let i = 0; i < ethContractsArr.length; i++) {
const name = ethContractsArr[i].name
if (typeof name === 'string') {
this.contracts[name.toLowerCase()] = ethContractsArr[i]
}
}
} catch (e) {
console.error('Error in buildContracts', e)
}
}
async buildSets() {
try {
this.sets = {}
const setsArr = await getAllSets()
console.log(`ArtIndexerBot: Building ${setsArr.length} sets`)
for (let i = 0; i < setsArr.length; i++) {
const setName = setsArr[i].name
if (typeof setName === 'string') {
// Store lowercase key mapping to actual set name for case-insensitive lookup
this.sets[setName.toLowerCase()] = setName
}
}
this.sets['ab500'] = 'Art Blocks 500'
} catch (e) {
console.error('Error in buildSets', e)
}
}
async buildProjectBots() {
try {
this.clearDictionaries()
const projects = await this.projectFetch()
console.log(
`ArtIndexerBot: Building ${projects.length} ProjectBots using: ${this.projectFetch.name}`
)
for (let i = 0; i < projects.length; i++) {
const project = projects[i]
if (project.invocations === '0') continue
let bday = project.start_datetime
// Only AB projects use vertical names. Other projects (Engine, Collabs, etc) should use the category name
const collection = this.toProjectKey(
project.vertical?.category_name?.toLowerCase() !==
Categories_Enum.Collections
? project.vertical?.category_name
: project.vertical_name
)
const tags: string[] = project.tags.map((tag) =>
this.toProjectKey(tag.tag_name)
)
const newBot = new ProjectBot({
id: project.id,
projectNumber: parseInt(project.project_id),
coreContract: project.contract_address,
editionSize: project.invocations,
maxEditionSize: project.max_invocations,
projectName: project.name ?? 'unknown',
description: project.description ?? '',
projectActive: project.active,
artistName: project.artist_name ?? 'unknown artist',
collection,
tags,
startTime: bday ? new Date(bday) : undefined,
})
const projectKey = this.toProjectKey(project.name ?? 'unknown project')
const projectKeyWithArtist = this.toProjectKey(
`${project.artist_name} ${project.name}`
)
this.projects[projectKeyWithArtist] = newBot
if (
project.vertical.category_name === 'collaborations' ||
project.vertical.category_name === 'explorations'
) {
project.is_artblocks = true
}
if (
(this.projects[projectKey] && project.is_artblocks) ||
!this.projects[projectKey]
) {
// Overwrite if it's a flagship project
this.projects[projectKey] = newBot
}
this.projectsById[project.id] = newBot
if (bday) {
const [, month, day] = bday.split('T')[0].split('-')
bday = month + '-' + day
this.birthdays[bday] = this.birthdays[bday] ?? []
this.birthdays[bday].push(newBot)
}
const artistName = this.cleanKey(
project.artist_name ?? 'unknown artist'
)
this.artists[artistName] = this.artists[artistName] ?? []
this.artists[artistName].push(newBot)
this.collections[collection] = this.collections[collection] ?? []
this.collections[collection].push(newBot)
for (let j = 0; j < tags.length; j++) {
const tag = tags[j]
this.tags[tag] = this.tags[tag] ?? []
this.tags[tag].push(newBot)
}
if (project.is_artblocks) {
this.flagship[projectKey] = newBot
this.platforms['artblocks'] = this.platforms['artblocks'] ?? []
this.platforms['artblocks'].push(newBot)
} else {
const platform = this.cleanKey(
project.contract.name ?? 'Unknown contract'
)
this.platforms[platform] = this.platforms[platform] ?? []
this.platforms[platform].push(newBot)
}
}
// Set up contract aliases
CONTRACT_ALIASES.forEach((item) => {
const aliases = item.aliases
const named_contracts = item.named_contracts
const allPlatformProjects: ProjectBot[] = []
named_contracts.forEach((named_contract) => {
const platformName = this.cleanKey(named_contract)
if (this.platforms[platformName]) {
allPlatformProjects.push(...this.platforms[platformName])
}
})
aliases.forEach((alias) => {
this.platforms[alias] = this.platforms[alias] ?? []
this.platforms[alias].push(...allPlatformProjects)
})
})
} catch (err) {
console.error(`Error while initializing ArtIndexerBots\n${err}`)
}
}
private clearDictionaries() {
this.projects = {}
this.artists = {}
this.birthdays = {}
this.collections = {}
this.tags = {}
this.projectsById = {}
this.platforms = {}
this.flagship = {}
// Don't clear contracts, walletTokens, or sets as they are managed separately
}
// Please update HASHTAG_MESSAGE in smartBotResponse.ts if you add more options here
getMessageType(
key: string,
afterTheHash: string,
messageContent?: string
): MessageTypes {
if (key === '#?') {
return MessageTypes.RANDOM
} else if (key === 'all') {
return MessageTypes.RANDOM_ALL
} else if (key === 'upcoming') {
return MessageTypes.UPCOMING
} else if (messageContent?.startsWith('#recent')) {
return MessageTypes.RECENT
} else if (messageContent?.startsWith('#entry')) {
return MessageTypes.ENTRY
} else if (messageContent?.startsWith('#set')) {
return MessageTypes.SET
} else if (key === 'open') {
return MessageTypes.OPEN
} else if (isVerticalName(key)) {
return MessageTypes.COLLECTION
} else if (this.tags[key]) {
return MessageTypes.TAG
} else if (this.artists[key]) {
return MessageTypes.ARTIST
} else if (this.platforms[key]) {
return MessageTypes.PLATFORM
} else if (isWallet(afterTheHash?.split(' ')[0])) {
return MessageTypes.WALLET
} else if (this.projects[key]) {
return MessageTypes.PROJECT
}
return MessageTypes.UNKNOWN
}
async projectBotForMessage(
key: string,
afterTheHash: string
): Promise<ProjectBot | undefined> {
const messageType = this.getMessageType(key, afterTheHash)
switch (messageType) {
case MessageTypes.RANDOM:
if (Object.keys(this.flagship).length > 0) {
return this.getRandomizedProjectBot(Object.values(this.flagship))
}
return this.getRandomizedProjectBot(Object.values(this.projectsById))
case MessageTypes.RANDOM_ALL:
return this.getRandomizedProjectBot(Object.values(this.projectsById))
case MessageTypes.OPEN:
return await this.getRandomOpenProjectBot()
case MessageTypes.COLLECTION:
return this.getRandomizedProjectBot(
this.collections[getVerticalName(key)]
)
case MessageTypes.TAG:
return this.getRandomizedProjectBot(this.tags[key])
case MessageTypes.ARTIST:
return this.getRandomizedProjectBot(this.artists[key])
case MessageTypes.PLATFORM:
return this.getRandomizedProjectBot(this.platforms[key])
case MessageTypes.PROJECT:
if (this.flagship[key]) {
return this.flagship[key]
}
return this.projects[key]
case MessageTypes.WALLET:
case MessageTypes.RECENT:
case MessageTypes.UPCOMING:
case MessageTypes.UNKNOWN:
return undefined
}
}
async handleNumberMessage(msg: Message) {
const content = msg.content
if (!msg.channel.isSendable()) {
return
}
if (content.length <= 1) {
msg.channel.send(
`Invalid format, enter # followed by the piece number of interest.`
)
return
}
console.log('Handling message', content)
if (content.toLowerCase().startsWith('#floor')) {
msg.channel.send(
`The \`#floor\` command has changed to \`#entry\`. Please try using \`#entry\` instead!`
)
return
}
// Handle #entry commands for groupings
if (content.toLowerCase().startsWith('#entry')) {
try {
await this.handleEntryMessage(msg)
} catch (error) {
msg.channel.send(`Sorry, I had trouble understanding that: ${content}`)
console.error('Error handling #entry message', error)
return
}
return
}
// Handle #set commands for set collections
if (content.toLowerCase().startsWith('#set')) {
try {
await this.handleSetMessage(msg)
} catch (error) {
msg.channel.send(`Sorry, I had trouble understanding that: ${content}`)
console.error('Error handling #set message', error)
return
}
return
}
let afterTheHash = content
.substr(content.indexOf(' ') + 1)
.replace('?details', '')
let projectKey = this.toProjectKey(afterTheHash)
const messageType = this.getMessageType(
projectKey,
afterTheHash,
msg.content.toLowerCase()
)
let projectBot
// Wallet has to be handled separately as it is dealing with specific tokens not whole projects
if (messageType === MessageTypes.WALLET) {
const wallet = afterTheHash.split(' ')[0]
afterTheHash = afterTheHash.replace(wallet, '')
projectKey = this.toProjectKey(afterTheHash)
projectKey = projectKey === '' ? '#?' : projectKey
if (
this.getMessageType(projectKey, afterTheHash) === MessageTypes.UNKNOWN
) {
msg.channel.send(
`Sorry, I wasn't able to understand that: ${afterTheHash}`
)
return
}
let token
try {
token = await this.getRandomWalletToken(wallet, projectKey)
} catch (err) {
msg.channel.send(err.message)
return
}
msg.content = `#${token?.invocation}`
projectBot = this.projects[this.toProjectKey(token.project.name ?? '')]
} else if (messageType === MessageTypes.RECENT) {
let token = await this.getContractTokenForKey(afterTheHash)
if (
!token &&
(afterTheHash === msg.content ||
afterTheHash.replace(' ', '').length === 0)
) {
// use flagship contract
token = await getMostRecentMintedFlagshipToken()
} else if (!token) {
console.error('Bad value specified for recent', afterTheHash)
msg.channel.send('Sorry, I was not able to understand that.')
return
}
const projectId = token.project_id
projectBot = this.projectsById[projectId]
msg.content = `#${token?.invocation}`
} else if (messageType === MessageTypes.UPCOMING) {
try {
const upcomingProjectDetails = await getArtblocksNextUpcomingProject()
projectBot = this.projectsById[upcomingProjectDetails.id]
projectBot.handleUpcomingMessage(msg, upcomingProjectDetails)
return
} catch (error) {
console.warn(error)
}
} else {
projectBot = await this.projectBotForMessage(projectKey, afterTheHash)
}
if (!projectBot) {
console.log("Wasn't able to parse message", content)
return
}
if (
messageType === MessageTypes.ARTIST &&
triviaBot.isArtistActiveTriviaAnswer(projectBot?.artistName)
) {
triviaBot.tally(msg)
}
projectBot.handleNumberMessage(msg)
}
async handleNumberTweet(tweet: string): Promise<ProjectBotAndToken> {
let content = tweet
let afterTheHash = content.replace(/#(\?|\d+)/g, '').trim()
let key = this.toProjectKey(afterTheHash)
key = content === '#?' ? '#?' : key
const messageType = this.getMessageType(key, afterTheHash)
let projectBot
if (messageType === MessageTypes.WALLET) {
const walletMatch = afterTheHash.match(
/(0x[a-fA-F0-9]{40})|([a-zA-Z0-9.-]+\.eth)/g
)
if (!walletMatch) {
throw new Error(`Wasn't able to parse wallet from tweet ${content}`)
}
const wallet = walletMatch[0]
afterTheHash = afterTheHash.replace(wallet, '')
key = this.toProjectKey(afterTheHash)
key = key === '' ? '#?' : key
if (this.getMessageType(key, afterTheHash) === MessageTypes.UNKNOWN) {
throw new Error(`Invalid wallet tweet: ${afterTheHash}`)
}
const token = await this.getRandomWalletToken(wallet, key)
content = `#${token?.invocation}`
projectBot = this.projects[this.toProjectKey(token.project.name ?? '')]
} else {
projectBot = await this.projectBotForMessage(key, afterTheHash)
}
if (!projectBot) {
throw new Error(`Wasn't able to parse tweet ${content}`)
}
const tokenId = await projectBot.handleTweet(content)
return { projectBot, tokenId }
}
cleanKey(key: string): string {
let projectKey = deburr(key)
.toLowerCase()
.replace(/[^a-z0-9]/gi, '')
// just in case there's a project name with no alphanumerical characters
if (projectKey === '') {
projectKey = deburr(key).toLowerCase().replace(/\s+/g, '')
}
return projectKey
}
toProjectKey(projectName: string) {
let projectKey = this.cleanKey(projectName)
if (PROJECT_ALIASES[projectKey]) {
projectKey = this.cleanKey(PROJECT_ALIASES[projectKey])
}
return projectKey
}
getRandomizedProjectBot(projectBots: ProjectBot[]): ProjectBot | undefined {
let attempts = 0
while (attempts < 10) {
const projBot =
projectBots[Math.floor(Math.random() * projectBots.length)]
if (projBot && projBot.editionSize > 1 && projBot.projectActive) {
return projBot
}
attempts++
}
return undefined
}
async getContractTokenForKey(
key: string
): Promise<ProjectTokenDetailFragment | null> {
try {
const lowerCaseKey = key.toLowerCase()
let contracts: string[]
const namedContract = this.contracts[lowerCaseKey]
const alias = CONTRACT_ALIASES.filter((obj) =>
obj.aliases.includes(lowerCaseKey)
)
if (namedContract) {
contracts = [namedContract.address]
} else if (alias.length > 0) {
// aliases
contracts = alias[0].named_contracts.map(
(contract) => this.contracts[contract.toLowerCase()].address
)
} else {
// try it being just a contract address
contracts = [lowerCaseKey]
}
const token = await getMostRecentMintedTokenByContracts(contracts)
return token
} catch (e) {
console.error('Error in getContractTokenForKey', e)
return null
}
}
// This function takes a channel and sends a message containing a random
// token from a random open project
async getRandomOpenProjectBot(): Promise<ProjectBot> {
// NOTE: this fxn can't use the clean logic of the others bc it is dealing with Hasura query
let attempts = 0
while (attempts < 10) {
const openProjects = await getArtblocksOpenProjects()
const project =
openProjects[Math.floor(Math.random() * openProjects.length)]
const projBot = this.projects[this.toProjectKey(project.name ?? '')]
if (projBot && projBot.editionSize > 1 && projBot.projectActive) {
return projBot
}
attempts++
}
throw new Error("Couldn't find an open project")
}
getRandomizedWalletProjectBot(
tokens: TokenDetailFragment[],
conditional: (projectBot: ProjectBot) => boolean
): TokenDetailFragment | undefined {
const myTokens = []
for (let index = 0; index < tokens.length; index++) {
const token = tokens[index]
if (
conditional(this.projects[this.toProjectKey(token.project.name ?? '')])
) {
myTokens.push(token)
}
}
return myTokens[Math.floor(Math.random() * myTokens.length)]
}
// Sends a random token from this wallet's collection
async getRandomWalletToken(
wallet: string,
projectKey = ''
): Promise<TokenDetailFragment> {
console.log(
`Getting random token${
projectKey ? ` from ${projectKey}` : ''
} in wallet ${wallet}`
)
// Resolve ENS name if ends in .eth
if (wallet.toLowerCase().endsWith('.eth')) {
const ensName = wallet
wallet = await resolveEnsName(ensName)
if (!wallet || wallet === '') {
throw new Error(`Sorry, I wasn't able to resolve ENS name ${ensName}`)
}
}
wallet = wallet.toLowerCase()
let tokens = []
if (this.walletTokens[wallet]) {
tokens = this.walletTokens[wallet]
} else {
tokens = (await getAllTokensInWallet(wallet)) ?? []
this.walletTokens[wallet] = tokens
}
if (tokens.length === 0) {
throw new Error(
`Sorry, I wasn't able to find any Art Blocks tokens in that wallet: ${wallet}`
)
}
const messageType = this.getMessageType(projectKey, '')
let chosenToken: TokenDetailFragment | undefined
switch (messageType) {
case MessageTypes.ARTIST:
chosenToken = this.getRandomizedWalletProjectBot(
tokens,
(projectBot) => {
return this.toProjectKey(projectBot.artistName) === projectKey
}
)
break
case MessageTypes.COLLECTION:
chosenToken = this.getRandomizedWalletProjectBot(
tokens,
(projectBot) => {
return projectBot.collection?.toLowerCase() === projectKey
}
)
break
case MessageTypes.TAG:
chosenToken = this.getRandomizedWalletProjectBot(
tokens,
(projectBot) => {
return projectBot.tags?.includes(projectKey) ?? false
}
)
break
case MessageTypes.PROJECT:
chosenToken = this.getRandomizedWalletProjectBot(
tokens,
(projectBot) => {
return this.toProjectKey(projectBot.projectName) === projectKey
}
)
break
case MessageTypes.RANDOM:
chosenToken = tokens[Math.floor(Math.random() * tokens.length)]
break
default:
break
}
if (!chosenToken) {
throw new Error(
`Sorry! Wasn't able to find any tokens matching ${projectKey} in that wallet ${wallet}`
)
}
return chosenToken
}
async checkBirthdays(
channels: Collection<string, Channel>,
projectConfig: ProjectConfig,
artistChannel: boolean
) {
const now = new Date()
const [year, month, day] = now.toISOString().split('T')[0].split('-')
const sentMessages: { [id: string]: boolean } = {}
console.log(`${this.birthdays[`${month}-${day}`]?.length} birthdays today!`)
if (this.birthdays[`${month}-${day}`]) {
this.birthdays[`${month}-${day}`].forEach((projBot) => {
if (
projBot.startTime &&
projBot.startTime.getFullYear().toString() !== year &&
!sentMessages[projBot.id]
) {
projBot.sendBirthdayMessage(channels, projectConfig, artistChannel)
sentMessages[projBot.id] = true
}
})
}
}
askRandomTriviaQuestion() {
let attempts = 0
while (attempts < 10) {
const keys = Object.keys(this.flagship)
const projectKey = keys[Math.floor(Math.random() * keys.length)]
const projBot = this.flagship[projectKey]
if (
projBot &&
projBot.editionSize > 1 &&
projBot.projectActive &&
!triviaBot.alreadyAsked(projBot)
) {
triviaBot.askTriviaQuestion(projBot)
return
}
attempts++
}
}
getProjectsWithNamedMappings(): ProjectBot[] {
const projects = Object.values(this.projects).filter((projBot) => {
return projBot.namedHandler?.hasNamed()
})
return projects
}
checkMintedOut(projectId: string, invocation: string) {
const projectBot = this.projectsById[projectId]
const invocationNumber = parseInt(invocation)
if (
!projectBot ||
!projectBot.maxEditionSize ||
projectBot.maxEditionSize - 1 !== invocationNumber
) {
return
}
console.log(
`Sending minted out message for ${projectBot.projectName} with ${projectBot.maxEditionSize} tokens. Invocation: ${invocation}`
)
projectBot.sendMintedOutMessage()
}
/**
* Check if a project has the AB500 tag
* @param projectId The project ID to check
* @returns true if the project has the "ab500" tag, false otherwise
*/
isAB500(projectId: string): boolean {
const ab500Projects = this.tags['ab500']
if (!ab500Projects) {
return false
}
return ab500Projects.some((projectBot) => projectBot.id === projectId)
}
/**
* Handle #entry commands for both projects and groupings (tags and verticals)
*/
async handleEntryMessage(msg: Message) {
if (!msg.channel.isSendable()) {
return
}
const content = msg.content.trim()
const parts = content.split(' ')
if (parts.length < 2) {
msg.channel.send(
'Please specify a project or grouping. Format: `#entry [project/grouping]`\n' +
'Examples: `#entry Fidenza`, `#entry AB500`, `#entry Curated`, `#entry Curated Series 1`'
)
return
}
// Extract the target name (everything after "#entry")
const target = content.substring(6).trim() // Remove "#entry"
const targetKey = this.toProjectKey(target)
const messageType = this.getMessageType(targetKey, target)
let projectBot: ProjectBot | undefined
if (messageType === MessageTypes.PROJECT) {
projectBot = await this.projectBotForMessage(targetKey, target)
} else if (messageType === MessageTypes.COLLECTION) {
const vertical = getVerticalName(target.toLowerCase())
const entryProjects = await getEntryByVertical(vertical, 1)
if (entryProjects.length === 0) {
msg.channel.send(
`Sorry, I wasn't able to find any projects for sale with the vertical ${vertical}`
)
return
}
const projectKey = this.toProjectKey(entryProjects[0].name ?? '')
projectBot = await this.projectBotForMessage(
projectKey,
`#entry ${entryProjects[0].name}`
)
} else if (messageType === MessageTypes.TAG) {
const tag = target
const entryProjects = await getEntryByTag(tag.toLowerCase(), 1)
if (entryProjects.length === 0) {
msg.channel.send(
`Sorry, I wasn't able to find any projects for sale with the tag ${tag}`
)
return
}
const projectKey = this.toProjectKey(entryProjects[0].name ?? '')
projectBot = await this.projectBotForMessage(
projectKey,
`#entry ${entryProjects[0].name}`
)
}
if (!projectBot) {
msg.channel.send(
`Sorry, I wasn't able to find any projects for sale with the query ${target}`
)
return
}
await projectBot?.handleNumberMessage(msg)
return
}
/**
* Handle #set commands for set collections
*/
async handleSetMessage(msg: Message) {
if (!msg.channel.isSendable()) {
return
}
const content = msg.content.trim()
const parts = content.split(' ')
if (parts.length < 2) {
msg.channel.send(
'Please specify a set name. Format: `#set [set name]`\n' +
'Example: `#set Curated`'
)
return
}
// Helper function for smart price formatting
const formatPrice = (price: number): string => {
if (price < 0.01) {
// For very small prices, use 5-6 decimals to show meaningful precision
return price < 0.001 ? price.toFixed(6) : price.toFixed(5)
} else if (price >= 10) {
// For larger numbers, trim trailing zeros
const formatted = price.toFixed(4)
return formatted.replace(/\.?0+$/, '')
} else {
// Standard 4 decimals for most cases
return price.toFixed(4)
}
}
// Extract the set name (everything after "#set")
const setName = content.substring(4).trim() // Remove "#set"
const setKey = setName.toLowerCase()
// Check if the set exists and get the correct case
const actualSetName = this.sets[setKey]
if (!actualSetName) {
msg.channel.send(
`Sorry, I wasn't able to find a set named "${setName}". Make sure the set name is spelled correctly. Some examples of valid set names are: \`Curated Series 4\`, \`AB500\`, \`Explorations\`, etc.`
)
return
}
try {
// Get the set data with all its buckets using the correct case
const setData = await getSetByName(actualSetName)
if (!setData || !setData.set_buckets) {
msg.channel.send(
`Sorry, I had trouble retrieving data for the set "${setName}". Try again later!`
)
return
}
// Filter out buckets that don't have valid projects
const validBuckets = setData.set_buckets.filter(
(bucket) => bucket.project
)
// Calculate total entry price and collect all prices for statistics
let totalPrice = 0
const totalProjects = validBuckets.length
let totalProjectsWithListings = 0
const projectPrices: {
price: number
name: string
contractAddress: string
projectId: string
slug?: string
}[] = []
const projectsWithoutListings: {
name: string
contractAddress: string
projectId: string
slug?: string
}[] = []
for (const bucket of validBuckets) {
if (bucket.project) {
const projectName = bucket.project.name || 'Unknown Project'
const contractAddress = bucket.project.contract_address
const projectId = bucket.project.project_id
const slug = bucket.project.slug
if (bucket.project.lowest_listing) {
const price = Number(bucket.project.lowest_listing)
totalPrice += price
totalProjectsWithListings++
projectPrices.push({
price,
name: projectName,
contractAddress,
projectId,
slug,
})
} else {
// Project exists but has no listings
projectsWithoutListings.push({
name: projectName,
contractAddress,
projectId,
slug,
})
}
}
}
// Calculate price statistics
let cheapestProject = 0
let mostExpensiveProject = 0
let medianProject = 0
if (projectPrices.length > 0) {
// Sort prices to find min, max, and median
const sortedProjectPrices = [...projectPrices].sort(
(a, b) => a.price - b.price
)
cheapestProject = sortedProjectPrices[0].price
mostExpensiveProject =