Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
testfax committed Oct 5, 2024
1 parent 0bb5d93 commit 5f5402f
Show file tree
Hide file tree
Showing 3 changed files with 212 additions and 30 deletions.
76 changes: 73 additions & 3 deletions commands/GuardianAI/promotionRequest/requestpromotion.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,78 @@ function getPercentage(part, whole) {
if (whole === 0) return 0 // Avoid division by zero
return ((part / whole) * 100).toFixed(2)
}

module.exports = {
getRankEmoji: async function (interaction) {

let roles = await interaction.member.roles.cache.map(role=>role.name)
roles = roles.filter(x=>x != '@everyone')


const rankObj = config[botIdent().activeBot.botName].officer_ranks.find(rank =>
roles.includes(rank.rank_name)
)
console.log(rankObj)
return rankObj.emoji
},
promotionChallengeResult: async function (data,interaction) {
try {
const values = [data.userId]
const sql = 'SELECT * FROM `promotion` WHERE userId = (?)'
const response = await database.query(sql,values)
if (response.length > 0) {
const challenge_score = response[0].challenge_state == 1 ? "Approved" : "Denied"
const challenge_score_color = response[0].challenge_state == 1 ? '#87FF2A' : '#F20505'
const leadership_thread = await interaction.guild.channels.fetch(response[0].leadership_threadId)
const requestor_thread = await interaction.guild.channels.fetch(response[0].requestor_threadId)
const requestor = await guild.members.fetch(data.userId)
const leadership_challenge = await leadership_thread.messages.fetch(response[0].challenge_leadership_embedId)

const requestor_challenge = await requestor_thread.messages.fetch(response[0].challenge_requestor_embedId)
const leadership_receivedEmbed = leadership_challenge.embeds[0]
const oldEmbedSchema = {
title: leadership_receivedEmbed.title,
author: { name: requestor.displayName, iconURL: requestor.user.displayAvatarURL({ dynamic: true }) },
description: leadership_receivedEmbed.description,
color: leadership_receivedEmbed.color,
fields: leadership_receivedEmbed.fields
}
const newEmbed = new Discord.EmbedBuilder()
.setTitle(oldEmbedSchema.title)
.setDescription(`Challenge Proof Reviewed by Leadership`)
// .setColor('#87FF2A') //bight green
// .setColor('#f20505') //bight red
// .setColor('#f2ff00') //bight yellow
.setAuthor(oldEmbedSchema.author)
.setThumbnail(botIdent().activeBot.icon)
// newEmbed.addFields(
// { name: "Promotion Status", value: "<:customEmojiName:emojiID> Promotion Approved!", inline: false }
// );
newEmbed.setColor(challenge_score_color)
let rank_emoji = await module.exports.getRankEmoji(interaction);
if (rank_emoji == null) { rank_emoji == "" }
oldEmbedSchema.fields.forEach((i,index) => {
if (index == 0) { newEmbed.addFields({name: i.name, value: i.value, inline: i.inline}) }
if (index == 1) { newEmbed.addFields({ name: "Promotion Challenge Status", value: "```" + challenge_score + "```", inline: true }) }
if (index == 2) { newEmbed.addFields({name: i.name, value: i.value, inline: i.inline}) }
if (index == 3) { newEmbed.addFields({name: "Reviewed By", value: `${rank_emoji}<@${data.reviewer}>`, inline: i.inline}) }
})
await leadership_challenge.edit( { embeds: [newEmbed], components: [] } )
await requestor_challenge.edit( { embeds: [newEmbed] } )
await requestor_thread.setLocked(true)

}
}
catch (err) {
console.log(err)
botLog(interaction.guild,new Discord.EmbedBuilder()
.setDescription('```' + err.stack + '```')
.setTitle(`⛔ Fatal error experienced`)
,2
,'error'
)
}
},
showPromotionChallenge: async function (data) {
const testTypes = {
"basic": "Aviator",
Expand All @@ -31,7 +102,6 @@ module.exports = {
"master": "General Staff",
}
const requestor = await guild.members.fetch(data.user.id)
// (!args.link.startsWith('https://')) { return interaction.editReply({ content: `❌ Please enter a valid URL, eg: https://...` }) }
const leadership_newEmbed = new Discord.EmbedBuilder()
.setTitle(`Promotion Challenege Proof`)
.setDescription(`Waiting on requestor to submit Promotion Challenge Proof.`)
Expand Down Expand Up @@ -65,8 +135,8 @@ module.exports = {
const requestor_embedId = await requestor_thread.send( { embeds: [requestor_newEmbed]} )

try {
const values = [leadership_embedId.id,requestor_embedId.id,data.promotion.userId]
const sql = `UPDATE promotion SET challenge_requestor_embedId = (?), challenge_leadership_embedId WHERE userId = (?);`
const values = [requestor_embedId.id,leadership_embedId.id,data.promotion.userId]
const sql = `UPDATE promotion SET grading_state = 3, challenge_requestor_embedId = (?), challenge_leadership_embedId = (?) WHERE userId = (?);`
await database.query(sql, values)
}
catch (err) {
Expand Down
37 changes: 36 additions & 1 deletion discordEvents/interactionCreate.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const { botLog, botIdent } = require('../functions')
const { leaderboardInteraction } = require('../commands/Warden/leaderboards/leaderboard_staffApproval')
const { nextTestQuestion, nextGradingQuestion } = require('../commands/GuardianAI/promotionRequest/requestpromotion')
const { nextTestQuestion, nextGradingQuestion, promotionChallengeResult } = require('../commands/GuardianAI/promotionRequest/requestpromotion')
const database = require(`../${botIdent().activeBot.botName}/db/database`)
// if (botIdent().activeBot.botName == 'Warden') {
// }
Expand Down Expand Up @@ -140,6 +140,41 @@ const exp = {
)
}

return;
}
if (interaction.customId.startsWith("promotionchallenge")) { //grade and update database
interaction.deferUpdate()
interaction.message.edit({ components: [] })
const customId_array = interaction.customId.split("-")
const challengeInfo = {
state: customId_array[1],
userId: customId_array[2],
reviewer: interaction.user.id
}
let score = 0
if (challengeInfo.state == 'approve') { score = 1 }
if (challengeInfo.state == 'deny') { score = 0 }

//Update progress number and save to database.
try {
const values = [Number(score), challengeInfo.userId]
const sql = `UPDATE promotion SET challenge_state = (?) WHERE userId = (?);`
const d = await database.query(sql, values)
if (d) {
// console.log('saved')
promotionChallengeResult(challengeInfo,interaction)
}
}
catch (err) {
console.log(err)
botLog(interaction.guild,new Discord.EmbedBuilder()
.setDescription('```' + err.stack + '```')
.setTitle(`⛔ Fatal error experienced`)
,2
,'error'
)
}

return;
}
}
Expand Down
129 changes: 103 additions & 26 deletions discordEvents/simpleEvents.js
Original file line number Diff line number Diff line change
@@ -1,54 +1,131 @@
const { generateDateTime, botLog, botIdent } = require('../functions')
const { nextTestQuestion } = require("../commands/GuardianAI/promotionRequest/requestpromotion")
const { nextTestQuestion,getRankEmoji } = require("../commands/GuardianAI/promotionRequest/requestpromotion")
const Discord = require('discord.js')
const database = require(`../${botIdent().activeBot.botName}/db/database`)
const config = require('../config.json')
const exp = {
messageCreate: async (message, bot) => {
if (botIdent().activeBot.botName == 'GuardianAI' && !message.author.bot) {
let applyForRanks_guardianai = null
let graderRank = []
if (process.env.MODE != "PROD") {
applyForRanks_guardianai = config[botIdent().activeBot.botName].general_stuff.testServer.knowledge_proficiency.embedChannel
console.log("[CAUTION]".bgYellow, "knowledge proficiency embed channel required. Check config.json file. guardianai.general_stuff.knowledge_proficiency.embedChannel. Using testServer input if available")
generalstaff = config[botIdent().activeBot.botName].general_stuff.testServer.allRanks_testServer.find(r=>r.rank_name === 'General Staff').id
colonel = config[botIdent().activeBot.botName].general_stuff.testServer.allRanks_testServer.find(r=>r.rank_name === 'Colonel').id
major = config[botIdent().activeBot.botName].general_stuff.testServer.allRanks_testServer.find(r=>r.rank_name === 'Major').id
captain = config[botIdent().activeBot.botName].general_stuff.testServer.allRanks_testServer.find(r=>r.rank_name === 'Captain').id
graderRank.push({"General Staff":generalstaff,"Colonel":colonel,"Major":major,"Captain":captain})
}
else {
applyForRanks_guardianai = config[botIdent().activeBot.botName].general_stuff.knowledge_proficiency.embedChannel
generalstaff = config[botIdent().activeBot.botName].general_stuff.allRanks.find(r=>r.rank_name === 'General Staff').id
colonel = config[botIdent().activeBot.botName].general_stuff.allRanks.find(r=>r.rank_name === 'Colonel').id
major = config[botIdent().activeBot.botName].general_stuff.allRanks.find(r=>r.rank_name === 'Major').id
captain = config[botIdent().activeBot.botName].general_stuff.allRanks.find(r=>r.rank_name === 'Captain').id
graderRank.push({"General Staff":generalstaff,"Colonel":colonel,"Major":major,"Captain":captain})
}
else { applyForRanks_guardianai = config[botIdent().activeBot.botName].general_stuff.knowledge_proficiency.embedChannel }

let messageParent = message.channel.parentId
if (messageParent == applyForRanks_guardianai) {
// const embedChannelObj = await message.guild.channels.fetch(applyForRanks_guardianai)
if (message.channel.name.includes("Submission") && message.attachments.size > 0) {
message.attachments.forEach(attachment => {
if (attachment.contentType && attachment.contentType.startsWith('image/')) {
console.log('Image detected:', attachment.url)
//todo DO STUFF TO CHANGE PROMOTION CHALLENGE EMBED

}
})
}
if (message.channel.name.includes("Submission") && message.attachments.size == 0) {
if (message.channel.name.includes("Submission")) {

// console.log("submitting")
// .setColor('#87FF2A') //bight green
// .setColor('#f20505') //bight red
// .setColor('#f2ff00') //bight yellow

const urlRegex = /(https:\/\/[^\s]+)/g
const urls = message.content.match(urlRegex)

try {
const values = [message.author.id]
const sql = 'SELECT leadership_threadId,grading_state FROM `promotion` WHERE userId = (?)'
const sql = 'SELECT * FROM `promotion` WHERE userId = (?)'
const response = await database.query(sql,values)
if (response[0].grading_state == 2 && urls != null) {
console.log("urls:",urls)

//todo DO STUFF TO CHANGE PROMOTION CHALLENGE EMBED
//For promotion challenge proof
if (response[0].grading_state == 3) {
const rankTypes = {
"basic": "Aviator",
"advanced": "Lieutenant",
"master": "Captain",
"master": "General Staff",
}
const testTypes = {
"Aviator": "basic",
"Lieutenant": "advanced",
"Captain": "master",
"General Staff": "master",
}
const graderTypes = {
"basic": "Captain",
"advanced": "Major",
"master": "Colonel"
}
const grader_ident = graderTypes[response[0].testType]
const leadership_thread = await message.guild.channels.fetch(response[0].leadership_threadId)
if (leadership_thread.id == message.channel.id) {
//If chat is discovered in the leadership thread, abandon this script.
return
}
//use 1 embed and modify both leadership embed and requestor embed
const leadership_challenge = await leadership_thread.messages.fetch(response[0].challenge_leadership_embedId)
const leadership_embed = leadership_challenge.embeds[0]

const requestor_thread = await message.guild.channels.cache.get(response[0].requestor_threadId)
const requestor_challenge = await requestor_thread.messages.fetch(response[0].challenge_requestor_embedId)

return
}
if (response[0].grading_state == 2 && urls == null) {
message.delete()
message.channel.send('❌ Please enter a valid URL, eg: https://...')
return
const leadership_oldEmbedSchema = {
title: leadership_embed.title,
author: { name: message.author.displayName, iconURL: message.author.displayAvatarURL({ dynamic: true }) },
description: leadership_embed.description,
color: leadership_embed.color
}

const newEmbed = new Discord.EmbedBuilder()
.setTitle(leadership_oldEmbedSchema.title)
.setDescription(`Waiting on approval from Leadership.`)
.setColor("#f2ff00")
// .setColor('#87FF2A') //bight green
// .setColor('#f20505') //bight red
// .setColor('#f2ff00') //bight yellow
.setAuthor(leadership_oldEmbedSchema.author)
.setThumbnail(botIdent().activeBot.icon)
.addFields(
{ name: "Promotion Rank", value: "```" + rankTypes[response[0].testType] + "```", inline: true },
{ name: "Promotion Challenge Status", value: "```" + 'Submitted, awaiting leadership approval' + "```", inline: true },
)
const row = new Discord.ActionRowBuilder()
.addComponents(new Discord.ButtonBuilder().setCustomId(`promotionchallenge-approve-${message.author.id}`).setLabel('Approve').setStyle(Discord.ButtonStyle.Success))
.addComponents(new Discord.ButtonBuilder().setCustomId(`promotionchallenge-deny-${message.author.id}`).setLabel('Deny').setStyle(Discord.ButtonStyle.Danger))
if (message.attachments.size > 0) {
message.attachments.forEach(async attachment => {
if (attachment.contentType && attachment.contentType.startsWith('image/')) {
newEmbed.addFields(
{ name: "Promotion Challenge Proof", value: attachment.url, inline: false },
{ name: "Required Approval by:", value: `<@&${graderRank[0][grader_ident]}> or Higher`, inline: false }
)
}
})
await leadership_challenge.edit( { embeds: [newEmbed], components: [row] } )
await requestor_challenge.edit( { embeds: [newEmbed] } )
return
}
const urlRegex = /(https:\/\/[^\s]+)/g
let urls = message.content.match(urlRegex)
if (urls == null && message.attachments.size == 0) {
message.delete()
message.channel.send('❌ Please enter a valid URL, eg: https://...')
return
}
if (urls != null && message.attachments.size == 0) {
urls = urls.map(i => i + "\n")
newEmbed.addFields(
{ name: "Promotion Challenge Proof", value: `${urls}`, inline: false },
{ name: "Required Approval by:", value: `<@&${graderRank[0][grader_ident]}> or Higher`, inline: false }
)
message.delete()
await leadership_challenge.edit( { embeds: [newEmbed], components: [row] } )
await requestor_challenge.edit( { embeds: [newEmbed] } )
return
}
}
if (response.length > 0) {
//requestor
Expand Down

0 comments on commit 5f5402f

Please sign in to comment.