Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Refactor errors and badpractices #144

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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ update.txt
note.txt
archives

.env

# Created by https://www.toptal.com/developers/gitignore/api/node,vim,visualstudiocode
# Edit at https://www.toptal.com/developers/gitignore?templates=node,vim,visualstudiocode

Expand Down
2 changes: 1 addition & 1 deletion events/guildBanAdd.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const { sendLogs } = require("../util/envoiMsg");

module.exports = {
name: Events.GuildBanAdd,
async execute(ban) {
execute(ban) {
const embedLog = new EmbedBuilder()
.setColor(DARK_RED)
.setAuthor({
Expand Down
2 changes: 1 addition & 1 deletion events/guildBanRemove.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const { sendLogs } = require("../util/envoiMsg");

module.exports = {
name: Events.GuildBanRemove,
async execute(ban) {
execute(ban) {
const embedLog = new EmbedBuilder()
.setColor(GREEN)
.setAuthor({
Expand Down
12 changes: 7 additions & 5 deletions events/guildMemberAdd.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ module.exports = {
const user = member.user;
const embed = new EmbedBuilder()
.setColor(CORNFLOWER_BLUE)
.setTitle(`Nouveau membre`)
.setTitle("Nouveau membre")
.setDescription(member.toString())
.addFields(
{
Expand All @@ -23,17 +23,19 @@ module.exports = {
const nouveau = member.guild.roles.cache.find(
(r) => r.name === "Nouveau",
);
if (nouveau) await member.roles.add(nouveau);
if (nouveau) {
await member.roles.add(nouveau);
}

// recup "a-lire"
let alire = member.client.channels.cache.find(
const alire = member.client.channels.cache.find(
(r) => r.name === "💬a-lire",
);
// recup "bienvenue"
let bienvenue = member.guild.systemChannel;
const bienvenue = member.guild.systemChannel;

if (alire && bienvenue) {
let msgBienvenue = `> Bienvenue à toi ${user}, tu trouveras ici d'autres chasseurs de succès francophones ! ${CDS}
const msgBienvenue = `> Bienvenue à toi ${user}, tu trouveras ici d'autres chasseurs de succès francophones ! ${CDS}
> Si tu veux accéder au reste du Discord, c'est par ici ➡️ ${alire}
> On espére te voir participer à la vie du groupe, et tu verras, ensemble, la chasse aux succès est encore plus amusante !`;

Expand Down
10 changes: 5 additions & 5 deletions events/guildMemberRemove.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ module.exports = {

const embed = new EmbedBuilder()
.setColor(DARK_RED)
.setTitle(`Membre parti`)
.setTitle("Membre parti")
.setDescription(member.toString())
.addFields(
{
Expand All @@ -24,7 +24,7 @@ module.exports = {
inline: true,
},
{
name: `Parti le `,
name: "Parti le ",
value: `<t:${Math.floor(Date.now() / 1000)}:D>`,
inline: true,
},
Expand All @@ -37,15 +37,15 @@ module.exports = {
const userDB = await client.getUser(member);
const groups = await client.findGroupByUser(userDB);

for (let group of groups) {
for (const group of groups) {
if (group.captain.userId === userDB.userId) {
if (group.members.length === 1) {
await dissolveGroup(client, guildId, group);
} else {
let memberGrp = group.members.find((u) =>
const memberGrp = group.members.find((u) =>
u._id.equals(userDB._id),
);
let indexMember = group.members.indexOf(memberGrp);
const indexMember = group.members.indexOf(memberGrp);
group.members.splice(indexMember, 1);
group.size--;
const newCaptainDB = group.members[0];
Expand Down
8 changes: 4 additions & 4 deletions events/guildMemberUpdate.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,12 @@ module.exports = {
}

// edit nickname
if (oldUser.nickname != newUser.nickname) {
let oldNickname = oldUser.nickname || "_Aucun_";
let newNickname = newUser.nickname || "_Aucun_";
if (oldUser.nickname !== newUser.nickname) {
const oldNickname = oldUser.nickname || "_Aucun_";
const newNickname = newUser.nickname || "_Aucun_";
const embed = new EmbedBuilder()
.setColor(ORANGE)
.setTitle(`Surnom modifier`)
.setTitle("Surnom modifier")
.setDescription(
`${newUser}\nAncien surnom: ${oldNickname}\nNouveau surnom: ${newNickname}`,
)
Expand Down
15 changes: 10 additions & 5 deletions events/interactions/ticket.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@ const { GREEN } = require("../../data/colors.json");
module.exports = {
async execute(interaction) {
if (interaction.isButton()) {
if (interaction.channel.type !== ChannelType.PrivateThread) return;
if (interaction.channel.type !== ChannelType.PrivateThread) {
return;
}

switch (interaction.customId.split("-")[1]) {
case "close":
case "close": {
await interaction.reply(
`Le ticket a été clos par ${interaction.user}.`,
);
Expand All @@ -24,14 +26,16 @@ module.exports = {
await interaction.channel.setLocked(true);
await interaction.channel.setArchived(true);
break;
case "resolve":
}
case "resolve": {
await interaction.reply(
`Le ticket a été marqué comme résolu par ${interaction.user}.`,
);

// Archivage du ticket
await interaction.channel.setArchived(true);
break;
}
}
} else if (interaction.isModalSubmit()) {
// Création de ticket
Expand All @@ -49,11 +53,12 @@ module.exports = {
);

// Gestion d'erreur si aucun salon de ticket n'est défini
if (!ticketChannelId)
return await interaction.reply({
if (!ticketChannelId) {
return interaction.reply({
content: `Aucun salon de ticket n'a été trouvé.`,
ephemeral: true,
});
}

const ticketChannel =
interaction.client.channels.cache.get(ticketChannelId);
Expand Down
64 changes: 4 additions & 60 deletions events/messageCreate.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,10 @@
const {
Collection,
EmbedBuilder,
Events,
WebhookClient,
} = require("discord.js");
const { CROSS_MARK } = require("../data/emojis.json");
const { User, Game } = require("../models/index.js");
const {
BAREME_XP,
BAREME_MONEY,
SALON,
crtHour,
} = require("../util/constants");
const { Collection, Events } = require("discord.js");
const { User } = require("../models/index.js");
const { BAREME_XP, BAREME_MONEY, SALON } = require("../util/constants");
const { addXp } = require("../util/xp.js");
const { getAchievement } = require("../util/msg/stats");
const { feedBotMetaAch } = require("../util/envoiMsg");

const SteamUser = require("steam-user");
const FS = require("fs");
const { retryAfter5min } = require("../util/util");

module.exports = {
name: Events.MessageCreate,
async execute(msg) {
Expand Down Expand Up @@ -159,50 +144,10 @@ module.exports = {
}

// TODO auto replies sur certains mots/phrase ?

// stop
return;
}
},
};

const recupIcon = async (steamClient, appid, game) => {
// Passing true as the third argument automatically requests access tokens, which are required for some apps
let result = await steamClient.getProductInfo([parseInt(appid)], [], true);
if (result.apps[parseInt(appid)].appinfo?.common?.clienticon)
game.iconHash = result.apps[parseInt(appid)].appinfo.common.clienticon;
else game.iconHash = result.apps[parseInt(appid)].appinfo.common.icon;

await game.save();
};

const recupAchievements = async (client, appid, game) => {
// - recup achievements (si présent)
const resp = await client.getSchemaForGame(appid);
// si jeu a des succès
if (resp.availableGameStats?.achievements) {
console.log(` * a des succès !`);
const achievements = resp.availableGameStats.achievements;

// - ajout & save succes dans Game
achievements.forEach((el) => {
el["apiName"] = el["name"];
delete el.name;
delete el.defaultvalue;
delete el.hidden;
});

game.achievements = achievements;

await game.save();
} else {
// - save tableau vide
// console.log('pas de succes');
game.achievements = [];
await game.save();
}
};

const cooldowns = new Collection();

const cooldownTimeLeft = (type, seconds, userID) => {
Expand All @@ -219,8 +164,7 @@ const cooldownTimeLeft = (type, seconds, userID) => {
const expirationTime = timestamps.get(userID) + cooldownAmount;

if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
return timeLeft;
return (expirationTime - now) / 1000;
}
}

Expand Down
8 changes: 5 additions & 3 deletions events/messageDelete.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@ module.exports = {
// delete msg sauvegardé dans bdd
await Msg.deleteMany({ msgId: msg.id });

if (msg.author.bot || msg.channel.type === "dm") return;
if (msg.author.bot || msg.channel.type === "dm") {
return;
}

let embedLog = new EmbedBuilder()
.setTitle(`Message supprimé`)
const embedLog = new EmbedBuilder()
.setTitle("Message supprimé")
.setColor(ORANGE)
.setDescription(`Auteur : ${msg.author}`)
.addFields({ name: "Message", value: msg.content || "None" })
Expand Down
2 changes: 1 addition & 1 deletion events/messageReactionAdd.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const { SALON } = require("../util/constants.js");

module.exports = {
name: Events.MessageReactionAdd,
async execute(msgReaction, user) {
async execute(msgReaction) {
try {
const msg = msgReaction.message;
const emoji = msgReaction.emoji;
Expand Down
2 changes: 1 addition & 1 deletion events/messageReactionRemove.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const { SALON } = require("../util/constants.js");

module.exports = {
name: Events.MessageReactionRemove,
async execute(msgReaction, user) {
async execute(msgReaction) {
try {
const msg = msgReaction.message;
const emoji = msgReaction.emoji;
Expand Down
12 changes: 5 additions & 7 deletions events/ready.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,11 @@ module.exports = {
const VERSION = process.env.VERSION;
const date = new Date();
logger.info(
"Logged in as " +
client.user.tag +
"! Version: " +
VERSION +
". On " +
date.format("{MM}/{DD}/{Y} at {hh}:{mm}:{ss}") +
".",
`Logged in as ${
client.user.tag
}! Version: ${VERSION}. On ${date.format(
"{MM}/{DD}/{Y} at {hh}:{mm}:{ss}",
)}.`,
);

client.user.setPresence({
Expand Down
11 changes: 5 additions & 6 deletions events/voiceStateUpdate.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,16 @@ module.exports = {
// si old et new rempli => passe de old à new

// si le channel vocal 'creator' est bien save dans bdd
if (config?.channels && config.channels["create_vocal"]) {
if (config?.channels?.create_vocal) {
// si user arrive sur le channel 'créateur'
if (config.channels["create_vocal"] === newState.channelId) {
if (config.channels.create_vocal === newState.channelId) {
// ici newState est le 'creator'
const parent = newState.channel.parent;

// -- trouver un nom random parmis liste
let name = getChannelName();
console.log(
".. voice channel creator, on créé un nouveau channel " +
name,
const name = getChannelName();
logger.info(
`.. voice channel creator, on créé un nouveau channel ${name}`,
);

// -- créer un salon vocal dans même catégorie que original
Expand Down
23 changes: 11 additions & 12 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
const { Client, GatewayIntentBits, Collection, Events } = require("discord.js");
const { Client, GatewayIntentBits, Events } = require("discord.js");
const {
loadCommands,
loadEvents,
loadBatch,
loadReactionGroup,
loadRoleGiver,
loadReactionMsg,
loadVocalCreator,
} = require("./util/loader");
const winston = require("winston");
require("winston-daily-rotate-file");
require("dotenv").config();

var transport = new winston.transports.DailyRotateFile({
const transport = new winston.transports.DailyRotateFile({
filename: "logs/app-%DATE%.log",
datePattern: "YYYY-MM-DD-HH",
zippedArchive: true,
Expand Down Expand Up @@ -72,7 +71,7 @@ client.login(process.env.TOKEN).then((c) => {
//loadReactionGroup(client);
});

client.once(Events.ClientReady, async (c) => {
client.once(Events.ClientReady, async () => {
console.log(`
oooooooo8 ooooooooo oooooooo8 oooooooooo ooooooo ooooooooooo
o888 88 888 88o 888 888 888 o888 888o 88 888 88
Expand All @@ -81,21 +80,21 @@ o888 88 888 88o 888 888 888 o888 888o 88 888 88
888oooo88 o888ooo88 o88oooo888 o888ooo888 88ooo88 o888o
`);

logger.info(`Chargement des batchs ..`);
logger.info("Chargement des batchs ..");
await loadBatch(client);
logger.info(`.. terminé`);
logger.info(".. terminé");

logger.info(`Chargement des messages 'events' ..`);
logger.info("Chargement des messages 'events' ..");
await loadReactionGroup(client);
logger.info(`.. terminé`);
logger.info(".. terminé");

logger.info(`Chargement des reactions hall héros/zéros ..`);
logger.info("Chargement des reactions hall héros/zéros ..");
await loadReactionMsg(client);
logger.info(`.. terminé`);
logger.info(".. terminé");

logger.info(`Chargement du chan vocal créateur ..`);
logger.info("Chargement du chan vocal créateur ..");
await loadVocalCreator(client);
logger.info(`.. terminé`);
logger.info(".. terminé");

// loadRoleGiver(client);
});
Loading