Skip to content

Commit

Permalink
Merge branch 'master' of https://github.com/oldschoolgg/oldschoolbot
Browse files Browse the repository at this point in the history
…into fletch-sepulchre
  • Loading branch information
TastyPumPum committed Jul 13, 2024
2 parents ef31ca8 + dac3c91 commit 0312359
Show file tree
Hide file tree
Showing 51 changed files with 651 additions and 584 deletions.
5 changes: 4 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ BOT_TOKEN=PUT_YOUR_TOKEN_HERE
# You may need to change these:
ROBOCHIMP_DATABASE_URL=postgresql://postgres:postgres@localhost:5436/robochimp_test
DATABASE_URL=postgresql://postgres:postgres@localhost:5435/osb_test
#REDIS_PORT=6379 #OPTIONAL

# Optional
#REDIS_PORT=6379
#TESTING_SERVER_ID=123456789012345678

# Dont change these:
TZ="UTC"
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
},
"dependencies": {
"@napi-rs/canvas": "^0.1.53",
"@oldschoolgg/toolkit": "git+https://github.com/oldschoolgg/toolkit.git#e148e18bec1be9bbb82151dced9e3f83ea0d4e85",
"@oldschoolgg/toolkit": "git+https://github.com/oldschoolgg/toolkit.git#87450a60c73136601714c77092793d2f432b70b5",
"@prisma/client": "^5.16.1",
"@sapphire/snowflake": "^3.5.3",
"@sapphire/time-utilities": "^1.6.0",
Expand Down
20 changes: 7 additions & 13 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,8 @@ model User {
cached_networth_value BigInt?
username String? @db.VarChar(32)
geListings GEListing[]
bingo_participant BingoParticipant[]
bingo Bingo[]
Expand Down Expand Up @@ -583,14 +585,13 @@ model Minigame {
}

model CommandUsage {
id Int @id @default(autoincrement())
date DateTime @default(now()) @db.Timestamp(6)
id Int @id @default(autoincrement())
date DateTime @default(now()) @db.Timestamp(6)
user_id BigInt
command_name String @db.VarChar(32)
status command_usage_status @default(value: Unknown)
is_continue Boolean @default(false)
command_name String @db.VarChar(32)
is_continue Boolean @default(false)
flags Json?
inhibited Boolean? @default(false)
inhibited Boolean? @default(false)
is_mention_command Boolean @default(false)
Expand Down Expand Up @@ -854,13 +855,6 @@ model HistoricalData {
@@map("historical_data")
}

enum command_usage_status {
Unknown
Success
Error
Inhibited
}

enum activity_type_enum {
Agility
Cooking
Expand Down
4 changes: 0 additions & 4 deletions src/config.example.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,8 @@ import type { IDiscordSettings } from './lib/types';

export const production = false;
export const SENTRY_DSN: string | null = null;
export const CLIENT_SECRET = '';
export const DEV_SERVER_ID = '';
export const DISCORD_SETTINGS: Partial<IDiscordSettings> = {};
// Add or replace these with your Discord ID:
export const OWNER_IDS = ['157797566833098752'];
export const ADMIN_IDS = ['425134194436341760'];
export const MAXING_MESSAGE = 'Congratulations on maxing!';
// Discord server where admin commands will be allowed:
export const SupportServer = '940758552425955348';
19 changes: 11 additions & 8 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import type { TextChannel } from 'discord.js';
import { GatewayIntentBits, Options, Partials } from 'discord.js';
import { isObject } from 'e';

import { DEV_SERVER_ID, SENTRY_DSN, SupportServer } from './config';
import { SENTRY_DSN, SupportServer } from './config';
import { syncActivityCache } from './lib/Task';
import { BLACKLISTED_GUILDS, BLACKLISTED_USERS } from './lib/blacklists';
import { Channel, Events, META_CONSTANTS, gitHash, globalConfig } from './lib/constants';
Expand Down Expand Up @@ -71,7 +71,10 @@ const client = new OldSchoolBotClient({
maxSize: 200,
keepOverLimit: member => CACHED_ACTIVE_USER_IDS.has(member.user.id)
},
GuildEmojiManager: { maxSize: 1, keepOverLimit: i => [DEV_SERVER_ID, SupportServer].includes(i.guild.id) },
GuildEmojiManager: {
maxSize: 1,
keepOverLimit: i => [globalConfig.testingServerID, SupportServer].includes(i.guild.id)
},
GuildStickerManager: { maxSize: 0 },
PresenceManager: { maxSize: 0 },
VoiceStateManager: { maxSize: 0 },
Expand All @@ -92,7 +95,7 @@ const client = new OldSchoolBotClient({
});

export const mahojiClient = new MahojiClient({
developmentServerID: DEV_SERVER_ID,
developmentServerID: globalConfig.testingServerID,
applicationID: globalConfig.clientID,
commands: allCommands,
handlers: {
Expand Down Expand Up @@ -138,13 +141,14 @@ client.on('interactionCreate', async interaction => {
if (interaction.guildId && BLACKLISTED_GUILDS.has(interaction.guildId)) return;

if (!client.isReady()) {
if (interaction.isChatInputCommand()) {
if (interaction.isRepliable()) {
await interaction.reply({
content:
'Old School Bot is currently down for maintenance/updates, please try again in a couple minutes! Thank you <3',
ephemeral: true
});
}

return;
}

Expand Down Expand Up @@ -180,19 +184,18 @@ client.on('guildCreate', guild => {
}
});

client.on('shardDisconnect', ({ wasClean, code, reason }) => debugLog('Shard Disconnect', { wasClean, code, reason }));
client.on('shardError', err => debugLog('Shard Error', { error: err.message }));
client.once('ready', () => runTimedLoggedFn('OnStartup', async () => onStartup()));

async function main() {
if (process.env.TEST) return;
await Promise.all([
runTimedLoggedFn('Sync Active User IDs', syncActiveUserIDs),
runTimedLoggedFn('Sync Activity Cache', syncActivityCache)
runTimedLoggedFn('Sync Activity Cache', syncActivityCache),
runTimedLoggedFn('Startup Scripts', runStartupScripts)
]);
await runTimedLoggedFn('Startup Scripts', runStartupScripts);

await runTimedLoggedFn('Log In', () => client.login(globalConfig.botToken));
console.log(`Logged in as ${globalClient.user.username}`);
}

process.on('uncaughtException', err => {
Expand Down
17 changes: 10 additions & 7 deletions src/lib/DynamicButtons.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import type {
ThreadChannel
} from 'discord.js';
import { ButtonBuilder, ButtonStyle } from 'discord.js';
import { Time, noOp } from 'e';
import { Time, isFunction, noOp } from 'e';
import murmurhash from 'murmurhash';

import { BLACKLISTED_USERS } from './blacklists';
Expand All @@ -23,7 +23,7 @@ export class DynamicButtons {
buttons: {
name: string;
id: string;
fn: DynamicButtonFn;
fn?: DynamicButtonFn;
emoji: string | undefined;
cantBeBusy: boolean;
style?: ButtonStyle;
Expand Down Expand Up @@ -109,18 +109,21 @@ export class DynamicButtons {
for (const button of this.buttons) {
if (collectedInteraction.customId === button.id) {
if (minionIsBusy(collectedInteraction.user.id) && button.cantBeBusy) {
return collectedInteraction.reply({
await collectedInteraction.reply({
content: "Your action couldn't be performed, because your minion is busy.",
ephemeral: true
});
return null;
}
await button.fn({ message: this.message!, interaction: collectedInteraction });
return collectedInteraction;
if ('fn' in button && isFunction(button.fn)) {
await button.fn({ message: this.message!, interaction: collectedInteraction });
}
return button;
}
}
}

return collectedInteraction;
return null;
}

add({
Expand All @@ -131,7 +134,7 @@ export class DynamicButtons {
style
}: {
name: string;
fn: DynamicButtonFn;
fn?: DynamicButtonFn;
emoji?: string;
cantBeBusy?: boolean;
style?: ButtonStyle;
Expand Down
17 changes: 17 additions & 0 deletions src/lib/InteractionID.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
export const InteractionID = {
PaginatedMessage: {
FirstPage: 'PM_FIRST_PAGE',
PreviousPage: 'PM_PREVIOUS_PAGE',
NextPage: 'PM_NEXT_PAGE',
LastPage: 'PM_LAST_PAGE'
},
Slayer: {
AutoSlaySaved: 'SLAYER_AUTO_SLAY_SAVED',
AutoSlayDefault: 'SLAYER_AUTO_SLAY_DEFAULT',
AutoSlayEHP: 'SLAYER_AUTO_SLAY_EHP',
AutoSlayBoss: 'SLAYER_AUTO_SLAY_BOSS',
SkipTask: 'SLAYER_SKIP_TASK',
CancelTask: 'SLAYER_CANCEL_TASK',
BlockTask: 'SLAYER_BLOCK_TASK'
}
} as const;
30 changes: 15 additions & 15 deletions src/lib/MUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { userIsBusy } from './busyCounterCache';
import { ClueTiers } from './clues/clueTiers';
import type { CATier } from './combat_achievements/combatAchievements';
import { CombatAchievements } from './combat_achievements/combatAchievements';
import { BitField, Emoji, badges, projectiles, usernameCache } from './constants';
import { BitField, projectiles } from './constants';
import { bossCLItems } from './data/Collections';
import { allPetIDs } from './data/CollectionsExport';
import { getSimilarItems } from './data/similarItems';
Expand All @@ -41,11 +41,12 @@ import type { BankSortMethod } from './sorts';
import type { ChargeBank } from './structures/Bank';
import { Gear, defaultGear } from './structures/Gear';
import type { ItemBank, Skills } from './types';
import { addItemToBank, convertXPtoLVL, itemNameFromID } from './util';
import { addItemToBank, cacheUsername, convertXPtoLVL, itemNameFromID } from './util';
import { determineRunes } from './util/determineRunes';
import { getKCByName } from './util/getKCByName';
import getOSItem, { getItem } from './util/getOSItem';
import { logError } from './util/logError';
import { makeBadgeString } from './util/makeBadgeString';
import { minionIsBusy } from './util/minionIsBusy';
import { minionName } from './util/minionUtils';
import type { TransactItemsArgs } from './util/transactItemsFromBank';
Expand Down Expand Up @@ -94,13 +95,18 @@ export class MUserClass {
gear!: UserFullGearSetup;
skillsAsXP!: Required<Skills>;
skillsAsLevels!: Required<Skills>;
badgesString!: string;

constructor(user: User) {
this.user = user;
this.id = user.id;
this.updateProperties();

syncPerkTierOfUser(this);

if (this.user.username) {
cacheUsername(this.id, this.user.username, this.badgesString);
}
}

private updateProperties() {
Expand Down Expand Up @@ -130,6 +136,8 @@ export class MUserClass {

this.skillsAsXP = this.getSkills(false);
this.skillsAsLevels = this.getSkills(true);

this.badgesString = makeBadgeString(this.user.badges, this.isIronman);
}

countSkillsAtleast99() {
Expand Down Expand Up @@ -213,23 +221,15 @@ export class MUserClass {
}

get rawUsername() {
return globalClient.users.cache.get(this.id)?.username ?? usernameCache.get(this.id) ?? 'Unknown';
return globalClient.users.cache.get(this.id)?.username ?? this.user.username ?? 'Unknown';
}

get usernameOrMention() {
return usernameCache.get(this.id) ?? this.mention;
}

get badgeString() {
const rawBadges = this.user.badges.map(num => badges[num]);
if (this.isIronman) {
rawBadges.push(Emoji.Ironman);
}
return rawBadges.join(' ');
return this.user.username ?? this.mention;
}

get badgedUsername() {
return `${this.badgeString} ${this.usernameOrMention}`;
return `${this.badgesString} ${this.usernameOrMention}`;
}

toString() {
Expand Down Expand Up @@ -950,12 +950,12 @@ declare global {
var GlobalMUserClass: typeof MUserClass;
}

async function srcMUserFetch(userID: string) {
async function srcMUserFetch(userID: string, updates: Prisma.UserUpdateInput = {}) {
const user = await prisma.user.upsert({
create: {
id: userID
},
update: {},
update: updates,
where: {
id: userID
}
Expand Down
22 changes: 14 additions & 8 deletions src/lib/PaginatedMessage.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,24 @@
import { UserError } from '@oldschoolgg/toolkit';
import type { BaseMessageOptions, ComponentType, MessageEditOptions, TextChannel } from 'discord.js';
import { ActionRowBuilder, ButtonBuilder, ButtonStyle } from 'discord.js';
import { Time } from 'e';
import { Time, isFunction } from 'e';

import { InteractionID } from './InteractionID';
import type { PaginatedMessagePage } from './util';
import { logError } from './util/logError';
import { logError, logErrorForInteraction } from './util/logError';

const controlButtons: {
customId: string;
emoji: string;
run: (opts: { paginatedMessage: PaginatedMessage }) => unknown;
}[] = [
{
customId: 'pm-first-page',
customId: InteractionID.PaginatedMessage.FirstPage,
emoji: '⏪',
run: ({ paginatedMessage }) => (paginatedMessage.index = 0)
},
{
customId: 'pm-previous-page',
customId: InteractionID.PaginatedMessage.PreviousPage,
emoji: '◀️',
run: ({ paginatedMessage }) => {
if (paginatedMessage.index === 0) {
Expand All @@ -28,7 +29,7 @@ const controlButtons: {
}
},
{
customId: 'pm-next-page',
customId: InteractionID.PaginatedMessage.NextPage,
emoji: '▶️',
run: ({ paginatedMessage }) => {
if (paginatedMessage.index === paginatedMessage.totalPages - 1) {
Expand All @@ -39,7 +40,7 @@ const controlButtons: {
}
},
{
customId: 'pm-last-page',
customId: InteractionID.PaginatedMessage.LastPage,
emoji: '⏩',
run: ({ paginatedMessage }) => (paginatedMessage.index = paginatedMessage.totalPages - 1)
}
Expand Down Expand Up @@ -76,8 +77,9 @@ export class PaginatedMessage {
const rawPage = !Array.isArray(this.pages)
? await this.pages.generate({ currentPage: this.index })
: this.pages[this.index];

return {
...rawPage,
...(isFunction(rawPage) ? await rawPage() : rawPage),
components:
numberOfPages === 1
? []
Expand Down Expand Up @@ -121,7 +123,11 @@ export class PaginatedMessage {
});

if (previousIndex !== this.index) {
await interaction.update(await this.render());
try {
await interaction.update(await this.render());
} catch (err) {
logErrorForInteraction(err, interaction);
}
return;
}
}
Expand Down
1 change: 0 additions & 1 deletion src/lib/Task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,6 @@ export async function processPendingActivities() {
}
export async function syncActivityCache() {
const tasks = await prisma.activity.findMany({ where: { completed: false } });

minionActivityCache.clear();
for (const task of tasks) {
activitySync(task);
Expand Down
Loading

0 comments on commit 0312359

Please sign in to comment.