style(src/prettier): updating with the prettier

This commit is contained in:
Raphael 2025-08-18 11:46:10 +02:00
parent b36925546c
commit bb46ad3996
17 changed files with 1909 additions and 1717 deletions

View file

@ -2,7 +2,7 @@ name: CheckBuild
on: on:
push: push:
branches: [ master ] branches: [master]
pull_request: pull_request:
permissions: permissions:

View file

@ -7,11 +7,13 @@ bun install
``` ```
To run in developpement bot: To run in developpement bot:
```bash ```bash
bun run dev bun run dev
``` ```
To build to javacript: To build to javacript:
```bash ```bash
bun run build bun run build
``` ```

53
eslint.config.js Normal file
View file

@ -0,0 +1,53 @@
import js from "@eslint/js";
export default [
js.configs.recommended,
{
languageOptions: {
ecmaVersion: "latest",
},
rules: {
"arrow-spacing": ["warn", { before: true, after: true }],
"brace-style": ["error", "stroustrup", { allowSingleLine: true }],
"comma-dangle": ["error", "always-multiline"],
"comma-spacing": "error",
"comma-style": "error",
curly: ["error", "multi-line", "consistent"],
"dot-location": ["error", "property"],
"handle-callback-err": "off",
indent: ["error", "tab"],
"keyword-spacing": "error",
"max-nested-callbacks": ["error", { max: 4 }],
"max-statements-per-line": ["error", { max: 2 }],
"no-console": "off",
"no-empty-function": "error",
"no-floating-decimal": "error",
"no-inline-comments": "error",
"no-lonely-if": "error",
"no-multi-spaces": "error",
"no-multiple-empty-lines": ["error", { max: 2, maxEOF: 1, maxBOF: 0 }],
"no-shadow": ["error", { allow: ["err", "resolve", "reject"] }],
"no-trailing-spaces": ["error"],
"no-var": "error",
"no-undef": "off",
"object-curly-spacing": ["error", "always"],
"prefer-const": "error",
quotes: ["error", "single"],
semi: ["error", "always"],
"space-before-blocks": "error",
"space-before-function-paren": [
"error",
{
anonymous: "never",
named: "never",
asyncArrow: "always",
},
],
"space-in-parens": "error",
"space-infix-ops": "error",
"space-unary-ops": "error",
"spaced-comment": "error",
yoda: "error",
},
},
];

View file

