Skip to content
This repository has been archived by the owner on Jan 26, 2024. It is now read-only.

Commit

Permalink
Updated code-quality | v1.0.4-beta
Browse files Browse the repository at this point in the history
  • Loading branch information
CrawlTheDev committed Jun 5, 2021
1 parent 36e9316 commit 9e2172d
Show file tree
Hide file tree
Showing 10 changed files with 148 additions and 92 deletions.
File renamed without changes.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@pbot-plus/bot",
"version": "1.0.3-beta",
"version": "1.0.4-beta",
"description": "A multi-purpose Discord bot with Typescript",
"main": "src/main.ts",
"scripts": {
Expand Down
78 changes: 42 additions & 36 deletions src/bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ export class PbotPlus {
await this.registerProviders();
this.registerCommands();
this.registerListeners();

await this.bot.login(this.config.client.token);
} catch (err) {
this.logger.error('Failed while initializing to the bot', err);
Expand All @@ -55,41 +54,53 @@ export class PbotPlus {
* Register listeners
*/
private registerListeners(): void {
// On message
this.bot.on(Constants.Events.MESSAGE_CREATE, (message: Message) =>
this.onMessage(message)
);

// On ready
this.bot.on(Constants.Events.CLIENT_READY, () => this.onReady());

// On guild create
this.bot.on(Constants.Events.GUILD_CREATE, (guild: Guild) =>
this.onGuildCreate(guild)
);
try {
// On message
this.bot.on(Constants.Events.MESSAGE_CREATE, (message: Message) =>
this.onMessage(message)
);

// On ready
this.bot.on(Constants.Events.CLIENT_READY, () => this.onReady());

// On guild create
this.bot.on(Constants.Events.GUILD_CREATE, (guild: Guild) =>
this.onGuildCreate(guild)
);
} catch (error) {
this.logger.error('Failed while registering listeners for bot', error);
}
}

/**
* Register providers
*/
private async registerProviders(): Promise<void> {
const database = new DatabaseProvider({
useNewUrlParser: true,
useUnifiedTopology: true
});
try {
const database = new DatabaseProvider(this, {
useNewUrlParser: true,
useUnifiedTopology: true
});

await database.initialize();
this.database = database;
await database.initialize();
this.database = database;
} catch (error) {
this.logger.error('Failed while registering providers', error);
}
}

/**
* Register commands
*/
private registerCommands(): void {
const commandService = new CommandService();
try {
const commandService = new CommandService(this);

commandService.initialize();
this.commands = commandService;
commandService.initialize();
this.commands = commandService;
} catch (error) {
this.logger.error('Failed while registering commands', error);
}
}

/**
Expand All @@ -99,14 +110,8 @@ export class PbotPlus {
private async onMessage(message: Message): Promise<void> {
if (message.author.bot ?? !message.guild?.member) return;

// const developingErrorEmbed = new MessageEmbed({
// color: this.config.color.error,
// description:
// 'I am currently under development so only my developers can use my commands'
// });

const commandPrefix =
(await GuildModel.findById(message.guild.id))?.main.prefix ||
(await this.database.findGuildById(message.guild.id))?.main.prefix ??
this.config.client.defaultPrefix;

if (message.content.match(new RegExp(`^<@!?${this.bot.user?.id}>( |)$`))) {
Expand All @@ -116,7 +121,7 @@ export class PbotPlus {
});
message.channel.send(PrefixEmbed);
} else if (message.content.startsWith(commandPrefix)) {
await this.commands.run(this, message);
await this.commands.run(message);
}
}

Expand All @@ -126,15 +131,14 @@ export class PbotPlus {
*/
private async onGuildCreate(guild: Guild): Promise<void> {
try {
const savedGuild = await GuildModel.findById(guild.id);
const savedGuild = await this.database.findGuildById(guild.id);

if (savedGuild) {
this.logger.warn(
`Guild with the id ${guild.id} is already in database`
);
this.logger.warn(`Guild with id ${guild.id} is already in database`);
} else {
const newGuild = new GuildModel({ _id: guild.id });
await newGuild.save();
this.logger.info(`Guild with the id ${guild.id} is saved to database`);
this.logger.info(`Guild with id ${guild.id} is saved to database`);
}
} catch (error) {
this.logger.error('Failed while saving new guild to database', error);
Expand All @@ -145,7 +149,9 @@ export class PbotPlus {
* On ready
*/
private async onReady(): Promise<void> {
await this.database.fetchNewGuilds(this.bot);
if (this.config.client.fetchNewGuilds) {
await this.database.fetchNewGuilds();
}

this.logger.info(`Signed in as ${this.bot.user?.tag}`);
this.bot.setPresence(
Expand Down
35 changes: 35 additions & 0 deletions src/commands/admin/change-prefix.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { ICommand, CommandContext } from '..';

export default class ChangePrefixCommand implements ICommand {
name = 'change-prefix';

async execute(ctx: CommandContext, prefix: string): Promise<void> {
if (ctx.guild.me.hasPermission('ADMINISTRATOR')) {
const guild = await ctx.database.findGuildById(ctx.guild.id);

if (guild) {
if (prefix) {
if (prefix === guild.main.prefix) {
await ctx.channel.send(
'Please provide a different prefix than the previous prefix'
);
} else {
guild.main.prefix = prefix;
await guild.save();
await ctx.channel.send('Prefix changed to: ' + guild?.main.prefix);
}
} else {
await ctx.channel.send('Please provide a valid prefix');
}
} else {
await ctx.channel.send(
`Guild with id **'${ctx.guild.id}'** not found in database`
);
}
} else {
await ctx.channel.send(
"You don't have permission(`ADMINISTRATOR`) for use this command"
);
}
}
}
4 changes: 3 additions & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,17 @@ async function initialize(): Promise<void> {
cachePresences: ConfigService.client.caches.presences,
disabledEvents: ConfigService.client.disabledEvents
});

const bot = new PbotPlus(client);

await bot.initialize();
}

// On unhandledRejection
process.on('unhandledRejection', (reason) => {
LoggerService.error('An unhandled promise rejection ocurred.', reason);
});

// Initialize
initialize().catch((error) => {
LoggerService.error('An unspecified error ocurred.', error);
});
70 changes: 39 additions & 31 deletions src/providers/database/database.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,8 @@
import { Guild } from 'discord.js-light';
import Mongoose, { ConnectOptions, Connection } from 'mongoose';

import { CustomClient } from '../../extensions';
import {
ConfigService,
ConfigTypes,
LoggerTypes,
LoggerService
} from '../../services';
import { GuildModel } from './models/guild/guild';
import { GuildModel, IGuildModel } from '..';
import { PbotPlus } from '../../bot';

export class DatabaseProvider {
/**
Expand All @@ -21,14 +15,12 @@ export class DatabaseProvider {
*/
public connection: Connection = this.getConnection();

private readonly config: ConfigTypes = ConfigService;
private readonly logger: LoggerTypes = LoggerService;

/**
* Database provider
* @param options
* @param pbot
*/
constructor(options: ConnectOptions) {
constructor(private pbot: PbotPlus, options: ConnectOptions) {
this.options = options;
}

Expand All @@ -42,34 +34,35 @@ export class DatabaseProvider {
this.registerListeners();

if (Mongoose.connections[0].readyState) {
this.logger.warn('Already connected to database');
this.pbot.logger.warn('Already connected to database');
} else {
await Mongoose.connect(connectionUri, this.options);
}
} catch (error) {
this.logger.error('Failed while connecting to database', error);
this.pbot.logger.error('Failed while connecting to database', error);
}
}

/**
* Fetch new guilds | Create
* @param bot
*/
public async fetchNewGuilds(bot: CustomClient): Promise<void> {
public async fetchNewGuilds(): Promise<void> {
try {
bot.guilds.cache.map(async (guild: Guild) => {
const guildExists = await GuildModel.findById(guild.id);
this.pbot.bot.guilds.cache.map(async (guild: Guild) => {
const id = guild.id;
const guildExists = await this.findGuildById(id);

if (!guildExists) {
const newGuild = new GuildModel({ _id: guild.id });
const newGuild = new GuildModel({ _id: id });
await newGuild.save();
this.logger.info(
`Guild with the id ${guild.id} is saved to database [OFFLINE_GUILD_CREATE]`
this.pbot.logger.info(
`Guild with id '${id}' is saved to database [OFFLINE_GUILD_CREATE]`
);
}
});
} catch (error) {
this.logger.error('Failed while fetching new guilds', error);
this.pbot.logger.error('Failed while fetching new guilds', error);
}
}

Expand All @@ -78,36 +71,51 @@ export class DatabaseProvider {
*/
private registerListeners(): void {
try {
Mongoose.connection.on('open', () => this.onReady());
this.connection.on('open', () => this.onReady());
} catch (error) {
this.logger.error('Failed while registering listeners', error);
this.pbot.logger.error(
'Failed while registering listeners for database',
error
);
}
}

/**
* Find guild by id
* @param id
* @returns Guild Model
*/
public async findGuildById(id: string): Promise<IGuildModel | null> {
const guild = await GuildModel.findById(id);

return guild ?? null;
}

/**
* Get database connection
*/
private getConnection(): Connection {
return Mongoose.connection;
private getConnection(): Connection | null {
const connection = Mongoose.connection;
return connection ?? null;
}

/**
* Get connection URI
*/
private getConnectionUri(): string {
const providerConfig = this.config.dbProvider;
const config = this.pbot.config.database;

if (providerConfig.local) {
return `mongodb://${providerConfig.hostname}:${providerConfig.port}/${providerConfig.database}`;
if (config.local) {
return `mongodb://${config.hostname}:${config.port}/${config.base}`;
} else {
return `mongodb+srv://${providerConfig.username}:${providerConfig.password}@${providerConfig.hostname}/${providerConfig.database}?retryWrites=true&w=majority`;
return `mongodb+srv://${config.username}:${config.password}@${config.hostname}/${config.base}?retryWrites=true&w=majority`;
}
}

/**
* On ready
*/
private async onReady(): Promise<void> {
this.logger.info('Connected to database');
private onReady(): void {
this.pbot.logger.info('Connected to database');
}
}
Loading

0 comments on commit 9e2172d

Please sign in to comment.