Skip to content

Commit baa1f9a

Browse files
committed
🎨 clean up code and tests 🔨
- make MyHandler the handler of Bot - better linting config - remove getHandler as it is unnecessary - add minor tests for pricelist - add ptf-api mocks - ensure mocks and tests don't build into prod - allow failsafe to detect required options in Options object
1 parent 8fbb7f7 commit baa1f9a

25 files changed

+289
-73
lines changed

.eslintignore

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,2 @@
11
local
22
dist
3-
*.json
4-
jest.config.js

.eslintrc.js

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1+
// eslint-disable-next-line no-undef
12
module.exports = {
23
root: true,
34
parser: '@typescript-eslint/parser',
45
parserOptions: {
5-
project: './tsconfig.json'
6+
project: './tsconfig.eslint.json'
67
},
78
plugins: ['@typescript-eslint', 'eslint-plugin-tsdoc', 'prettier'],
89
extends: [
@@ -21,9 +22,12 @@ module.exports = {
2122
'@typescript-eslint/no-use-before-define': [0],
2223
'no-console': 'error',
2324
'tsdoc/syntax': 'error',
24-
'prettier/prettier': ['error', {
25-
'endOfLine': 'auto',
26-
'arrowParens': 'avoid'
27-
}]
25+
'prettier/prettier': [
26+
'error',
27+
{
28+
endOfLine: 'auto',
29+
arrowParens: 'avoid'
30+
}
31+
]
2832
}
2933
};

.gitattributes

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
# Auto detect text files and perform LF normalization
2-
*.txt text
2+
*.txt text

.prettierrc.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// eslint-disable-next-line no-undef
12
module.exports = {
23
semi: true,
34
trailingComma: 'none',

jest.config.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1+
// eslint-disable-next-line no-undef
12
module.exports = {
23
preset: 'ts-jest',
34
testEnvironment: 'node',
4-
testMatch: [ "**/__tests__/**/*.ts?(x)", "**/?(*.)+(spec|test).ts?(x)" ]
5-
};
6-
5+
testMatch: ['**/__tests__/**/*.ts?(x)', '**/?(*.)+(spec|test).ts?(x)']
6+
};

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@
99
"pretest": "npm run lint",
1010
"test": "jest",
1111
"prelint": "npm run eslint-check",
12-
"lint": "eslint \"src/**/*\"",
13-
"prettier": "prettier --check src/**/*",
12+
"lint": "eslint .",
13+
"prettier": "prettier --check src/**/* && prettier --check *.json",
1414
"eslint-check": "eslint --print-config src/app.ts | eslint-config-prettier-check",
1515
"update": "git stash && git checkout master && git pull && npm install && npm run build"
1616
},

src/classes/Bot.ts

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ import request from 'request-retry-dayjs';
1919

