Skip to content

Commit

Permalink
Various improvements/fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
gc committed Jul 15, 2024
1 parent bbdc2ec commit 96aae48
Show file tree
Hide file tree
Showing 12 changed files with 73 additions and 156 deletions.
4 changes: 2 additions & 2 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ services:
depends_on:
- db
environment:
ROBOCHIMP_DATABASE_URL: postgresql://postgres:postgres@db:5435/robochimp_integration_test?connection_limit=500&pool_timeout=0&schema=public
DATABASE_URL: postgresql://postgres:postgres@db:5435/osb_integration_test?connection_limit=500&pool_timeout=0&schema=public
ROBOCHIMP_DATABASE_URL: postgresql://postgres:postgres@db:5435/robochimp_integration_test?connection_limit=10&pool_timeout=0&schema=public
DATABASE_URL: postgresql://postgres:postgres@db:5435/osb_integration_test?connection_limit=10&pool_timeout=0&schema=public
WAIT_HOSTS: db:5435

volumes:
Expand Down
14 changes: 11 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@ import { isObject } from 'e';

import { SENTRY_DSN, SupportServer } from './config';
import { syncActivityCache } from './lib/Task';
import { BLACKLISTED_GUILDS, BLACKLISTED_USERS } from './lib/blacklists';
import { cacheBadges } from './lib/badges';
import { BLACKLISTED_GUILDS, BLACKLISTED_USERS, syncBlacklists } from './lib/blacklists';
import { Channel, Events, META_CONSTANTS, gitHash, globalConfig } from './lib/constants';
import { economyLog } from './lib/economyLogs';
import { onMessage } from './lib/events';
import { GrandExchange } from './lib/grandExchange';
import { modalInteractionHook } from './lib/modals';
import { runStartupScripts } from './lib/startupScripts';
import { OldSchoolBotClient } from './lib/structures/OldSchoolBotClient';
Expand All @@ -24,8 +26,9 @@ import { CACHED_ACTIVE_USER_IDS, syncActiveUserIDs } from './lib/util/cachedUser
import { interactionHook } from './lib/util/globalInteractions';
import { handleInteractionError } from './lib/util/interactionReply';
import { logError } from './lib/util/logError';
import { syncDisabledCommands } from './lib/util/syncDisabledCommands';
import { allCommands } from './mahoji/commands/allCommands';
import { onStartup } from './mahoji/lib/events';
import { onStartup, syncCustomPrices } from './mahoji/lib/events';
import { postCommand } from './mahoji/lib/postCommand';
import { preCommand } from './mahoji/lib/preCommand';
import { convertMahojiCommandToAbstractCommand } from './mahoji/lib/util';
Expand Down Expand Up @@ -193,7 +196,12 @@ async function main() {
await Promise.all([
runTimedLoggedFn('Sync Active User IDs', syncActiveUserIDs),
runTimedLoggedFn('Sync Activity Cache', syncActivityCache),
runTimedLoggedFn('Startup Scripts', runStartupScripts)
runTimedLoggedFn('Startup Scripts', runStartupScripts),
runTimedLoggedFn('Sync Disabled Commands', syncDisabledCommands),
runTimedLoggedFn('Sync Blacklist', syncBlacklists),
runTimedLoggedFn('Syncing prices', syncCustomPrices),
runTimedLoggedFn('Caching badges', cacheBadges),
runTimedLoggedFn('Init Grand Exchange', () => GrandExchange.init())
]);
await runTimedLoggedFn('Log In', () => client.login(globalConfig.botToken));
console.log(`Logged in as ${globalClient.user.username}`);
Expand Down
13 changes: 5 additions & 8 deletions src/lib/grandExchange.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,8 +260,6 @@ class GrandExchangeSingleton {
}
});

for (const tx of allActiveListingsInTimePeriod) sanityCheckTransaction(tx);

const item = getOSItem(geListing.item_id);
const buyLimit = this.getItemBuyLimit(item);
const totalSold = sumArr(allActiveListingsInTimePeriod.map(listing => listing.quantity_bought));
Expand Down Expand Up @@ -414,6 +412,7 @@ ${type} ${toKMB(quantity)} ${item.name} for ${toKMB(price)} each, for a total of
...makeTransactFromTableBankQueries({ bankToAdd: result.cost })
]);