@ -1,251 +1,268 @@
import { prisma } from '../../lib/prisma.ts'; import { prisma } from "../../lib/prisma.ts";
import { ActionRowBuilder, ChannelType, PermissionsBitField, ComponentType, StringSelectMenuBuilder, StringSelectMenuInteraction, StringSelectMenuOptionBuilder, SlashCommandBuilder, ChatInputCommandInteractionActivityType, channelMention, roleMention, PresenceUpdateStatus, MessageFlags, SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import {
import emoji from '../../../assets/emoji.json' assert { type: "json" }; ActionRowBuilder,
ChannelType,
PermissionsBitField,
ComponentType,
StringSelectMenuBuilder,
StringSelectMenuInteraction,
StringSelectMenuOptionBuilder,
SlashCommandBuilder,
ChatInputCommandInteractionActivityType,
channelMention,
roleMention,
PresenceUpdateStatus,
MessageFlags,
SlashCommandBuilder,
EmbedBuilder,
} from "discord.js";
import emoji from "../../../assets/emoji.json" assert { type: "json" };
export default { export default {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName('logs') .setName("logs")
.setDescription('edit the logs configuration') .setDescription("edit the logs configuration")
.addStringOption(option => option .addStringOption((option) =>
.setName('action') option
.setDescription('What is the action you to perform') .setName("action")
.setRequired(true) .setDescription("What is the action you to perform")
.addChoices( .setRequired(true)
{ .addChoices(
name: 'Show', {
value: 'logs_show' name: "Show",
}, value: "logs_show",
{ },
name: 'Auto-configuration', {
value: 'logs_auto' name: "Auto-configuration",
}, value: "logs_auto",
{ },
name: 'Configuration', {
value: 'logs_config' name: "Configuration",
}, value: "logs_config",
) },
), ),
async execute(interaction: CommandInteraction) { ),
let guildData: Guild; async execute(interaction: CommandInteraction) {
try { let guildData: Guild;
guildData = await prisma.guild.findUnique({ try {
where: { guildData = await prisma.guild.findUnique({
id: interaction.guild.id where: {
} id: interaction.guild.id,
}); },
} catch (err) { });
console.error(`\t⚠ | Cannot get the database connection!\n\t\t(${err}).`); } catch (err) {
await interaction.reply({ console.error(
content: `${emoji.answer.error} | Cannot connect to the database`, `\t⚠ | Cannot get the database connection!\n\t\t(${err}).`,
flags: MessageFlags.Ephemeral );
}); await interaction.reply({
return; content: `${emoji.answer.error} | Cannot connect to the database`,
} flags: MessageFlags.Ephemeral,
let userData: User; });
try { return;
userData = await prisma.user.findUnique({ }
where: { let userData: User;
id: interaction.user.id try {
} userData = await prisma.user.findUnique({
}); where: {
} catch (err) { id: interaction.user.id,
throw(`\t⚠ | Cannot get the database connection!\n\t\t(${err}).`); },
await interaction.reply({ });
content: `${emoji.answer.error} | Cannot connect to the database`, } catch (err) {
flags: MessageFlags.Ephemeral throw `\t⚠ | Cannot get the database connection!\n\t\t(${err}).`;
}); await interaction.reply({
return; content: `${emoji.answer.error} | Cannot connect to the database`,
} flags: MessageFlags.Ephemeral,
const choice: string = interaction.options.getString('action'); });
switch (choice) { return;
case 'logs_show': }
if (guildData.logEnable) { const choice: string = interaction.options.getString("action");
const logsData: EmbedBuilder = new EmbedBuilder() switch (choice) {
.setTitle(`Logs for ${interaction.guild.name}`) case "logs_show":
.setColor(`${guildData.color}`) if (guildData.logEnable) {
.setFooter({ const logsData: EmbedBuilder = new EmbedBuilder()
text: guildData.footer .setTitle(`Logs for ${interaction.guild.name}`)
}) .setColor(`${guildData.color}`)
.setDescription(` .setFooter({
text: guildData.footer,
}).setDescription(`
${guildData.logCategory ? `${emoji.answer.yes} | Categories` : `${emoji.answer.no} | Categories`} ${guildData.logCategory ? `${emoji.answer.yes} | Categories` : `${emoji.answer.no} | Categories`}
${guildData.logBot ? `${emoji.answer.yes} | Bot` : `${emoji.answer.no} | Bot`} ${guildData.logBot ? `${emoji.answer.yes} | Bot` : `${emoji.answer.no} | Bot`}
${guildData.logChannels ? `${emoji.answer.yes} | Channels` : `${emoji.answer.no} | Channels`} ${guildData.logChannels ? `${emoji.answer.yes} | Channels` : `${emoji.answer.no} | Channels`}
${guildData.logMember ? `${emoji.answer.yes} | Member` : `${emoji.answer.no} | Member`} ${guildData.logMember ? `${emoji.answer.yes} | Member` : `${emoji.answer.no} | Member`}
${guildData.logMod ? `${emoji.answer.yes} | Moderation` : `${emoji.answer.no} | Moderation`} ${guildData.logMod ? `${emoji.answer.yes} | Moderation` : `${emoji.answer.no} | Moderation`}
${guildData.logMsg ? `${emoji.answer.yes} | Message` : `${emoji.answer.no} | Message`} ${guildData.logMsg ? `${emoji.answer.yes} | Message` : `${emoji.answer.no} | Message`}
${guildData.logServer ? `${emoji.answer.yes} | Server` : `${emoji.answer.no} | Server`} ${guildData.logServer ? `${emoji.answer.yes} | Server` : `${emoji.answer.no} | Server`}
`) `);
await interaction.reply({
embeds: [
logsData
]
});
} else {
await interaction.reply({
content: `${emoji.answer.no} | The log is disable on the server`,
flags: MessageFlags.Ephemeral
});
}
return;
case 'logs_auto':
if (guildData.logEnable) {
await interaction.reply({
content: `${emoji.answer.error} | The log is already setup on this server`,
flags: MessageFlags.Ephemeral
});
return;
}
const roles = interaction.guild?.roles.cache await interaction.reply({
.filter(role => !role.managed && role.id !== interaction.guild?.id) embeds: [logsData],
.sort((a, b) => b.position - a.position) });
} else {
await interaction.reply({
content: `${emoji.answer.no} | The log is disable on the server`,
flags: MessageFlags.Ephemeral,
});
}
return;
case "logs_auto":
if (guildData.logEnable) {
await interaction.reply({
content: `${emoji.answer.error} | The log is already setup on this server`,
flags: MessageFlags.Ephemeral,
});
return;
}
const menu = new StringSelectMenuBuilder() const roles = interaction.guild?.roles.cache
.setCustomId('role_select') .filter((role) => !role.managed && role.id !== interaction.guild?.id)
.setPlaceholder('Choose the role that will have logs access') .sort((a, b) => b.position - a.position);
.setMinValues(1)
.setMaxValues(Math.min(roles.size, 25))
.addOptions(roles.map(role =>
new StringSelectMenuOptionBuilder()
.setLabel(role.name)
.setValue(role.id)
)
);
const roleSelection = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(menu); const menu = new StringSelectMenuBuilder()
.setCustomId("role_select")
.setPlaceholder("Choose the role that will have logs access")
.setMinValues(1)
.setMaxValues(Math.min(roles.size, 25))
.addOptions(
roles.map((role) =>
new StringSelectMenuOptionBuilder()
.setLabel(role.name)
.setValue(role.id),
),
);
let permSelector: EmbedBuilder = new EmbedBuilder() const roleSelection =
.setTitle(`Which role will have access`) new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(menu);
.setColor(`${guildData.color}`)
.setFooter({
text: guildData.footer
})
const msg = await interaction.reply({
embeds: [
permSelector
],
components: [
roleSelection
],
flags: MessageFlags.fetchReply
});
const collector = msg.createMessageComponentCollector({
componentType: ComponentType.StringSelect,
time: 60_000,
max: 25
});
collector.on('collect', async (selectInteraction: StringSelectMenuInteraction) => {
if (selectInteraction.user.id !== interaction.user.id) {
selectInteraction.reply({
content: `${emoji.answer.no} | You cannot use this selector !`,
ephemeral: true
});
return;
}
const selectedRoles = selectInteraction.values;
const permissionOverwrites = [
{
id: interaction.guild.roles.everyone.id,
deny: [
PermissionsBitField.Flags.ViewChannel,
PermissionsBitField.Flags.SendMessages
],
},
...selectedRoles.map(id => ({
id,
allow: [
PermissionsBitField.Flags.ViewChannel
],
}))
];
const category = await interaction.guild.channels.create({ let permSelector: EmbedBuilder = new EmbedBuilder()
name: 'Logs', .setTitle(`Which role will have access`)
type: ChannelType.GuildCategory, .setColor(`${guildData.color}`)
permissionOverwrites .setFooter({
}) as CategoryChannel; text: guildData.footer,
});
const logBot = await interaction.guild.channels.create({ const msg = await interaction.reply({
name: 'bot-logs', embeds: [permSelector],
type: ChannelType.GuildText, components: [roleSelection],
parent: category, flags: MessageFlags.fetchReply,
permissionOverwrites });
}) as TextChannel; const collector = msg.createMessageComponentCollector({
componentType: ComponentType.StringSelect,
time: 60_000,
max: 25,
});
collector.on(
"collect",
async (selectInteraction: StringSelectMenuInteraction) => {
if (selectInteraction.user.id !== interaction.user.id) {
selectInteraction.reply({
content: `${emoji.answer.no} | You cannot use this selector !`,
ephemeral: true,
});
return;
}
const selectedRoles = selectInteraction.values;
const permissionOverwrites = [
{
id: interaction.guild.roles.everyone.id,
deny: [
PermissionsBitField.Flags.ViewChannel,
PermissionsBitField.Flags.SendMessages,
],
},
...selectedRoles.map((id) => ({
id,
allow: [PermissionsBitField.Flags.ViewChannel],
})),
];
const logChannels = await interaction.guild.channels.create({ const category = (await interaction.guild.channels.create({
name: 'channel-logs', name: "Logs",
type: ChannelType.GuildText, type: ChannelType.GuildCategory,
parent: category, permissionOverwrites,
permissionOverwrites })) as CategoryChannel;
}) as TextChannel;
const logMember = await interaction.guild.channels.create({ const logBot = (await interaction.guild.channels.create({
name: 'member-logs', name: "bot-logs",
type: ChannelType.GuildText, type: ChannelType.GuildText,
parent: category, parent: category,
permissionOverwrites permissionOverwrites,
}) as TextChannel; })) as TextChannel;
const logMod = await interaction.guild.channels.create({ const logChannels = (await interaction.guild.channels.create({
name: 'mod-logs', name: "channel-logs",
type: ChannelType.GuildText, type: ChannelType.GuildText,
parent: category, parent: category,
permissionOverwrites permissionOverwrites,
}) as TextChannel; })) as TextChannel;
const logMsg = await interaction.guild.channels.create({ const logMember = (await interaction.guild.channels.create({
name: 'message-logs', name: "member-logs",
type: ChannelType.GuildText, type: ChannelType.GuildText,
parent: category, parent: category,
permissionOverwrites permissionOverwrites,
}) as TextChannel; })) as TextChannel;
const logServer = await interaction.guild.channels.create({ const logMod = (await interaction.guild.channels.create({
name: 'server-logs', name: "mod-logs",
type: ChannelType.GuildText, type: ChannelType.GuildText,
parent: category, parent: category,
permissionOverwrites permissionOverwrites,
}) as TextChannel; })) as TextChannel;
await prisma.guild.update({ const logMsg = (await interaction.guild.channels.create({
where: { name: "message-logs",
id: interaction.guild.id type: ChannelType.GuildText,
}, parent: category,
data: { permissionOverwrites,
logEnable: true, })) as TextChannel;
logCategory: category.id,
logBot: logBot.id, const logServer = (await interaction.guild.channels.create({
logChannels: logChannels.id, name: "server-logs",
logMember: logMember.id, type: ChannelType.GuildText,
logMod: logMod.id, parent: category,
logMsg: logMsg.id, permissionOverwrites,
logServer: logServer.id })) as TextChannel;
}
}); await prisma.guild.update({
const mentionList = selectedRoles.map(id => `- <@&${id}>`).join('\n'); where: {
const autoConfig = new EmbedBuilder() id: interaction.guild.id,
.setTitle(`The logs category is created`) },
.setDescription(` data: {
logEnable: true,
logCategory: category.id,
logBot: logBot.id,
logChannels: logChannels.id,
logMember: logMember.id,
logMod: logMod.id,
logMsg: logMsg.id,
logServer: logServer.id,
},
});
const mentionList = selectedRoles
.map((id) => `- <@&${id}>`)
.join("\n");
const autoConfig = new EmbedBuilder()
.setTitle(`The logs category is created`)
.setDescription(
`
This following roles will have access to the logs. This following roles will have access to the logs.
${mentionList} ${mentionList}
`) `,
.setColor(`${guildData.color}`) )
.setFooter({ .setColor(`${guildData.color}`)
text: guildData.footer .setFooter({
}) text: guildData.footer,
await selectInteraction.update({ });
embeds: [ await selectInteraction.update({
autoConfig embeds: [autoConfig],
], components: [],
components: [] });
}); return;
return; },
}); );
default: default:
console.error(`no choice on logs command ${choice}`); console.error(`no choice on logs command ${choice}`);
return; return;
} }
} },
} };

View file

@ -1,309 +1,335 @@
import { prisma } from '../../lib/prisma.ts'; import { prisma } from "../../lib/prisma.ts";
import { ActivityType, userMention, roleMention, PresenceUpdateStatus, MessageFlags, SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import {
import emoji from '../../../assets/emoji.json' assert { type: "json" }; ActivityType,
userMention,
roleMention,
PresenceUpdateStatus,
MessageFlags,
SlashCommandBuilder,
EmbedBuilder,
} from "discord.js";
import emoji from "../../../assets/emoji.json" assert { type: "json" };
export default { export default {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName('set') .setName("set")
.setDescription('edit the default behavour of the bot') .setDescription("edit the default behavour of the bot")
.addSubcommand(subcommand => subcommand .addSubcommand((subcommand) =>
.setName('color') subcommand
.setDescription('Change the default color for the embed') .setName("color")
.addStringOption(option => .setDescription("Change the default color for the embed")
option.setName('color') .addStringOption((option) =>
.setDescription('The new color by default') option
.setRequired(true) .setName("color")
) .setDescription("The new color by default")
) .setRequired(true),
.addSubcommand(subcommand => subcommand ),
.setName('footer') )
.setDescription('Change the default footer for the embed') .addSubcommand((subcommand) =>
.addStringOption(option => subcommand
option.setName('text') .setName("footer")
.setDescription('The new text by default of the bot') .setDescription("Change the default footer for the embed")
.setRequired(true) .addStringOption((option) =>
) option
) .setName("text")
.addSubcommand(subcommand => subcommand .setDescription("The new text by default of the bot")
.setName('pp') .setRequired(true),
.setDescription('Change the bot profile picture') ),
.addStringOption(option => )
option.setName('link') .addSubcommand((subcommand) =>
.setDescription('The new link to the new profile picture') subcommand
.setRequired(true) .setName("pp")
) .setDescription("Change the bot profile picture")
) .addStringOption((option) =>
.addSubcommand(subcommand => subcommand option
.setName('status') .setName("link")
.setDescription('Change the status of the bot') .setDescription("The new link to the new profile picture")
.addStringOption(option => .setRequired(true),
option.setName('status') ),
.setDescription('The new status used by the bot') )
.setRequired(true) .addSubcommand((subcommand) =>
) subcommand
.addStringOption(option => .setName("status")
option.setName('presence') .setDescription("Change the status of the bot")
.setDescription('The new presence of the bot') .addStringOption((option) =>
.setRequired(true) option
.addChoices( .setName("status")
{ .setDescription("The new status used by the bot")
name: 'Online', .setRequired(true),
value: 'online' )
}, .addStringOption((option) =>
{ option
name: 'Do not disturb', .setName("presence")
value: 'dnd' .setDescription("The new presence of the bot")
}, .setRequired(true)
{ .addChoices(
name: 'Idle', {
value: 'idle' name: "Online",
}, value: "online",
{ },
name: 'Invisible', {
value: 'invisible' name: "Do not disturb",
}, value: "dnd",
) },
) {
.addStringOption(option => name: "Idle",
option.setName('type') value: "idle",
.setDescription('The type of the new activity') },
.setRequired(true) {
.addChoices( name: "Invisible",
{ value: "invisible",
name: 'Playing', },
value: 'play' ),
}, )
{ .addStringOption((option) =>
name: 'Watching', option
value: 'watch' .setName("type")
}, .setDescription("The type of the new activity")
{ .setRequired(true)
name: 'Listening', .addChoices(
value: 'listen' {
}, name: "Playing",
{ value: "play",
name: 'Competing', },
value: 'competing' {
}, name: "Watching",
{ value: "watch",
name: 'Streaming', },
value: 'stream' {
}, name: "Listening",
) value: "listen",
) },
), {
async execute(interaction: CommandInteraction) { name: "Competing",
let guildData: Guild; value: "competing",
try { },
guildData = await prisma.guild.findUnique({ {
where: { name: "Streaming",
id: interaction.guild.id value: "stream",
} },
}); ),
} catch (err) { ),
console.error(`\t⚠ | Cannot get the database connection!\n\t\t(${err}).`); ),
await interaction.reply({ async execute(interaction: CommandInteraction) {
content: `${emoji.answer.error} | Cannot connect to the database`, let guildData: Guild;
flags: MessageFlags.Ephemeral try {
}); guildData = await prisma.guild.findUnique({
return; where: {
} id: interaction.guild.id,
let userData: User; },
try { });
userData = await prisma.user.findUnique({ } catch (err) {
where: { console.error(
id: interaction.user.id `\t⚠ | Cannot get the database connection!\n\t\t(${err}).`,
} );
}); await interaction.reply({
} catch (err) { content: `${emoji.answer.error} | Cannot connect to the database`,
console.error(`\t⚠ | Cannot get the database connection!\n\t\t(${err}).`); flags: MessageFlags.Ephemeral,
await interaction.reply({ });
content: `${emoji.answer.error} | Cannot connect to the database`, return;
flags: MessageFlags.Ephemeral }
}); let userData: User;
return; try {
} userData = await prisma.user.findUnique({
const subcommand: string = interaction.options.getSubcommand(); where: {
switch (subcommand) { id: interaction.user.id,
case 'color': },
if (!userData.isOwner) { });
await interaction.reply({ } catch (err) {
content: `${emoji.answer.no} | This command is only for owner`, console.error(
flags: MessageFlags.Ephemeral `\t⚠ | Cannot get the database connection!\n\t\t(${err}).`,
}); );
return; await interaction.reply({
} content: `${emoji.answer.error} | Cannot connect to the database`,
const newColor: string = interaction.options.getString('color'); flags: MessageFlags.Ephemeral,
if (!/^#[0-9A-Fa-f]{6}$/.test(newColor)) { });
await interaction.reply({ return;
content: `${emoji.answer.no} | You have to give a color with the syntax: \`#000000\`.`, }
flags: MessageFlags.Ephemeral const subcommand: string = interaction.options.getSubcommand();
}); switch (subcommand) {
return; case "color":
} if (!userData.isOwner) {
await prisma.guild.upsert({ await interaction.reply({
where: { content: `${emoji.answer.no} | This command is only for owner`,
id: interaction.guild.id flags: MessageFlags.Ephemeral,
}, });
update: { return;
color: newColor }
}, const newColor: string = interaction.options.getString("color");
create: { if (!/^#[0-9A-Fa-f]{6}$/.test(newColor)) {
id: interaction.guild.id, await interaction.reply({
color: newColor content: `${emoji.answer.no} | You have to give a color with the syntax: \`#000000\`.`,
} flags: MessageFlags.Ephemeral,
}); });
await interaction.reply({ return;
content: `${emoji.answer.yes} | The default color for embed will be now changed by \`${newColor}\``, }
flags: MessageFlags.Ephemeral await prisma.guild.upsert({
}); where: {
return; id: interaction.guild.id,
case 'footer': },
if (!userData.isOwner) { update: {
await interaction.reply({ color: newColor,
content: `${emoji.answer.no} | This command is only for owner`, },
flags: MessageFlags.Ephemeral create: {
}); id: interaction.guild.id,
return; color: newColor,
} },
const newFooter: string = interaction.options.getString('text'); });
if (newFooter.length > 2048) { await interaction.reply({
await interaction.reply({ content: `${emoji.answer.yes} | The default color for embed will be now changed by \`${newColor}\``,
content: `${emoji.answer.no} | The maximum lenght for the footer is 2048`, flags: MessageFlags.Ephemeral,
flags: MessageFlags.Ephemeral });
}); return;
return; case "footer":
} if (!userData.isOwner) {
await prisma.guild.upsert({ await interaction.reply({
where: { content: `${emoji.answer.no} | This command is only for owner`,
id: interaction.guild.id flags: MessageFlags.Ephemeral,
}, });
update: { return;
footer: newFooter }
}, const newFooter: string = interaction.options.getString("text");
create: { if (newFooter.length > 2048) {
id: interaction.guild.id, await interaction.reply({
footer: newFooter content: `${emoji.answer.no} | The maximum lenght for the footer is 2048`,
} flags: MessageFlags.Ephemeral,
}); });
await interaction.reply({ return;
content: `${emoji.answer.yes} | The default footer for embed will be now changed by \`${newFooter}\`.`, }
flags: MessageFlags.Ephemeral await prisma.guild.upsert({
}); where: {
return; id: interaction.guild.id,
case 'pp': },
if (!userData.isBuyer) { update: {
await interaction.reply({ footer: newFooter,
content: `${emoji.answer.no} | This command is only for buyer`, },
flags: MessageFlags.Ephemeral create: {
}); id: interaction.guild.id,
return; footer: newFooter,
} },
const newPicture: string = interaction.options.getString('link'); });
try { await interaction.reply({
interaction.client.user.setAvatar(newPicture); content: `${emoji.answer.yes} | The default footer for embed will be now changed by \`${newFooter}\`.`,
} catch (err) { flags: MessageFlags.Ephemeral,
await interaction.reply({ });
content: `${emoji.answer.no} | Error during changing the bot profile picture`, return;
flags: MessageFlags.Ephemeral case "pp":
}); if (!userData.isBuyer) {
} await interaction.reply({
await interaction.reply({ content: `${emoji.answer.no} | This command is only for buyer`,
content: `${emoji.answer.yes} | The picture profile of the bot is now updated.`, flags: MessageFlags.Ephemeral,
flags: MessageFlags.Ephemeral });
}); return;
return; }
case 'status': const newPicture: string = interaction.options.getString("link");
if (!userData.isBuyer) { try {
await interaction.reply({ interaction.client.user.setAvatar(newPicture);
content: `${emoji.answer.no} | This command is only for buyer`, } catch (err) {
flags: MessageFlags.Ephemeral await interaction.reply({
}); content: `${emoji.answer.no} | Error during changing the bot profile picture`,
return; flags: MessageFlags.Ephemeral,
} });
const newStatus: string = interaction.options.getString('status'); }
const tmpType: string = interaction.options.getString('type'); await interaction.reply({
let newType: ActivityType; content: `${emoji.answer.yes} | The picture profile of the bot is now updated.`,
switch (tmpType) { flags: MessageFlags.Ephemeral,
case 'play': });
newType = ActivityType.Playing; return;
break; case "status":
case 'listen': if (!userData.isBuyer) {
newType = ActivityType.Listening; await interaction.reply({
break; content: `${emoji.answer.no} | This command is only for buyer`,
case 'watch': flags: MessageFlags.Ephemeral,
newType = ActivityType.Watching; });
break; return;
case 'stream': }
newType = ActivityType.Streaming; const newStatus: string = interaction.options.getString("status");
break; const tmpType: string = interaction.options.getString("type");
case 'competing': let newType: ActivityType;
newType = ActivityType.Competing; switch (tmpType) {
break; case "play":
} newType = ActivityType.Playing;
const tmpPresence: string = interaction.options.getString('presence'); break;
let newPresence: PresenceUpdateStatus; case "listen":
switch (tmpPresence) { newType = ActivityType.Listening;
case 'online': break;
newPresence = PresenceUpdateStatus.Online; case "watch":
break; newType = ActivityType.Watching;
case 'idle': break;
newPresence = PresenceUpdateStatus.Idle; case "stream":
break; newType = ActivityType.Streaming;
case 'dnd': break;
newPresence = PresenceUpdateStatus.DoNotDisturb; case "competing":
break; newType = ActivityType.Competing;
case 'invisible': break;
newPresence = PresenceUpdateStatus.Invisible; }
break; const tmpPresence: string = interaction.options.getString("presence");
} let newPresence: PresenceUpdateStatus;
try { switch (tmpPresence) {
await prisma.bot.upsert({ case "online":
where: { newPresence = PresenceUpdateStatus.Online;
id: 1 break;
}, case "idle":
update: { newPresence = PresenceUpdateStatus.Idle;
status: newStatus, break;
type: tmpType, case "dnd":
presence: newPresence newPresence = PresenceUpdateStatus.DoNotDisturb;
}, break;
create: { case "invisible":
id: 1, newPresence = PresenceUpdateStatus.Invisible;
status: newStatus, break;
type: tmpType, }
presence: newPresence try {
} await prisma.bot.upsert({
}); where: {
if (tmpType === 'steam') { id: 1,
interaction.client.user.setPresence({ },
status: newPresence, update: {
activities: [{ status: newStatus,
name: newStatus, type: tmpType,
type: newType, presence: newPresence,
url: 'https://twitch.tv/EniumRaphael' },
}] create: {
}); id: 1,
} else { status: newStatus,
interaction.client.user.setPresence({ type: tmpType,
status: newPresence, presence: newPresence,
activities: [{ },
name: newStatus, });
type: newType, if (tmpType === "steam") {
}] interaction.client.user.setPresence({
}); status: newPresence,
} activities: [
} catch (err) { {
await interaction.reply({ name: newStatus,
content: `${emoji.answer.no} | Cannot change the status\n\n\t${err}`, type: newType,
flags: MessageFlags.Ephemeral url: "https://twitch.tv/EniumRaphael",
}); },
return; ],
} });
await interaction.reply({ } else {
content: `${emoji.answer.yes} | The new activity is now \`${newStatus}\``, interaction.client.user.setPresence({
flags: MessageFlags.Ephemeral status: newPresence,
}); activities: [
return; {
} name: newStatus,
} type: newType,
} },
],
});
}
} catch (err) {
await interaction.reply({
content: `${emoji.answer.no} | Cannot change the status\n\n\t${err}`,
flags: MessageFlags.Ephemeral,
});
return;
}
await interaction.reply({
content: `${emoji.answer.yes} | The new activity is now \`${newStatus}\``,
flags: MessageFlags.Ephemeral,
});
return;
}
},
};

View file

@ -1,236 +1,252 @@
import { EmbedBuilder, userMention, MessageFlags, SlashCommandBuilder } from 'discord.js'; import {
import { prisma } from '../../lib/prisma.ts'; EmbedBuilder,
import emoji from '../../../assets/emoji.json' assert { type: "json" }; userMention,
MessageFlags,
SlashCommandBuilder,
} from "discord.js";
import { prisma } from "../../lib/prisma.ts";
import emoji from "../../../assets/emoji.json" assert { type: "json" };
export default { export default {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName('buyer') .setName("buyer")
.setDescription('Interact with the buyers') .setDescription("Interact with the buyers")
.addSubcommand(subcommand => subcommand .addSubcommand((subcommand) =>
.setName('add') subcommand
.setDescription('Add a user on the buyer list') .setName("add")
.addUserOption(option => .setDescription("Add a user on the buyer list")
option.setName('target') .addUserOption((option) =>
.setDescription('The user who will be added to the list') option
.setRequired(true) .setName("target")
) .setDescription("The user who will be added to the list")
) .setRequired(true),
.addSubcommand(subcommand => subcommand ),
.setName('delete') )
.setDescription('Delete a user on the buyer list') .addSubcommand((subcommand) =>
.addUserOption(option => subcommand
option.setName('target') .setName("delete")
.setDescription('The user who will be deleted to the list') .setDescription("Delete a user on the buyer list")
.setRequired(true) .addUserOption((option) =>
) option
) .setName("target")
.addSubcommand(subcommand => subcommand .setDescription("The user who will be deleted to the list")
.setName('list') .setRequired(true),
.setDescription('The list of the buyer') ),
), )
async execute(interaction: CommandInteraction) { .addSubcommand((subcommand) =>
const subcommand = interaction.options.getSubcommand(); subcommand.setName("list").setDescription("The list of the buyer"),
let userData: User; ),
try { async execute(interaction: CommandInteraction) {
userData = await prisma.user.findUnique({ const subcommand = interaction.options.getSubcommand();
where: { let userData: User;
id: interaction.user.id try {
} userData = await prisma.user.findUnique({
}); where: {
} catch (err) { id: interaction.user.id,
console.error(`\t⚠ | Cannot get the database connection!\n\t\t(${err}).`); },
await interaction.reply({ });
content: `${emoji.answer.error} | Cannot connect to the database`, } catch (err) {
flags: MessageFlags.Ephemeral console.error(
}); `\t⚠ | Cannot get the database connection!\n\t\t(${err}).`,
return; );
} await interaction.reply({
let guildData: Guild; content: `${emoji.answer.error} | Cannot connect to the database`,
try { flags: MessageFlags.Ephemeral,
guildData = await prisma.guild.findUnique({ });
where: { return;
id: interaction.guild.id }
} let guildData: Guild;
}); try {
} catch (err) { guildData = await prisma.guild.findUnique({
console.error(`\t⚠ | Cannot get the database connection!\n\t\t(${err}).`); where: {
await interaction.reply({ id: interaction.guild.id,
content: `${emoji.answer.error} | Cannot connect to the database`, },
flags: MessageFlags.Ephemeral });
}); } catch (err) {
return; console.error(
} `\t⚠ | Cannot get the database connection!\n\t\t(${err}).`,
const target: GuildMember = interaction.options.getUser('target') );
switch (subcommand) { await interaction.reply({
case 'add': content: `${emoji.answer.error} | Cannot connect to the database`,
if (!userData.isDev) { flags: MessageFlags.Ephemeral,
await interaction.reply({ });
content: `${emoji.answer.no} | This command is only for the developper of the bot`, return;
flags: MessageFlags.Ephemeral }
}); const target: GuildMember = interaction.options.getUser("target");
return; switch (subcommand) {
} case "add":
try { if (!userData.isDev) {
await prisma.bot.update({ await interaction.reply({
where: { content: `${emoji.answer.no} | This command is only for the developper of the bot`,
id: 1 flags: MessageFlags.Ephemeral,
}, });
data: { return;
buyers: { }
connect: { try {
id: target.id await prisma.bot.update({
} where: {
}, id: 1,
owners: { },
connect: { data: {
id: target.id buyers: {
} connect: {
} id: target.id,
} },
}); },
await prisma.user.upsert({ owners: {
where: { connect: {
id: target.id id: target.id,
}, },
update: { },
isBuyer: true, },
isOwner: true });
}, await prisma.user.upsert({
create: { where: {
id: target.id, id: target.id,
isBuyer: true, },
isOwner: true update: {
} isBuyer: true,
}); isOwner: true,
} catch (err) { },
console.error(`⚠️ | Error when adding ${target.username} to the buyer list`); create: {
await interaction.reply({ id: target.id,
content: `${emoji.answer.error} | Error when adding ${target.username} to the owner list`, isBuyer: true,
flags: MessageFlags.Ephemeral isOwner: true,
}); },
return; });
} } catch (err) {
await interaction.reply({ console.error(
content: `${emoji.answer.yes} | ${target.username} has been added to the buyer list`, `⚠️ | Error when adding ${target.username} to the buyer list`,
flags: MessageFlags.Ephemeral );
}); await interaction.reply({
return; content: `${emoji.answer.error} | Error when adding ${target.username} to the owner list`,
case 'delete': flags: MessageFlags.Ephemeral,
if (!userData.isDev) { });
await interaction.reply({ return;
content: `${emoji.answer.no} | This command is only for buyer`, }
flags: MessageFlags.Ephemeral await interaction.reply({
}); content: `${emoji.answer.yes} | ${target.username} has been added to the buyer list`,
return; flags: MessageFlags.Ephemeral,
} else if (interaction.user.id === target.id) { });
await interaction.reply({ return;
content: `${emoji.answer.no} | You cannot removing yourself from the buyer list`, case "delete":
flags: MessageFlags.Ephemeral if (!userData.isDev) {
}); await interaction.reply({
return; content: `${emoji.answer.no} | This command is only for buyer`,
} flags: MessageFlags.Ephemeral,
try { });
await prisma.bot.update({ return;
where: { } else if (interaction.user.id === target.id) {
id: 1 await interaction.reply({
}, content: `${emoji.answer.no} | You cannot removing yourself from the buyer list`,
data: { flags: MessageFlags.Ephemeral,
buyers: { });
disconnect: { return;
id: target.id }
} try {
}, await prisma.bot.update({
owners: { where: {
disconnect: { id: 1,
id: target.id },
} data: {
} buyers: {
} disconnect: {
}); id: target.id,
await prisma.user.upsert({ },
where: { },
id: target.id owners: {
}, disconnect: {
update: { id: target.id,
isBuyer: false, },
isOwner: false },
}, },
create: { });
id: target.id, await prisma.user.upsert({
isBuyer: false, where: {
isOwner: false id: target.id,
} },
}); update: {
} catch (err) { isBuyer: false,
console.error(`⚠️ | Error when removing ${target.username} to the username`); isOwner: false,
return; },
} create: {
await interaction.reply({ id: target.id,
content: `${emoji.answer.yes} | ${target.username} has been removing to the buyer list`, isBuyer: false,
flags: MessageFlags.Ephemeral isOwner: false,
}); },
return; });
case 'list': } catch (err) {
if (!userData.isBuyer) { console.error(
await interaction.reply({ `⚠️ | Error when removing ${target.username} to the username`,
content: `${emoji.answer.no} | This command is only for buyer`, );
flags: MessageFlags.Ephemeral return;
}); }
return; await interaction.reply({
} content: `${emoji.answer.yes} | ${target.username} has been removing to the buyer list`,
try { flags: MessageFlags.Ephemeral,
const bot = await prisma.bot.findUnique({ });
where: { return;
id: 1 case "list":
}, if (!userData.isBuyer) {
include: { await interaction.reply({
buyers: true content: `${emoji.answer.no} | This command is only for buyer`,
} flags: MessageFlags.Ephemeral,
}); });
return;
}
try {
const bot = await prisma.bot.findUnique({
where: {
id: 1,
},
include: {
buyers: true,
},
});
if (!bot || bot.buyers.length === 0) { if (!bot || bot.buyers.length === 0) {
await interaction.reply({ await interaction.reply({
content: `${emoji.answer.error} | There is no buyer registered.`, content: `${emoji.answer.error} | There is no buyer registered.`,
flags: MessageFlags.Ephemeral flags: MessageFlags.Ephemeral,
}); });
break; break;
} }
const buyerList = await Promise.all( const buyerList = await Promise.all(
bot.buyers.map(async (buyer) => { bot.buyers.map(async (buyer) => {
try { try {
const user = await interaction.client.users.fetch(buyer.id); const user = await interaction.client.users.fetch(buyer.id);
return `- ${user.username} (\`${user.id}\`)\n`; return `- ${user.username} (\`${user.id}\`)\n`;
} catch (err) { } catch (err) {
console.warn(`⚠️ | ${buyer.id} : ${err}`); console.warn(`⚠️ | ${buyer.id} : ${err}`);
return null; return null;
} }
}) }),
); );
const toSend: EmbedBuilder = new EmbedBuilder() const toSend: EmbedBuilder = new EmbedBuilder()
.setTitle(`${emoji.badge.buyer} | Buyer list`) .setTitle(`${emoji.badge.buyer} | Buyer list`)
.setColor(guildData.color) .setColor(guildData.color)
.setFooter({ .setFooter({
text: guildData.footer text: guildData.footer,
}) })
.setDescription(buyerList.filter(Boolean).join('')) .setDescription(buyerList.filter(Boolean).join(""));
await interaction.reply({ await interaction.reply({
embeds: [ embeds: [toSend],
toSend flags: MessageFlags.Ephemeral,
], });
flags: MessageFlags.Ephemeral } catch (err) {
}); console.error(
} catch (err) { `⚠️ | error when fetching infromation from the database: ${err}`,
console.error(`⚠️ | error when fetching infromation from the database: ${err}`); );
await interaction.reply({ await interaction.reply({
content: `${emoji.answer.error} | Cannot fetch the infromation of the database.`, content: `${emoji.answer.error} | Cannot fetch the infromation of the database.`,
flags: MessageFlags.Ephemeral flags: MessageFlags.Ephemeral,
}); });
return; return;
} }
break; break;
return; return;
} }
} },
} };

View file

@ -1,225 +1,241 @@
import { EmbedBuilder, userMention, MessageFlags, SlashCommandBuilder } from 'discord.js'; import {
import { prisma } from '../../lib/prisma.ts'; EmbedBuilder,
import emoji from '../../../assets/emoji.json' assert { type: "json" }; userMention,
MessageFlags,
SlashCommandBuilder,
} from "discord.js";
import { prisma } from "../../lib/prisma.ts";
import emoji from "../../../assets/emoji.json" assert { type: "json" };
export default { export default {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName('owner') .setName("owner")
.setDescription('Interact with the owners') .setDescription("Interact with the owners")
.addSubcommand(subcommand => subcommand .addSubcommand((subcommand) =>
.setName('add') subcommand
.setDescription('Add a user on the owner list') .setName("add")
.addUserOption(option => .setDescription("Add a user on the owner list")
option.setName('target') .addUserOption((option) =>
.setDescription('The user who will be added to the list') option
.setRequired(true) .setName("target")
) .setDescription("The user who will be added to the list")
) .setRequired(true),
.addSubcommand(subcommand => subcommand ),
.setName('delete') )
.setDescription('Delete a user on the owner list') .addSubcommand((subcommand) =>
.addUserOption(option => subcommand
option.setName('target') .setName("delete")
.setDescription('The user who will be deleted to the list') .setDescription("Delete a user on the owner list")
.setRequired(true) .addUserOption((option) =>
) option
) .setName("target")
.addSubcommand(subcommand => subcommand .setDescription("The user who will be deleted to the list")
.setName('list') .setRequired(true),
.setDescription('The list of the owner') ),
), )
async execute(interaction: CommandInteraction) { .addSubcommand((subcommand) =>
const subcommand = interaction.options.getSubcommand(); subcommand.setName("list").setDescription("The list of the owner"),
let userData: User; ),
try { async execute(interaction: CommandInteraction) {
userData = await prisma.user.findUnique({ const subcommand = interaction.options.getSubcommand();
where: { let userData: User;
id: interaction.user.id try {
} userData = await prisma.user.findUnique({
}); where: {
} catch (err) { id: interaction.user.id,
console.error(`\t⚠ | Cannot get the database connection!\n\t\t(${err}).`); },
await interaction.reply({ });
content: `${emoji.answer.error} | Cannot connect to the database`, } catch (err) {
flags: MessageFlags.Ephemeral console.error(
}); `\t⚠ | Cannot get the database connection!\n\t\t(${err}).`,
return; );
} await interaction.reply({
let guildData: Guild; content: `${emoji.answer.error} | Cannot connect to the database`,
try { flags: MessageFlags.Ephemeral,
guildData = await prisma.guild.findUnique({ });
where: { return;
id: interaction.guild.id }
} let guildData: Guild;
}); try {
} catch (err) { guildData = await prisma.guild.findUnique({
console.error(`\t⚠ | Cannot get the database connection!\n\t\t(${err}).`); where: {
await interaction.reply({ id: interaction.guild.id,
content: `${emoji.answer.error} | Cannot connect to the database`, },
flags: MessageFlags.Ephemeral });
}); } catch (err) {
return; console.error(
} `\t⚠ | Cannot get the database connection!\n\t\t(${err}).`,
const target: GuildMember = interaction.options.getUser('target') );
switch (subcommand) { await interaction.reply({
case 'add': content: `${emoji.answer.error} | Cannot connect to the database`,
if (!userData.isBuyer) { flags: MessageFlags.Ephemeral,
await interaction.reply({ });
content: `${emoji.answer.no} | This command is only for buyer`, return;
flags: MessageFlags.Ephemeral }
}); const target: GuildMember = interaction.options.getUser("target");
return; switch (subcommand) {
} case "add":
try { if (!userData.isBuyer) {
await prisma.bot.update({ await interaction.reply({
where: { content: `${emoji.answer.no} | This command is only for buyer`,
id: 1 flags: MessageFlags.Ephemeral,
}, });
data: { return;
owners: { }
connect: { try {
id: target.id await prisma.bot.update({
} where: {
} id: 1,
} },
}); data: {
await prisma.user.upsert({ owners: {
where: { connect: {
id: target.id id: target.id,
}, },
update: { },
isOwner: true },
}, });
create: { await prisma.user.upsert({
id: target.id, where: {
isOwner: true id: target.id,
} },
}); update: {
} catch (err) { isOwner: true,
console.error(`⚠️ | Error when adding ${target.username} to the username`); },
await interaction.reply({ create: {
content: `${emoji.answer.error} | Error when adding ${target.username} to the owner list`, id: target.id,
flags: MessageFlags.Ephemeral isOwner: true,
}); },
return; });
} } catch (err) {
await interaction.reply({ console.error(
content: `${emoji.answer.yes} | ${target.username} has been added to the owner list`, `⚠️ | Error when adding ${target.username} to the username`,
flags: MessageFlags.Ephemeral );
}); await interaction.reply({
return; content: `${emoji.answer.error} | Error when adding ${target.username} to the owner list`,
case 'delete': flags: MessageFlags.Ephemeral,
if (!userData.isBuyer) { });
await interaction.reply({ return;
content: `${emoji.answer.no} | This command is only for buyer`, }
flags: MessageFlags.Ephemeral await interaction.reply({
}); content: `${emoji.answer.yes} | ${target.username} has been added to the owner list`,
return; flags: MessageFlags.Ephemeral,
} else if (interaction.user.id === target.id) { });
await interaction.reply({ return;
content: `${emoji.answer.no} | You cannot removing yourself from the owner list`, case "delete":
flags: MessageFlags.Ephemeral if (!userData.isBuyer) {
}); await interaction.reply({
return; content: `${emoji.answer.no} | This command is only for buyer`,
} flags: MessageFlags.Ephemeral,
try { });
await prisma.bot.update({ return;
where: { } else if (interaction.user.id === target.id) {
id: 1 await interaction.reply({
}, content: `${emoji.answer.no} | You cannot removing yourself from the owner list`,
data: { flags: MessageFlags.Ephemeral,
owners: { });
disconnect: { return;
id: target.id }
} try {
} await prisma.bot.update({
} where: {
}); id: 1,
await prisma.user.upsert({ },
where: { data: {
id: target.id owners: {
}, disconnect: {
update: { id: target.id,
isOwner: false },
}, },
create: { },
id: target.id, });
isOwner: false await prisma.user.upsert({
} where: {
}); id: target.id,
} catch (err) { },
console.error(`⚠️ | Error when removing ${target.username} to the username`); update: {
await interaction.reply({ isOwner: false,
content: `${emoji.answer.error} | Cannot removing the user from the owner list`, },
flags: MessageFlags.Ephemeral create: {
}); id: target.id,
return; isOwner: false,
} },
await interaction.reply({ });
content: `${emoji.answer.yes} | ${target.username} has been removing to the owner list`, } catch (err) {
flags: MessageFlags.Ephemeral console.error(
}); `⚠️ | Error when removing ${target.username} to the username`,
return; );
case 'list': await interaction.reply({
if (!userData.isOwner) { content: `${emoji.answer.error} | Cannot removing the user from the owner list`,
await interaction.reply({ flags: MessageFlags.Ephemeral,
content: `${emoji.answer.no} | This command is only for owner`, });
flags: MessageFlags.Ephemeral return;
}); }
return; await interaction.reply({
} content: `${emoji.answer.yes} | ${target.username} has been removing to the owner list`,
try { flags: MessageFlags.Ephemeral,
const bot = await prisma.bot.findUnique({ });
where: { return;
id: 1 case "list":
}, if (!userData.isOwner) {
include: { await interaction.reply({
owners: true content: `${emoji.answer.no} | This command is only for owner`,
} flags: MessageFlags.Ephemeral,
}); });
return;
}
try {
const bot = await prisma.bot.findUnique({
where: {
id: 1,
},
include: {
owners: true,
},
});
if (!bot || bot.owners.length === 0) { if (!bot || bot.owners.length === 0) {
await interaction.reply({ await interaction.reply({
content: `${emoji.answer.error} | There is no owner registered.`, content: `${emoji.answer.error} | There is no owner registered.`,
flags: MessageFlags.Ephemeral flags: MessageFlags.Ephemeral,
}); });
break; break;
} }
const ownerList = await Promise.all( const ownerList = await Promise.all(
bot.owners.map(async (owner) => { bot.owners.map(async (owner) => {
try { try {
const user = await interaction.client.users.fetch(owner.id); const user = await interaction.client.users.fetch(owner.id);
return `- ${user.username} (\`${user.id}\`)\n`; return `- ${user.username} (\`${user.id}\`)\n`;
} catch (err) { } catch (err) {
console.warn(`⚠️ | ${owner.id} : ${err}`); console.warn(`⚠️ | ${owner.id} : ${err}`);
return null; return null;
} }
}) }),
); );
const toSend: EmbedBuilder = new EmbedBuilder() const toSend: EmbedBuilder = new EmbedBuilder()
.setTitle(`${emoji.badge.owner} | Owner list`) .setTitle(`${emoji.badge.owner} | Owner list`)
.setColor(guildData.color) .setColor(guildData.color)
.setFooter({ .setFooter({
text: guildData.footer text: guildData.footer,
}) })
.setDescription(ownerList.filter(Boolean).join('')) .setDescription(ownerList.filter(Boolean).join(""));
await interaction.reply({ await interaction.reply({
embeds: [ embeds: [toSend],
toSend flags: MessageFlags.Ephemeral,
], });
flags: MessageFlags.Ephemeral } catch (err) {
}); console.error(
} catch (err) { `⚠️ | error when fetching infromation from the database: ${err}`,
console.error(`⚠️ | error when fetching infromation from the database: ${err}`); );
await interaction.reply({ await interaction.reply({
content: `${emoji.answer.error} | Cannot fetch the infromation of the database.`, content: `${emoji.answer.error} | Cannot fetch the infromation of the database.`,
flags: MessageFlags.Ephemeral flags: MessageFlags.Ephemeral,
}); });
} }
break; break;
return; return;
} }
} },
} };

View file

@ -1,233 +1,249 @@
import { EmbedBuilder, userMention, MessageFlags, SlashCommandBuilder } from 'discord.js'; import {
import { prisma } from '../../lib/prisma.ts'; EmbedBuilder,
import emoji from '../../../assets/emoji.json' assert { type: "json" }; userMention,
MessageFlags,
SlashCommandBuilder,
} from "discord.js";
import { prisma } from "../../lib/prisma.ts";
import emoji from "../../../assets/emoji.json" assert { type: "json" };
export default { export default {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName('whitelist') .setName("whitelist")
.setDescription('Interact with the whitelist') .setDescription("Interact with the whitelist")
.addSubcommand(subcommand => subcommand .addSubcommand((subcommand) =>
.setName('add') subcommand
.setDescription('Add a user on the whitelist') .setName("add")
.addUserOption(option => .setDescription("Add a user on the whitelist")
option.setName('target') .addUserOption((option) =>
.setDescription('The user who will be added to the whitelist') option
.setRequired(true) .setName("target")
) .setDescription("The user who will be added to the whitelist")
) .setRequired(true),
.addSubcommand(subcommand => subcommand ),
.setName('delete') )
.setDescription('Delete a user on the whitelist') .addSubcommand((subcommand) =>
.addUserOption(option => subcommand
option.setName('target') .setName("delete")
.setDescription('The user who will be deleted to the whitelist') .setDescription("Delete a user on the whitelist")
.setRequired(true) .addUserOption((option) =>
) option
) .setName("target")
.addSubcommand(subcommand => subcommand .setDescription("The user who will be deleted to the whitelist")
.setName('list') .setRequired(true),
.setDescription('Show the whitelist') ),
), )
async execute(interaction: CommandInteraction) { .addSubcommand((subcommand) =>
const subcommand = interaction.options.getSubcommand(); subcommand.setName("list").setDescription("Show the whitelist"),
let userData: User; ),
try { async execute(interaction: CommandInteraction) {
userData = await prisma.user.findUnique({ const subcommand = interaction.options.getSubcommand();
where: { let userData: User;
id: interaction.user.id try {
} userData = await prisma.user.findUnique({
}); where: {
} catch (err) { id: interaction.user.id,
console.error(`\t⚠ | Whitelist => Cannot get the database connection!\n\t\t(${err}).`); },
await interaction.reply({ });
content: `${emoji.answer.error} | Cannot connect to the database`, } catch (err) {
flags: MessageFlags.Ephemeral console.error(
}); `\t⚠ | Whitelist => Cannot get the database connection!\n\t\t(${err}).`,
return; );
} await interaction.reply({
let guildData: Guild; content: `${emoji.answer.error} | Cannot connect to the database`,
try { flags: MessageFlags.Ephemeral,
guildData = await prisma.guild.findUnique({ });
where: { return;
id: interaction.guild.id }
} let guildData: Guild;
}); try {
} catch (err) { guildData = await prisma.guild.findUnique({
console.error(`\t⚠ | Cannot get the database connection!\n\t\t(${err}).`); where: {
await interaction.reply({ id: interaction.guild.id,
content: `${emoji.answer.error} | Cannot connect to the database`, },
flags: MessageFlags.Ephemeral });
}); } catch (err) {
return; console.error(
} `\t⚠ | Cannot get the database connection!\n\t\t(${err}).`,
const target: GuildMember = interaction.options.getUser('target') );
switch (subcommand) { await interaction.reply({
case 'add': content: `${emoji.answer.error} | Cannot connect to the database`,
if (!userData.isOwner) { flags: MessageFlags.Ephemeral,
await interaction.reply({ });
content: `${emoji.answer.no} | This command is only for owner`, return;
flags: MessageFlags.Ephemeral }
}); const target: GuildMember = interaction.options.getUser("target");
return; switch (subcommand) {
} case "add":
try { if (!userData.isOwner) {
await prisma.guildUser.upsert({ await interaction.reply({
where: { content: `${emoji.answer.no} | This command is only for owner`,
userId_guildId: { flags: MessageFlags.Ephemeral,
userId: target.id, });
guildId: interaction.guild.id return;
} }
}, try {
update: { await prisma.guildUser.upsert({
isWlUser: true where: {
}, userId_guildId: {
create: { userId: target.id,
userId: target.id, guildId: interaction.guild.id,
guildId: interaction.guild.id, },
isWlUser: true },
} update: {
}); isWlUser: true,
await prisma.guild.update({ },
where: { create: {
id: interaction.guild.id userId: target.id,
}, guildId: interaction.guild.id,
data: { isWlUser: true,
WlUsers: { },
connect: { });
id: target.id await prisma.guild.update({
} where: {
} id: interaction.guild.id,
} },
}); data: {
} catch (err) { WlUsers: {
console.error(`⚠️ | Error when adding ${target.username} to the whitelist\n\t${err}`); connect: {
await interaction.reply({ id: target.id,
content: `${emoji.answer.error} | Error when adding ${target.username} to the whitelist`, },
flags: MessageFlags.Ephemeral },
}); },
return; });
} } catch (err) {
await interaction.reply({ console.error(
content: `${emoji.answer.yes} | ${target.username} has been added to the whitelist`, `⚠️ | Error when adding ${target.username} to the whitelist\n\t${err}`,
flags: MessageFlags.Ephemeral );
}); await interaction.reply({
return; content: `${emoji.answer.error} | Error when adding ${target.username} to the whitelist`,
case 'delete': flags: MessageFlags.Ephemeral,
if (!userData.isOwner) { });
await interaction.reply({ return;
content: `${emoji.answer.no} | This command is only for owner`, }
flags: MessageFlags.Ephemeral await interaction.reply({
}); content: `${emoji.answer.yes} | ${target.username} has been added to the whitelist`,
return; flags: MessageFlags.Ephemeral,
} else if (interaction.user.id === target.id) { });
await interaction.reply({ return;
content: `${emoji.answer.no} | You cannot removing yourself from the whitelist`, case "delete":
flags: MessageFlags.Ephemeral if (!userData.isOwner) {
}); await interaction.reply({
return; content: `${emoji.answer.no} | This command is only for owner`,
} flags: MessageFlags.Ephemeral,
try { });
await prisma.guildUser.upsert({ return;
where: { } else if (interaction.user.id === target.id) {
userId_guildId: { await interaction.reply({
userId: target.id, content: `${emoji.answer.no} | You cannot removing yourself from the whitelist`,
guildId: interaction.guild.id flags: MessageFlags.Ephemeral,
} });
}, return;
update: { }
isWlUser: false try {
}, await prisma.guildUser.upsert({
create: { where: {
userId: target.id, userId_guildId: {
guildId: interaction.guild.id, userId: target.id,
isWlUser: false guildId: interaction.guild.id,
} },
}); },
await prisma.guild.update({ update: {
where: { isWlUser: false,
id: interaction.guild.id },
}, create: {
data: { userId: target.id,
WlUsers: { guildId: interaction.guild.id,
disconnect: { isWlUser: false,
id: target.id },
} });
} await prisma.guild.update({
} where: {
}); id: interaction.guild.id,
} catch (err) { },
console.error(`⚠️ | Error when removing ${target.username} to the username\n\t${err}`); data: {
await interaction.reply({ WlUsers: {
content: `${emoji.answer.error} | Cannot remove ${target.username} from the whitelist`, disconnect: {
flags: MessageFlags.Ephemeral id: target.id,
}); },
return; },
} },
await interaction.reply({ });
content: `${emoji.answer.yes} | ${target.username} has been removing to the whitelist`, } catch (err) {
flags: MessageFlags.Ephemeral console.error(
}); `⚠️ | Error when removing ${target.username} to the username\n\t${err}`,
return; );
case 'list': await interaction.reply({
if (!userData.isOwner) { content: `${emoji.answer.error} | Cannot remove ${target.username} from the whitelist`,
await interaction.reply({ flags: MessageFlags.Ephemeral,
content: `${emoji.answer.no} | This command is only for owner`, });
flags: MessageFlags.Ephemeral return;
}); }
return; await interaction.reply({
} content: `${emoji.answer.yes} | ${target.username} has been removing to the whitelist`,
try { flags: MessageFlags.Ephemeral,
const guild = await prisma.guild.findUnique({ });
where: { return;
id: interaction.guild.id case "list":
}, if (!userData.isOwner) {
include: { await interaction.reply({
WlUsers: true content: `${emoji.answer.no} | This command is only for owner`,
} flags: MessageFlags.Ephemeral,
}); });
return;
}
try {
const guild = await prisma.guild.findUnique({
where: {
id: interaction.guild.id,
},
include: {
WlUsers: true,
},
});
if (!guild || guild.WlUsers.length === 0) { if (!guild || guild.WlUsers.length === 0) {
await interaction.reply({ await interaction.reply({
content: `${emoji.answer.error} | There is no whitelisted user.`, content: `${emoji.answer.error} | There is no whitelisted user.`,
flags: MessageFlags.Ephemeral flags: MessageFlags.Ephemeral,
}); });
break; break;
} }
const WlUsers = await Promise.all( const WlUsers = await Promise.all(
guild.WlUsers.map(async (whitelist) => { guild.WlUsers.map(async (whitelist) => {
try { try {
const user = await interaction.client.users.fetch(whitelist.id); const user = await interaction.client.users.fetch(whitelist.id);
return `- ${user.username} (\`${user.id}\`)\n`; return `- ${user.username} (\`${user.id}\`)\n`;
} catch (err) { } catch (err) {
console.warn(`⚠️ | ${whitelist.id} : ${err}`); console.warn(`⚠️ | ${whitelist.id} : ${err}`);
return null; return null;
} }
}) }),
); );
const toSend: EmbedBuilder = new EmbedBuilder() const toSend: EmbedBuilder = new EmbedBuilder()
.setTitle(`🗞️ | Whitelist`) .setTitle(`🗞️ | Whitelist`)
.setColor(guildData.color) .setColor(guildData.color)
.setFooter({ .setFooter({
text: guildData.footer text: guildData.footer,
}) })
.setDescription(WlUsers.filter(Boolean).join('')) .setDescription(WlUsers.filter(Boolean).join(""));
await interaction.reply({ await interaction.reply({
embeds: [ embeds: [toSend],
toSend flags: MessageFlags.Ephemeral,
], });
flags: MessageFlags.Ephemeral } catch (err) {
}); console.error(
} catch (err) { `⚠️ | Whitelist => error when fetching infromation from the database: ${err}`,
console.error(`⚠️ | Whitelist => error when fetching infromation from the database: ${err}`); );
await interaction.reply({ await interaction.reply({
content: `${emoji.answer.error} | Cannot fetch the infromation of the database.`, content: `${emoji.answer.error} | Cannot fetch the infromation of the database.`,
flags: MessageFlags.Ephemeral flags: MessageFlags.Ephemeral,
}); });
} }
break; break;
return; return;
} }
} },
} };

View file

@ -1,58 +1,75 @@
import { MessageFlags, ChatInputCommandInteraction, CategoryChannel, ChannelType, PermissionsBitField, SlashCommandBuilder } from 'discord.js'; import {
import emoji from '../../../assets/emoji.json' assert { type: "json" }; MessageFlags,
import { prisma } from '../../lib/prisma.ts'; ChatInputCommandInteraction,
CategoryChannel,
ChannelType,
PermissionsBitField,
SlashCommandBuilder,
} from "discord.js";
import emoji from "../../../assets/emoji.json" assert { type: "json" };
import { prisma } from "../../lib/prisma.ts";
export default { export default {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName('deletecat') .setName("deletecat")
.setDescription('Delete the categorie given in parameter') .setDescription("Delete the categorie given in parameter")
.addChannelOption(opt => opt .addChannelOption((opt) =>
.setName('category') opt
.setDescription('Choose the categorie you want to delete') .setName("category")
.setRequired(true) .setDescription("Choose the categorie you want to delete")
.addChannelTypes(ChannelType.GuildCategory) .setRequired(true)
), .addChannelTypes(ChannelType.GuildCategory),
async execute(interaction: CommandInteraction) { ),
let userData: User; async execute(interaction: CommandInteraction) {
try { let userData: User;
userData = await prisma.user.findUnique({ try {
where: { userData = await prisma.user.findUnique({
id: interaction.user.id where: {
} id: interaction.user.id,
}); },
} catch (err) { });
console.error(`\t⚠ | Whitelist => Cannot get the database connection!\n\t\t(${err}).`); } catch (err) {
await interaction.reply({ console.error(
content: `${emoji.answer.error} | Cannot connect to the database`, `\t⚠ | Whitelist => Cannot get the database connection!\n\t\t(${err}).`,
flags: MessageFlags.Ephemeral );
}); await interaction.reply({
console.error(`Cannot connect to the database:\n\t${err}`); content: `${emoji.answer.error} | Cannot connect to the database`,
return; flags: MessageFlags.Ephemeral,
} });
if (!userData.isOwner) { console.error(`Cannot connect to the database:\n\t${err}`);
await interaction.reply({ return;
content: `${emoji.answer.no} | This command is only for owner`, }
flags: MessageFlags.Ephemeral if (!userData.isOwner) {
}); await interaction.reply({
return; content: `${emoji.answer.no} | This command is only for owner`,
} flags: MessageFlags.Ephemeral,
const category: GuildCategory = interaction.options.getChannel('category', true); });
try { return;
for (const channel of category.children.cache.values()) { }
await channel.delete(`Delete cat of ${channel.name} (by ${interaction.username})`); const category: GuildCategory = interaction.options.getChannel(
} "category",
await category.delete(`Delete cat of ${category.name} (by ${interaction.username})`); true,
await interaction.reply({ );
content: `${emoji.answer.yes} | Suppressed the ${category.name}`, try {
flags: MessageFlags.Ephemeral for (const channel of category.children.cache.values()) {
}); await channel.delete(
} catch (err) { `Delete cat of ${channel.name} (by ${interaction.username})`,
await interaction.reply({ );
content: `${emoji.answer.error} | Cannot suppress the category's channels`, }
flags: MessageFlags.Ephemeral await category.delete(
}); `Delete cat of ${category.name} (by ${interaction.username})`,
console.error(`Cannot suppress the category's channel:\n\t${err}`); );
return; await interaction.reply({
} content: `${emoji.answer.yes} | Suppressed the ${category.name}`,
} flags: MessageFlags.Ephemeral,
} });
} catch (err) {
await interaction.reply({
content: `${emoji.answer.error} | Cannot suppress the category's channels`,
flags: MessageFlags.Ephemeral,
});
console.error(`Cannot suppress the category's channel:\n\t${err}`);
return;
}
},
};

View file

@ -1,122 +1,136 @@
import { prisma } from '../../lib/prisma.ts'; import { prisma } from "../../lib/prisma.ts";
import { userMention, roleMention, MessageFlags, SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import {
import emoji from '../../../assets/emoji.json' assert { type: "json" }; userMention,
roleMention,
MessageFlags,
SlashCommandBuilder,
EmbedBuilder,
} from "discord.js";
import emoji from "../../../assets/emoji.json" assert { type: "json" };
function getGuildRoles(guild: Guild): string { function getGuildRoles(guild: Guild): string {
const roles = guild.roles.cache const roles = guild.roles.cache
.filter(role => role.id !== guild.id) .filter((role) => role.id !== guild.id)
.sort((a, b) => b.position - a.position) .sort((a, b) => b.position - a.position)
.map(role => roleMention(role.id)); .map((role) => roleMention(role.id));
return roles.length > 0 ? roles.join(', ') : 'No role'; return roles.length > 0 ? roles.join(", ") : "No role";
} }
function getUserRoles(target: GuildMember): string { function getUserRoles(target: GuildMember): string {
const roles = target.roles.cache const roles = target.roles.cache
.filter(role => role.id !== target.guild.id) .filter((role) => role.id !== target.guild.id)
.sort((a, b) => b.position - a.position) .sort((a, b) => b.position - a.position)
.map(role => `${roleMention(role.id)}`); .map((role) => `${roleMention(role.id)}`);
return roles.length > 0 ? roles.join(', ') : 'No role'; return roles.length > 0 ? roles.join(", ") : "No role";
} }
function getUserBadges(userData: { function getUserBadges(userData: {
isDev?: boolean; isDev?: boolean;
isEnium?: boolean; isEnium?: boolean;
isBuyer?: boolean; isBuyer?: boolean;
isOwner?: boolean; isOwner?: boolean;
}): string { }): string {
const badges: string[] = []; const badges: string[] = [];
if (userData.isDev) if (userData.isDev) badges.push(`${emoji.badge.dev}`);
badges.push(`${emoji.badge.dev}`); if (userData.isEnium) badges.push(`${emoji.badge.enium}`);
if (userData.isEnium) if (userData.isPwn) badges.push(`${emoji.badge.dash}`);
badges.push(`${emoji.badge.enium}`); if (userData.isBuyer) badges.push(`${emoji.badge.buyer}`);
if (userData.isPwn) if (userData.isOwner) badges.push(`${emoji.badge.owner}`);
badges.push(`${emoji.badge.dash}`);
if (userData.isBuyer)
badges.push(`${emoji.badge.buyer}`);
if (userData.isOwner)
badges.push(`${emoji.badge.owner}`);
return badges.length > 0 ? badges.join(" ") : "Aucun badge"; return badges.length > 0 ? badges.join(" ") : "Aucun badge";
} }
export default { export default {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName('info') .setName("info")
.setDescription('Show the infromation of one of these categories (user, server, bot)') .setDescription(
.addSubcommand(subcommand => subcommand "Show the infromation of one of these categories (user, server, bot)",
.setName('user') )
.setDescription('Show the infromation of one user') .addSubcommand((subcommand) =>
.addUserOption(option => subcommand
option.setName('target') .setName("user")
.setDescription('The user to show the infromation') .setDescription("Show the infromation of one user")
) .addUserOption((option) =>
) option
.addSubcommand(subcommand => subcommand .setName("target")
.setName('server') .setDescription("The user to show the infromation"),
.setDescription('Show the infromation of the server') ),
), )
async execute(interaction: CommandInteraction) { .addSubcommand((subcommand) =>
let guildData: Guild; subcommand
try { .setName("server")
guildData = await prisma.guild.findUnique({ .setDescription("Show the infromation of the server"),
where: { ),
id: interaction.guild.id async execute(interaction: CommandInteraction) {
} let guildData: Guild;
}); try {
} catch (err) { guildData = await prisma.guild.findUnique({
console.error(`\t⚠ | Cannot get the database connection!\n\t\t(${err}).`); where: {
await interaction.reply({ id: interaction.guild.id,
content: `${emoji.answer.error} | Cannot connect to the database`, },
flags: MessageFlags.Ephemeral });
}); } catch (err) {
return; console.error(
} `\t⚠ | Cannot get the database connection!\n\t\t(${err}).`,
const subcommand: string = interaction.options.getSubcommand(); );
switch (subcommand) { await interaction.reply({
case 'user': content: `${emoji.answer.error} | Cannot connect to the database`,
const targetGlobal: GuildMember = interaction.options.getUser('target') || interaction.user; flags: MessageFlags.Ephemeral,
await targetGlobal.fetch(); });
let userData: User; return;
try { }
userData = await prisma.user.findUnique({ const subcommand: string = interaction.options.getSubcommand();
where: { switch (subcommand) {
id: targetGlobal.id case "user":
} const targetGlobal: GuildMember =
}); interaction.options.getUser("target") || interaction.user;
} catch (err) { await targetGlobal.fetch();
console.error(`\t⚠ | Cannot get the database connection!\n\t\t(${err}).`); let userData: User;
await interaction.reply({ try {
content: `${emoji.answer.error} | Cannot connect to the database`, userData = await prisma.user.findUnique({
flags: MessageFlags.Ephemeral where: {
}); id: targetGlobal.id,
} },
let targetServer: GuildMember; });
} catch (err) {
try { console.error(
targetServer = await interaction.guild.members.fetch(targetGlobal.id); `\t⚠ | Cannot get the database connection!\n\t\t(${err}).`,
} catch (err) { );
console.error(`\t⚠ | Cannot get the targetServer!\n\t\t(${err}).`); await interaction.reply({
await interaction.reply({ content: `${emoji.answer.error} | Cannot connect to the database`,
content: `${emoji.answer.error} | Cannot get the guild profile of the user`, flags: MessageFlags.Ephemeral,
flags: MessageFlags.Ephemeral });
}); }
return; let targetServer: GuildMember;
}
const userResult: EmbedBuilder = new EmbedBuilder() try {
.setTitle(`${targetGlobal.displayName}'s information`) targetServer = await interaction.guild.members.fetch(targetGlobal.id);
.setColor(`${guildData.color}`) } catch (err) {
.setThumbnail(`${targetGlobal.displayAvatarURL({dynamic: true, size: 2048})}`) console.error(`\t⚠ | Cannot get the targetServer!\n\t\t(${err}).`);
.setFooter({ await interaction.reply({
text: guildData.footer content: `${emoji.answer.error} | Cannot get the guild profile of the user`,
}) flags: MessageFlags.Ephemeral,
.setImage(targetGlobal.bannerURL({ });
size: 2048, return;
dynamic: true }
})) const userResult: EmbedBuilder = new EmbedBuilder()
.setDescription(` .setTitle(`${targetGlobal.displayName}'s information`)
.setColor(`${guildData.color}`)
.setThumbnail(
`${targetGlobal.displayAvatarURL({ dynamic: true, size: 2048 })}`,
)
.setFooter({
text: guildData.footer,
})
.setImage(
targetGlobal.bannerURL({
size: 2048,
dynamic: true,
}),
).setDescription(`
**👤 | Username:** **👤 | Username:**
${targetGlobal.username} ${targetGlobal.username}
**🆔 | ID:** **🆔 | ID:**
@ -131,25 +145,23 @@ export default {
<t:${parseInt(targetGlobal.createdTimestamp / 1000)}:f> (<t:${parseInt(targetGlobal.createdTimestamp / 1000)}:R>) <t:${parseInt(targetGlobal.createdTimestamp / 1000)}:f> (<t:${parseInt(targetGlobal.createdTimestamp / 1000)}:R>)
**🛬 | Server Join:** **🛬 | Server Join:**
<t:${parseInt(targetServer.joinedTimestamp / 1000)}:f> (<t:${parseInt(targetServer.joinedTimestamp / 1000)}:R>) <t:${parseInt(targetServer.joinedTimestamp / 1000)}:f> (<t:${parseInt(targetServer.joinedTimestamp / 1000)}:R>)
`) `);
await interaction.reply({ await interaction.reply({
embeds: [ embeds: [userResult],
userResult flags: MessageFlags.Ephemeral,
], });
flags: MessageFlags.Ephemeral return;
}); case "server":
return; const guild: Guild = interaction.guild;
case 'server': const serverResult: EmbedBuilder = new EmbedBuilder()
const guild: Guild = interaction.guild; .setTitle(`${guild.name} Informations`)
const serverResult: EmbedBuilder = new EmbedBuilder() .setColor(guildData.color)
.setTitle(`${guild.name} Informations`) .setThumbnail(guild.iconURL({ dynamic: true, size: 2048 }))
.setColor(guildData.color) .setFooter({
.setThumbnail(guild.iconURL({dynamic: true, size: 2048})) text: guildData.footer,
.setFooter({ })
text: guildData.footer .setImage(guild.bannerURL({ dynamic: true, size: 2048 }))
}) .setDescription(`
.setImage(guild.bannerURL({dynamic: true, size: 2048}))
.setDescription(`
**🆔 | ID:** **🆔 | ID:**
${guild.id} ${guild.id}
@ -173,13 +185,11 @@ export default {
**🏅 | Roles:** **🏅 | Roles:**
There is ${guild.roles.cache.size - 1} on __${guild.name}__ There is ${guild.roles.cache.size - 1} on __${guild.name}__
${getGuildRoles(guild)} ${getGuildRoles(guild)}
`) `);
await interaction.reply({ await interaction.reply({
embeds: [ embeds: [serverResult],
serverResult flags: MessageFlags.Ephemeral,
], });
flags: MessageFlags.Ephemeral }
}); },
} };
}
}

View file

@ -1,19 +1,19 @@
import { MessageFlags, SlashCommandBuilder } from 'discord.js'; import { MessageFlags, SlashCommandBuilder } from "discord.js";
import emoji from '../../../assets/emoji.json' assert { type: "json" }; import emoji from "../../../assets/emoji.json" assert { type: "json" };
export default { export default {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName('ping') .setName("ping")
.setDescription('Show your latency'), .setDescription("Show your latency"),
async execute(interaction: CommandInteraction) { async execute(interaction: CommandInteraction) {
const time: number = Date.now(); const time: number = Date.now();
await interaction.reply({ await interaction.reply({
content: `${emoji.answer.loading} | Calculating your ping !`, content: `${emoji.answer.loading} | Calculating your ping !`,
flags: MessageFlags.Ephemeral flags: MessageFlags.Ephemeral,
}); });
await interaction.editReply({ await interaction.editReply({
content: `⏱️ | Response latency: **${Date.now() - time}**ms` content: `⏱️ | Response latency: **${Date.now() - time}**ms`,
}); });
} },
} };

View file

@ -1,55 +1,57 @@
import { Events, MessageFlags } from 'discord.js' import { Events, MessageFlags } from "discord.js";
import { prisma } from '../../lib/prisma.ts'; import { prisma } from "../../lib/prisma.ts";
export default { export default {
name: Events.GuildCreate, name: Events.GuildCreate,
async execute(guild, client) { async execute(guild, client) {
const botData = await prisma.bot.findUnique({ const botData = await prisma.bot.findUnique({
where: { where: {
id: 1 id: 1,
}, },
include: { include: {
buyers: true buyers: true,
} },
}); });
await prisma.guild.upsert({ await prisma.guild.upsert({
where: { where: {
id: guild.id id: guild.id,
}, },
update: {}, update: {},
create: { create: {
id: guild.id id: guild.id,
} },
}); });
const members = await guild.members.fetch(); const members = await guild.members.fetch();
let i = 0; let i = 0;
for (const [memberId, member] of members) { for (const [memberId, member] of members) {
await prisma.user.upsert({ await prisma.user.upsert({
where: { where: {
id: memberId id: memberId,
}, },
update: {}, update: {},
create: { create: {
id: memberId id: memberId,
} },
}); });
await prisma.guildUser.upsert({ await prisma.guildUser.upsert({
where: { where: {
userId_guildId: { userId_guildId: {
userId: memberId, userId: memberId,
guildId: guild.id guildId: guild.id,
} },
}, },
update: {}, update: {},
create: { create: {
userId: memberId, userId: memberId,
guildId: guild.id guildId: guild.id,
} },
}); });
i++; i++;
} }
console.log(`✅ | Guild ${guild.name} synchronisée avec ${members.size} membres.`); console.log(
} `✅ | Guild ${guild.name} synchronisée avec ${members.size} membres.`,
} );
},
};

View file

@ -1,75 +1,81 @@
import { ActivityType, PresenceUpdateStatus, Events } from 'discord.js' import { ActivityType, PresenceUpdateStatus, Events } from "discord.js";
import { prisma } from '../../lib/prisma.ts'; import { prisma } from "../../lib/prisma.ts";
export default { export default {
name: Events.ClientReady, name: Events.ClientReady,
once: true, once: true,
async execute(client) { async execute(client) {
try { try {
let botData: Bot; let botData: Bot;
botData = await prisma.bot.findUnique({ botData = await prisma.bot.findUnique({
where: { where: {
id: 1 id: 1,
} },
}); });
const newStatus: string = botData.status; const newStatus: string = botData.status;
const tmpType: string = botData.type; const tmpType: string = botData.type;
let newType: ActivityType; let newType: ActivityType;
switch (tmpType) { switch (tmpType) {
case 'play': case "play":
newType = ActivityType.Playing; newType = ActivityType.Playing;
break; break;
case 'listen': case "listen":
newType = ActivityType.Listening; newType = ActivityType.Listening;
break; break;
case 'watch': case "watch":
newType = ActivityType.Watching; newType = ActivityType.Watching;
break; break;
case 'stream': case "stream":
newType = ActivityType.Streaming; newType = ActivityType.Streaming;
break; break;
case 'comptet': case "comptet":
newType = ActivityType.Competing; newType = ActivityType.Competing;
break; break;
} }
const tmpPresence: string = botData.presence const tmpPresence: string = botData.presence;
let newPresence: PresenceUpdateStatus; let newPresence: PresenceUpdateStatus;
switch (tmpPresence) { switch (tmpPresence) {
case 'online': case "online":
newPresence = PresenceUpdateStatus.Online; newPresence = PresenceUpdateStatus.Online;
break; break;
case 'idle': case "idle":
newPresence = PresenceUpdateStatus.Idle; newPresence = PresenceUpdateStatus.Idle;
break; break;
case 'dnd': case "dnd":
newPresence = PresenceUpdateStatus.DoNotDisturb; newPresence = PresenceUpdateStatus.DoNotDisturb;
break; break;
case 'invisible': case "invisible":
newPresence = PresenceUpdateStatus.Invisible; newPresence = PresenceUpdateStatus.Invisible;
break; break;
} }
if (botData.type === 'steam') { if (botData.type === "steam") {
client.user.setPresence({ client.user.setPresence({
status: newPresence, status: newPresence,
activities: [{ activities: [
name: newStatus, {
type: newType, name: newStatus,
url: 'https://twich.tv/EniumRaphael' type: newType,
}] url: "https://twich.tv/EniumRaphael",
}); },
} else { ],
client.user.setPresence({ });
status: newPresence, } else {
activities: [{ client.user.setPresence({
name: newStatus, status: newPresence,
type: newType, activities: [
}] {
}); name: newStatus,
} type: newType,
} catch (err) { },
console.error(`\t⚠ | Cannot get the database connection!\n\t\t(${err}).`); ],
return; });
} }
console.log(`✅ | ${client.user.username} is now running under TTS bot`); } catch (err) {
}, console.error(
`\t⚠ | Cannot get the database connection!\n\t\t(${err}).`,
);
return;
}
console.log(`✅ | ${client.user.username} is now running under TTS bot`);
},
}; };

View file

@ -1,35 +1,36 @@
import { Events, MessageFlags } from 'discord.js' import { Events, MessageFlags } from "discord.js";
import emoji from '../../../assets/emoji.json' assert { type: "json" }; import emoji from "../../../assets/emoji.json" assert { type: "json" };
export default { export default {
name: Events.InteractionCreate, name: Events.InteractionCreate,
async execute(interaction) { async execute(interaction) {
if (!interaction.isChatInputCommand()) if (!interaction.isChatInputCommand()) return;
return; const command = interaction.client.commands.get(interaction.commandName);
const command = interaction.client.commands.get(interaction.commandName); if (!command) {
if (!command) { console.error(`⚠️ | Can't execute ${interaction.commandName}`);
console.error(`⚠️ | Can't execute ${interaction.commandName}`); await interaction.reply({
await interaction.reply({ content: `${emoji.answer.error} | Cannot execute the command ${interaction.commandName}`,
content: `${emoji.answer.error} | Cannot execute the command ${interaction.commandName}`, flags: MessageFlags.Ephemeral,
flags: MessageFlags.Ephemeral });
}); return;
return; }
} try {
try { await command.execute(interaction);
await command.execute(interaction); } catch (error) {
} catch (error) { console.error(
console.error(`⚠️ | Error when occured this command ${interaction.commandName}\n\t${error}`); `⚠️ | Error when occured this command ${interaction.commandName}\n\t${error}`,
if (interaction.replied || interaction.deferred) { );
await interaction.followUp({ if (interaction.replied || interaction.deferred) {
content: `${emoji.answer.error} | ${interaction.commandName} seems have a problem, thanks report that to the support (After Print)`, await interaction.followUp({
flags: MessageFlags.Ephemeral content: `${emoji.answer.error} | ${interaction.commandName} seems have a problem, thanks report that to the support (After Print)`,
}); flags: MessageFlags.Ephemeral,
} else { });
await interaction.reply({ } else {
content: `${emoji.answer.error} | ${interaction.commandName} seems have a problem, thanks report that to the support (Before Print)`, await interaction.reply({
flags: MessageFlags.Ephemeral content: `${emoji.answer.error} | ${interaction.commandName} seems have a problem, thanks report that to the support (Before Print)`,
}); flags: MessageFlags.Ephemeral,
} });
} }
}, }
},
}; };

View file

@ -1,128 +1,130 @@
import fs from 'node:fs' import fs from "node:fs";
import path from 'node:path' import path from "node:path";
import 'dotenv/config'; import "dotenv/config";
import { Client, Collection, GatewayIntentBits } from 'discord.js'; import { Client, Collection, GatewayIntentBits } from "discord.js";
import { PrismaClient } from '@prisma/client'; import { PrismaClient } from "@prisma/client";
import { deployCommands } from './internal/deploy-commands.ts'; import { deployCommands } from "./internal/deploy-commands.ts";
const prisma = new PrismaClient(); const prisma = new PrismaClient();
const client = new Client({ const client = new Client({
intents: [ intents: [
GatewayIntentBits.Guilds, GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent, GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildMembers,
], ],
}); });
client.login(process.env.DSC_TOKEN); client.login(process.env.DSC_TOKEN);
client.commands = new Collection(); client.commands = new Collection();
const commandFolderPath = path.join(__dirname, 'commands'); const commandFolderPath = path.join(__dirname, "commands");
const commandFolders = fs.readdirSync(commandFolderPath); const commandFolders = fs.readdirSync(commandFolderPath);
console.log(`\n🔍 | Commands search:`) console.log(`\n🔍 | Commands search:`);
for (const folder of commandFolders) { for (const folder of commandFolders) {
const commandsPath = path.join(commandFolderPath, folder); const commandsPath = path.join(commandFolderPath, folder);
const commandFiles = fs const commandFiles = fs
.readdirSync(commandsPath) .readdirSync(commandsPath)
.filter(file => file.endsWith('.js') || file.endsWith('.ts')); .filter((file) => file.endsWith(".js") || file.endsWith(".ts"));
for (const file of commandFiles) { for (const file of commandFiles) {
const fullCommandPath = path.join(commandsPath, file); const fullCommandPath = path.join(commandsPath, file);
try { try {
const commandModule = await import(fullCommandPath); const commandModule = await import(fullCommandPath);
const command = commandModule.default || commandModule; const command = commandModule.default || commandModule;
if ('data' in command && 'execute' in command) { if ("data" in command && "execute" in command) {
client.commands.set(command.data.name, command); client.commands.set(command.data.name, command);
console.log(`\t✅ | ${command.data.name}`); console.log(`\t✅ | ${command.data.name}`);
} }
} catch (err) { } catch (err) {
console.error(`\t⚠ | Command at ${file}\n\t\t(${err}).`); console.error(`\t⚠ | Command at ${file}\n\t\t(${err}).`);
} }
} }
} }
console.log('\n\n'); console.log("\n\n");
const eventFolderPath = path.join(__dirname, 'events'); const eventFolderPath = path.join(__dirname, "events");
const eventFolders = fs.readdirSync(eventFolderPath); const eventFolders = fs.readdirSync(eventFolderPath);
console.log(`\n🔍 | Events search:`) console.log(`\n🔍 | Events search:`);
for (const folder of eventFolders) { for (const folder of eventFolders) {
const eventsPath = path.join(eventFolderPath, folder); const eventsPath = path.join(eventFolderPath, folder);
const eventFiles = fs const eventFiles = fs
.readdirSync(eventsPath) .readdirSync(eventsPath)
.filter(file => file.endsWith('.js') || file.endsWith('.ts')); .filter((file) => file.endsWith(".js") || file.endsWith(".ts"));
for (const file of eventFiles) { for (const file of eventFiles) {
const fullEventPath = path.join(eventsPath, file); const fullEventPath = path.join(eventsPath, file);
try { try {
const eventModule = await import(fullEventPath); const eventModule = await import(fullEventPath);
const event = eventModule.default || eventModule; const event = eventModule.default || eventModule;
if ('name' in event && 'execute' in event) { if ("name" in event && "execute" in event) {
if (event.once) { if (event.once) {
client.once(event.name, (...args) => event.execute(...args)); client.once(event.name, (...args) => event.execute(...args));
} else { } else {
client.on(event.name, (...args) => event.execute(...args)); client.on(event.name, (...args) => event.execute(...args));
} }
console.log(`\t✅ | ${event.name}`); console.log(`\t✅ | ${event.name}`);
} }
} catch (err) { } catch (err) {
console.error(`\t⚠ | Event at ${file}\n\t\t(${err}).`); console.error(`\t⚠ | Event at ${file}\n\t\t(${err}).`);
} }
} }
} }
console.log('\n\n'); console.log("\n\n");
client.once('ready', async () => { client.once("ready", async () => {
console.log(`🤖 | Connecté en tant que ${client.user?.tag}`); console.log(`🤖 | Connecté en tant que ${client.user?.tag}`);
await prisma.bot.upsert({ await prisma.bot.upsert({
where: { where: {
id: 1 id: 1,
}, },
update: {}, update: {},
create: {} create: {},
}); });
for (const [guildId, guild] of client.guilds.cache) { for (const [guildId, guild] of client.guilds.cache) {
await prisma.guild.upsert({ await prisma.guild.upsert({
where: { where: {
id: guildId id: guildId,
}, },
update: {}, update: {},
create: { create: {
id: guildId id: guildId,
} },
}); });
const members = await guild.members.fetch(); const members = await guild.members.fetch();
for (const [memberId, member] of members) { for (const [memberId, member] of members) {
await prisma.user.upsert({ await prisma.user.upsert({
where: { where: {
id: memberId id: memberId,
}, },
update: {}, update: {},
create: { create: {
id: memberId id: memberId,
} },
}); });
await prisma.guildUser.upsert({ await prisma.guildUser.upsert({
where: { where: {
userId_guildId: { userId_guildId: {
userId: memberId, userId: memberId,
guildId: guildId guildId: guildId,
} },
}, },
update: {}, update: {},
create: { create: {
userId: memberId, userId: memberId,
guildId: guildId guildId: guildId,
} },
}); });
} }
console.log(`✅ | Guild ${guild.name} synchronisée avec ${members.size} membres.`); console.log(
} `✅ | Guild ${guild.name} synchronisée avec ${members.size} membres.`,
);
}
}); });

View file

@ -1,51 +1,59 @@
import { REST, Routes } from 'discord.js' import { REST, Routes } from "discord.js";
import { pathToFileURL } from 'node:url'; import { pathToFileURL } from "node:url";
import { Client, Collection, Events, GatewayIntentBits, MessageFlags } from 'discord.js'; import {
import 'dotenv/config'; Client,
import fs from 'node:fs' Collection,
import path from 'node:path' Events,
GatewayIntentBits,
MessageFlags,
} from "discord.js";
import "dotenv/config";
import fs from "node:fs";
import path from "node:path";
const client = new Client({ const client = new Client({
intents: [ intents: [GatewayIntentBits.Guilds],
GatewayIntentBits.Guilds
]
}); });
client.commands = new Collection(); client.commands = new Collection();
const commands = []; const commands = [];
const foldersPath = path.join(__dirname, '../commands'); const foldersPath = path.join(__dirname, "../commands");
const commandFolders = fs.readdirSync(foldersPath); const commandFolders = fs.readdirSync(foldersPath);
for (const folder of commandFolders) { for (const folder of commandFolders) {
const commandsPath = path.join(foldersPath, folder); const commandsPath = path.join(foldersPath, folder);
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.ts') || file.endsWith('.js')); const commandFiles = fs
for (const file of commandFiles) { .readdirSync(commandsPath)
const filesPath = path.join(commandsPath, file); .filter((file) => file.endsWith(".ts") || file.endsWith(".js"));
const commandModule = await import(filesPath); for (const file of commandFiles) {
const command = commandModule.default || commandModule; const filesPath = path.join(commandsPath, file);
if ('data' in command && 'execute' in command) { const commandModule = await import(filesPath);
commands.push(command.data.toJSON()); const command = commandModule.default || commandModule;
} else { if ("data" in command && "execute" in command) {
console.log(`⚠️ | A Command is missing a required "data" or "execute" property.`); commands.push(command.data.toJSON());
} } else {
} console.log(
`⚠️ | A Command is missing a required "data" or "execute" property.`,
);
}
}
} }
const rest = new REST().setToken(process.env.DSC_TOKEN); const rest = new REST().setToken(process.env.DSC_TOKEN);
(async () => { (async () => {
try { try {
console.log(`🔍 | ${commands.length} commands found.`); console.log(`🔍 | ${commands.length} commands found.`);
const data = await rest.put( const data = await rest.put(
Routes.applicationCommands(process.env.CLIENT_ID), Routes.applicationCommands(process.env.CLIENT_ID),
{ {
body: commands body: commands,
}, },
); );
console.log(`✅ | ${data.length} is now reloaded`); console.log(`✅ | ${data.length} is now reloaded`);
} catch (error) { } catch (error) {
console.error(error); console.error(error);
} }
})(); })();

View file

@ -1,3 +1,3 @@
import { PrismaClient } from '@prisma/client'; import { PrismaClient } from "@prisma/client";
export const prisma = new PrismaClient(); export const prisma = new PrismaClient();