Skip to content

Commit

Permalink
V1.2.0
Browse files Browse the repository at this point in the history
  • Loading branch information
LucasB25 committed May 1, 2024
1 parent d718d22 commit e15450b
Show file tree
Hide file tree
Showing 8 changed files with 82 additions and 80 deletions.
2 changes: 1 addition & 1 deletion .eslintcache

Large diffs are not rendered by default.

13 changes: 7 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
{
"name": "midjourney",
"version": "1.1.0",
"version": "1.2.0",
"description": "A simple midjourney bot for discord",
"type": "module",
"main": "dist/index.js",
"scripts": {
"start": "npm run build && node dist/index.js",
"clean": "rm -rf dist",
"cleanw": "rmdir /s /q dist",
"cleanl": "rm -rf dist",
"build": "tsc --project tsconfig.json",
"lint": "eslint . --cache --ext .js,.jsx,.ts,.tsx",
"lint:fix": "eslint . --fix --cache --ext .js,.jsx,.ts,.tsx",
Expand All @@ -25,9 +26,9 @@
"@types/node": "^20.12.7",
"@types/signale": "^1.4.7",
"ts-node": "^10.9.2",
"@typescript-eslint/eslint-plugin": "^7.7.1",
"@typescript-eslint/parser": "^7.7.1",
"eslint": "^8.56.0",
"@typescript-eslint/eslint-plugin": "^7.8.0",
"@typescript-eslint/parser": "^7.8.0",
"eslint": "^8.57.0",
"eslint-plugin-import": "^2.29.1",
"eslint-plugin-unicorn": "^52.0.0",
"prettier": "^3.2.5"
Expand All @@ -49,7 +50,7 @@
"discord.js": "^14.14.1",
"replicate": "^0.29.1",
"signale": "^1.4.0",
"undici": "^6.14.0",
"undici": "^6.15.0",
"dotenv": "^16.4.5"
}
}
20 changes: 10 additions & 10 deletions src/events/client/InteractionCreate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,24 +15,24 @@ export default class InteractionCreate extends Event {
try {
await command.run(this.client, interaction);
} catch (error) {
if (
error.message ===
'Prediction failed: NSFW content detected. Try running it again, or try a different prompt.'
) {
if (error instanceof Error && error.message === 'Prediction failed: NSFW content detected. Try running it again, or try a different prompt.') {
await interaction[interaction.replied ? 'editReply' : 'reply']({
content: 'NSFW content detected. You can\' generate NSFW images!',
ephemeral: true,
});

return;
}
if (error instanceof Error) {
this.client.logger.error(error);

this.client.logger.error(error);

await interaction[interaction.replied ? 'editReply' : 'reply']({
content: 'There was an error while executing this command!',
ephemeral: true,
});
await interaction[interaction.replied ? 'editReply' : 'reply']({
content: 'There was an error while executing this command!',
ephemeral: true,
});
} else {
console.error('An unexpected error occurred:', error);
}
}
}
}
Expand Down
12 changes: 8 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@ const client = new Bot(clientOptions);

client.start(config.token);

process.on('unhandledRejection', (error: Error) => client.logger.error(error));
process.on('uncaughtException', (error: Error) => client.logger.error(error));
process.on('warning', (warning: Error) => client.logger.warn(warning));
process.on('exit', () => client.logger.warn('Process exited!'));
function setupEventListeners(): void {
process.on('unhandledRejection', (error: Error) => client.logger.error(error));
process.on('uncaughtException', (error: Error) => client.logger.error(error));
process.on('warning', (warning: Error) => client.logger.warn(warning));
process.on('exit', () => client.logger.warn('Process exited!'));
}

