Skip to content

Commit

Permalink
Merge pull request #493 from Project-Coda/auto-clean
Browse files Browse the repository at this point in the history
Auto clean
  • Loading branch information
ikifar2012 authored Oct 7, 2024
2 parents 5768596 + e101b48 commit 85e2cda
Show file tree
Hide file tree
Showing 5 changed files with 205 additions and 4 deletions.
51 changes: 51 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const vctools = require('./utilities/vc-tools.js');
const { checkMention } = require('./utilities/message-filter.js');
const nodecron = require('node-cron');
const vclogs = require('./utilities/vc-logs.js');
const { cleanupDB } = require('./utilities/cleanup.js');
global.client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMessageReactions, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.DirectMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildModeration],
partials: [Partials.Message, Partials.Channel, Partials.Reaction],
Expand All @@ -36,6 +37,7 @@ global.client.once('ready', async () => {
const members = await guild.members.fetch();
// set the client's presence
global.client.user.setActivity(`${members.size} members`, { type: ActivityType.Watching });
await cleanupDB();
});

(async () => {
Expand Down Expand Up @@ -180,6 +182,7 @@ global.client.on('messageReactionAdd', async (reaction, user) => {
const db = await mariadb.getConnection();
const role = await db.query('SELECT * FROM roles WHERE emoji = ? AND message_id = ?', [emoji, message.id]);
db.end();
if (role.length === 0) return;
const roleId = String(role[0].id);
console.log(role);
console.log(roleId);
Expand Down Expand Up @@ -327,6 +330,52 @@ global.client.on(Events.GuildAuditLogEntryCreate, async auditLog => {
await embedcreator.kickAlert(user, kickedUser, reasonformatted);
console.log(`${user.tag} kicked ${kickedUser.tag}! Reason: ${reasonformatted}`);
}
await cleanupDB();
});
global.client.on('guildMemberRemove', async member => {
try {
const embed = embedcreator.setembed({
title: 'Member Left',
description: `${member.user.tag} has left the server.`,
image: member.user.displayAvatarURL({ dynamic: true }),
color: 0xe74c3c,
});
global.client.channels.cache.get(env.discord.logs_channel).send({ embeds: [embed] });
}
catch (error) {
console.error(error);
embedcreator.sendError(error);
}
});

global.client.on('roleDelete', async role => {
try {
const embed = embedcreator.setembed({
title: 'Role Deleted',
description: `${role.name} was deleted.`,
color: 0xe74c3c,
});
global.client.channels.cache.get(env.discord.logs_channel).send({ embeds: [embed] });
}
catch (error) {
console.error(error);
embedcreator.sendError(error);
}
});

global.client.on('channelDelete', async channel => {
try {
const embed = embedcreator.setembed({
title: 'Channel Deleted',
description: `${channel.name} was deleted.`,
color: 0xe74c3c,
});
global.client.channels.cache.get(env.discord.logs_channel).send({ embeds: [embed] });
}
catch (error) {
console.error(error);
embedcreator.sendError(error);
}
});

// clear coda strkes older than an hour
Expand All @@ -336,6 +385,8 @@ nodecron.schedule('0 0 * * *', async () => {
await db.query('DELETE FROM coda_strikes WHERE timestamp < DATE_SUB(NOW(), INTERVAL 1 HOUR)');
db.end();
embedcreator.log('Coda strikes older than an hour have been deleted.');
await cleanupDB();
embedcreator.log('Ran database cleanup.');
}
catch (error) {
console.error(error);
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "coda-utilities",
"version": "3.7.0",
"version": "3.8.0",
"description": "A general utilities bot for Coda",
"main": "index.js",
"scripts": {
Expand Down
147 changes: 147 additions & 0 deletions utilities/cleanup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
const embedcreator = require('../embed.js');
const mariadb = require('../db.js');
const env = require('../env.js');

async function cleanupDBRoles() {
const db = await mariadb.getConnection();
const queryroles = 'SELECT id FROM roles';
const queryrolesresult = await db.query(queryroles);
const roles = await queryrolesresult.map(role => role.id);
const guild = await client.guilds.cache.get(env.discord.guild);
const guildroles = guild.roles.cache.map(role => role.id);
const rolesToDelete = roles.filter(role => !guildroles.includes(role));
for (const role of rolesToDelete) {
const query = 'DELETE FROM roles WHERE id = ?';
await db.query(query, [role]);
console.log(`Deleted role id: ${role} from roles table`);

}
const queryChannels = 'SELECT channel_id FROM roles';
const queryChannelsResult = await db.query(queryChannels);
const channels = await queryChannelsResult.map(channel => channel.channel_id);
const guildchannels = guild.channels.cache.map(channel => channel.id);
const channelsToDelete = channels.filter(channel => !guildchannels.includes(channel));
for (const channel of channelsToDelete) {
const query = 'DELETE FROM roles WHERE channel_id = ?';
await db.query(query, [channel]);
console.log(`Deleted channel id: ${channel} from roles table`);
}
const queryMessages = 'SELECT message_id FROM roles';
const queryMessagesResult = await db.query(queryMessages);
const messages = await queryMessagesResult.map(message => message.message_id);
let messagesToDelete = 0;
for (const message of messages) {
// check if message exists if it doesn't delete it
const channel = await db.query('SELECT channel_id FROM roles WHERE message_id = ?', [message]);
const messageExists = await guild.channels.cache.get(channel[0].channel_id).messages.fetch(message).catch(() => false);
if (!messageExists) {
messagesToDelete += 1;
const query = 'DELETE FROM roles WHERE message_id = ?';
await db.query(query, [message]);
console.log(`Deleted message id: ${message} from roles table`);
}
}
// add up all the items that were deleted
const totalItemsDeleted = rolesToDelete.length + channelsToDelete.length + messagesToDelete;

const embed = embedcreator.setembed({
title: 'Ran Cleanup on Role Assign 🧹',
description: `${totalItemsDeleted} item${totalItemsDeleted !== 1 ? 's were' : ' was'} removed from the database`,
color: 0xe74c3c,
});
if (totalItemsDeleted > 0) {
await global.client.channels.cache.get(env.discord.logs_channel).send({ content: '<@&' + env.discord.admin_role + '> Ran Cleanup on Role Assign 🧹', embeds: [embed] });
}
await db.end();
}

async function cleanupDBAutoRoles() {
const db = await mariadb.getConnection();
const queryroles = 'SELECT role_id FROM auto_role';
const queryrolesresult = await db.query(queryroles);
const roles = await queryrolesresult.map(role => role.role_id);
const guild = await client.guilds.cache.get(env.discord.guild);
const guildroles = await guild.roles.cache.map(role => role.id);
const rolesToDelete = roles.filter(role => !guildroles.includes(role));
for (const role of rolesToDelete) {
const query = 'DELETE FROM auto_role WHERE role_id = ?';
await db.query(query, [role]);
console.log(`Deleted role id: ${role} from auto_role table`);
}
const embed = embedcreator.setembed({
title: 'Ran Cleanup on Auto Roles 🧹',
description: `${rolesToDelete.length} role${rolesToDelete.length !== 1 ? 's were' : ' was'} removed from the database`,
color: 0xe74c3c,
});
if (rolesToDelete.length > 0) {
await global.client.channels.cache.get(env.discord.logs_channel).send({ content: '<@&' + env.discord.admin_role + '> Ran Cleanup on Auto Roles 🧹', embeds: [embed] });
}
await db.end();
}

async function cleanupDBNotify() {
const db = await mariadb.getConnection();
const queryusers = 'SELECT user_id FROM notify';
const queryusersresult = await db.query(queryusers);
const users = queryusersresult.map(user => user.user_id);
const guild = await client.guilds.cache.get(env.discord.guild);
const guildmembers = guild.members.cache.map(member => member.id);
const usersToDelete = users.filter(user => !guildmembers.includes(user));
for (const user of usersToDelete) {
const query = 'DELETE FROM notify WHERE user_id = ?';
await db.query(query, [user]);
console.log(`Deleted user id ${user} from notify table`);
}
const embed = embedcreator.setembed({
title: 'Ran Cleanup on Notify',
description: `${usersToDelete.length} user${usersToDelete.length !== 1 ? 's were' : ' was'} removed from the database`,
color: 0xe74c3c,
});
if (usersToDelete.length > 0) {
await global.client.channels.cache.get(env.discord.logs_channel).send({ content: '<@&' + env.discord.admin_role + '> Ran Cleanup on Notify 🧹', embeds: [embed] });
}
await db.end();
}
async function cleanupDBVC_Logs() {
const db = await mariadb.getConnection();
const queryusers = 'SELECT user_id FROM vc_logs';
const queryusersresult = await db.query(queryusers);
const users = queryusersresult.map(user => user.user_id);
const guild = await client.guilds.cache.get(env.discord.guild);
const guildmembers = guild.members.cache.map(member => member.id);
const usersToDelete = users.filter(user => !guildmembers.includes(user));
for (const user of usersToDelete) {
const query = 'DELETE FROM vc_logs WHERE user_id = ?';
await db.query(query, [user]);
console.log(`Deleted user id ${user} from vc_logs table`);
}
const embed = embedcreator.setembed({
title: 'Ran Cleanup on VC Logs',
description: `${usersToDelete.length} user${usersToDelete.length !== 1 ? 's were' : ' was'} removed from the database`,
color: 0xe74c3c,
});
if (usersToDelete.length > 0) {
await global.client.channels.cache.get(env.discord.logs_channel).send({ content: '<@&' + env.discord.admin_role + '> Ran Cleanup on VC Logs 🧹', embeds: [embed] });
}
await db.end();
}

async function cleanupDB() {
try {
await cleanupDBRoles();
await cleanupDBAutoRoles();
await cleanupDBNotify();
await cleanupDBVC_Logs();
}
catch (err) {
console.log(err);
embedcreator.sendError(err);
}
}

module.exports = {
cleanupDB,
cleanupDBRoles,
cleanupDBAutoRoles,
cleanupDBNotify,
};
5 changes: 4 additions & 1 deletion utilities/vc-tools.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,10 @@ async function returnUserToPreviousChannel(userid) {
await db.end();
const guild = await global.client.guilds.cache.get(env.discord.guild);
const member = await guild.members.cache.get(userid);
if (!previouschannel) {
// ensure previous channel is not in the custom vc category or the asktojoin category
const parentchannel = await getParentChannel(previouschannel);
const custom_vc_category = await getParentChannel(env.utilities.customvc.channel);
if (parentchannel === custom_vc_category || parentchannel === env.utilities.customvc.asktojoin || previouschannel === null) {
return await member.voice.setChannel(null);
}
else {
Expand Down

0 comments on commit 85e2cda

Please sign in to comment.