Skip to content

Commit

Permalink
Merge pull request #10 from tannnxr/dev
Browse files Browse the repository at this point in the history
Changed a shit ton, I honestly don't even know what to explain here.  look at commits.
  • Loading branch information
tannnxr authored May 30, 2024
2 parents b0f9c68 + 7dcdb94 commit 8b36332
Show file tree
Hide file tree
Showing 13 changed files with 168 additions and 47 deletions.
4 changes: 4 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"tabWidth": 2,
"useTabs": false
}
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,11 @@
## For Miss Sneak's Discord community.

**Please Read All These**



# Credits

[Discord.js](https://github.com/discordjs) for the [discord.js](https://github.com/discordjs/discord.js) library.

[Hidden Devs](https://github.com/HiddenDevs) for the [discord-prompts](https://github.com/HiddenDevs/discord-prompts.js) library we use.
31 changes: 31 additions & 0 deletions docs/Utils.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Shork Utilities

Shork makes use of several utility files to make some parts of development easier. They can be found in the ../src/utils/ directory.


## Channel (TS)

The `getChannel` function is used to get a text channel within the guild. It returns a Discord.js type of TextChannel.

```ts
getChannel(): TextChannel
```

## Commands (TS) (SINGLETON)

The `getCommandFiles` function is used to get all the command files within the /commands/ directory.
Due to the fact that it makes use of a redis cache this should only be used ONCE. All other needs to access command files should be done by grabbing from the Redis cache

```ts
async getCommandFiles()
```

## Files (TS)

The `getFilesRecursively` function should be used to get all the files of a specific directory. You shouldn't need to use this unless you're improving it or trying to get files from a directory (obviously)

TODO: Make this more efficient or something.

```ts
getFilesRecursively()
```
9 changes: 9 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"author": "",
"license": "ISC",
"dependencies": {
"@hidden-devs/discord-prompts.js": "^1.2.3",
"@types/node": "^20.12.7",
"bad-words-next": "^2.3.1",
"chalk": "^4.1.2",
Expand Down
52 changes: 46 additions & 6 deletions src/Shork.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,64 @@
import { Client, ClientOptions, PermissionFlagsBits } from "discord.js";
import { registerEvents } from "./events/register";
import { getCommandFiles } from "./utils/commands";
import { CommandReferenceType } from './registerCommands';

import { Logger, LogType } from "./utils/logging";

class Shork extends Client {
eventsRegistered: number;
eventsRegistered: string[];
commandsRegistered: CommandReferenceType[];
logger: Logger
constructor (options: ClientOptions) {
super(options);
this.eventsRegistered = 0;

this.registerEvents()
this.logger = new Logger(__filename, LogType.DEBUG)
this.eventsRegistered = [];
this.commandsRegistered = [];

this.registerEvents();
this.registerCommands();

return this
}

registerEvents() {
registerEvents(this)
async registerEvents() {
const eventsOr = await registerEvents(this)
if (eventsOr == false) {
this.logger.log(`Events unable to be registered for some reason.`, LogType.ERROR)
throw new Error("Fatal error: Events not registered.")
}

this.eventsRegistered = eventsOr as string[];

}

async registerCommands() {
const commandFiles = await getCommandFiles()

commandFiles.forEach(async (file) => {
this.logger.log(file)
const cmdFile = await import(file);
const importedCmd = cmdFile.default as CommandReferenceType;
console.log(importedCmd)
if (importedCmd.data !== null && importedCmd.execute !== null) {
this.commandsRegistered.push(importedCmd);
}
})

this.logger.log(`Commands Registered (${this.commandsRegistered.length})`);
}

getRegisteredEvents() {
return this.eventsRegistered;
return {events: this.eventsRegistered, count: this.eventsRegistered.length}
}

getRegisteredCommands() {
const commands: string[] = []
this.commandsRegistered.forEach((command) => {
commands.push(command.data.name)
})
return {commands: commands, count: commands.length}
}
}

Expand Down
46 changes: 28 additions & 18 deletions src/commands/moderation/warn.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,33 @@
import { ChatInputCommandInteraction, PermissionFlagsBits, SlashCommandBuilder, SlashCommandMentionableOption, SlashCommandStringOption } from "discord.js";
import {
ChatInputCommandInteraction,
PermissionFlagsBits,
SlashCommandBuilder,
SlashCommandMentionableOption,
SlashCommandStringOption,
} from "discord.js";
import { LogType, Logger } from "../../utils/logging";

export default {
data: new SlashCommandBuilder()
.setName('warn')
.setDescription('Warn a user.')
.setDefaultMemberPermissions(PermissionFlagsBits.ManageChannels)
.addMentionableOption(option =>
option.setName('user')
.setDescription('The user to warn.')
.setRequired(true))
.addStringOption(option =>
option.setName('reason')
.setDescription('The reason you\'re warning the user for')
.setRequired(false)),
data: new SlashCommandBuilder()
.setName("warn")
.setDescription("Warn a user.")
.setDefaultMemberPermissions(PermissionFlagsBits.ManageChannels)
.addMentionableOption((option) =>
option
.setName("user")
.setDescription("The user to warn.")
.setRequired(true)
)
.addStringOption((option) =>
option
.setName("reason")
.setDescription("The reason you're warning the user for")
.setRequired(false)
),

async execute(interaction: ChatInputCommandInteraction) {
const logger = new Logger(__filename, LogType.DEBUG)
async execute(interaction: ChatInputCommandInteraction) {
const logger = new Logger(__filename, LogType.DEBUG);

logger.log('warn command')
}
}
logger.log("warn command");
},
};
24 changes: 13 additions & 11 deletions src/events/interactions/interactionCreate.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
import { BaseInteraction, Events, InteractionType, TextChannel } from "discord.js";
import {
BaseInteraction,
Events,
InteractionType,
TextChannel,
} from "discord.js";
import { Shork } from "../../Shork";
import { getChannel } from "../../utils/channel";
import { shorkCache } from "../../db/cache";
import { CommandReferenceType } from "../../registerCommands";

import { getCommandFiles } from "../../utils/commands";

export default {
name: Events.InteractionCreate,
execute: async (interaction: BaseInteraction) => {
if (interaction.type == InteractionType.ApplicationCommand) {
const redisCmdFiles = await shorkCache.get('commandFiles')
if (!redisCmdFiles) {
getCommandFiles()
}

}
name: Events.InteractionCreate,
execute: async (interaction: BaseInteraction) => {
const client = interaction.client as Shork;
if (interaction.type == InteractionType.ApplicationCommand) {
}
}
},
};
14 changes: 7 additions & 7 deletions src/events/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { LogType, Logger } from "../utils/logging";

const logger = new Logger(__filename, LogType.DEBUG)

async function bindEvent(client: Client, eventPath: string): Promise<boolean> {
async function bindEvent(client: Shork, eventPath: string): Promise<boolean> {
let eventModule: ShorkEvent;

try {
Expand Down Expand Up @@ -42,23 +42,23 @@ async function getFilesRecursively(directory: string): Promise<string[]> {
return filePaths.flat();
}

export const registerEvents = async (client: Shork): Promise<boolean> => {
export const registerEvents = async (client: Shork): Promise<string[] | boolean> => {
logger.log("Registering Events...");
try {
const allFiles = await getFilesRecursively(__dirname);

const filtered = allFiles.filter(file => (file.endsWith('.js') || file.endsWith('.ts')) && !file.endsWith('.d.ts'));

let eventCount = 0;
let events = []
for (const file of filtered) {
const success = await bindEvent(client, file);
if (success) {
eventCount++;
events.push(file)
}
}
logger.log(`Registered Events (${eventCount})`, LogType.SUCCESS);
client.eventsRegistered = eventCount;
return true;
logger.log(`Registered Events (${events.length})`, LogType.SUCCESS);
client.eventsRegistered = events;
return events
} catch (err) {
logger.log("Error registering events:", LogType.ERROR);
return false;
Expand Down
4 changes: 2 additions & 2 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ dotenv.config();

const logger = new Logger(__filename, LogType.DEBUG);

export const rootDir = __dirname;

const SHORK = new Shork({
intents: [
GatewayIntentBits.Guilds,
Expand All @@ -21,6 +23,4 @@ process.on('exit', (errCode) => {
logger.log(`Process Exiting (${errCode})`, LogType.ERROR);
})

export const rootDir = __dirname;

SHORK.login(process.env.TOKEN);
4 changes: 2 additions & 2 deletions src/registerCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const foldersPath = path.join(__dirname, 'commands');
console.log(foldersPath)
const commandFolders = fs.readdirSync(foldersPath);

interface Command {
export interface CommandReferenceType {
data: any; // Adjust this to match the type of data
execute(interaction: ChatInputCommandInteraction): Promise<void>;
}
Expand All @@ -29,7 +29,7 @@ for (const folder of commandFolders) {

for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command: Command = require(filePath).default; // Use .default to import the default export
const command: CommandReferenceType = require(filePath).default; // Use .default to import the default export
if ('data' in command && 'execute' in command) {
commands.push(command.data.toJSON());
} else {
Expand Down
15 changes: 15 additions & 0 deletions src/tests/mocks/MockClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { ClientOptions, REST } from "discord.js";

/**
* A mock client used for testing, derived from the official Client class from discord.js
* @extends {null}
*/
class MockClient {
rest: REST;
constructor(options: ClientOptions) {
// Rest manager of the MockClient
this.rest = new REST()
}
}

export {MockClient}
3 changes: 2 additions & 1 deletion src/utils/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { getFilesRecursively } from "./files";
const logger = new Logger(__filename, LogType.DEBUG)

export async function getCommandFiles() {
console.log(rootDir, typeof rootDir)
const cmdDir = path.join(rootDir, 'commands')
if (!fs.existsSync(cmdDir)) {
logger.log(`Directory '${cmdDir}' does not exist. Failing.`, LogType.ERROR)
Expand All @@ -19,5 +20,5 @@ export async function getCommandFiles() {

const filteredCommands = commandFiles.filter(file => (file.endsWith('.js') || file.endsWith('.ts')) && !file.endsWith('.d.ts'));

shorkCache.set('commandFiles', JSON.stringify(filteredCommands))
return filteredCommands;
}

0 comments on commit 8b36332

Please sign in to comment.