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

Merge dev-welcome to Dev #87

Merged
merged 22 commits into from
Oct 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
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
6 changes: 3 additions & 3 deletions commands/administration/autorole-configure.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ module.exports = {
var localEmbedResponse = embedReply(
embedColors.failure,
"AutoRole Configure: Error",
"You can only set autorole in a server.",
"You can only set up autorole in a server.",
interaction
);
}
Expand All @@ -43,12 +43,12 @@ module.exports = {
const autoRoleGuildId = query[0]?.guildId || null;
const autoRoleRoleId = query[0]?.roleId || null;

//if autorole has already been configured at this server...
//if autorole has already been configured for this server...
if (autoRoleRoleId == targetRole) {
var localEmbedResponse = embedReply(
embedColors.failure,
"AutoRole Configure: Error",
"Autorole has been already configured for this server with this role. :x:\nRun the command with another role to overwrite the current role.\nRun `/autorole-disable` to disable this feature.",
"Autorole has already been configured for this server with this role. :x:\nRun the command with another role to overwrite the current role.\nRun `/autorole-disable` to disable this feature completely.",
interaction
);
}
Expand Down
138 changes: 138 additions & 0 deletions commands/administration/welcome-configure.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
const { SlashCommandBuilder, PermissionFlagsBits } = require("discord.js");
const { embedReplySuccessColor, embedReplySuccessSecondaryColor, embedReplyWarningColor, embedReplyFailureColor } = require("../../helpers/embed-reply");
const { logToFileAndDatabase } = require("../../helpers/logger");
const db = require("../../helpers/db");

module.exports = {
data: new SlashCommandBuilder()
.setName("welcome-configure")
.setDescription("Sets a welcome message that will be displayed for the new members in a specified channel.")
.addChannelOption(option =>
option
.setName("channel")
.setDescription("A channel where the welcome message will be displayed.")
.addChannelTypes(0) //= GUILD_TEXT aka. text channels
.setRequired(true)
)
.addStringOption(option =>
option
.setName("message")
//the description length is limited to 100 characters ¯\_(ツ)_/¯
.setDescription("A message that the new members will see.") //You can use the following placeholders: {user} - the new member's username, {server} - the server's name, {memberCount} - the server's member count.
.setRequired(true)
)
.addBooleanOption(option =>
option
.setName("embed")
.setDescription("Whether the message should be sent as an embed (doesn't supports pinging users).")
.setRequired(false)
)
.addIntegerOption(option =>
option
.setName("embed-color")
.setDescription("The HEX color of the embed message. Leave empty for default color.")
.setRequired(false)
)
.setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
.setDMPermission(false),
async execute(interaction) {
if (!interaction.inGuild()) {
var embedReply = embedReplyFailureColor(
"Welcome Configure: Error",
"You can only set a welcome message in a server.",
interaction
);
}
else if (!interaction.guild.members.me.permissions.has(PermissionFlagsBits.Administrator)) {
var embedReply = embedReplyFailureColor(
"Welcome Disable: Error",
"This feature requires **administrator** *(8)* privileges which the bot currently lacks.\nIf you want this feature to work, please re-invite the bot with accurate privileges.",
interaction
);
}
else {
try {
const channelId = interaction.options.getChannel("channel").id;
const welcomeMessage = interaction.options.getString("message");
const isEmbed = interaction.options.getBoolean("embed") || 0;
const embedColor = interaction.options.getInteger("embed-color") || null;

const guildId = interaction.guild.id;
const adderId = interaction.user.id;
const adderUsername = interaction.user.username;

const query = await db.query("SELECT channelId, message, isEmbed, embedColor FROM welcome WHERE guildId = ?", [guildId]);
const existingChannelId = query[0]?.channelId || null;
const existingWelcomeMessage = query[0]?.message || null;
const existingIsEmbed = query[0]?.isEmbed || 0;
const existingEmbedColor = query[0]?.embedColor || null;

//if welcome messages haven't been configured for the current server
if (!existingChannelId) {
var embedReply = embedReplySuccessColor(
"Welcome Configure: Configuration Set",
"The **welcome message** has been successfully **set**. :white_check_mark:\nRun this command again later if you want to modify the current configuration.\nRun `/welcome-disable` if you want to disable this feature.",
interaction
);
}
else {
//checks if anything has been modified in the the command
let modifications = [];
if (welcomeMessage != existingWelcomeMessage) {
modifications.push("**welcome message**");
}
if (isEmbed != existingIsEmbed) {
modifications.push("**embed option**");
}
if (embedColor != existingEmbedColor) {
modifications.push("**embed color**");
}
if (channelId != existingChannelId) {
modifications.push(`**welcome channel** to <#${channelId}>`);
}

//if the exact same welcome configuration is set for the current server (aka. nothing got modified)
if (modifications.length === 0) {
var embedReply = embedReplyWarningColor(
"Welcome Configure: Warning",
"The exact same welcome configuration has been set for this server already. :x:\nRun the command again with different options to overwrite the current configuration.\nRun `/welcome-disable`, if you want to disable this feature.",
interaction
);
}
//if the welcome configuration has been modified
else {
let modificationsMessage;
if (modifications.length === 1) {
modificationsMessage = modifications[0];
} else {
modificationsMessage = modifications.slice(0, -1).join(", ") + " and " + modifications[modifications.length - 1];
}

var embedReply = embedReplySuccessSecondaryColor(
"Welcome Configure: Configuration Modified",
`Successfully modified ${modificationsMessage}. :white_check_mark:\nRun the command again with different options to overwrite the current configuration.\nRun \`/welcome-disable\`, if you want to disable this feature.`,
interaction
);
}
}

await db.query("INSERT INTO welcome (guildId, channelId, message, isEmbed, embedColor, adderId, adderUsername) VALUES (?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE channelId = ?, message = ?, adderId = ?, adderUsername = ?, isEmbed = ?, embedColor = ?",
[guildId, channelId, welcomeMessage, isEmbed, embedColor, adderId, adderUsername, channelId, welcomeMessage, adderId, adderUsername, isEmbed, embedColor]
);
}
catch (error) {
var embedReply = embedReplyFailureColor(
"Welcome Configure: Error",
"There was an error while trying to configure the welcome messages.",
interaction
);
}
}

await interaction.reply({ embeds: [embedReply] });

//logging
const response = JSON.stringify(embedReply.toJSON());
await logToFileAndDatabase(interaction, response);
}
}
62 changes: 62 additions & 0 deletions commands/administration/welcome-disable.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
const { SlashCommandBuilder, PermissionFlagsBits } = require("discord.js");
const { embedReplyPrimaryColor, embedReplyFailureColor, embedReplyWarningColor, embedReplySuccessColor } = require("../../helpers/embed-reply");
const { logToFileAndDatabase } = require("../../helpers/logger");
const db = require("../../helpers/db");

module.exports = {
data: new SlashCommandBuilder()
.setName("welcome-disable")
.setDescription("Disables welcome messages for the current server.")
.setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
.setDMPermission(false),
async execute(interaction) {
if (!interaction.inGuild()) {
var embedReply = embedReplyFailureColor(
"Welcome Disable: Error",
"You can only disable the welcome messages in a server.",
interaction
);
}
else if (!interaction.guild.members.me.permissions.has(PermissionFlagsBits.Administrator)) {
var embedReply = embedReplyFailureColor(
"Welcome Disable: Error",
"This feature requires **administrator** *(8)* privileges which the bot currently lacks.\nIf you want this feature to work, please re-invite the bot with accurate privileges.",
interaction
);
}
else {
try {
const currentGuildId = interaction.guild.id;
const query = await db.query("SELECT guildId FROM welcome WHERE guildId = ?", [currentGuildId]);
const welcomeGuildId = query[0]?.guildId || null;

if (welcomeGuildId) {
await db.query("DELETE FROM welcome WHERE guildId = ?", [welcomeGuildId]);

var embedReply = embedReplySuccessColor(
"Welcome Disable: Success",
"The welcome messages have been disabled successfully for this server.\nYou can re-enable them with the `/welcome-configure` command.",
interaction
);
}
else {
var embedReply = embedReplyWarningColor(
"Welcome Disable: Warning",
"Welcome messages have not been configured for this server.\nTherefore, you can't disable them.\nYou can enable this feature with the `/welcome-configure` command.",
interaction
);
}
}
catch (error) {
var embedReply = embedReplyFailureColor(
"Welcome Disable: Error",
"There was an error while trying to disable the welcome messages.",
interaction
);
// console.error(error);
}
}

await interaction.reply({ embeds: [embedReply] });
}
}
2 changes: 2 additions & 0 deletions commands/utility/help.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ module.exports = {
"**__NOTE__**: The following commands require relevant **administration permissions** for both the bot and the command's executor to work.\n" +
"`/autorole-configure` - Sets / modifies the autorole feature. When a new member joins the server, a specified role will get assigned to them automatically.\n" +
"`/autorole-disable` - Disables the autorole feature. New members won't get the specified role automatically on join anymore.\n" +
"`/welcome-configure` - Sets / modifies the welcome messages feature. When a new member joins the server, the bot send a specified welcome message.\n" +
"`/welcome-disable` - Disables the welcome messages feature. The bot won't send a welcome message on join anymore.\n" +
"`/rename` - Renames a specified user to a specified nickname in the current server."
};

Expand Down
15 changes: 8 additions & 7 deletions create-tables.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const fs = require("fs");
const path = require("path");
const db = require("./helpers/db");
db.getConnection();

// reads the SQL queries from a folder's subfolder
function readSQLFiles(dir) {
Expand All @@ -9,8 +10,8 @@ function readSQLFiles(dir) {

for (const file of sqlFiles) {
const filePath = path.join(dir, file);
const query = fs.readFileSync(filePath, "utf8");
sqlQueries.push(query);
const queries = fs.readFileSync(filePath, "utf8").split(';').filter(query => query.trim() !== '');
sqlQueries.push(...queries);
}

return sqlQueries;
Expand All @@ -37,21 +38,21 @@ async function createTables() {
}
}

//executes the table creation queries
//executes the table creation (and other) queries
for (const query of sqlQueries) {
try {
await db.query(query);
console.log("Table created successfully.");
console.log("Query executed successfully.");
}
catch (error) {
console.error("Error creating table: ", error);
console.error("Error executing query: ", error);
}
}

console.log("All tables are processed.") ;
console.log("All queries are executed & all tables are processed.");
}
catch (error) {
console.error("Error creating tables: ", error);
console.error("Error executing queries & creating tables: ", error);
}
}

