Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dev #128

Merged
merged 6 commits into from
Oct 24, 2024
Merged

Dev #128

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions .env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@
BOT_TOKEN =
#used for adding bot/application to server
CLIENT_ID =
# invite link:
# https://discord.com/api/oauth2/authorize?CLIENT_ID=<clientId>&permissions=0&scope=bot%20applications.commands
SERVER_ID =
# Mongo configuration
MONGO_URI=
MONGO_PORT=
Expand Down
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
"build": "npm run deldist && tsc -p .",
"start:ts-node": "ts-node src/main.ts",
"start": "nest start",
"tunnel": "ngrok http 3000",
"start:debug": "nest start --debug --watch",
"build:prod": "docker build --pull --rm -f \"dockerfiles\\Dockerfile.prod\" -t ghcr.io/blvckleg/bingusboingus:latest \".\"",
"build:test": "docker build --pull --rm -f \"dockerfiles\\Dockerfile.test\" -t ghcr.io/blvckleg/bingusboingus:test \".\"",
Expand Down
23 changes: 17 additions & 6 deletions src/deployment/deploy.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { REST, RESTPostAPIChatInputApplicationCommandsJSONBody, Routes } from 'discord.js';
import {
REST,
RESTPostAPIChatInputApplicationCommandsJSONBody,
Routes,
} from 'discord.js';
import { Injectable } from '@nestjs/common';
import { CommandService } from '../modules/command/command.service';
import { AppConfigService } from '../config/config.service';
Expand All @@ -18,18 +22,25 @@ export class DeployServcice {
return commands.map((command) => command.data.toJSON());
}

