-
-
Notifications
You must be signed in to change notification settings - Fork 79
/
MyHandler.ts
2663 lines (2261 loc) · 109 KB
/
MyHandler.ts
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
import SKU from '@tf2autobot/tf2-sku';
import request from 'request-retry-dayjs';
import { EClanRelationship, EFriendRelationship, EPersonaState, EResult } from 'steam-user';
import TradeOfferManager, {
TradeOffer,
PollData,
CustomError,
ItemsDict,
Meta,
WrongAboutOffer,
Prices,
Items
} from '@tf2autobot/tradeoffer-manager';
import pluralize from 'pluralize';
import SteamID from 'steamid';
import Currencies from '@tf2autobot/tf2-currencies';
import async from 'async';
import dayjs from 'dayjs';
import { UnknownDictionary } from '../../types/common';
import { accepted, declined, cancelled, acceptEscrow, invalid } from './offer/notify/export-notify';
import { processAccepted, updateListings, PriceCheckQueue } from './offer/accepted/exportAccepted';
import processDeclined from './offer/processDeclined';
import { sendReview } from './offer/review/export-review';
import { keepMetalSupply, craftDuplicateWeapons, craftClassWeapons } from './utils/export-utils';
import { BPTFGetUserInfo } from './interfaces';
import Handler from '../Handler';
import Bot from '../Bot';
import { Entry, PricesDataObject, PricesObject } from '../Pricelist';
import Commands from '../Commands/Commands';
import CartQueue from '../Carts/CartQueue';
import Inventory from '../Inventory';
import TF2Inventory from '../TF2Inventory';
import Autokeys from '../Autokeys/Autokeys';
import { Paths } from '../../resources/paths';
import log from '../../lib/logger';
import * as files from '../../lib/files';
import { exponentialBackoff } from '../../lib/helpers';
import { noiseMakers } from '../../lib/data';
import { sendAlert, sendStats } from '../../lib/DiscordWebhook/export';
import { summarize, uptime, getHighValueItems, testSKU } from '../../lib/tools/export';
import genPaths from '../../resources/paths';
import IPricer, { RequestCheckFn } from '../IPricer';
import Options, { OfferType } from '../Options';
import { Listing } from '@tf2autobot/bptf-listings';
const filterReasons = (reasons: string[]) => {
const filtered = new Set(reasons);
return [...filtered];
};
export default class MyHandler extends Handler {
readonly commands: Commands;
readonly autokeys: Autokeys;
readonly cartQueue: CartQueue;
private groupsStore: string[];
private requestCheck: RequestCheckFn;
private get opt(): Options {
return this.bot.options;
}
private get groups(): string[] {
if (this.groupsStore === undefined) {
const groups = this.opt.groups;
if (groups !== null && Array.isArray(groups)) {
groups.forEach(groupID64 => {
if (!new SteamID(groupID64).isValid()) {
throw new Error(`Invalid group SteamID64 "${groupID64}"`);
}
});
this.groupsStore = groups;
return groups;
}
} else {
return this.groupsStore;
}
}
private friendsToKeepStore: string[];
get friendsToKeep(): string[] {
if (this.friendsToKeepStore === undefined) {
const friendsToKeep = this.opt.keep.concat(this.bot.getAdmins.map(steamID => steamID.getSteamID64()));
if (friendsToKeep !== null && Array.isArray(friendsToKeep)) {
friendsToKeep.forEach(steamID64 => {
if (!new SteamID(steamID64).isValid()) {
throw new Error(`Invalid SteamID64 "${steamID64}"`);
}
});
this.friendsToKeepStore = friendsToKeep;
return friendsToKeep;
}
} else {
return this.friendsToKeepStore;
}
}
private get minimumScrap(): number {
return this.opt.crafting.metals.minScrap;
}
private get minimumReclaimed(): number {
return this.opt.crafting.metals.minRec;
}
private get combineThreshold(): number {
return this.opt.crafting.metals.threshold;
}
get dupeCheckEnabled(): boolean {
return this.opt.offerReceived.duped.enableCheck;
}
get minimumKeysDupeCheck(): number {
return this.opt.offerReceived.duped.minKeys;
}
private get isPriceUpdateWebhook(): boolean {
return this.opt.discordWebhook.priceUpdate.enable && this.opt.discordWebhook.priceUpdate.url !== '';
}
get isWeaponsAsCurrency(): { enable: boolean; withUncraft: boolean } {
return {
enable: this.opt.miscSettings.weaponsAsCurrency.enable,
withUncraft: this.opt.miscSettings.weaponsAsCurrency.withUncraft
};
}
private get invalidValueException(): number {
return Currencies.toScrap(this.opt.offerReceived.invalidValue.exceptionValue.valueInRef);
}
private hasInvalidValueException = false;
private get sendStatsEnabled(): boolean {
return this.opt.statistics.sendStats.enable;
}
private isTradingKeys = false;
get customGameName(): string {
const customGameName = this.opt.miscSettings.game.customName;
return customGameName ? customGameName : `TF2Autobot`;
}
private get isCraftingManual(): boolean {
return this.opt.crafting.manual;
}
private get isDeletingUntradableJunk(): boolean {
return this.opt.miscSettings.deleteUntradableJunk.enable;
}
private isPremium = false;
private botName = '';
private botAvatarURL = '';
private botSteamID: SteamID;
get getBotInfo(): BotInfo {
return { name: this.botName, avatarURL: this.botAvatarURL, steamID: this.botSteamID, premium: this.isPremium };
}
recentlySentMessage: UnknownDictionary<number> = {};
private sentSummary: UnknownDictionary<boolean> = {};
private resetSentSummaryTimeout: NodeJS.Timeout;
private paths: Paths;
private isUpdating = false;
set isUpdatingStatus(setStatus: boolean) {
this.isUpdating = setStatus;
}
private retryRequest: NodeJS.Timeout;
private poller: NodeJS.Timeout;
private refreshTimeout: NodeJS.Timeout;
private sendStatsInterval: NodeJS.Timeout;
private classWeaponsTimeout: NodeJS.Timeout;
private autoRefreshListingsInterval: NodeJS.Timeout;
private alreadyExecutedRefreshlist = false;
set isRecentlyExecuteRefreshlistCommand(setExecuted: boolean) {
this.alreadyExecutedRefreshlist = setExecuted;
}
private executedDelayTime = 30 * 60 * 1000;
set setRefreshlistExecutedDelay(delay: number) {
this.executedDelayTime = delay;
}
constructor(public bot: Bot, private priceSource: IPricer) {
super(bot);
this.commands = new Commands(bot, priceSource);
this.cartQueue = new CartQueue(bot);
this.autokeys = new Autokeys(bot);
this.paths = genPaths(this.opt.steamAccountName);
PriceCheckQueue.setBot(this.bot);
PriceCheckQueue.setRequestCheckFn(this.priceSource.requestCheck.bind(this.priceSource));
}
onRun(): Promise<OnRun> {
this.poller = setInterval(() => {
this.recentlySentMessage = {};
}, 1000);
return Promise.all([
files.readFile(this.paths.files.loginKey, false),
files.readFile(this.paths.files.pricelist, true),
files.readFile(this.paths.files.loginAttempts, true),
files.readFile(this.paths.files.pollData, true)
]).then(([loginKey, pricelist, loginAttempts, pollData]: [string, PricesDataObject, number[], PollData]) => {
return { loginKey, pricelist, loginAttempts, pollData };
});
}
onReady(): void {
log.info(
`TF2Autobot v${process.env.BOT_VERSION} is ready | ${pluralize(
'item',
this.bot.pricelist.getLength,
true
)} in pricelist | Listings cap: ${String(this.bot.listingManager.cap)} | Startup time: ${process
.uptime()
.toFixed(0)} s`
);
this.bot.client.gamesPlayed(this.opt.miscSettings.game.playOnlyTF2 ? 440 : [this.customGameName, 440]);
this.bot.client.setPersona(EPersonaState.Online);
this.botSteamID = this.bot.client.steamID;
// Get Premium info from backpack.tf
void this.getBPTFAccountInfo();
if (this.isCraftingManual === false) {
// Smelt / combine metal if needed
keepMetalSupply(this.bot, this.minimumScrap, this.minimumReclaimed, this.combineThreshold);
// Craft duplicate weapons
void craftDuplicateWeapons(this.bot);
// Craft class weapons
this.classWeaponsTimeout = setTimeout(() => {
// called after 5 seconds to craft metals and duplicated weapons first.
void craftClassWeapons(this.bot);
}, 5 * 1000);
}
if (this.isDeletingUntradableJunk) {
// Delete untradable junk
this.deleteUntradableJunk();
}
// Auto sell and buy keys if ref < minimum
this.autokeys.check();
// Sort the inventory after crafting / combining metal
this.sortInventory();
// Check friend requests that we got while offline
this.checkFriendRequests();
// Check group invites that we got while offline
this.checkGroupInvites();
// Initialize send stats
this.sendStats();
// Check for missing listings every 30 minutes, initiate setInterval 5 minutes after start
this.refreshTimeout = setTimeout(() => {
this.enableAutoRefreshListings();
}, 5 * 60 * 1000);
// Send notification to admin/Discord Webhook if there's any item failed to go through updateOldPrices
const failedToUpdateOldPrices = this.bot.pricelist.failedUpdateOldPrices;
if (failedToUpdateOldPrices.length > 0) {
const dw = this.opt.discordWebhook.sendAlert;
const isDwEnabled = dw.enable && dw.url.main !== '';
if (this.opt.sendAlert.enable && this.opt.sendAlert.failedToUpdateOldPrices) {
if (isDwEnabled) {
sendAlert('failedToUpdateOldPrices', this.bot, '', null, null, failedToUpdateOldPrices);
} else {
this.bot.messageAdmins(
`Failed to update old prices (probably because autoprice is set to true but item does not exist` +
` on the pricer source):\n\n${failedToUpdateOldPrices.join(
'\n'
)}\n\nAll items above has been temporarily disabled.`,
[]
);
}
}
this.bot.pricelist.resetFailedUpdateOldPrices = 0;
}
// Send notification to admin/Discord Webhook if there's any partially priced item got reset on updateOldPrices
const bulkUpdatedPartiallyPriced = this.bot.pricelist.partialPricedUpdateBulk;
const count = bulkUpdatedPartiallyPriced.length;
if (count > 0 && count < 20) {
// we send only if less than 20
const dw = this.opt.discordWebhook.sendAlert;
const isDwEnabled = dw.enable && (dw.url.main !== '' || dw.url.partialPriceUpdate !== '');
const msg = `All items below has been updated with partial price:\n\n• ${bulkUpdatedPartiallyPriced.join(
'\n --- '
)}`;
if (this.opt.sendAlert.enable && this.opt.sendAlert.partialPrice.onBulkUpdatePartialPriced) {
if (isDwEnabled) {
sendAlert('onBulkUpdatePartialPriced', this.bot, msg);
} else {
this.bot.messageAdmins(msg, []);
}
}
}
// Send notification to admin/Discord Webhook if there's any partially priced item got reset on updateOldPrices
const bulkResetPartiallyPriced = this.bot.pricelist.autoResetPartialPriceBulk;
if (bulkResetPartiallyPriced.length > 0) {
const dw = this.opt.discordWebhook.sendAlert;
const isDwEnabled = dw.enable && (dw.url.main !== '' || dw.url.partialPriceUpdate !== '');
const msg =
`All partially priced items below has been reset to use the current prices ` +
`because no longer in stock or exceed the threshold:\n\n• ${bulkResetPartiallyPriced
.map(sku => {
const name = this.bot.schema.getName(SKU.fromString(sku), this.opt.tradeSummary.showProperName);
return `${isDwEnabled ? `[${name}](https://autobot.tf/items/${sku})` : name} (${sku})`;
})
.join('\n• ')}`;
if (this.opt.sendAlert.enable && this.opt.sendAlert.partialPrice.onResetAfterThreshold) {
if (isDwEnabled) {
sendAlert('autoResetPartialPriceBulk', this.bot, msg);
} else {
this.bot.messageAdmins(msg, []);
}
}
}
}
onShutdown(): Promise<void> {
if (this.poller) {
clearInterval(this.poller);
}
if (this.refreshTimeout) {
clearInterval(this.refreshTimeout);
}
if (this.sendStatsInterval) {
clearInterval(this.sendStatsInterval);
}
if (this.autoRefreshListingsInterval) {
clearInterval(this.autoRefreshListingsInterval);
}
if (this.classWeaponsTimeout) {
clearTimeout(this.classWeaponsTimeout);
}
if (this.retryRequest) {
clearTimeout(this.retryRequest);
}
return new Promise(resolve => {
if (this.opt.autokeys.enable) {
log.debug('Disabling Autokeys and disabling key entry in the pricelist...');
this.autokeys
.disable(this.bot.pricelist.getKeyPrices)
.catch(() => {
log.warn('Unable to disable Mann Co. Supply Crate Key...');
})
.finally(() => {
if (this.bot.listingManager.ready !== true) {
// We have not set up the listing manager, don't try and remove listings
return resolve();
}
void this.bot.listings.removeAll().asCallback(err => {
if (err) {
log.warn('Failed to remove all listings on shutdown (autokeys was enabled): ', err);
}
resolve();
});
});
} else {
if (this.bot.listingManager.ready !== true) {
// We have not set up the listing manager, don't try and remove listings
return resolve();
}
void this.bot.listings.removeAll().asCallback(err => {
if (err) {
log.warn('Failed to remove all listings on shutdown: ', err);
}
resolve();
});
}
});
}
onLoggedOn(): void {
if (this.bot.isReady) {
this.bot.client.setPersona(EPersonaState.Online);
this.bot.client.gamesPlayed(this.opt.miscSettings.game.playOnlyTF2 ? 440 : [this.customGameName, 440]);
}
}
async onMessage(steamID: SteamID, message: string): Promise<void> {
if (!this.opt.commands.enable) {
if (!this.bot.isAdmin(steamID)) {
const custom = this.opt.commands.customDisableReply;
return this.bot.sendMessage(steamID, custom ? custom : '❌ Command function is disabled by the owner.');
}
}
if (this.isUpdating) {
return this.bot.sendMessage(steamID, '⚠️ The bot is updating, please wait until I am back online.');
}
const steamID64 = steamID.toString();
if (!this.bot.friends.isFriend(steamID64)) {
return;
}
const friend = this.bot.friends.getFriend(steamID64);
if (friend === null) {
log.info(`Message from ${steamID64}: ${message}`);
} else {
log.info(`Message from ${friend.player_name} (${steamID64}): ${message}`);
}
if (this.recentlySentMessage[steamID64] !== undefined && this.recentlySentMessage[steamID64] >= 1) {
return;
}
this.recentlySentMessage[steamID64] =
(this.recentlySentMessage[steamID64] === undefined ? 0 : this.recentlySentMessage[steamID64]) + 1;
await this.commands.processMessage(steamID, message);
}
onLoginKey(loginKey: string): void {
log.debug('New login key');
files.writeFile(this.paths.files.loginKey, loginKey, false).catch(err => {
log.warn('Failed to save login key: ', err);
});
}
onLoginError(err: CustomError): void {
if (err.eresult === EResult.InvalidPassword) {
files.deleteFile(this.paths.files.loginKey).catch(err => {
log.warn('Failed to delete login key: ', err);
});
}
}
onLoginAttempts(attempts: number[]): void {
files.writeFile(this.paths.files.loginAttempts, attempts, true).catch(err => {
log.warn('Failed to save login attempts: ', err);
});
}
onFriendRelationship(steamID: SteamID, relationship: number): void {
if (relationship === EFriendRelationship.Friend) {
this.onNewFriend(steamID);
this.checkFriendsCount(steamID);
} else if (relationship === EFriendRelationship.RequestRecipient) {
this.respondToFriendRequest(steamID);
}
}
onGroupRelationship(groupID: SteamID, relationship: number): void {
log.debug('Group relation changed', { steamID: groupID, relationship: relationship });
if (relationship === EClanRelationship.Invited) {
const join = this.groups.includes(groupID.getSteamID64());
log.info(`Got invited to group ${groupID.getSteamID64()}, ${join ? 'accepting...' : 'declining...'}`);
this.bot.client.respondToGroupInvite(groupID, join);
} else if (relationship === EClanRelationship.Member) {
log.info(`Joined group ${groupID.getSteamID64()}`);
}
}
onBptfAuth(auth: { apiKey: string; accessToken: string }): void {
const details = Object.assign({ private: true }, auth);
log.warn('Please add your backpack.tf API key and access token to your environment variables!', details);
}
enableAutoRefreshListings(): void {
// Automatically check for missing listings every 30 minutes
let pricelistLength = 0;
this.autoRefreshListingsInterval = setInterval(
() => {
const opt = this.opt;
const createListingsEnabled = opt.miscSettings.createListings.enable;
if (this.alreadyExecutedRefreshlist || !createListingsEnabled) {
log.debug(
`❌ ${
this.alreadyExecutedRefreshlist
? 'Just recently executed refreshlist command'
: 'miscSettings.createListings.enable is set to false'
}, will not run automatic check for missing listings.`
);
setTimeout(() => {
this.enableAutoRefreshListings();
}, this.executedDelayTime);
// reset to default
this.setRefreshlistExecutedDelay = 30 * 60 * 1000;
clearInterval(this.autoRefreshListingsInterval);
return;
}
pricelistLength = 0;
log.debug('Running automatic check for missing/mismatch listings...');
const listings: { [sku: string]: Listing[] } = {};
this.bot.listingManager.getListings(false, async err => {
if (err) {
log.warn('Error getting listings on auto-refresh listings operation:', err);
setTimeout(() => {
this.enableAutoRefreshListings();
}, 30 * 60 * 1000);
clearInterval(this.autoRefreshListingsInterval);
return;
}
const inventoryManager = this.bot.inventoryManager;
const inventory = inventoryManager.getInventory;
const isFilterCantAfford = opt.pricelist.filterCantAfford.enable;
this.bot.listingManager.listings.forEach(listing => {
let listingSKU = listing.getSKU();
if (listing.intent === 1) {
if (opt.normalize.painted.our && /;[p][0-9]+/.test(listingSKU)) {
listingSKU = listingSKU.replace(/;[p][0-9]+/, '');
}
if (opt.normalize.festivized.our && listingSKU.includes(';festive')) {
listingSKU = listingSKU.replace(';festive', '');
}
if (opt.normalize.strangeAsSecondQuality.our && listingSKU.includes(';strange')) {
listingSKU = listingSKU.replace(';strange', '');
}
} else {
if (/;[p][0-9]+/.test(listingSKU)) {
listingSKU = listingSKU.replace(/;[p][0-9]+/, '');
}
}
const match = this.bot.pricelist.getPrice(listingSKU);
if (isFilterCantAfford && listing.intent === 0 && match !== null) {
const canAffordToBuy = inventoryManager.isCanAffordToBuy(match.buy, inventory);
if (!canAffordToBuy) {
// Listing for buying exist but we can't afford to buy, remove.
log.debug(`Intent buy, removed because can't afford: ${match.sku}`);
listing.remove();
}
}
if (listing.intent === 1 && match !== null && !match.enabled) {
// Listings for selling exist, but the item is currently disabled, remove it.
log.debug(`Intent sell, removed because not selling: ${match.sku}`);
listing.remove();
}
listings[listingSKU] = (listings[listingSKU] ?? []).concat(listing);
});
const pricelist = Object.assign({}, this.bot.pricelist.getPrices);
const keyPrice = this.bot.pricelist.getKeyPrice.metal;
for (const sku in pricelist) {
if (!Object.prototype.hasOwnProperty.call(pricelist, sku)) {
continue;
}
const entry = pricelist[sku];
const _listings = listings[sku];
const amountCanBuy = inventoryManager.amountCanTrade(sku, true);
const amountAvailable = inventory.getAmount(sku, false, true);
if (_listings) {
_listings.forEach(listing => {
if (
_listings.length === 1 &&
listing.intent === 0 && // We only check if the only listing exist is buy order
entry.max > 1 &&
amountAvailable > 0 &&
amountAvailable > entry.min
) {
// here we only check if the bot already have that item
log.debug(`Missing sell order listings: ${sku}`);
} else if (
listing.intent === 0 &&
listing.currencies.toValue(keyPrice) !== entry.buy.toValue(keyPrice)
) {
// if intent is buy, we check if the buying price is not same
log.debug(`Buying price for ${sku} not updated`);
} else if (
listing.intent === 1 &&
listing.currencies.toValue(keyPrice) !== entry.sell.toValue(keyPrice)
) {
// if intent is sell, we check if the selling price is not same
log.debug(`Selling price for ${sku} not updated`);
} else {
delete pricelist[sku];
}
});
continue;
}
// listing not exist
if (!entry.enabled) {
delete pricelist[sku];
log.debug(`${sku} disabled, skipping...`);
continue;
}
if (
(amountCanBuy > 0 && inventoryManager.isCanAffordToBuy(entry.buy, inventory)) ||
amountAvailable > 0
) {
// if can amountCanBuy is more than 0 and isCanAffordToBuy is true OR amountAvailable is more than 0
// return this entry
log.debug(`Missing${isFilterCantAfford ? '/Re-adding can afford' : ' listings'}: ${sku}`);
} else {
delete pricelist[sku];
}
}
const skusToCheck = Object.keys(pricelist);
const pricelistCount = skusToCheck.length;
if (pricelistCount > 0) {
log.debug(
'Checking listings for ' +
pluralize('item', pricelistCount, true) +
` [${skusToCheck.join(', ')}]...`
);
await this.bot.listings.recursiveCheckPricelist(
skusToCheck,
pricelist,
true,
pricelistCount > 4000 ? 400 : 200,
true
);
log.debug('✅ Done checking ' + pluralize('item', pricelistCount, true));
} else {
log.debug('❌ Nothing to refresh.');
}
pricelistLength = pricelistCount;
});
},
// set check every 60 minutes if pricelist to check was more than 4000 items
(pricelistLength > 4000 ? 60 : 30) * 60 * 1000
);
}
disableAutoRefreshListings(): void {
if (this.isPremium) {
return;
}
clearInterval(this.autoRefreshListingsInterval);
}
sendStats(): void {
clearInterval(this.sendStatsInterval);
if (this.sendStatsEnabled) {
this.sendStatsInterval = setInterval(() => {
const opt = this.bot.options;
let times: string[];
if (opt.statistics.sendStats.time.length === 0) {
times = ['T05:59', 'T11:59', 'T17:59', 'T23:59'];
} else {
times = opt.statistics.sendStats.time;
}
const now = dayjs()
.tz(opt.timezone ? opt.timezone : 'UTC')
.format();
if (times.some(time => now.includes(time))) {
if (opt.discordWebhook.sendStats.enable && opt.discordWebhook.sendStats.url !== '') {
void sendStats(this.bot);
} else {
this.bot.getAdmins.forEach(admin => {
this.commands.useStatsCommand(admin);
});
}
}
}, 60 * 1000);
}
}
disableSendStats(): void {
clearInterval(this.sendStatsInterval);
}
async onNewTradeOffer(offer: TradeOffer): Promise<null | OnNewTradeOffer> {
offer.log('info', 'is being processed...');
// Allow sending notifications
offer.data('notify', true);
// If crafting class weapons still waiting, cancel it.
clearTimeout(this.classWeaponsTimeout);
const opt = this.opt;
const isAdmin = this.bot.isAdmin(offer.partner);
const items = {
our: Inventory.fromItems(
this.bot.client.steamID === null ? this.botSteamID : this.bot.client.steamID,
offer.itemsToGive,
this.bot.manager,
this.bot.schema,
opt,
this.bot.effects,
this.bot.paints,
this.bot.strangeParts,
'our'
).getItems,
their: Inventory.fromItems(
offer.partner,
offer.itemsToReceive,
this.bot.manager,
this.bot.schema,
opt,
this.bot.effects,
this.bot.paints,
this.bot.strangeParts,
isAdmin ? 'admin' : 'their'
).getItems
};
const exchange = {
contains: { items: false, metal: false, keys: false },
our: { value: 0, keys: 0, scrap: 0, contains: { items: false, metal: false, keys: false } },
their: { value: 0, keys: 0, scrap: 0, contains: { items: false, metal: false, keys: false } }
};
const itemsDict: ItemsDict = { our: {}, their: {} };
const getHighValue: GetHighValue = {
our: {
items: {},
isMention: false
},
their: {
items: {},
isMention: false
}
};
let isDuelingNotFullUses = false;
let isNoiseMakerNotFullUses = false;
const noiseMakerNotFullSKUs: string[] = [];
let hasNonTF2Items = false;
const states = [false, true];
for (let i = 0; i < states.length; i++) {
const buying = states[i];
const which = buying ? 'their' : 'our';
for (const sku in items[which]) {
if (!Object.prototype.hasOwnProperty.call(items[which], sku)) {
continue;
}
if (!testSKU(sku)) {
// Offer contains an item that is not from TF2
hasNonTF2Items = true;
}
if (sku === '5000;6') {
exchange.contains.metal = true;
exchange[which].contains.metal = true;
} else if (sku === '5001;6') {
exchange.contains.metal = true;
exchange[which].contains.metal = true;
} else if (sku === '5002;6') {
exchange.contains.metal = true;
exchange[which].contains.metal = true;
} else if (sku === '5021;6') {
exchange.contains.keys = true;
exchange[which].contains.keys = true;
} else {
exchange.contains.items = true;
exchange[which].contains.items = true;
}
// assign amount for sku
itemsDict[which][sku] = items[which][sku].length;
// Get High-value items
items[which][sku].forEach(item => {
if (item.hv !== undefined) {
// If hv exist, get the high value and assign into items
getHighValue[which].items[sku] = item.hv;
Object.keys(item.hv).forEach(attachment => {
if (item.hv[attachment] !== undefined) {
for (const pSku in item.hv[attachment]) {
if (!Object.prototype.hasOwnProperty.call(item.hv[attachment], pSku)) {
continue;
}
if (item.hv[attachment as 's' | 'sp' | 'ks' | 'ke' | 'p'][pSku] === true) {
getHighValue[which].isMention = true;
}
}
}
});
} else if (item.isFullUses !== undefined) {
getHighValue[which].items[sku] = { isFull: item.isFullUses };
if (which === 'their') {
// Only check for their side
if (sku === '241;6' && item.isFullUses === false) {
isDuelingNotFullUses = true;
} else if (noiseMakers.has(sku) && item.isFullUses === false) {
isNoiseMakerNotFullUses = true;
noiseMakerNotFullSKUs.push(sku);
}
}
}
});
}
}
offer.data('dict', itemsDict);
// Always check if trade partner is taking higher value items (such as spelled or strange parts) that are not in our pricelist
const highValueMeta = {
items: {
our: getHighValue.our.items,
their: getHighValue.their.items
},
isMention: {
our: getHighValue.our.isMention,
their: getHighValue.their.isMention
}
};
const isContainsHighValue =
Object.keys(getHighValue.our.items).length > 0 || Object.keys(getHighValue.their.items).length > 0;
// Check if the offer is from an admin
if (isAdmin) {
offer.log(
'trade',
`is from an admin, accepting. Summary:\n${JSON.stringify(
summarize(offer, this.bot, 'summary-accepting', false),
null,
4
)}`
);
return {
action: 'accept',
reason: 'ADMIN',
meta: isContainsHighValue ? { highValue: highValueMeta } : undefined
};
}
const itemsToGiveCount = offer.itemsToGive.length;
const itemsToReceiveCount = offer.itemsToReceive.length;
// check if the trade is valid
const isCannotProceedProcessingOffer = itemsToGiveCount === 0 && itemsToReceiveCount === 0;
if (isCannotProceedProcessingOffer) {
log.warn('isCannotProceedProcessingOffer', {
status: isCannotProceedProcessingOffer,
offerData: offer
});
// Both itemsToGive and itemsToReceive are an empty array, abort.
this.bot.sendMessage(
offer.partner,
`❌ Looks like there was some issue with Steam getting your offer data.` +
` I will retry to get the offer data now.` +
` My owner has been informed, and they might manually act on your offer later.`
);
const optDw = opt.discordWebhook;
if (opt.sendAlert.enable && opt.sendAlert.unableToProcessOffer) {
if (optDw.sendAlert.enable && optDw.sendAlert.url.main !== '') {
sendAlert('failed-processing-offer', this.bot, null, null, null, [
offer.partner.getSteamID64(),
offer.id
]);
} else {
this.bot.messageAdmins(
'',
`Unable to process offer #${offer.id} with ${offer.partner.getSteamID64()}.` +
' The offer data received was broken because our side and their side are both empty.' +
`\nPlease manually check the offer (login as me): https://steamcommunity.com/tradeoffer/${offer.id}/` +
`\nSend "!faccept ${offer.id}" to force accept, or "!fdecline ${offer.id}" to decline.`,
[]
);
}
}
// Abort processing the offer.
return;
}
// A list of things that is wrong about the offer and other information
const wrongAboutOffer: WrongAboutOffer[] = [];
let checkBannedFailed = false;
offer.log('info', 'checking escrow...');
try {
const hasEscrow = await this.bot.checkEscrow(offer);
if (hasEscrow) {
offer.log('info', 'would be held if accepted, declining...');
return {
action: 'decline',
reason: 'ESCROW',
meta: isContainsHighValue ? { highValue: highValueMeta } : undefined
};
}
} catch (err) {
wrongAboutOffer.push({
reason: '⬜_ESCROW_CHECK_FAILED'
});
log.warn('Failed to check escrow: ', err);
}
offer.log('info', 'checking bans...');
try {
const isBanned = await this.bot.checkBanned(offer.partner.getSteamID64());
if (isBanned.isBanned) {
offer.log('info', 'partner is banned in one or more communities, declining...');
this.bot.client.blockUser(offer.partner, err => {
if (err) {