sanityCheckListing(listing);
debugLog(`${user.id} created ${type} listing, removing ${result.cost}, adding it to the g.e bank.`);

return {
Expand Down Expand Up @@ -567,7 +566,7 @@ ${type} ${toKMB(quantity)} ${item.name} for ${toKMB(price)} each, for a total of
}
);

await prisma.$transaction([
const [newTx] = await prisma.$transaction([
prisma.gETransaction.create({
data: {
buy_listing_id: buyerListing.id,
Expand Down Expand Up @@ -617,6 +616,8 @@ ${type} ${toKMB(quantity)} ${item.name} for ${toKMB(price)} each, for a total of
...makeTransactFromTableBankQueries({ bankToRemove: bankToRemoveFromGeBank })
]);

sanityCheckTransaction(newTx);

debugLog(`Transaction completed, the new G.E bank is ${JSON.stringify((await this.fetchOwnedBank()).bank)}.`);

const buyerUser = await mUserFetch(buyerListing.user_id);
Expand Down Expand Up @@ -767,11 +768,7 @@ ${type} ${toKMB(quantity)} ${item.name} for ${toKMB(price)} each, for a total of
}

async extensiveVerification() {
await Promise.all([
prisma.gETransaction.findMany().then(txs => txs.map(tx => sanityCheckTransaction(tx))),
prisma.gEListing.findMany().then(listings => listings.map(listing => sanityCheckListing(listing))),
this.checkGECanFullFilAllListings()
]);
await this.checkGECanFullFilAllListings();
return true;
}

Expand Down
33 changes: 30 additions & 3 deletions src/lib/roboChimp.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { formatOrdinal } from '@oldschoolgg/toolkit';
import { PerkTier, formatOrdinal } from '@oldschoolgg/toolkit';
import type { TriviaQuestion, User } from '@prisma/robochimp';
import { calcWhatPercent, round, sumArr } from 'e';
import deepEqual from 'fast-deep-equal';

import { pick } from 'lodash';
import type { Bank } from 'oldschooljs';
import { BOT_TYPE, globalConfig, masteryKey } from './constants';
import { SupportServer } from '../config';
import { BOT_TYPE, BitField, Roles, globalConfig, masteryKey } from './constants';
import { getTotalCl } from './data/Collections';
import { calculateMastery } from './mastery';
import { MUserStats } from './structures/MUserStats';
Expand Down Expand Up @@ -163,5 +164,31 @@ function cacheRoboChimpUser(user: RobochimpUser) {
}

export function getPerkTierSync(user: string | MUser) {
return roboChimpCache.get(typeof user === 'string' ? user : user.id)?.perk_tier ?? 0;
const elligibleTiers = [];
if (typeof user !== 'string') {
if (
[BitField.isContributor, BitField.isModerator, BitField.IsWikiContributor].some(bit =>
user.bitfield.includes(bit)
)
) {
return PerkTier.Four;
}

if (
user.bitfield.includes(BitField.IsPatronTier1) ||
user.bitfield.includes(BitField.HasPermanentTierOne) ||
user.bitfield.includes(BitField.BothBotsMaxedFreeTierOnePerks)
) {
elligibleTiers.push(PerkTier.Two);
} else {
const guild = globalClient.guilds.cache.get(SupportServer);
const member = guild?.members.cache.get(user.id);
if (member && [Roles.Booster].some(roleID => member.roles.cache.has(roleID))) {
elligibleTiers.push(PerkTier.One);
}
}
}

elligibleTiers.push(roboChimpCache.get(typeof user === 'string' ? user : user.id)?.perk_tier ?? 0);
return Math.max(...elligibleTiers);
}
47 changes: 0 additions & 47 deletions src/lib/util/linkedAccountsUtil.ts

This file was deleted.

20 changes: 20 additions & 0 deletions src/lib/util/syncDisabledCommands.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { DISABLED_COMMANDS, globalConfig } from '../constants';

export async function syncDisabledCommands() {
const disabledCommands = await prisma.clientStorage.upsert({
where: {
id: globalConfig.clientID
},
select: { disabled_commands: true },
create: {
id: globalConfig.clientID
},
update: {}
});

if (disabledCommands.disabled_commands) {
for (const command of disabledCommands.disabled_commands) {
DISABLED_COMMANDS.add(command);
}
}
}
21 changes: 4 additions & 17 deletions src/mahoji/commands/minion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,12 @@ import type { AttackStyles } from '../../lib/minions/functions';
import { blowpipeCommand, blowpipeDarts } from '../../lib/minions/functions/blowpipeCommand';
import { degradeableItemsCommand } from '../../lib/minions/functions/degradeableItemsCommand';
import { allPossibleStyles, trainCommand } from '../../lib/minions/functions/trainCommand';
import { roboChimpUserFetch } from '../../lib/roboChimp';
import { roboChimpCache, roboChimpUserFetch } from '../../lib/roboChimp';
import { Minigames } from '../../lib/settings/minigames';
import Skills from '../../lib/skilling/skills';
import creatures from '../../lib/skilling/skills/hunter/creatures';
import { MUserStats } from '../../lib/structures/MUserStats';
import { convertLVLtoXP, getUsername, isValidNickname } from '../../lib/util';
import { convertLVLtoXP, isValidNickname } from '../../lib/util';
import { getKCByName } from '../../lib/util/getKCByName';
import getOSItem, { getItem } from '../../lib/util/getOSItem';
import { handleMahojiConfirmation } from '../../lib/util/handleMahojiConfirmation';
Expand Down Expand Up @@ -81,21 +81,10 @@ export async function getUserInfo(user: MUser) {
const task = minionActivityCache.get(user.id);
const taskText = task ? `${task.type}` : 'None';

const premiumDate = Number(user.user.premium_balance_expiry_date);
const premiumTier = user.user.premium_balance_tier;

const result = {
perkTier: user.perkTier(),
isBlacklisted: BLACKLISTED_USERS.has(user.id),
badges: user.badgesString,
mainAccount:
user.user.main_account !== null
? `${user.user.username ?? 'Unknown Username'}[${user.user.main_account}]`
: 'None',
ironmanAlts: user.user.ironman_alts.map(async id => `${await getUsername(id)}[${id}]`),
premiumBalance: `${premiumDate ? new Date(premiumDate).toLocaleString() : ''} ${
premiumTier ? `Tier ${premiumTier}` : ''
}`,
isIronman: user.isIronman,
bitfields,
currentTask: taskText,
Expand All @@ -107,16 +96,14 @@ export async function getUserInfo(user: MUser) {
2
);

const roboCache = await roboChimpCache.get(user.id);
return {
...result,
everythingString: `${user.badgedUsername}[${user.id}]
**Current Trip:** ${taskText}
**Perk Tier:** ${result.perkTier}
**Perk Tier:** ${roboCache?.perk_tier ?? 'None'}
**Blacklisted:** ${result.isBlacklisted}
**Badges:** ${result.badges}
**Main Account:** ${result.mainAccount}
**Ironman Alts:** ${result.ironmanAlts}
**Patron Balance:** ${result.premiumBalance}
**Ironman:** ${result.isIronman}
**Bitfields:** ${result.bitfields}
**Patreon Connected:** ${result.patreon}
Expand Down
15 changes: 0 additions & 15 deletions src/mahoji/commands/rp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ import getOSItem from '../../lib/util/getOSItem';
import { handleMahojiConfirmation } from '../../lib/util/handleMahojiConfirmation';
import { deferInteraction } from '../../lib/util/interactionReply';
import itemIsTradeable from '../../lib/util/itemIsTradeable';
import { syncLinkedAccounts } from '../../lib/util/linkedAccountsUtil';
import { makeBankImage } from '../../lib/util/makeBankImage';
import { migrateUser } from '../../lib/util/migrateUser';
import { parseBank } from '../../lib/util/parseStringBank';
Expand Down Expand Up @@ -694,20 +693,6 @@ ORDER BY item_id ASC;`);
return returnStringOrFile(`[${result.map(i => i.item_id).join(',')}]`);
}

if (options.action?.patreon_reset) {
const bitfieldsToRemove = [
BitField.IsPatronTier1,
BitField.IsPatronTier2,
BitField.IsPatronTier3,
BitField.IsPatronTier4,
BitField.IsPatronTier5,
BitField.IsPatronTier6
];
await prisma.$queryRaw`UPDATE users SET bitfield = bitfield - '{${bitfieldsToRemove.join(',')}'::int[];`;
await syncLinkedAccounts();
return 'Finished.';
}

if (options.player?.set_buy_date) {
const userToCheck = await mUserFetch(options.player.set_buy_date.user.user.id);
const res = SnowflakeUtil.deconstruct(options.player.set_buy_date.message_id);
Expand Down
8 changes: 0 additions & 8 deletions src/mahoji/lib/abstracted_commands/ironmanCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,13 +95,9 @@ After becoming an ironman:
const mUser = (await mUserFetch(user.id)).user;

type KeysThatArentReset =
| 'ironman_alts'
| 'main_account'
| 'bank_bg_hex'
| 'bank_sort_weightings'
| 'bank_sort_method'
| 'premium_balance_expiry_date'
| 'premium_balance_tier'
| 'minion_bought_date'
| 'id'
| 'pets'
Expand All @@ -127,15 +123,11 @@ After becoming an ironman:

const createOptions: Required<Pick<Prisma.UserCreateInput, KeysThatArentReset>> = {
id: user.id,
main_account: mUser.main_account,
ironman_alts: mUser.ironman_alts,
bank_bg_hex: mUser.bank_bg_hex,
bank_sort_method: mUser.bank_sort_method,
bank_sort_weightings: mUser.bank_sort_weightings as ItemBank,
minion_bought_date: mUser.minion_bought_date,
RSN: mUser.RSN,
premium_balance_expiry_date: mUser.premium_balance_expiry_date,
premium_balance_tier: mUser.premium_balance_tier,
pets: mUser.pets as ItemBank,
bitfield: bitFieldsToKeep.filter(i => user.bitfield.includes(i))
};
Expand Down
37 changes: 1 addition & 36 deletions src/mahoji/lib/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,12 @@ import type { ItemBank } from 'oldschooljs/dist/meta/types';

import { bulkUpdateCommands } from '@oldschoolgg/toolkit';
import { production } from '../../config';
import { cacheBadges } from '../../lib/badges';
import { syncBlacklists } from '../../lib/blacklists';
import { Channel, DISABLED_COMMANDS, META_CONSTANTS, globalConfig } from '../../lib/constants';
import { Channel, META_CONSTANTS, globalConfig } from '../../lib/constants';
import { initCrons } from '../../lib/crons';
import { GrandExchange } from '../../lib/grandExchange';

import { initTickers } from '../../lib/tickers';
import { runTimedLoggedFn } from '../../lib/util';
import { cacheCleanup } from '../../lib/util/cachedUserIDs';
import { mahojiClientSettingsFetch } from '../../lib/util/clientSettings';
import { syncLinkedAccounts } from '../../lib/util/linkedAccountsUtil';
import { sendToChannelID } from '../../lib/util/webhook';
import { CUSTOM_PRICE_CACHE } from '../commands/sell';

Expand All @@ -23,28 +18,8 @@ export async function syncCustomPrices() {
}
}

async function syncDisabledCommands() {
const disabledCommands = await prisma.clientStorage.upsert({
where: {
id: globalConfig.clientID
},
select: { disabled_commands: true },
create: {
id: globalConfig.clientID
},
update: {}
});

if (disabledCommands.disabled_commands) {
for (const command of disabledCommands.disabled_commands) {
DISABLED_COMMANDS.add(command);
}
}
}

export async function onStartup() {
globalClient.application.commands.fetch({ guildId: production ? undefined : globalConfig.testingServerID });

if (!production) {
console.log('Syncing commands locally...');
await bulkUpdateCommands({
Expand All @@ -54,18 +29,8 @@ export async function onStartup() {
});
}

runTimedLoggedFn('Sync Disabled Commands', syncDisabledCommands);

runTimedLoggedFn('Sync Blacklist', syncBlacklists);

runTimedLoggedFn('Syncing prices', syncCustomPrices);

runTimedLoggedFn('Caching badges', cacheBadges);
cacheCleanup();

runTimedLoggedFn('Sync Linked Accounts', syncLinkedAccounts);
runTimedLoggedFn('Init Grand Exchange', GrandExchange.init.bind(GrandExchange));

initCrons();
initTickers();

Expand Down
Loading

0 comments on commit 96aae48

Please sign in to comment.