Expand Down
22 changes: 4 additions & 18 deletions events/guildMemberAdd.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,10 @@
const db = require("../helpers/db");
const autorole = require("./scripts/guildMemberAdd/autorole");
const welcome = require("./scripts/guildMemberAdd/welcome");

module.exports = {
name: "guildMemberAdd",
async execute(member) {
const guildId = member.guild.id;

try {
const rows = await db.query("SELECT roleId FROM autorole WHERE guildId = ?", [guildId]);
const roleId = rows[0].roleId;

if (roleId) {
const role = member.guild.roles.cache.get(roleId);
if (role) {
await member.roles.add(role);
console.log(`Assigned ${role.name} role to ${member.user.tag} in ${member.guild.name}`);
}
}
}
catch (error) {
console.error(error);
}
await autorole.assignRole(member);
await welcome.sendWelcomeMessage(member);
},
};
26 changes: 26 additions & 0 deletions events/scripts/guildMemberAdd/autorole.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const db = require("../../../helpers/db");

module.exports = {
async assignRole (member) {
const guildId = member.guild.id;
const serverName = member.guild.name;

const userTag = member.user.tag;

try {
const rows = await db.query("SELECT roleId FROM autorole WHERE guildId = ?", [guildId]);
const roleId = rows[0]?.roleId;

if (roleId) {
const role = member.guild.roles.cache.get(roleId);
if (role) {
await member.roles.add(role);
console.log(`Assigned ${role.name} role to ${userTag} in ${serverName}`);
}
}
}
catch (error) {
console.error(`Failed to assign role: ${error}`);
}
}
}
49 changes: 49 additions & 0 deletions events/scripts/guildMemberAdd/welcome.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
const db = require("../../../helpers/db");
const { embedColors } = require("../../../config.json");
const { embedMessage } = require("../../../helpers/embed-reply");

module.exports = {
async sendWelcomeMessage(member) {
const guildId = member.guild.id;
const serverName = member.guild.name;
const memberCount = member.guild.memberCount;
const userTag = member.user.tag;
const userId = member.user.id;

try {
const rows = await db.query("SELECT channelId, message, isEmbed, embedColor FROM welcome WHERE guildId = ?", [guildId]);
const channelId = rows[0]?.channelId;
let message = rows[0]?.message;
const isEmbed = rows[0]?.isEmbed;
const embedColor = rows[0]?.embedColor || embedColors.primary;

if (channelId && message) {
const channel = member.guild.channels.cache.get(channelId);
if (channel) {
message = message
.replace("{user}", `<@${userId}>`)
.replace("{server}", serverName)
.replace("{memberCount}", memberCount);

if (isEmbed) {
const embedContent = embedMessage(
embedColor,
"Welcome!",
message,
);

await channel.send({ embeds: [embedContent] });
}
else {
await channel.send(message);
}

console.log(`Sent welcome message to ${userTag} in ${serverName}.`);
}
}
}
catch (error) {
console.error(`Failed to display welcome message: ${error}`);
}
}
};
Loading
Loading