setupEventListeners();
37 changes: 16 additions & 21 deletions src/structures/Client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,31 +26,26 @@ export default class Bot extends Client {
public commands = new Collection<string, any>();
private data: RESTPostAPIChatInputApplicationCommandsJSONBody[] = [];
public replicate: Replicate | null = null;
public canvas: Canvas = new Canvas();
public canvas = new Canvas();

constructor(options: ClientOptions) {
super(options);
this.config = config;
}

public async start(token: string) {
this.logger.start('Starting bot...');
if (!config.replicateToken) {
this.logger.error('Replicate token is missing.');
return;
public async start(token: string): Promise<void> {
try {
this.logger.start('Starting bot...');
if (!config.replicateToken) throw new Error('Replicate token is missing.');
this.replicate = new Replicate({ auth: config.replicateToken });
if (!this.replicate) throw new Error('Failed to initialize Replicate.');
this.logger.info('Replicate is initialized.');
await this.loadCommands();
await this.loadEvents();
await this.login(token);
} catch (error) {
this.logger.error(error);
}
this.replicate = new Replicate({
auth: config.replicateToken,
});
if (!this.replicate) {
this.logger.error('Failed to initialize Replicate.');
return;
}
this.logger.info('Replicate is initialized.');

await this.loadCommands();
await this.loadEvents();
await this.login(token);
}

public embed(): EmbedBuilder {
Expand All @@ -66,7 +61,7 @@ export default class Bot extends Client {
for (const file of eventFiles) {
const eventFile = (await import(`../events/${event}/${file}`)).default;
const eventClass = new eventFile(this, file);
this.on(eventClass.name, (...args: any[]) => eventClass.run(...args));
this.on(eventClass.name, (...args: unknown[]) => eventClass.run(...args));
}
}
}
Expand Down Expand Up @@ -103,9 +98,9 @@ export default class Bot extends Client {
}

this.once('ready', async () => {
const applicationCommands = Routes.applicationCommands(this.config.clientId ?? '');
const applicationCommands = Routes.applicationCommands(config.clientId ?? '');
try {
const rest = new REST({ version: '10' }).setToken(this.config.token ?? '');
const rest = new REST({ version: '10' }).setToken(config.token ?? '');
await rest.put(applicationCommands, { body: this.data });
this.logger.info(`Successfully loaded slash commands!`);
} catch (error) {
Expand Down
26 changes: 9 additions & 17 deletions src/structures/Command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,49 +3,41 @@ import { ApplicationCommandOption, PermissionResolvable } from 'discord.js';
import { Bot } from './index.js';

interface CommandDescription {
content: string | null;
usage: string | null;
examples: string[] | null;
content: string;
usage: string;
examples: string[];
}

interface CommandOptions {
name: string;
nameLocalizations?: any;
nameLocalizations?: Record<string, string>;
description?: CommandDescription;
descriptionLocalizations?: any;
descriptionLocalizations?: Record<string, string>;
aliases?: string[];
cooldown?: number;
args?: boolean;
player?: {
voice: boolean;
dj: boolean;
active: boolean;
djPerm: string | null;
};
permissions?: {
dev: boolean;
client: string[] | PermissionResolvable;
user: string[] | PermissionResolvable;
};
slashCommand?: boolean;
options?: ApplicationCommandOption[];
category?: string;
}

export default class Command {
public client: Bot;
public name: string;
public nameLocalizations: any;
public nameLocalizations: Record<string, string>;
public description: CommandDescription;
public descriptionLocalizations: any;
public descriptionLocalizations: Record<string, string> | null;
public cooldown: number;
public permissions: {
dev: boolean;
client: string[] | PermissionResolvable;
user: string[] | PermissionResolvable;
};
public options: ApplicationCommandOption[];
public category: string | null;
public category: string;

constructor(client: Bot, options: CommandOptions) {
this.client = client;
Expand All @@ -67,7 +59,7 @@ export default class Command {
this.category = options.category || 'general';
}

public async run(client: Bot, message: any): Promise<any> {
public async run(_client: Bot, _message: any): Promise<any> {
return await Promise.resolve();
}
}
2 changes: 1 addition & 1 deletion src/structures/Event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export default class Event {
this.fileName = file.split('.')[0];
}

public async run(...args: any[]): Promise<void> {
public async run(..._args: unknown[]): Promise<void> {
return await Promise.resolve();
}
}
50 changes: 30 additions & 20 deletions src/structures/Logger.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,52 @@
import pkg from 'signale';
const { Signale } = pkg;

enum LogLevel {
INFO = 'info',
WARN = 'warn',
ERROR = 'error',
DEBUG = 'debug',
SUCCESS = 'success',
LOG = 'log',
PAUSE = 'pause',
START = 'start',
}

interface LoggerOptions {
disabled?: boolean;
interactive?: boolean;
logLevel?: string;
logLevel?: LogLevel;
scope?: string;
types?: {
info: { badge: string; color: string; label: string };
warn: { badge: string; color: string; label: string };
error: { badge: string; color: string; label: string };
debug: { badge: string; color: string; label: string };
success: { badge: string; color: string; label: string };
log: { badge: string; color: string; label: string };
pause: { badge: string; color: string; label: string };
start: { badge: string; color: string; label: string };
};
types?: Record<LogLevel, { badge: string; color: string; label: string }>;
}

const defaultOptions: LoggerOptions = {
disabled: false,
interactive: false,
logLevel: 'info',
logLevel: LogLevel.INFO,
scope: 'Midjourney',
types: {
info: { badge: 'ℹ', color: 'blue', label: 'info' },
warn: { badge: '⚠', color: 'yellow', label: 'warn' },
error: { badge: '✖', color: 'red', label: 'error' },
debug: { badge: '🐛', color: 'magenta', label: 'debug' },
success: { badge: '✔', color: 'green', label: 'success' },
log: { badge: '📝', color: 'white', label: 'log' },
pause: { badge: '⏸', color: 'yellow', label: 'pause' },
start: { badge: '▶', color: 'green', label: 'start' },
[LogLevel.INFO]: { badge: 'ℹ', color: 'blue', label: 'info' },
[LogLevel.WARN]: { badge: '⚠', color: 'yellow', label: 'warn' },
[LogLevel.ERROR]: { badge: '✖', color: 'red', label: 'error' },
[LogLevel.DEBUG]: { badge: '🐛', color: 'magenta', label: 'debug' },
[LogLevel.SUCCESS]: { badge: '✔', color: 'green', label: 'success' },
[LogLevel.LOG]: { badge: '📝', color: 'white', label: 'log' },
[LogLevel.PAUSE]: { badge: '⏸', color: 'yellow', label: 'pause' },
[LogLevel.START]: { badge: '▶', color: 'green', label: 'start' },
},
};

export default class Logger extends Signale {
constructor(options: LoggerOptions = {}) {
super({ ...defaultOptions, ...options });
this.validateOptions(options);
}

private validateOptions(options: LoggerOptions): void {
const validLogLevels = Object.values(LogLevel);
if (options.logLevel && !validLogLevels.includes(options.logLevel)) {
throw new Error(`Invalid log level: ${options.logLevel}`);
}
}
}

0 comments on commit e15450b

Please sign in to comment.