2020
import InventoryManager from './InventoryManager';
2121
import Pricelist, { Entry, EntryData } from './Pricelist';
22-
import Handler from './Handler';
2322
import Friends from './Friends';
2423
import Trades from './Trades';
2524
import Listings from './Listings/Listings';
@@ -61,7 +60,7 @@ export default class Bot {
6160

6261
readonly tf2gc: TF2GC;
6362

64-
readonly handler: Handler;
63+
readonly handler: MyHandler;
6564

6665
readonly inventoryManager: InventoryManager;
6766

@@ -197,10 +196,6 @@ export default class Bot {
197196
this.handlePriceChange = this.handler.onPriceChange.bind(this.handler);
198197
}
199198

200-
getHandler(): Handler {
201-
return this.handler;
202-
}
203-
204199
isAdmin(steamID: SteamID | string): boolean {
205200
const steamID64 = steamID.toString();
206201
return this.admins.some(adminSteamID => adminSteamID.toString() === steamID64);

src/classes/BotManager.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { getSchema } from '../lib/ptf-api';
1313
import EconItem from 'steam-tradeoffer-manager/lib/classes/EconItem.js';
1414
import CEconItem from 'steamcommunity/classes/CEconItem.js';
1515
import TradeOffer from 'steam-tradeoffer-manager/lib/classes/TradeOffer';
16+
import { camelCase } from 'change-case';
1617

1718
const REQUIRED_OPTS = ['STEAM_ACCOUNT_NAME', 'STEAM_PASSWORD', 'STEAM_SHARED_SECRET', 'STEAM_IDENTITY_SECRET'];
1819

@@ -94,7 +95,7 @@ export default class BotManager {
9495
start(options: Options): Promise<void> {
9596
return new Promise((resolve, reject) => {
9697
REQUIRED_OPTS.forEach(optName => {
97-
if (!process.env[optName]) {
98+
if (!process.env[optName] && !options[camelCase(optName)]) {
9899
return reject(new Error(`Missing required environment variable "${optName}"`));
99100
}
100101
});

src/classes/Carts/UserCart.ts

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ import { CurrencyObject } from '../../types/TeamFortress2';
1717
import Cart from './Cart';
1818
import Inventory from '../Inventory';
1919
import TF2Inventory from '../TF2Inventory';
20-
import MyHandler from '../MyHandler/MyHandler';
2120

2221
import log from '../../lib/logger';
2322
import { craftAll, uncraftAll, noiseMakerSKUs } from '../../lib/data';
@@ -45,7 +44,7 @@ export default class UserCart extends Cart {
4544

4645
// TODO: Check for dupes
4746

48-
const isDupedCheckEnabled = (this.bot.handler as MyHandler).hasDupeCheckEnabled();
47+
const isDupedCheckEnabled = this.bot.handler.hasDupeCheckEnabled();
4948
const keyPrice = this.bot.pricelist.getKeyPrice();
5049

5150
let theirItemsValue: number;
@@ -55,7 +54,7 @@ export default class UserCart extends Cart {
5554
theirItemsValue = this.getTheirCurrencies().toValue(keyPrice.metal);
5655
}
5756

58-
const minimumKeysDupeCheck = (this.bot.handler as MyHandler).getMinimumKeysDupeCheck() * keyPrice.toValue();
57+
const minimumKeysDupeCheck = this.bot.handler.getMinimumKeysDupeCheck() * keyPrice.toValue();
5958

6059
if (isDupedCheckEnabled && theirItemsValue > minimumKeysDupeCheck) {
6160
const assetidsToCheck = this.offer.data('_dupeCheck') as string[];
@@ -658,8 +657,7 @@ export default class UserCart extends Cart {
658657

659658
const addToDupeCheckList =
660659
item.effect !== null &&
661-
match.buy.toValue(keyPrice.metal) >
662-
(this.bot.handler as MyHandler).getMinimumKeysDupeCheck() * keyPrice.toValue();
660+
match.buy.toValue(keyPrice.metal) > this.bot.handler.getMinimumKeysDupeCheck() * keyPrice.toValue();
663661

664662
theirItemsCount += amount;
665663
let missing = amount;
@@ -728,7 +726,7 @@ export default class UserCart extends Cart {
728726
}
729727
}
730728

731-
const toMention = (this.bot.handler as MyHandler).getToMention();
729+
const toMention = this.bot.handler.getToMention();
732730
const highValueOur = await check.highValue(
733731
ourItemsToCheck,
734732
toMention.sheens,
@@ -1558,7 +1556,7 @@ export default class UserCart extends Cart {
15581556
// Figure out what pure to pick from the buyer, and if change is needed
15591557

15601558
const buyerCurrenciesWithAssetids = buyerInventory.getCurrencies();
1561-
const weapons = (this.bot.handler as MyHandler).getWeapons();
1559+
const weapons = this.bot.handler.getWeapons();
15621560

15631561
const pures = ['5021;6', '5002;6', '5001;6', '5000;6'];
15641562
const combine = pures.concat(weapons);
@@ -1666,8 +1664,7 @@ export default class UserCart extends Cart {
16661664

16671665
const addToDupeCheckList =
16681666
item.effect !== null &&
1669-
match.buy.toValue(keyPrice.metal) >
1670-
(this.bot.handler as MyHandler).getMinimumKeysDupeCheck() * keyPrice.toValue();
1667+
match.buy.toValue(keyPrice.metal) > this.bot.handler.getMinimumKeysDupeCheck() * keyPrice.toValue();
16711668

16721669
theirItemsCount += amount;
16731670
let missing = amount;
@@ -1736,7 +1733,7 @@ export default class UserCart extends Cart {
17361733
}
17371734
}
17381735

1739-
const toMention = (this.bot.handler as MyHandler).getToMention();
1736+
const toMention = this.bot.handler.getToMention();
17401737
const highValueOur = await check.highValue(
17411738
ourItemsToCheck,
17421739
toMention.sheens,

src/classes/Commands/Commands.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ import CommandParser from '../CommandParser';
1313
import Cart from '../Carts/Cart';
1414
import AdminCart from '../Carts/AdminCart';
1515
import UserCart from '../Carts/UserCart';
16-
import MyHandler from '../MyHandler/MyHandler';
1716
import CartQueue from '../Carts/CartQueue';
1817
import Autokeys from '../Autokeys/Autokeys';
1918

@@ -37,7 +36,7 @@ export default class Commands {
3736
}
3837

3938
get cartQueue(): CartQueue {
40-
return (this.bot.getHandler() as MyHandler).cartQueue;
39+
return this.bot.handler.cartQueue;
4140
}
4241

4342
processMessage(steamID: SteamID, message: string): void {
@@ -598,7 +597,7 @@ export default class Commands {
598597
}
599598

600599
private queueCommand(steamID: SteamID): void {
601-
const position = (this.bot.handler as MyHandler).cartQueue.getPosition(steamID);
600+
const position = this.bot.handler.cartQueue.getPosition(steamID);
602601

603602
if (position === -1) {
604603
this.bot.sendMessage(steamID, '❌ You are not in the queue.');

src/classes/Commands/functions/manager.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ import { utils } from './export';
1212
import Bot from '../../Bot';
1313
import CommandParser from '../../CommandParser';
1414

15-
import MyHandler from '../../MyHandler/MyHandler';
1615
import Autokeys from '../../Autokeys/Autokeys';
1716
import CartQueue from '../../Carts/CartQueue';
1817

@@ -556,7 +555,7 @@ export function updaterepoCommand(steamID: SteamID, bot: Bot, message: string):
556555
bot.client.setPersona(EPersonaState.Snooze);
557556

558557
// Set isUpdating status, so any command will not be processed
559-
(bot.handler as MyHandler).setIsUpdatingStatus(true);
558+
bot.handler.setIsUpdatingStatus(true);
560559

561560
// Stop polling offers
562561
bot.manager.pollInterval = -1;
@@ -596,7 +595,7 @@ async function generateAutokeysReply(steamID: SteamID, bot: Bot, auto: Autokeys)
596595
const keyPrices = bot.pricelist.getKeyPrices();
597596

598597
const userPure = autokeys.userPure;
599-
const status = (bot.handler as MyHandler).getAutokeysStatus();
598+
const status = bot.handler.getAutokeysStatus();
600599

601600
const keyBlMin = ` X`;
602601
const keyAbMax = ` X`;

src/classes/Commands/functions/options.ts

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ import { getOptionsPath, JsonOptions, removeCliOptions } from '../../Options';
88
import { deepMerge } from '../../../lib/tools/deep-merge';
99
import validator from '../../../lib/validator';
1010
import log from '../../../lib/logger';
11-
import MyHandler from '../../MyHandler/MyHandler';
1211

1312
export function optionsCommand(steamID: SteamID, bot: Bot): void {
1413
const liveOptions = deepMerge({}, bot.options) as JsonOptions;
@@ -170,33 +169,34 @@ export function updateOptionsCommand(steamID: SteamID, message: string, bot: Bot
170169
if (typeof knownParams.weaponsAsCurrency === 'object') {
171170
if (knownParams.weaponsAsCurrency.enable !== undefined) {
172171
if (knownParams.weaponsAsCurrency.enable === true) {
173-
(bot.handler as MyHandler).shuffleWeapons();
172+
bot.handler.shuffleWeapons();
174173
} else {
175-
(bot.handler as MyHandler).disableWeaponsAsCurrency();
174+
bot.handler.disableWeaponsAsCurrency();
176175
}
177176
}
178177

179178
if (knownParams.weaponsAsCurrency.withUncraft !== undefined) {
180-
(bot.handler as MyHandler).shuffleWeapons();
179+
bot.handler.shuffleWeapons();
181180
}
182181
}
183182

184183
if (knownParams.autobump !== undefined) {
185184
if (knownParams.autobump === true) {
186185
bot.listings.setupAutorelist();
187-
(bot.handler as MyHandler).disableAutoRefreshListings();
186+
bot.handler.disableAutoRefreshListings();
188187
} else {
189188
bot.listings.disableAutorelistOption();
190-
(bot.handler as MyHandler).enableAutoRefreshListings();
189+
bot.handler.enableAutoRefreshListings();
191190
}
192191
}
193192

194193
if (knownParams.autokeys !== undefined) {
194+
bot.handler.autokeys.check();
195195
if (knownParams.autokeys.enable !== undefined && !knownParams.autokeys.enable) {
196-
(bot.handler as MyHandler).autokeys.disable();
196+
bot.handler.autokeys.disable();
197197
}
198-
(bot.handler as MyHandler).autokeys.check();
199-
(bot.handler as MyHandler).updateAutokeysStatus();
198+
bot.handler.autokeys.check();
199+
bot.handler.updateAutokeysStatus();
200200
}
201201

202202
if (steamID) return bot.sendMessage(steamID, msg);

src/classes/Commands/functions/pricelistManager.ts

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,14 @@ import { Entry, EntryData, PricelistChangedSource } from '../../Pricelist';
1515

1616
import validator from '../../../lib/validator';
1717
import log from '../../../lib/logger';
18-
import MyHandler from '../../MyHandler/MyHandler';
1918

2019
// Pricelist manager
2120

2221
export function addCommand(steamID: SteamID, message: string, bot: Bot): void {
2322
message = removeLinkProtocol(message);
2423
const params = CommandParser.parseParams(CommandParser.removeCommand(message));
2524

26-
const isPremium = (bot.handler as MyHandler).getBotInfo().premium;
25+
const isPremium = bot.handler.getBotInfo().premium;
2726

2827
if (params.enabled === undefined) {
2928
params.enabled = true;
@@ -156,7 +155,7 @@ export async function updateCommand(steamID: SteamID, message: string, bot: Bot)
156155
message = removeLinkProtocol(message);
157156
const params = CommandParser.parseParams(CommandParser.removeCommand(message));
158157

159-
const isPremium = (bot.handler as MyHandler).getBotInfo().premium;
158+
const isPremium = bot.handler.getBotInfo().premium;
160159

161160
if (typeof params.intent === 'string') {
162161
const intent = ['buy', 'sell', 'bank'].indexOf(params.intent.toLowerCase());
@@ -398,7 +397,7 @@ export async function updateCommand(steamID: SteamID, message: string, bot: Bot)
398397
// FIXME: Make it so that it is not needed to remove all listings
399398

400399
if (params.autoprice !== true) {
401-
void bot.getHandler().onPricelist(newPricelist);
400+
await bot.handler.onPricelist(newPricelist);
402401
bot.sendMessage(steamID, '✅ Updated pricelist!');
403402
await bot.listings.redoListings();
404403
return;
@@ -701,7 +700,7 @@ export async function shuffleCommand(steamID: SteamID, bot: Bot): Promise<void>
701700
clearTimeout(executeTimeout);
702701
lastExecutedTime = dayjs().valueOf();
703702

704-
void bot.getHandler().onPricelist(shufflePricelist(pricelist));
703+
await bot.handler.onPricelist(shufflePricelist(pricelist));
705704
bot.sendMessage(steamID, '✅ Pricelist shuffled!');
706705
await bot.listings.redoListings();
707706

src/classes/Friends.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ import request from 'request-retry-dayjs';
88
import { UnknownDictionary } from '../types/common';
99

1010
import Bot from './Bot';
11-
import MyHandler from './MyHandler/MyHandler';
1211

1312
export default class Friends {
1413
private readonly bot: Bot;
@@ -77,7 +76,7 @@ export default class Friends {
7776
qs: {
7877
key: this.bot.manager.apiKey,
7978
steamid: (this.bot.client.steamID === null
80-
? (this.bot.handler as MyHandler).getBotSteamID()
79+
? this.bot.handler.getBotSteamID()
8180
: this.bot.client.steamID
8281
).getSteamID64()
8382
}
@@ -93,7 +92,7 @@ export default class Friends {
9392
const result = body.response;
9493
const level = result.player_level;
9594

96-
const friendToKeep = (this.bot.handler as MyHandler).getFriendToKeep();
95+
const friendToKeep = this.bot.handler.getFriendToKeep();
9796
const enableAddFriends = this.bot.options.enableAddFriends;
9897

9998
const base = 250;

0 commit comments

Comments
 (0)