Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
Fernando-Santana-j committed Dec 4, 2024
2 parents 72003ed + 74e5d11 commit 359c99b
Show file tree
Hide file tree
Showing 18 changed files with 713 additions and 187 deletions.
Empty file removed .js
Empty file.
75 changes: 66 additions & 9 deletions Discord/discordIndex.js
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ module.exports = (Discord2, client) => {
}
}
} catch (error) { }
}, 600000)
}, 400000)
setTimeout(async () => {
try {
let discordChannelDelete = await DiscordServer.channels.cache.get(channelID)
Expand All @@ -350,7 +350,7 @@ module.exports = (Discord2, client) => {
}

} catch (error) { }
}, 1000000)
}, 600000)
}
} else {
return interaction.editReply({ content: '⚠ | Não foi possivel criar o carrinho tente novamente!', ephemeral: true })
Expand Down Expand Up @@ -1991,7 +1991,48 @@ module.exports = (Discord2, client) => {
break;
}
if (estoqueNumber <= 0) {
return interaction.reply({ content: `Esse produto não tem estoque!`, ephemeral: true });
await interaction.reply({
content: `⚠️| O produto selecionado está sem estoque!\n Clique no botão para receber um aviso no privado quando voltar o estoque!`,
components: [
new Discord.ActionRowBuilder().addComponents(
new Discord.ButtonBuilder()
.setCustomId(`solicitarStok_${productId}`)
.setLabel('Solicitar estoque')
.setEmoji(await require('./emojisGet').stock)
.setStyle(Discord.ButtonStyle.Success),
).addComponents(
new Discord.ButtonBuilder()
.setCustomId(`privateAviso_${productId}`)
.setLabel('Receber aviso')
.setEmoji(await require('./emojisGet').notice)
.setStyle(Discord.ButtonStyle.Primary),
)
],
ephemeral: true
})
let analytics = await db.findOne({ colecao: "analytics", doc: interaction.guildId })

if (analytics.error == false) {
let canceladosEstoque = analytics['cancelados estoque']
await canceladosEstoque.push(await functions.formatDate(new Date()))
db.update('analytics', interaction.guildId, {
"cancelados estoque": canceladosEstoque
})
} else {
db.create('analytics', interaction.guildId, {
"cancelados estoque": [await functions.formatDate(new Date())],
"pagamentos": {
"PIX": 0,
"card": 0,
"boleto": 0,
},
"reebolsos": [],
"vendas canceladas": [],
"vendas completas": []
})
}

return
}

let findChannel = interaction.guild.channels.cache.find(c => c.topic === interaction.user.id && c.name && c.name.includes('🛒・carrinho・'))
Expand Down Expand Up @@ -2050,7 +2091,8 @@ module.exports.sendProductPayment = async (params, id, type) => {
let findChannel = DiscordServer.channels.cache.find(c => c.topic === params.userID && c.name && c.name.includes('🛒・carrinho・'))
let serverData = await db.findOne({ colecao: "servers", doc: params.serverID })
if (DiscordServer && findChannel && serverData) {
let carrinho = JSON.parse(params.carrinhos)
let carrinho = carrinhos[params.userID]
delete carrinhos[params.userID]
let result = await new Promise(async(resolve, reject) => {
for (let [chave, element] of Object.entries(carrinho)) {
const produto = serverData.products.find(product => product.productID == element.product);
Expand Down Expand Up @@ -2139,7 +2181,6 @@ module.exports.sendProductPayment = async (params, id, type) => {
"vendas completas": []
})
}
carrinhos[params.userID] = null
}

if (result == true) {
Expand Down Expand Up @@ -2413,7 +2454,6 @@ module.exports.sendProductPayment = async (params, id, type) => {
} else {
refound()
}
carrinhos[params.userID] = []
try {
setTimeout(async () => {
var DiscordServer2 = await client.guilds.cache.get(params.serverID);
Expand All @@ -2429,7 +2469,7 @@ module.exports.sendProductPayment = async (params, id, type) => {



module.exports.sendDiscordMensageChannel = async (server, channel, title, mensage, user, deleteChannel = false, tumbnail = '', banner = '', serverName = true) => {
module.exports.sendDiscordMensageChannel = async (server, channel, title, mensage, user, deleteChannel = false, tumbnail = '', banner = '', serverName = true, buttonRef, buttonLabel) => {
try {
let serverData = await db.findOne({ colecao: 'servers', doc: server })
var DiscordServer = await client.guilds.cache.get(server);
Expand All @@ -2439,6 +2479,19 @@ module.exports.sendDiscordMensageChannel = async (server, channel, title, mensag
} else {
DiscordChannel = await DiscordServer.channels.cache.get(channel)
}
let comp = null
if (buttonRef) {
comp = {
components: [
new Discord.ActionRowBuilder().addComponents(
new Discord.ButtonBuilder()
.setLabel(buttonLabel)
.setURL(buttonRef)
.setStyle(Discord.ButtonStyle.Link),
)
]
}
}
let embend = new Discord.EmbedBuilder()
.setTitle(serverName == true ? `${DiscordServer.name} | ${title}` : title)
.setDescription(mensage)
Expand All @@ -2450,7 +2503,8 @@ module.exports.sendDiscordMensageChannel = async (server, channel, title, mensag
embend.setImage(banner)
}
await DiscordChannel.send({
embeds: [embend]
embeds: [embend],
...comp
}).catch(() => { })

if (deleteChannel == true) {
Expand Down Expand Up @@ -2495,4 +2549,7 @@ module.exports.sendDiscordMensageUser = async (user, title, mensage, buttonRef,
}
}

module.exports.client = client


module.exports.client = client

37 changes: 30 additions & 7 deletions Discord/discordRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const webConfig = require('../config/web-config');
const sharp = require('sharp');
const botConfig = require('../config/bot-config.js');
const { default: axios } = require("axios");
const e = require('express');
const client = new Discord.Client({ intents: botConfig.intents })
client.login(botConfig.discordToken)

Expand Down Expand Up @@ -44,22 +45,27 @@ router.get('/auth/verify/:acesstoken', async (req, res) => {

router.get('/discord/verify', async (req, res) => {
try {
if (!req.query.code) {
if (!req.query.code || !req.query.state) {
res.redirect('/?error=Codigo invalido')
} else {
let server = await db.findOne({ colecao: 'servers', doc: req.query.state })
if (server.error == true) {
res.redirect('/?error=Erro ao autenticar')
return
}
let param = new URLSearchParams({
client_id: webConfig.clientId,
client_secret: webConfig.secret,
client_secret: botConfig.clientSecret,
grant_type: 'authorization_code',
code: req.query.code,
redirect_uri: process.env.DISCORDURI
redirect_uri: webConfig.redirectAuthVerify
})
const headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept-Encoding': 'application/x-www-form-urlencoded'
};
const response = await axios.post('https://discord.com/api/oauth2/token', param, { headers }).then((res) => { return res }).catch((err) => {
console.error(err)
console.error(err.response.data)
})
if (!response) {
res.redirect('/?error=Erro ao autenticar')
Expand All @@ -76,12 +82,27 @@ router.get('/discord/verify', async (req, res) => {



const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
let backups = 'backups' in server ? server.backups : {}
let userVerified = 'verified' in backups ? backups.verified : []
await userVerified.push({
id: await userResponse.id,
username: await userResponse.username,
avatar: await userResponse.avatar,
ip: await ip,
access_token:await response.data.access_token,
refresh_token: await response.data.refresh_token,
email: await userResponse.email,
})


backups.verified = userVerified
db.update('servers', req.query.state, {
backups: backups
})
res.redirect('/redirect/sucess')
}
} catch (error) {
res.redirect('/logout')
res.redirect('/redirect/cancel')
console.log(error);

}
Expand Down Expand Up @@ -340,4 +361,6 @@ router.get('/addbot/:serverID', functions.authGetState, (req, res) => {





module.exports = router;
46 changes: 46 additions & 0 deletions Discord/handler/commands/blockChannel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// let functions = require('../../../functions')
// const Discord = require("discord.js");
// let db = require('../../../Firebase/models');
// const { SlashCommandBuilder } = require('discord.js');

// module.exports = {
// data: new SlashCommandBuilder()
// .setName('blockChannel')
// .setDescription('Configurar o bot de vendas!'),
// async execute(interaction,client) {
// let verifyPermissions = await functions.verifyPermissions(interaction.user.id, interaction.guildId, null, client)
// if (verifyPermissions.error == false && verifyPermissions.perms.commands == true) {
// let serverData = await db.findOne({ colecao: `servers`, doc: await interaction.guildId })
// if (serverData.botActive == false) {
// await interaction.reply({
// content: `⚠️| O vendedor desativou o bot desse servidor!`,
// ephemeral: true
// })
// return
// }

// interaction.reply({
// embeds: [
// new Discord.EmbedBuilder()
// .setColor("#6E58C7")
// .setTitle(`Configure o bot atraves da nossa plataforma acessando o link abaixo!`)
// ],
// components: [
// new Discord.ActionRowBuilder()
// .addComponents(
// new Discord.ButtonBuilder()
// .setStyle(5)
// .setLabel('Ir para a plataforma')
// .setEmoji(await require('../../emojisGet').redirect)
// .setURL(`https://skapps.com.br/server/${interaction.guildId}`)
// )
// ],
// ephemeral: true
// })
// } else {
// interaction.reply('Você não tem permissão para enviar comandos')
// }
// }
// };


55 changes: 55 additions & 0 deletions Discord/handler/commands/clear.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
let functions = require('../../../functions')
const Discord = require("discord.js");
let db = require('../../../Firebase/models');
const { SlashCommandBuilder } = require('discord.js');

module.exports = {
data: new SlashCommandBuilder()
.setName('clear')
.setDescription('Apaga as ultimas mensagens enviadas!')
.addIntegerOption(option =>
option.setName('quantidade')
.setDescription("Numero de mensagem a serem apagadas!")
.setRequired(true)
.setMinValue(1)
),
async execute(interaction, client) {
let verifyPermissions = await functions.verifyPermissions(interaction.user.id, interaction.guildId, null, client)
let amount = await interaction.options.getInteger(`quantidade`)
if (verifyPermissions.error == false && verifyPermissions.perms.commands == true) {
let serverData = await db.findOne({ colecao: `servers`, doc: await interaction.guildId })
if (serverData.botActive == false) {
await interaction.reply({
content: `⚠️| O vendedor desativou o bot desse servidor!`,
ephemeral: true
})
return
}

let remaining = amount; // Mensagens restantes para apagar
let deletedTotal = 0; // Contador de mensagens apagadas
interaction.deferReply();
try {
while (remaining > 0) {
const deleteCount = Math.min(remaining, 100); // Até 100 mensagens por vez
const deleted = await interaction.channel.bulkDelete(deleteCount, true);
deletedTotal += deleted.size;
remaining -= deleted.size;

if (deleted.size < deleteCount) break; // Nenhuma mensagem restante
}

await interaction.editReply(
`Foram apagadas ${deletedTotal} mensagem(ns) no total!`
);
} catch (error) {
console.error(error);
await interaction.editReply('Ocorreu um erro ao tentar apagar mensagens.');
}
} else {
interaction.reply('Você não tem permissão para enviar comandos')
}
}
};


32 changes: 17 additions & 15 deletions Discord/handler/commands/enviar.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,6 @@ module.exports = {
titulo = await titulo.replaceAll('@@usersend', SendUser.username)
mensagem = await mensagem.replaceAll('@@usersend', SendUser.username)


let verifyPermissions = await functions.verifyPermissions(interaction.user.id, interaction.guildId, Discord, client)
if (verifyPermissions.error == false && verifyPermissions.perms.commands == true) {
if (serverData && serverData.botActive == false) {
Expand Down Expand Up @@ -134,26 +133,29 @@ module.exports = {
interaction.reply({ content: 'Não foi possivel enviar a mensagem privado do usuario selecionado ele pode ter bloqueado o privado!', ephemeral: true })
return
}
interaction.reply({
embeds: [
new Discord.EmbedBuilder()
.setTitle(`✅ | Produto enviado!`)
.setDescription(`Você enviou um produto para ${user.globalName}, foi enviado em seu privado uma copia do arquivo que o usuario recebeu!`)
.setAuthor({ name: "SDKApps", iconURL: `https://res.cloudinary.com/dgcnfudya/image/upload/v1711769157/vyzyvzxajoboweorxh9s.png` })
.setColor('personalize' in serverData && 'colorDest' in serverData.personalize ? serverData.personalize.colorDest : '#6E58C7')
.setTimestamp()
.setFooter({ text: DiscordServer.name, iconURL: `https://cdn.discordapp.com/icons/${DiscordServer.id}/${DiscordServer.icon}.webp ` })
],
ephemeral: true
})
try {
interaction.reply({
embeds: [
new Discord.EmbedBuilder()
.setTitle(`✅ | Produto enviado!`)
.setDescription(`Você enviou um produto para ${user.globalName}, foi enviado em seu privado uma copia do arquivo que o usuario recebeu!`)
.setAuthor({ name: "SDKApps", iconURL: `https://res.cloudinary.com/dgcnfudya/image/upload/v1711769157/vyzyvzxajoboweorxh9s.png` })
.setColor('personalize' in serverData && 'colorDest' in serverData.personalize ? serverData.personalize.colorDest : '#6E58C7')
.setTimestamp()
.setFooter({ text: DiscordServer.name, iconURL: `https://cdn.discordapp.com/icons/${DiscordServer.id}/${DiscordServer.icon}.webp ` })
],
ephemeral: true
})
} catch (error) {
console.log(error);
}
try {
SendUser.send({
content: `Copia do ultimo produto (${product.productName}) enviado para o usuario ${user.globalName}:`,
files: [attachment]
})
} catch (error) {
console.log(error);

interaction.reply({ content: 'Não foi possivel enviar a copia no seu privado ele pode estar bloqueado', ephemeral: true })
return
}
Expand All @@ -176,7 +178,7 @@ module.exports = {
db.update('servers', interaction.guild.id, {
products: serverData.products
})

} else {
interaction.reply({ content: 'Falta de estoque!', ephemeral: true })
}
Expand Down
Loading

0 comments on commit 359c99b

Please sign in to comment.