async deployCommands(commands: RESTPostAPIChatInputApplicationCommandsJSONBody[]) {
async deployCommands(
commands: RESTPostAPIChatInputApplicationCommandsJSONBody[],
) {
// Construct and prepare an instance of the REST module
const rest = new REST().setToken(this.configService.botToken);

// and deploy your commands!
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);
console.log(
`Started refreshing ${commands.length} application (/) commands.`,
);

// The put method is used to fully refresh all commands in the guild with the current set
const data = await rest.put(Routes.applicationGuildCommands(process.env.CLIENT_ID ?? '', process.env.SERVER_ID ?? ''), {
body: commands,
});
const data = await rest.put(
Routes.applicationCommands(process.env.CLIENT_ID ?? ''),
{
body: commands,
},
);

let log = '';
if (Array.isArray(data)) log = data.length + ' ';
Expand Down
11 changes: 10 additions & 1 deletion src/modules/command/command.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import { SomeoneOnceSaidModule } from '../models/someone-once-said/module/someon
import { PollModule } from '../models/poll/module/poll.module';
import { VersionModule } from '../models/version/module/version.module';
import { BirthdayEntryModule } from '../models/birthday/module/birthday-entry.module';
import ConfigureServerChannelCommand from './commands/server-config';
import { ServerConfigModule } from '../models/config/module/server-config.module';

@Module({
providers: [
Expand All @@ -34,10 +36,17 @@ import { BirthdayEntryModule } from '../models/birthday/module/birthday-entry.mo
PollCommand,
VersionCommand,
AddBirthdayEntryCommand,
ConfigureServerChannelCommand,
DeactivateBirthdayEntryShoutoutCommand,
ActivateBirthdayEntryShoutoutCommand,
],
imports: [SomeoneOnceSaidModule, PollModule, VersionModule, BirthdayEntryModule],
imports: [
SomeoneOnceSaidModule,
PollModule,
VersionModule,
BirthdayEntryModule,
ServerConfigModule,
],
exports: [CommandService],
})
export class CommandModule {}
3 changes: 3 additions & 0 deletions src/modules/command/command.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { BirthdayEntry } from '../../schemas/birthday-entry.schema';
import AddBirthdayEntryCommand from './commands/add-birthday-entry';
import DeactivateBirthdayEntryShoutoutCommand from './commands/deactivate-birthday-shoutout';
import ActivateBirthdayEntryShoutoutCommand from './commands/activate-birthday-shoutout';
import ConfigureServerChannelCommand from './commands/server-config';

@Injectable()
export class CommandService {
Expand All @@ -34,6 +35,7 @@ export class CommandService {
addBirthdayEntryModule: AddBirthdayEntryCommand,
deactivateBirthdayEntryShoutoutModule: DeactivateBirthdayEntryShoutoutCommand,
activateBirthdayEntryShoutoutModule: ActivateBirthdayEntryShoutoutCommand,
configureServerChannelIdModule: ConfigureServerChannelCommand,
) {
const commands: ACommand[] = [
//pingpongModule,
Expand All @@ -50,6 +52,7 @@ export class CommandService {
addBirthdayEntryModule,
deactivateBirthdayEntryShoutoutModule,
activateBirthdayEntryShoutoutModule,
configureServerChannelIdModule,
];
commands.forEach((command) => {
if (command.data.name && !!command.execute) {
Expand Down
1 change: 1 addition & 0 deletions src/modules/command/commands/activate-birthday-shoutout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export default class ActivateBirthdayEntryShoutoutCommand extends ACommand {
const instance: CreateOrUpdateBirthdayEntryDto = {
username: arg.user.username,
secName: arg.user.displayName,
serverId: arg.guildId,
active: true,
};
const inactive =
Expand Down
5 changes: 1 addition & 4 deletions src/modules/command/commands/add-birthday-entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,6 @@ import { ACommand } from '../command.abstract';
import { Inject } from '@nestjs/common';
import { BirthdayEntryService } from '../../models/birthday/service/birthday-entry.service';
import { CreateOrUpdateBirthdayEntryDto } from '../../models/birthday/dto/create-or-update-birthday-entry.dto';
import {
CommandAccessLevel,
Role,
} from '../../../common/decoratos/role.decorator';

export default class AddBirthdayEntryCommand extends ACommand {
constructor(
Expand Down Expand Up @@ -56,6 +52,7 @@ export default class AddBirthdayEntryCommand extends ACommand {
birthDate: dateValue,
username: arg.user.username,
secName: arg.user.displayName,
serverId: arg.guildId,
active: true,
};
const created =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export default class DeactivateBirthdayEntryShoutoutCommand extends ACommand {
const instance: CreateOrUpdateBirthdayEntryDto = {
username: arg.user.username,
secName: arg.user.displayName,
serverId: arg.guildId,
active: false,
};
const inactive =
Expand Down
4 changes: 3 additions & 1 deletion src/modules/command/commands/get-a-quote.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ export default class GetRandomQuote extends ACommand {

// @Role(CommandAccessLevel.member)
async execute(arg: CommandInteraction<CacheType>): Promise<boolean> {
const someoneOnceSaid = await this.someoneonceSaidService.getRandomQuote();
const someoneOnceSaid = await this.someoneonceSaidService.getRandomQuote(
arg.guildId,
);
if (!someoneOnceSaid) return;
const quoteEmbed = new EmbedBuilder()
.setTitle(
Expand Down
57 changes: 57 additions & 0 deletions src/modules/command/commands/server-config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import {
CacheType,
CommandInteraction,
EmbedBuilder,
SlashCommandBuilder,
} from 'discord.js';
import { ACommand } from '../command.abstract';
import { Inject } from '@nestjs/common';
import { ServerConfigService } from '../../models/config/service/server-config.service';
import { CreateOrUpdateServerConfigDto } from '../../models/config/dto/create-or-update-server-config.dto';

export default class ConfigureServerChannelCommand extends ACommand {
constructor(
@Inject(ServerConfigService)
private readonly configService: ServerConfigService,
) {
super();
}
data = new SlashCommandBuilder()
.setName('configure')
.setDescription(
'set the channel id where the bot will send all scheduled messages',
)
.addStringOption((option) =>
option.setName('channelid').setDescription('the Id of the text-channel'),
);

// @Role(CommandAccessLevel.member)
async execute(arg: CommandInteraction<CacheType>): Promise<boolean> {
const channelId = arg.options.get('channelid');
if (!channelId) {
await arg.reply({
content: 'you need to provide a valid channel Id! 🤓',
ephemeral: true,
});
return false;
}
await arg.deferReply();
const channelIdValue = channelId.value as unknown as string;
const instance: CreateOrUpdateServerConfigDto = {
channelId: channelIdValue,
serverId: arg.guildId,
};
const created =
await this.configService.createOrUpdateServerConfig(instance);
const quoteEmbed = new EmbedBuilder()
.setTitle('Your scheduled messages textchannel was configured! 🤓')
.setDescription('🤓')
.setFooter({
text: 'scheduled messages activated',
})
.setTimestamp(new Date());
await arg.editReply({ embeds: [quoteEmbed] });
return true;
}
}

2 changes: 2 additions & 0 deletions src/modules/command/commands/someone-once-said.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
CommandAccessLevel,
Role,
} from '../../../common/decoratos/role.decorator';
import { server } from 'typescript';

export default class SomeoneOnceSaidCommand extends ACommand {
constructor(
Expand Down Expand Up @@ -46,6 +47,7 @@ export default class SomeoneOnceSaidCommand extends ACommand {
phrase: phraseValue,
username: arg.user.username,
secName: arg.user.displayName,
serverId: arg.guildId,
});
const created = await this.someoneonceSaidService.create(instance);
const quoteEmbed = new EmbedBuilder()
Expand Down
46 changes: 27 additions & 19 deletions src/modules/cron-tasks/cron.service.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { Client, TextChannel } from 'discord.js';
import { TextChannel } from 'discord.js';
import BirthdayShoutoutTask from './tasks/birthday-shoutout.task';
import { Inject, Injectable } from '@nestjs/common';
import WakeUpTask from './tasks/wake-up.task';
import * as cron from 'node-cron';
import { BirthdayEntryService } from '../models/birthday/service/birthday-entry.service';
import { TaskEntry } from './interfaces/task-entry.interface';
import { DiscordService } from '../discord/discord.service';
import { ServerConfigService } from '../models/config/service/server-config.service';
import { ServerConfigDocument } from '../../schemas/server-config.schema';

@Injectable()
export class CronService {
Expand All @@ -17,6 +19,8 @@ export class CronService {
private readonly birthdayService: BirthdayEntryService,
@Inject(DiscordService)
private readonly discordService: DiscordService,
@Inject(ServerConfigService)
private readonly serverConfigService: ServerConfigService,
) {
if (CronService.instance) {
throw new Error(`ERROR: An instance has already been created.`);
Expand All @@ -29,28 +33,32 @@ export class CronService {
return CronService.instance;
}

public init() {
this.tasks = [
{
public async init() {
const servers: ServerConfigDocument[] =
await this.serverConfigService.getAll();
let birthdayTasks = [];
servers.forEach((server) => {
const birthdayChannel = this.discordService.client.channels.cache.find(
(channel) => channel.id === server.channelId,
) as TextChannel;
birthdayTasks.push({
name: 'birthday-shoutout',
schedule: '0 10 * * *',
task: new BirthdayShoutoutTask(
this.discordService.client.channels.cache.find(
(channel) => channel.id === '447554141724737548',
) as TextChannel,
this.birthdayService,
),
},
{
task: new BirthdayShoutoutTask(birthdayChannel, this.birthdayService),
});
});
let wakeUpTasks = [];
servers.forEach((server) => {
const wakeUpChannel = this.discordService.client.channels.cache.find(
(channel) => channel.id === server.channelId,
) as TextChannel;
wakeUpTasks.push({
name: 'first-of-the-month',
schedule: '0 12 1 * *',
task: new WakeUpTask(
this.discordService.client.channels.cache.find(
(channel) => channel.id === '447554141724737548',
) as TextChannel,
),
},
];
task: new WakeUpTask(wakeUpChannel),
});
});
this.tasks = [...birthdayTasks, ...wakeUpTasks];
this.registerTasks();
}

Expand Down
3 changes: 2 additions & 1 deletion src/modules/cron-tasks/task.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ import { Module } from '@nestjs/common';
import { BirthdayEntryModule } from '../models/birthday/module/birthday-entry.module';
import { CronService } from './cron.service';
import { DiscordModule } from '../discord/discord.module';
import { ServerConfigModule } from '../models/config/module/server-config.module';

@Module({
imports: [DiscordModule, BirthdayEntryModule],
imports: [DiscordModule, BirthdayEntryModule, ServerConfigModule],
providers: [CronService],
exports: [CronService],
})
Expand Down
65 changes: 38 additions & 27 deletions src/modules/cron-tasks/tasks/birthday-shoutout.task.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,46 @@
import { EmbedBuilder, TextChannel } from 'discord.js'
import { ITask } from './interfaces/task.interface'
import { BirthdayEntryService } from '../../models/birthday/service/birthday-entry.service'
import { EmbedBuilder, TextChannel } from 'discord.js';
import { ITask } from './interfaces/task.interface';
import { BirthdayEntryService } from '../../models/birthday/service/birthday-entry.service';

export default class BirthdayShoutoutTask implements ITask {
private channel: TextChannel
private channel: TextChannel;

constructor(channel: TextChannel, private readonly birthdayService: BirthdayEntryService) {
this.channel = channel
}

async execute(): Promise<void> {
const birthDayEntries = await this.birthdayService.getEntryForToday()
constructor(
channel: TextChannel,
private readonly birthdayService: BirthdayEntryService,
) {
this.channel = channel;
}

if (!birthDayEntries || birthDayEntries.length < 1) {
return
}
async execute(): Promise<void> {
const birthDayEntries = await this.birthdayService.getEntryForToday();

birthDayEntries.forEach((entry) => {
const creator = this.channel.members.find((member) => member.user.username === entry.username || member.user.displayName === entry.secName)
if (!birthDayEntries || birthDayEntries.length < 1) {
return;
}

const embed = new EmbedBuilder()
.setTitle(`🚨 Birthday Alert!! 🚨`)
.setColor('Random')
.setDescription(`${entry.username ?? entry.secName} is turning **${new Date().getFullYear() - entry.birthDate.getFullYear()}** years old today! 🎉🎂🎈`)
.setFooter({
text: creator?.user.username ?? 'bingus',
iconURL: creator?.displayAvatarURL() ?? undefined,
})
.setTimestamp(new Date())
birthDayEntries.forEach((entry) => {
const creator = this.channel.members.find(
(member) =>
member.user.username === entry.username ||
member.user.displayName === entry.secName,
);

this.channel.send({ embeds: [embed] })
const embed = new EmbedBuilder()
.setTitle(`🚨 Birthday Alert!! 🚨`)
.setColor('Random')
.setDescription(
`${entry.username ?? entry.secName} is turning **${
new Date().getFullYear() - entry.birthDate.getFullYear()
}** years old today! 🎉🎂🎈`,
)
.setFooter({
text: creator?.user.username ?? 'bingus',
iconURL: creator?.displayAvatarURL() ?? undefined,
})
}
}
.setTimestamp(new Date());

this.channel.send({ embeds: [embed] });
});
}
}
Loading