This commit is contained in:
arthur
2024-06-25 12:15:45 +02:00
parent 515019f25d
commit 77673accb1
22 changed files with 4423 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
TOKEN=YOUR_BOT_TOKEN
+3
View File
@@ -1,3 +1,6 @@
# Database
db.sqlite
# Logs
logs
*.log
+330
View File
@@ -0,0 +1,330 @@
const addCommand = require("../fonctions/addCommand");
const {
SlashCommandBuilder,
EmbedBuilder,
ButtonBuilder,
ButtonStyle,
ActionRowBuilder,
} = require("discord.js");
const getPrefix = require("../fonctions/getPrefix");
module.exports = addCommand(
(this.name = "help"),
(this.description = "Affiche la liste des commandes disponibles."),
(this.aliases = ["h", "aide"]),
(this.permissions = []),
(this.botOwnerOnly = false),
(this.dm = true),
(this.executePrefix = async (client, message, args) => {
if (args[0]) {
const command =
client.commands.get(args[0]) ||
client.commands.find(
(cmd) => cmd.aliases && cmd.aliases.includes(args[0]),
);
if (!command) {
const embed = new EmbedBuilder()
.setTitle("Commande introuvable")
.setDescription(
"La commande spécifiée n'existe pas. Veuillez réessayer.",
)
.setColor("#0099FF")
.setTimestamp()
.setFooter({
text: `Demandé par ${message.author.tag}`,
iconURL: message.author.displayAvatarURL(),
});
return message.reply({ embeds: [embed] });
}
const embed = new EmbedBuilder()
.setTitle(command.name)
.setDescription(
`> **Description :** ${command.description}\n> **Utilisation :** \`${command.utilisation}\`\n> **Catégorie :** ${command.category}`,
)
.setColor("#0099FF")
.setTimestamp()
.setFooter({
text: `Demandé par ${message.author.tag}`,
iconURL: message.author.displayAvatarURL(),
});
return message.reply({ embeds: [embed] });
}
let prefix;
if (message.channel.type === 1) {
prefix = await getPrefix(message.channel.id);
} else {
prefix = await getPrefix(message.guild.id);
}
const categories = new Set();
client.commands.forEach((command) => {
if (command.category) {
categories.add(command.category);
}
});
const categoriesArray = Array.from(categories);
const welcomeEmbed = new EmbedBuilder()
.setTitle("📚・Accueil")
.setDescription(
`Voici le panel d'aide du bot. Pour plus d'informations sur une commande, utilisez \`${prefix}help <commande>\``,
)
.setColor("#0099FF")
.setTimestamp()
.setFooter({
text: `Page 1/${categories.size + 1} - Demandé par ${message.author.tag}`,
iconURL: message.author.displayAvatarURL(),
});
function createEmbedByCategory(client, category) {
const commands = [];
client.commands.forEach((command) => {
if (command.category && command.category === category) {
commands.push(command);
}
});
const embed = new EmbedBuilder()
.setTitle(category)
.setDescription(
commands
.map(
(command) =>
`> \`${prefix + command.name} ${command.utilisation}\`\n> ┖ ${command.description}`,
)
.join("\n\n"),
)
.setColor("#0099FF")
.setTimestamp()
.setFooter({
text: `Page ${categoriesArray.indexOf(category) + 2}/${categories.size + 1} - Demandé par ${message.author.tag}`,
iconURL: message.author.displayAvatarURL(),
});
return embed;
}
let returnEmbed = [welcomeEmbed];
categories.forEach((category) => {
returnEmbed.push(createEmbedByCategory(client, category));
});
let page = 1;
const leftButton = new ButtonBuilder()
.setCustomId("left")
.setLabel("◀")
.setStyle(ButtonStyle.Primary);
const rightButton = new ButtonBuilder()
.setCustomId("right")
.setLabel("▶")
.setStyle(ButtonStyle.Primary);
const row = new ActionRowBuilder().addComponents(leftButton, rightButton);
const sendMessage = await message.reply({
embeds: [returnEmbed[0]],
components: [row],
});
const filter = (i) => i.customId === "left" || i.customId === "right";
const collector = sendMessage.createMessageComponentCollector({
filter,
time: 120000,
});
collector.on("collect", async (i) => {
if (i.user.id !== message.author.id)
return i.reply({
content: "Vous n'êtes pas l'auteur du message.",
ephemeral: true,
});
if (i.customId === "left") {
if (page === 1) {
page = returnEmbed.length;
} else {
page--;
}
} else if (i.customId === "right") {
if (page === returnEmbed.length) {
page = 1;
} else {
page++;
}
}
sendMessage.edit({ embeds: [returnEmbed[page - 1]] });
i.deferUpdate();
});
collector.on("end", async () => {
sendMessage.edit({ components: [] });
});
}),
(this.executeSlash = async (client, interaction) => {
if (interaction.options.getString("command")) {
const command =
client.commands.get(interaction.options.getString("command")) ||
client.commands.find(
(cmd) =>
cmd.aliases &&
cmd.aliases.includes(interaction.options.getString("command")),
);
if (!command) {
const embed = new EmbedBuilder()
.setTitle("Commande introuvable")
.setDescription(
"La commande spécifiée n'existe pas. Veuillez réessayer.",
)
.setColor("#0099FF")
.setTimestamp()
.setFooter({
text: `Demandé par ${interaction.user.tag}`,
iconURL: message.author.displayAvatarURL(),
});
return interaction.reply({ embeds: [embed] });
}
const embed = new EmbedBuilder()
.setTitle(command.name)
.setDescription(
`> **Description :** ${command.description}\n> **Utilisation :** \`${command.utilisation}\`\n> **Catégorie :** ${command.category}`,
)
.setColor("#0099FF")
.setTimestamp()
.setFooter({
text: `Demandé par ${interaction.user.tag}`,
iconURL: message.author.displayAvatarURL(),
});
return interaction.reply({ embeds: [embed] });
}
let prefix;
if (interaction.channel.type === 1) {
prefix = await getPrefix(interaction.channel.id);
} else {
prefix = await getPrefix(interaction.guild.id);
}
const categories = new Set();
client.commands.forEach((command) => {
if (command.category) {
categories.add(command.category);
}
});
const categoriesArray = Array.from(categories);
const welcomeEmbed = new EmbedBuilder()
.setTitle("📚・Accueil")
.setDescription(
`Voici le panel d'aide du bot. Pour plus d'informations sur une commande, utilisez \`${prefix}help <commande>\``,
)
.setColor("#0099FF")
.setTimestamp()
.setFooter({
text: `Page 1/${categories.size + 1} - Demandé par ${interaction.user.tag}`,
iconURL: interaction.user.displayAvatarURL(),
});
function createEmbedByCategory(client, category) {
const commands = [];
client.commands.forEach((command) => {
if (command.category && command.category === category) {
commands.push(command);
}
});
const embed = new EmbedBuilder()
.setTitle(category)
.setDescription(
commands
.map(
(command) =>
`> \`${prefix + command.name} ${command.utilisation}\`\n> ┖ ${command.description}`,
)
.join("\n\n"),
)
.setColor("#0099FF")
.setTimestamp()
.setFooter({
text: `Page ${categoriesArray.indexOf(category) + 2}/${categories.size + 1} - Demandé par ${interaction.user.tag}`,
iconURL: interaction.user.displayAvatarURL(),
});
return embed;
}
let returnEmbed = [welcomeEmbed];
categories.forEach((category) => {
returnEmbed.push(createEmbedByCategory(client, category));
});
let page = 1;
const leftButton = new ButtonBuilder()
.setCustomId("left")
.setLabel("◀")
.setStyle(ButtonStyle.Primary);
const rightButton = new ButtonBuilder()
.setCustomId("right")
.setLabel("▶")
.setStyle(ButtonStyle.Primary);
const row = new ActionRowBuilder().addComponents(leftButton, rightButton);
const sendMessage = await interaction.reply({
embeds: [returnEmbed[0]],
components: [row],
});
const filter = (i) => i.customId === "left" || i.customId === "right";
const collector = sendMessage.createMessageComponentCollector({
filter,
time: 120000,
});
collector.on("collect", async (i) => {
if (i.user.id !== interaction.user.id)
return i.reply({
content: "Vous n'êtes pas l'auteur du message.",
ephemeral: true,
});
if (i.customId === "left") {
if (page === 1) {
page = returnEmbed.length;
} else {
page--;
}
} else if (i.customId === "right") {
if (page === returnEmbed.length) {
page = 1;
} else {
page++;
}
}
sendMessage.edit({ embeds: [returnEmbed[page - 1]] });
i.deferUpdate();
});
}),
(this.slashOptions = new SlashCommandBuilder().addStringOption((option) =>
option
.setName("command")
.setDescription(
"La commande pour laquelle vous voulez plus d'informations.",
)
.setRequired(false),
)),
);
+170
View File
@@ -0,0 +1,170 @@
const addCommand = require("../fonctions/addCommand");
const {
SlashCommandBuilder,
ButtonStyle,
ButtonBuilder,
ActionRowBuilder,
EmbedBuilder,
} = require("discord.js");
module.exports = addCommand(
(this.name = "ping"),
(this.description = "Cette commande permet de vérifier la latence du bot."),
(this.aliases = ["latency", "lag", "responseTime"]),
(this.permissions = []),
(this.botOwnerOnly = false),
(this.dm = true),
(this.executePrefix = async (client, message, args) => {
const pingBtn = new ButtonBuilder()
.setCustomId("pingBtn")
.setLabel("🔄")
.setStyle(ButtonStyle.Primary);
const row = new ActionRowBuilder().addComponents(pingBtn);
const embed = new EmbedBuilder()
.setTitle("Pong !")
.setDescription(`La latence du bot est de \`${client.ws.ping}\`ms.`)
.setColor("#0099FF")
.setTimestamp()
.setFooter({
text: `Demandé par ${message.author.tag}`,
iconURL: message.author.displayAvatarURL(),
});
const sendMessage = await message.reply({
embeds: [embed],
components: [row],
});
const filter = (i) => i.customId === "pingBtn";
const collector = sendMessage.createMessageComponentCollector({
filter,
time: 120000,
});
collector.on("collect", async (i) => {
if (i.user.id !== message.author.id)
return i.reply({
content: "Vous n'êtes pas l'auteur du message.",
ephemeral: true,
});
const embed = new EmbedBuilder()
.setTitle("Pong !")
.setDescription(`La latence du bot est de \`${client.ws.ping}\`ms.`)
.setColor("#0099FF")
.setTimestamp()
.setFooter({
text: `Demandé par ${message.author.tag}`,
iconURL: message.author.displayAvatarURL(),
});
sendMessage.edit({ embeds: [embed], components: [row] });
i.reply({ content: "La latence a été rafraichie.", ephemeral: true });
});
collector.on("end", async () => {
const embed = new EmbedBuilder()
.setTitle("Pong !")
.setDescription(`La latence du bot est de \`${client.ws.ping}\`ms.`)
.setColor("#0099FF")
.setTimestamp()
.setFooter({
text: `Demandé par ${message.author.tag}`,
iconURL: message.author.displayAvatarURL(),
});
sendMessage.edit({ embeds: [embed], components: [] });
});
}),
(this.executeSlash = async (client, interaction) => {
const pingBtn = new ButtonBuilder()
.setCustomId("pingBtn")
.setLabel("🔄")
.setStyle(ButtonStyle.Primary);
const row = new ActionRowBuilder().addComponents(pingBtn);
const embed = new EmbedBuilder()
.setTitle("Pong !")
.setDescription(`La latence du bot est de \`${client.ws.ping}\`ms.`)
.setColor("#0099FF")
.setTimestamp()
.setFooter({
text: `Demandé par ${interaction.user.tag}`,
iconURL: interaction.user.displayAvatarURL(),
});
if (interaction.options.getBoolean("actualiser") === false) {
const sendMessage = await interaction.reply({
embeds: [embed],
components: [row],
});
const filter = (i) => i.customId === "pingBtn";
const collector = sendMessage.createMessageComponentCollector({
filter,
time: 120000,
});
collector.on("collect", async (i) => {
if (i.user.id !== interaction.user.id)
return i.reply({
content: "Vous n'êtes pas l'auteur du message.",
ephemeral: true,
});
const embed = new EmbedBuilder()
.setTitle("Pong !")
.setDescription(`La latence du bot est de \`${client.ws.ping}\`ms.`)
.setColor("#0099FF")
.setTimestamp()
.setFooter({
text: `Demandé par ${interaction.user.tag}`,
iconURL: interaction.user.displayAvatarURL(),
});
sendMessage.edit({ embeds: [embed], components: [row] });
i.reply({ content: "La latence a été rafraichie.", ephemeral: true });
});
collector.on("end", async () => {
const embed = new EmbedBuilder()
.setTitle("Pong !")
.setDescription(`La latence du bot est de \`${client.ws.ping}\`ms.`)
.setColor("#0099FF")
.setTimestamp()
.setFooter({
text: `Demandé par ${interaction.user.tag}`,
iconURL: interaction.user.displayAvatarURL(),
});
sendMessage.edit({ embeds: [embed], components: [] });
});
} else {
const sendMessage = await interaction.reply({ embeds: [embed] });
const interval = setInterval(() => {
const embed = new EmbedBuilder()
.setTitle("Pong !")
.setDescription(`La latence du bot est de \`${client.ws.ping}\`ms.`)
.setColor("#0099FF")
.setTimestamp()
.setFooter({
text: `Demandé par ${interaction.user.tag}`,
iconURL: interaction.user.displayAvatarURL(),
});
sendMessage.edit({ embeds: [embed] });
}, 10000);
setTimeout(() => {
clearInterval(interval);
}, 120000);
}
}),
(this.slashOptions = new SlashCommandBuilder().addBooleanOption((option) =>
option
.setName("actualiser")
.setDescription(
"Actualiser automatiquement la latence du bot toute les 10 secondes pandant 2 minutes.",
)
.setRequired(false),
)),
);
+38
View File
@@ -0,0 +1,38 @@
const addCommand = require("../fonctions/addCommand");
const { SlashCommandBuilder, EmbedBuilder } = require("discord.js");
const getPrefix = require("../fonctions/getPrefix");
module.exports = addCommand(
(this.name = "prefix"),
(this.description = "Affiche le préfixe actuel du bot."),
(this.aliases = ["getprefix", "showprefix"]),
(this.permissions = []),
(this.botOwnerOnly = false),
(this.dm = true),
(this.executePrefix = async (client, message, args) => {
let prefix;
if (message.channel.type === 1) {
prefix = await getPrefix(message.channel.id);
} else {
prefix = await getPrefix(message.guild.id);
}
const embed = new EmbedBuilder()
.setTitle("Préfixe du Bot")
.setDescription(`Le préfixe actuel du bot est: \`${prefix}\``)
.setColor("#0099FF")
.setTimestamp();
message.reply({ embeds: [embed] });
}),
(this.executeSlash = async (client, interaction) => {
const prefix = await getPrefix(interaction.guild.id);
const embed = new EmbedBuilder()
.setTitle("Préfixe du Bot")
.setDescription(`Le préfixe actuel du bot est: \`${prefix}\``)
.setColor("#0099FF")
.setTimestamp();
await interaction.reply({ embeds: [embed] });
}),
(this.slashOptions = new SlashCommandBuilder()),
);
+54
View File
@@ -0,0 +1,54 @@
const addCommand = require("../fonctions/addCommand");
const { SlashCommandBuilder, EmbedBuilder } = require("discord.js");
module.exports = addCommand(
(this.name = "uptime"),
(this.description = "Affiche depuis combien de temps le bot est en ligne."),
(this.aliases = ["up", "online"]),
(this.permissions = []),
(this.botOwnerOnly = false),
(this.dm = true),
(this.executePrefix = async (client, message, args) => {
const totalSeconds = client.uptime / 1000;
const days = Math.floor(totalSeconds / 86400);
const hours = Math.floor(totalSeconds / 3600) % 24;
const minutes = Math.floor(totalSeconds / 60) % 60;
const seconds = Math.floor(totalSeconds % 60);
const embed = new EmbedBuilder()
.setTitle("Temps d'activité")
.setDescription(
`Le bot est en ligne depuis ${days > 0 ? `${days} jours, ` : ""}${hours > 0 ? `${hours} heures, ` : ""}${minutes > 0 ? `${minutes} minutes et ` : ""}${seconds} secondes.`,
)
.setColor("#0099FF")
.setTimestamp()
.setFooter({
text: `Demandé par ${message.author.tag}`,
iconURL: message.author.displayAvatarURL(),
});
await message.reply({ embeds: [embed] });
}),
(this.executeSlash = async (client, interaction) => {
const totalSeconds = client.uptime / 1000;
const days = Math.floor(totalSeconds / 86400);
const hours = Math.floor(totalSeconds / 3600) % 24;
const minutes = Math.floor(totalSeconds / 60) % 60;
const seconds = Math.floor(totalSeconds % 60);
const embed = new EmbedBuilder()
.setTitle("Temps d'activité")
.setDescription(
`Le bot est en ligne depuis ${days} jours, ${hours} heures, ${minutes} minutes et ${seconds} secondes.`,
)
.setColor("#0099FF")
.setTimestamp()
.setFooter({
text: `Demandé par ${interaction.user.tag}`,
iconURL: interaction.user.displayAvatarURL(),
});
await interaction.reply({ embeds: [embed] });
}),
(this.slashOptions = new SlashCommandBuilder()),
);
+33
View File
@@ -0,0 +1,33 @@
const addCommand = require("../../fonctions/addCommand");
const { SlashCommandBuilder, PermissionsBitField } = require("discord.js");
module.exports = addCommand(
(this.name = "say"),
(this.description = "Fait dire au bot le message spécifié."),
(this.aliases = ["repeat", "echo", "dire"]),
(this.permissions = [PermissionsBitField.Flags.Administrator]),
(this.botOwnerOnly = false),
(this.dm = true),
(this.executePrefix = async (client, message, args) => {
const text = args.join(" ");
if (!text) return message.reply("Vous devez spécifier un message à dire.");
message.delete().catch(() => {});
message.channel.send(text);
}),
(this.executeSlash = async (client, interaction) => {
const text = interaction.options.getString("text");
if (!text)
return interaction.reply({
content: "Vous devez spécifier un message à dire.",
ephemeral: true,
});
interaction.channel.send(text);
interaction.reply({ content: "Message envoyé.", ephemeral: true });
}),
(this.slashOptions = new SlashCommandBuilder().addStringOption((option) =>
option
.setName("text")
.setDescription("Le message à dire.")
.setRequired(true),
)),
);
+178
View File
@@ -0,0 +1,178 @@
const addCommand = require("../../fonctions/addCommand");
const {
SlashCommandBuilder,
PermissionsBitField,
EmbedBuilder,
} = require("discord.js");
module.exports = addCommand(
(this.name = "servers"),
(this.description = "Affiche la liste des serveurs où le bot est présent."),
(this.aliases = ["serv", "server", "serverlist", "servlist", "serverslist"]),
(this.permissions = []),
(this.botOwnerOnly = true),
(this.dm = true),
(this.executePrefix = async (client, message, args) => {
if (args[0]) {
const guild = client.guilds.cache.get(args[0]);
if (!guild) {
const embed = new EmbedBuilder()
.setTitle("Erreur")
.setDescription(
"Ce serveur n'existe pas ou le bot n'est pas présent dessus.",
)
.setColor("#FF0000")
.setTimestamp()
.setFooter({
text: `Demandé par ${message.author.tag}`,
iconURL: message.author.displayAvatarURL(),
});
return message.reply({ embeds: [embed] });
}
const owner = guild.members.cache.get(guild.ownerId);
const ownerName = owner ? owner.user.tag : "Inconnu";
const joinedTimestamp = guild.joinedTimestamp;
const joinedDate = new Date(joinedTimestamp).toLocaleString("fr-FR", {
dateStyle: "short",
timeStyle: "short",
});
const createdAt = new Date(guild.createdAt).toLocaleString("fr-FR", {
dateStyle: "short",
timeStyle: "short",
});
const embed = new EmbedBuilder()
.setTitle(`Informations sur le serveur ${guild.name}`)
.setColor("#00FF00")
.addFields(
{ name: "Nom", value: guild.name, inline: true },
{ name: "ID", value: guild.id, inline: true },
{ name: "A rejoint le", value: joinedDate, inline: true },
{ name: "Propriétaire", value: ownerName, inline: true },
{
name: "Membres",
value: guild.memberCount.toString(),
inline: true,
},
{ name: "Région", value: guild.preferredLocale, inline: true },
{ name: "Créé le", value: createdAt, inline: true },
)
.setThumbnail(guild.iconURL())
.setTimestamp()
.setFooter({
text: `Demandé par ${message.author.tag}`,
iconURL: message.author.displayAvatarURL(),
});
message.reply({ embeds: [embed] });
return;
}
const guilds = client.guilds.cache;
let description = `Nombre de serveurs : ${guilds.size}\n`;
guilds.forEach((guild) => {
if (message.guild && guild.id === message.guild.id) {
description += `**${guild.name} - ${guild.id}**\n`;
} else {
description += `${guild.name} - ${guild.id}\n`;
}
});
const embed = new EmbedBuilder()
.setTitle("Liste des serveurs")
.setColor("#00FF00")
.setDescription(description)
.setTimestamp()
.setFooter({
text: `Demandé par ${message.author.tag}`,
iconURL: message.author.displayAvatarURL(),
});
message.reply({ embeds: [embed] });
}),
(this.executeSlash = async (client, interaction) => {
const guildId = interaction.options.getString("id");
if (guildId) {
const guild = client.guilds.cache.get(guildId);
if (!guild) {
const embed = new EmbedBuilder()
.setTitle("Erreur")
.setDescription(
"Ce serveur n'existe pas ou le bot n'est pas présent dessus.",
)
.setColor("#FF0000")
.setTimestamp()
.setFooter({
text: `Demandé par ${interaction.user.tag}`,
iconURL: interaction.user.displayAvatarURL(),
});
return message.reply({ embeds: [embed] });
}
const owner = guild.members.cache.get(guild.ownerId);
const ownerName = owner ? owner.user.tag : "Inconnu";
const joinedTimestamp = guild.joinedTimestamp;
const joinedDate = new Date(joinedTimestamp).toLocaleString("fr-FR", {
dateStyle: "short",
timeStyle: "short",
});
const createdAt = new Date(guild.createdAt).toLocaleString("fr-FR", {
dateStyle: "short",
timeStyle: "short",
});
const embed = new EmbedBuilder()
.setTitle(`Informations sur le serveur ${guild.name}`)
.setColor("#00FF00")
.addFields(
{ name: "Nom", value: guild.name, inline: true },
{ name: "ID", value: guild.id, inline: true },
{ name: "A rejoint le", value: joinedDate, inline: true },
{ name: "Propriétaire", value: ownerName, inline: true },
{
name: "Membres",
value: guild.memberCount.toString(),
inline: true,
},
{ name: "Région", value: guild.preferredLocale, inline: true },
{ name: "Créé le", value: createdAt, inline: true },
)
.setThumbnail(guild.iconURL())
.setTimestamp()
.setFooter({
text: `Demandé par ${interaction.user.tag}`,
iconURL: interaction.user.displayAvatarURL(),
});
interaction.reply({ embeds: [embed] });
return;
}
const guilds = client.guilds.cache;
let description = `Nombre de serveurs : ${guilds.size}\n`;
guilds.forEach((guild) => {
if (interaction.guild && guild.id === interaction.guild.id) {
description += `**${guild.name} - ${guild.id}**\n`;
} else {
description += `${guild.name} - ${guild.id}\n`;
}
});
const embed = new EmbedBuilder()
.setTitle("Liste des serveurs")
.setColor("#00FF00")
.setDescription(description)
.setTimestamp()
.setFooter({
text: `Demandé par ${interaction.user.tag}`,
iconURL: interaction.user.displayAvatarURL(),
});
interaction.reply({ embeds: [embed] });
}),
(this.slashOptions = new SlashCommandBuilder().addStringOption((option) =>
option
.setName("id")
.setDescription("L'ID du serveur à afficher.")
.setRequired(false),
)),
);
+106
View File
@@ -0,0 +1,106 @@
const addCommand = require("../../fonctions/addCommand");
const {
SlashCommandBuilder,
EmbedBuilder,
PermissionsBitField,
} = require("discord.js");
const getPrefix = require("../../fonctions/getPrefix");
const db = require("../../fonctions/setDatabase");
module.exports = addCommand(
(this.name = "setprefix"),
(this.description = "Modifie le préfixe du bot."),
(this.aliases = ["prefixset", "changeprefix"]),
(this.permissions = [PermissionsBitField.Flags.Administrator]),
(this.botOwnerOnly = false),
(this.dm = true),
(this.executePrefix = async (client, message, args) => {
const newPrefix = args[0];
if (!newPrefix) return message.reply("Vous devez spécifier un préfixe.");
if (newPrefix.length > 5)
return message.reply("Le préfixe ne doit pas dépasser 5 caractères.");
let prefix;
if (message.channel.type === 1) {
prefix = await getPrefix(message.channel.id);
} else {
prefix = await getPrefix(message.guild.id);
}
if (newPrefix === prefix)
return message.reply("Le préfixe spécifié est déjà le préfixe actuel.");
db.run(
`INSERT OR REPLACE INTO prefix (guildId, prefix) VALUES (?, ?)`,
[message.guild.id, newPrefix],
(err) => {
if (err) {
console.error(err.message);
return message.reply("Une erreur s'est produite.");
}
const embed = new EmbedBuilder()
.setTitle("Préfixe modifié")
.setDescription(
`Le préfixe du bot a été modifié pour \`${newPrefix}\`.`,
)
.setColor("#0099FF")
.setTimestamp()
.setFooter({
text: `Demandé par ${message.author.tag}`,
iconURL: message.author.displayAvatarURL(),
});
message.reply({ embeds: [embed] });
},
);
}),
(this.executeSlash = async (client, interaction) => {
const newPrefix = interaction.options.getString("prefix");
if (!newPrefix)
return interaction.reply("Vous devez spécifier un préfixe.");
if (newPrefix.length > 5)
return interaction.reply("Le préfixe ne doit pas dépasser 5 caractères.");
let prefix;
if (interaction.channel.type === 1) {
prefix = await getPrefix(interaction.channel.id);
} else {
prefix = await getPrefix(interaction.guild.id);
}
if (newPrefix === prefix)
return interaction.reply(
"Le préfixe spécifié est déjà le préfixe actuel.",
);
db.run(
`INSERT OR REPLACE INTO prefix (guildId, prefix) VALUES (?, ?)`,
[interaction.guild.id, newPrefix],
(err) => {
if (err) {
console.error(err.message);
return interaction.reply("Une erreur s'est produite.");
}
const embed = new EmbedBuilder()
.setTitle("Préfixe modifié")
.setDescription(
`Le préfixe du bot a été modifié pour \`${newPrefix}\`.`,
)
.setColor("#0099FF")
.setTimestamp()
.setFooter({
text: `Demandé par ${interaction.user.tag}`,
iconURL: interaction.user.displayAvatarURL(),
});
interaction.reply({ embeds: [embed] });
},
);
}),
(this.slashOptions = new SlashCommandBuilder().addStringOption((option) =>
option
.setName("prefix")
.setDescription("Le nouveau préfixe du bot.")
.setRequired(true),
)),
);
+21
View File
@@ -0,0 +1,21 @@
const getPrefix = require("../fonctions/getPrefix.js");
module.exports = {
name: "messageCreate",
async execute(client, message) {
if (!message || !message.author) return;
if (message.author.bot) return;
if (
message.content === `<@!${client.user.id}>` ||
message.content === `<@${client.user.id}>`
) {
let prefix;
if (message.channel.type === 1) {
prefix = await getPrefix(message.channel.id);
} else {
prefix = await getPrefix(message.guild.id);
}
message.reply(`Mon préfixe est \`${prefix}\`.`);
}
},
};
+65
View File
@@ -0,0 +1,65 @@
require("dotenv").config();
const getPrefix = require("../../fonctions/getPrefix");
module.exports = {
name: "messageCreate",
async execute(client, message) {
if (!message || !message.author) return;
if (message.author.bot) return;
if (!message.content) return;
let prefix;
if (message.channel.type === 1) {
prefix = await getPrefix(message.channel.id);
} else {
prefix = await getPrefix(message.guild.id);
}
if (!message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
const command =
client.commands.get(commandName) ||
client.commands.find(
(cmd) => cmd.aliases && cmd.aliases.includes(commandName),
);
if (!command) return;
if (command.dm !== true && message.channel.type === 1)
return message
.reply({
content: "Cette commande ne peut pas être utilisée en message privé.",
})
.then((msg) => setTimeout(() => msg.delete(), 5000));
if (process.env.OWNER && !process.env.OWNER === message.author.id) {
if (command.botOwnerOnly)
return message
.reply({
content: "Cette commande est réservée au propriétaire du bot.",
})
.then((msg) => setTimeout(() => msg.delete(), 5000));
if (
command.permissions &&
message.channel.type !== 1 &&
!command.permissions.every((permission) =>
message.member.permissions.has(permission),
)
)
return message
.reply({
content: "Vous n'avez pas la permission d'utiliser cette commande.",
})
.then((msg) => setTimeout(() => msg.delete(), 5000));
}
try {
command.executePrefix(client, message, args);
console.log(`[CMD - PREFIX] ${message.author.tag} | ${commandName}`);
} catch (error) {
console.error(
`Erreur lors de l'exécution de la commande '${commandName}':`,
error,
);
}
},
};
+47
View File
@@ -0,0 +1,47 @@
require("dotenv").config();
module.exports = {
name: "interactionCreate",
async execute(client, interaction) {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
if (command.dm !== true && interaction.channel.type === 1)
return interaction.reply({
content: "Cette commande ne peut pas être utilisée en message privé.",
ephemeral: true,
});
if (process.env.OWNER && !process.env.OWNER === interaction.user.id) {
if (command.botOwnerOnly)
return interaction.reply({
content: "Cette commande est réservée au propriétaire du bot.",
ephemeral: true,
});
if (
command.permissions &&
interaction.channel.type !== 1 &&
!command.permissions.every((permission) =>
interaction.member.permissions.has(permission),
)
)
return interaction.reply({
content: "Vous n'avez pas la permission d'utiliser cette commande.",
ephemeral: true,
});
}
try {
command.executeSlash(client, interaction);
console.log(
`[CMD - SLASH] ${interaction.user.tag} | ${interaction.commandName}`,
);
} catch (error) {
console.error(
`Erreur lors de l'exécution de la commande slash '${interaction.commandName}':`,
error,
);
}
},
};
+6
View File
@@ -0,0 +1,6 @@
module.exports = {
name: "messageReactionAdd",
async execute(client, reaction) {
await reaction.message.react(reaction._emoji.name).catch(() => {});
},
};
+40
View File
@@ -0,0 +1,40 @@
const { ActivityType } = require("discord.js");
const { REST } = require("@discordjs/rest");
const { Routes } = require("discord-api-types/v9");
require("dotenv").config();
module.exports = {
name: "ready",
once: true,
async execute(client) {
const commands = [];
client.commands.forEach((command) => {
commands.push(command.data.toJSON());
});
const rest = new REST({ version: "9" }).setToken(process.env.TOKEN);
try {
console.log("Started refreshing application (/) commands.");
await rest.put(Routes.applicationCommands(client.user.id), {
body: commands,
});
console.log("Successfully reloaded application (/) commands.");
} catch (error) {
console.error(error);
}
console.log(
`[READY] ${client.user.tag} est prêt | ${client.guilds.cache.size.toLocaleString("fr-FR")} serveurs | ${client.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0).toLocaleString("fr-FR")} utilisateurs\n`,
);
setInterval(() => {
let random = Math.floor(Math.random() * status.length);
client.user.setActivity(status[random]);
}, 6000);
},
};
let status = [
{
name: "/help",
type: ActivityType.Custom,
},
];
+172
View File
@@ -0,0 +1,172 @@
const { SlashCommandBuilder, PermissionsBitField } = require("discord.js");
/**
* Ajoute une nouvelle commande au bot.
*
* @param {string} name - Le nom de la commande.
* @param {string} description - La description de la commande.
* @param {Array<string>} aliases - Les alias de la commande.
* @param {Array<PermissionsBitField>} permissions - Les permissions nécessaires pour exécuter la commande.
* @param {boolean} botOwnerOnly - Si la commande est réservée au propriétaire du bot.
* @param {boolean} dm - Si la commande peut être exécutée en message privé.
* @param {Function} executePrefix - La fonction à exécuter avec un préfixe.
* @param {Function} executeSlash - La fonction à exécuter comme commande slash.
* @param {Array<Object>} slashOptions - Les options pour la commande slash.
*
* @returns {void} Ne retourne rien.
*/
function addCommand(
name,
description,
aliases,
permissions,
botOwnerOnly,
dm,
executePrefix,
executeSlash,
slashOptions,
) {
if (!name) return console.error("Le nom de la commande est requis.");
name = name.toString();
name = name.toLowerCase();
name = name.replace(/ /g, "_");
if (!description)
return console.error("La description de la commande est requise.");
description = description.toString();
if (!aliases) aliases = [];
if (!Array.isArray(aliases)) aliases = [aliases];
aliases = aliases.map((alias) => alias.toString());
if (!permissions) permissions = [];
if (!Array.isArray(permissions)) permissions = [permissions];
if (!botOwnerOnly) botOwnerOnly = false;
botOwnerOnly = Boolean(botOwnerOnly);
if (!dm) dm = false;
dm = Boolean(dm);
if (!executePrefix)
return console.error("La fonction executePrefix est requise.");
if (!executeSlash)
return console.error("La fonction executeSlash est requise.");
if (
typeof executePrefix !== "function" ||
executePrefix.constructor.name !== "AsyncFunction"
) {
return console.error(
"La fonction executePrefix doit être une fonction asynchrone.",
);
}
if (
typeof executeSlash !== "function" ||
executeSlash.constructor.name !== "AsyncFunction"
) {
return console.error(
"La fonction executeSlash doit être une fonction asynchrone.",
);
}
const executePrefixParams = executePrefix
.toString()
.match(/\(([^)]+)\)/)[1]
.split(",")
.map((param) => param.trim());
if (
executePrefixParams.length !== 3 ||
executePrefixParams[0] !== "client" ||
executePrefixParams[1] !== "message" ||
executePrefixParams[2] !== "args"
) {
return console.error(
'La fonction executePrefix doit avoir les paramètres "client", "message" et "args".',
);
}
const executeSlashParams = executeSlash
.toString()
.match(/\(([^)]+)\)/)[1]
.split(",")
.map((param) => param.trim());
if (
executeSlashParams.length !== 2 ||
executeSlashParams[0] !== "client" ||
executeSlashParams[1] !== "interaction"
) {
return console.error(
'La fonction executeSlash doit avoir les paramètres "client" et "interaction".',
);
}
const command = {
name,
description,
aliases,
permissions,
botOwnerOnly,
dm,
executePrefix,
executeSlash,
};
let default_member_permissions;
if (command.permissions.length === 0) {
default_member_permissions = null;
} else {
default_member_permissions = new PermissionsBitField();
command.permissions.forEach(
(permission) => (default_member_permissions += BigInt(permission)),
);
}
command.data = new SlashCommandBuilder()
.setName(command.name)
.setDescription(command.description)
.setDMPermission(command.dm)
.setDefaultMemberPermissions(default_member_permissions);
for (const key in command.data) {
if (command.data.hasOwnProperty(key)) {
const value = command.data[key];
if (value !== undefined && key !== "options") {
slashOptions[key] = value;
}
}
}
command.data = slashOptions;
let utilisation = "";
command.data.options.forEach((option) => {
let optionUsage = "";
if (option.choices) {
optionUsage = option.required
? `<${option.choices.map((choice) => choice.name).join("|")}>`
: `[${option.choices.map((choice) => choice.name).join("|")}]`;
} else {
if (option.type === 3) {
optionUsage = option.required ? `<${option.name}>` : `[${option.name}]`;
} else if (option.type === 4) {
optionUsage = option.required ? `<${option.name}>` : `[${option.name}]`;
} else if (option.type === 5) {
optionUsage = option.required ? `<True|False>` : `[True|False]`;
} else if (option.type === 6) {
optionUsage = option.required ? `<@member>` : `[@member]`;
} else if (option.type === 7) {
optionUsage = option.required ? `<#channel>` : `[#channel]`;
} else if (option.type === 8) {
optionUsage = option.required ? `<@role>` : `[@role]`;
} else if (option.type === 9) {
optionUsage = option.required ? `<@mention>` : `[@mention]`;
} else if (option.type === 10) {
optionUsage = option.required ? `<${option.name}>` : `[${option.name}]`;
} else if (option.type === 11) {
optionUsage = option.required ? `<${option.name}>` : `[${option.name}]`;
}
}
utilisation += ` ${optionUsage}`;
});
utilisation = utilisation.trim();
command.utilisation = utilisation;
return command;
}
module.exports = addCommand;
+16
View File
@@ -0,0 +1,16 @@
const db = require("./setDatabase.js");
module.exports = async function getPrefix(guildId) {
const prefix = await new Promise((resolve, reject) => {
db.get(
`SELECT prefix FROM prefix WHERE guildId = ?`,
[guildId],
(err, row) => {
if (err) reject(err);
resolve(row);
},
);
});
return prefix ? prefix.prefix : process.env.PREFIX;
};
+18
View File
@@ -0,0 +1,18 @@
require("dotenv").config();
const sqlite3 = require("sqlite3").verbose();
const db = new sqlite3.Database(process.env.DATABASE, (err) => {
if (err) {
console.error(err.message);
return;
}
console.log("Connected to the database.");
});
db.run(`CREATE TABLE IF NOT EXISTS prefix (
guildId TEXT NOT NULL,
prefix TEXT NOT NULL DEFAULT '${process.env.PREFIX}',
PRIMARY KEY (guildId)
)`);
module.exports = db;
+59
View File
@@ -0,0 +1,59 @@
const fs = require("fs");
const path = require("path");
const { Collection } = require("discord.js");
module.exports = (client) => {
client.commands = new Collection();
function loadCommandsFromDirectory(directory) {
fs.readdir(directory, (err, files) => {
if (err) {
console.error("Erreur lors de la lecture du dossier:", err);
return;
}
files.forEach((file) => {
const filePath = path.join(directory, file);
fs.stat(filePath, (err, stats) => {
if (err) {
console.error(
"Erreur lors de la récupération des informations du fichier:",
err,
);
return;
}
if (stats.isDirectory()) {
loadCommandsFromDirectory(filePath);
} else if (stats.isFile() && file.endsWith(".js")) {
try {
const command = require(filePath);
const commandName = command.name || file.split(".")[0];
if (!command.category) {
const parentDir = path.basename(path.dirname(filePath));
command.category =
parentDir === "commands" ? "🌟・Other" : parentDir;
}
if (!command.dm) command.dm = false;
if (!command.botOwnerOnly) command.botOwnerOnly = false;
if (!command.permissions) command.permissions = [];
if (!command.aliases) command.aliases = [];
if (!command.description)
command.description = "Aucune description.";
client.commands.set(commandName, command);
delete require.cache[require.resolve(filePath)];
} catch (error) {
console.error(
`Erreur lors du chargement de la commande '${file}':`,
error,
);
}
}
});
});
});
}
loadCommandsFromDirectory(path.join(__dirname, "..", "commands"));
};
+45
View File
@@ -0,0 +1,45 @@
const fs = require("fs");
const path = require("path");
module.exports = (client) => {
function loadEventsFromDirectory(directory) {
fs.readdir(directory, (err, files) => {
if (err) {
console.error("Erreur lors de la lecture du dossier:", err);
return;
}
files.forEach((file) => {
const filePath = path.join(directory, file);
fs.stat(filePath, (err, stats) => {
if (err) {
console.error(
"Erreur lors de la récupération des informations du fichier:",
err,
);
return;
}
if (stats.isDirectory()) {
loadEventsFromDirectory(filePath);
} else if (stats.isFile() && file.endsWith(".js")) {
try {
const event = require(filePath);
let eventName = event.name || file.split(".")[0];
client.on(eventName, event.execute.bind(null, client));
delete require.cache[require.resolve(filePath)];
} catch (error) {
console.error(
`Erreur lors du chargement de l'événement '${file}':`,
error,
);
}
}
});
});
});
}
loadEventsFromDirectory(path.join(__dirname, "..", "events"));
};
+60
View File
@@ -0,0 +1,60 @@
const {
Client,
GatewayIntentBits,
Partials,
ActivityType,
} = require("discord.js");
require("dotenv").config();
const db = require("./fonctions/setDatabase.js");
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildModeration,
GatewayIntentBits.GuildEmojisAndStickers,
GatewayIntentBits.GuildIntegrations,
GatewayIntentBits.GuildWebhooks,
GatewayIntentBits.GuildInvites,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildMessageTyping,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.DirectMessageReactions,
GatewayIntentBits.DirectMessageTyping,
GatewayIntentBits.GuildScheduledEvents,
GatewayIntentBits.GuildPresences,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
partials: [
Partials.Channel,
Partials.GuildMember,
Partials.GuildScheduledEvent,
Partials.Message,
Partials.Reaction,
Partials.ThreadMember,
Partials.User,
],
restTimeOffset: 0,
failIfNotExists: false,
presence: {
activities: [
{
name: `starting...`,
type: ActivityType.Custom,
},
],
status: "Online",
},
allowedMentions: {
parse: ["roles", "users", "everyone"],
repliedUser: false,
},
});
require("./loader/events.js")(client);
require("./loader/commands.js")(client);
client.login(process.env.TOKEN);
+2934
View File
File diff suppressed because it is too large Load Diff
+27
View File
@@ -0,0 +1,27 @@
{
"name": "corps-de-bot-discord-js",
"version": "1.0.0",
"description": "Le corp de base d'un bon bot discord en Java Script.",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Arthur.pbty",
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "https://github.com/arthur-pbty/corps-de-bot-discord-js.git"
},
"readme": "README.md",
"licenses": [
{
"type": "Apache-2.0",
"url": "https://www.apache.org/licenses/LICENSE-2.0"
}
],
"dependencies": {
"discord.js": "^14.13.0",
"dotenv": "^16.4.5",
"sqlite3": "^5.1.7"
}
}