Skip to content

Commit

Permalink
feat: multi-guild compatible
Browse files Browse the repository at this point in the history
  • Loading branch information
Codeize committed Dec 27, 2023
1 parent 2a05e4b commit 2bb2d7a
Show file tree
Hide file tree
Showing 8 changed files with 97 additions and 24 deletions.
28 changes: 28 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,39 @@ datasource db {
url = env("DATABASE_URL")
}

model Guild {
id String @id
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tags Tag[]
}

model User {
id String @id
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tags Tag[]
lastEditedTags Tag[] @relation("LastEditedBy")
}

model Tag {
id String @id @default(uuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
guild Guild @relation(fields: [guildId], references: [id])
guildId String
author User @relation(fields: [authorId], references: [id])
authorId String
trigger String
content String
uses Int @default(0)
lastUsed DateTime?
lastEditedBy User? @relation(fields: [lastEditedById], references: [id], name: "LastEditedBy")
lastEditedById String?
lastEditedAt DateTime?
}
2 changes: 1 addition & 1 deletion src/commands/create-tag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ export default class CreateTagCommand extends SlashCommand {
});
}

const createdTag = await createTag(trigger, content);
const createdTag = await createTag(ctx.guildID, ctx.user.id, trigger, content);
if (!createdTag) {
return ctx.send({
content: 'Something went wrong!',
Expand Down
2 changes: 1 addition & 1 deletion src/commands/delete-tag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export default class DeleteTagCommand extends SlashCommand {
}

async autocomplete(ctx: AutocompleteContext) {
const allTags = await getAllTags();
const allTags = await getAllTags(ctx.guildID);
const tag = allTags
.map((tag) => ({
name: tag.trigger,
Expand Down
4 changes: 2 additions & 2 deletions src/commands/edit-tag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ export default class EditTagCommand extends SlashCommand {
});
}

const editedTag = await editTag(tagId, trigger, content);
const editedTag = await editTag(tagId, ctx.user.id, trigger, content);
if (!editedTag) {
return ctx.send({
content: 'Something went wrong!',
Expand All @@ -109,7 +109,7 @@ export default class EditTagCommand extends SlashCommand {
}

async autocomplete(ctx: AutocompleteContext) {
const allTags = await getAllTags();
const allTags = await getAllTags(ctx.guildID);
const tag = allTags
.map((tag) => ({
name: tag.trigger,
Expand Down
18 changes: 15 additions & 3 deletions src/commands/list-tags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,27 @@ export default class ListTagsCommand extends SlashCommand {
async run(ctx: CommandContext) {
const privateReply = ctx.options.private ?? false;

const tags = await getAllTags();
const tags = await getAllTags(ctx.guildID);
if (!tags || tags.length === 0) {
return ctx.send({
content: 'No tags exist!',
ephemeral: true
});
}

const tagList = tags.map((tag) => `**${tag.trigger}** - ${tag.uses} uses - \`${tag.id}\``).join('\n');
const tagList = tags
.map((tag) => {
const isLastUsed = tag.lastUsed ? `<t:${Math.floor(new Date(tag.lastUsed).getTime() / 1000)}:R>` : 'Never';
const isLastEditedAt = tag.lastEditedAt
? `<t:${Math.floor(new Date(tag.lastEditedAt).getTime() / 1000)}:R>`
: 'Never';
return `**__${tag.trigger}__**\n- **Uses**: ${tag.uses}\n- **Last Used**: ${isLastUsed}\n- **Author**: <@${
tag.authorId
}>\n- **Last Edited By**: <@${tag.lastEditedById}>\n- **Created At**: <t:${Math.floor(
new Date(tag.createdAt).getTime() / 1000
)}:f>\n- **Last Edited At**: ${isLastEditedAt}`;
})
.join('\n\n');
const embed = new EmbedBuilder().setTitle('All Tags').setDescription(tagList).setColor(0x6472e0);

return ctx.send({
Expand All @@ -40,7 +52,7 @@ export default class ListTagsCommand extends SlashCommand {
}

async autocomplete(ctx: AutocompleteContext) {
const allTags = await getAllTags();
const allTags = await getAllTags(ctx.guildID);
const tag = allTags
.map((tag) => ({
name: tag.trigger,
Expand Down
2 changes: 1 addition & 1 deletion src/commands/send-tag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export default class SendTagCommand extends SlashCommand {
}

async autocomplete(ctx: AutocompleteContext) {
const allTags = await getAllTags();
const allTags = await getAllTags(ctx.guildID);
const tag = allTags
.map((tag) => ({
name: tag.trigger,
Expand Down
36 changes: 23 additions & 13 deletions src/db.ts
Original file line number Diff line number Diff line change
@@ -1,67 +1,77 @@
import { PrismaClient } from '@prisma/client';

const db = new PrismaClient({
export const db = new PrismaClient({
errorFormat: 'pretty'
});

export const createTag = async (trigger: string, content: string) => {
return db.tag.create({
export const createTag = async (guildId: string, authorId: string, trigger: string, content: string) => {
return await db.tag.create({
data: {
guildId,
authorId,
trigger,
content
content,
lastEditedById: authorId
}
});
};

export const getTag = async (tagId: string) => {
return db.tag.findUnique({
return await db.tag.findUnique({
where: {
id: tagId
}
});
};

export const getTagByTrigger = async (trigger: string) => {
return db.tag.findFirst({
return await db.tag.findFirst({
where: {
trigger
}
});
};

export const getAllTags = async () => {
return db.tag.findMany();
export const getAllTags = async (guildId: string) => {
return await db.tag.findMany({
where: {
guildId
}
});
};

export const editTag = async (tagId: string, trigger: string, content: string) => {
return db.tag.update({
export const editTag = async (tagId: string, editorId: string, trigger: string, content: string) => {
return await db.tag.update({
where: {
id: tagId
},
data: {
lastEditedById: editorId,
lastEditedAt: new Date(),
trigger,
content
}
});
};

export const deleteTag = async (tagId: string) => {
return db.tag.delete({
return await db.tag.delete({
where: {
id: tagId
}
});
};

export const incrementTagUses = async (tagId: string) => {
return db.tag.update({
return await db.tag.update({
where: {
id: tagId
},
data: {
uses: {
increment: 1
}
},
lastUsed: new Date()
}
});
};
29 changes: 26 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import dotenv from 'dotenv';
import { SlashCreator, FastifyServer } from 'slash-create';
import path from 'path';
import CatLoggr from 'cat-loggr/ts';
import { db } from './db';

let dotenvPath = path.join(process.cwd(), '.env');
if (path.parse(process.cwd()).name === 'dist') dotenvPath = path.join(process.cwd(), '..', '.env');
Expand All @@ -21,9 +22,31 @@ creator.on('debug', (message) => logger.log(message));
creator.on('warn', (message) => logger.warn(message));
creator.on('error', (error) => logger.error(error));
creator.on('synced', () => logger.info('Commands synced!'));
creator.on('commandRun', (command, _, ctx) =>
logger.info(`${ctx.user.username} (${ctx.user.id}) ran command ${command.commandName}`)
);
creator.on('commandRun', async (command, _, ctx) => {
await db.guild.upsert({
where: {
id: ctx.guildID
},
create: {
id: ctx.guildID
},
update: {
id: ctx.guildID
}
});
await db.user.upsert({
where: {
id: ctx.user.id
},
create: {
id: ctx.user.id
},
update: {
id: ctx.user.id
}
});
logger.info(`${ctx.user.username} (${ctx.user.id}) ran command ${command.commandName}`);
});
creator.on('commandRegister', (command) => logger.info(`Registered command ${command.commandName}`));
creator.on('commandError', (command, error) => logger.error(`Command ${command.commandName}:`, error));

Expand Down

0 comments on commit 2bb2d7a

Please sign in to comment.