From 802dc331f38dc77399e815cc80f26337e762acc9 Mon Sep 17 00:00:00 2001 From: Daniel Guirra Date: Mon, 25 Mar 2024 12:29:46 -0300 Subject: [PATCH] update --- .gitignore | 3 +- data/json/newbible.json | 4 +- src/command/allComands.ts | 2 + src/command/commandAdvice.ts | 23 ++--- src/command/commandAllSkinsOfChampLol.ts | 119 ++++++++++++++++++++-- src/command/commandAvatar.ts | 8 +- src/command/commandBible.ts | 26 +++-- src/command/commandClearChannel.ts | 14 +-- src/command/commandDice.ts | 6 +- src/command/commandGoogleImage.ts | 11 +- src/command/commandHour.ts | 4 +- src/command/commandLoreLeagueOfLegends.ts | 19 ++-- src/service/guildMemberAdd.ts | 3 - src/service/interactionCreate.ts | 2 +- src/service/messageCreate.ts | 37 ++++--- src/service/on.ts | 4 +- src/util/loadin.ts | 82 ++++++++++++++- 17 files changed, 268 insertions(+), 99 deletions(-) diff --git a/.gitignore b/.gitignore index a7d657d..920aed2 100644 --- a/.gitignore +++ b/.gitignore @@ -19,4 +19,5 @@ node_modules logs.txt database.sqlite users.json -.vscode \ No newline at end of file +.vscode +.vs \ No newline at end of file diff --git a/data/json/newbible.json b/data/json/newbible.json index cc43b18..069465b 100644 --- a/data/json/newbible.json +++ b/data/json/newbible.json @@ -12534,7 +12534,7 @@ "E dispôs todo o povo, a cada um com as suas armas na mão, desde o lado direito da casa até o lado esquerdo da casa, do lado do altar e da casa, em redor do rei.", "Então tiraram para fora ao filho do rei, e lhe puseram a coroa; deram-lhe o testemunho, e o fizeram rei; e Joiada e seus filhos o ungiram, e disseram: Viva o rei!", "Ouvindo, pois, Atalia a voz do povo que concorria e louvava o rei, veio ao povo, à casa do Senhor.", - "E olhou, e eis que o rei estava junto à coluna, à entrada, e os pri…ncipes e as trombetas junto ao rei; e todo o povo da terra estava alegre e tocava as trombetas; e também os cantores tocavam instrumentos musicais, e dirigiam o cantar de louvores; então Atalia rasgou os seus vestidos, e clamou: Traição, traição!", + "E olhou, e eis que o rei estava junto à coluna, à entrada, e os principes e as trombetas junto ao rei; e todo o povo da terra estava alegre e tocava as trombetas; e também os cantores tocavam instrumentos musicais, e dirigiam o cantar de louvores; então Atalia rasgou os seus vestidos, e clamou: Traição, traição!", "Porém o sacerdote Joiada trouxe para fora os centuriões que estavam postos sobre o exército e disse-lhes: Tirai-a para fora das fileiras, e o que a seguir, morrerá à espada; porque dissera o sacerdote: Não a mateis na casa do Senhor.", "E lançaram mão dela; e ela foi pelo caminho da entrada da porta dos cavalos, à casa do rei, e ali a mataram.", "E Joiada fez aliança entre si e o povo e o rei, para que fossem o povo do Senhor.", @@ -33885,4 +33885,4 @@ } ] } -] +] \ No newline at end of file diff --git a/src/command/allComands.ts b/src/command/allComands.ts index 0fa932e..6d5f1c1 100644 --- a/src/command/allComands.ts +++ b/src/command/allComands.ts @@ -1,4 +1,5 @@ import { advice } from './commandAdvice'; +import { allSkinsLol } from './commandAllSkinsOfChampLol'; import { avatar } from './commandAvatar'; import { ban } from './commandBan'; import { bible } from './commandBible'; @@ -70,4 +71,5 @@ export const allComands = [ deleteUser, editUser, climateDaily, + allSkinsLol, ]; diff --git a/src/command/commandAdvice.ts b/src/command/commandAdvice.ts index 0538c85..a10918b 100644 --- a/src/command/commandAdvice.ts +++ b/src/command/commandAdvice.ts @@ -1,21 +1,15 @@ import axios from 'axios'; import { - CommandInteraction, - Interaction, - Message, - SlashCommandBuilder, + CommandInteraction, + Interaction, + Message, + SlashCommandBuilder, } from 'discord.js'; import { embedBuilder } from '../../src/util/getEmbed'; -import { translateText } from '../util/translate'; import { Command } from '../interfaces/Command'; +import { translateText } from '../util/translate'; -/** - * Don't forget to export - * Não esqueça de exportar - * @param Command - * @danielguirra - */ export const advice: Command = { data: new SlashCommandBuilder() .setName('conselho') @@ -42,14 +36,11 @@ export const advice: Command = { }); }, }; -/** - * - * @returns Conselho um em portugues - */ + async function getRandomAdvice() { const url = `https://api.adviceslip.com/advice`; const advice = await axios.get(url); const text = advice.data.slip.advice; - const result: any = (await translateText(text)).text || ''; + const result = (await translateText(text)).text || ''; return result; } diff --git a/src/command/commandAllSkinsOfChampLol.ts b/src/command/commandAllSkinsOfChampLol.ts index 53b57f7..f1b1a77 100644 --- a/src/command/commandAllSkinsOfChampLol.ts +++ b/src/command/commandAllSkinsOfChampLol.ts @@ -4,8 +4,10 @@ import { Message, SlashCommandBuilder, } from 'discord.js'; - +import names from '../../data/json/nameslol.json'; import { Command } from '../interfaces/Command'; +import axios from 'axios'; +import { loadinCreator } from '../util/loadin'; /** * Don't forget to export @@ -15,14 +17,14 @@ import { Command } from '../interfaces/Command'; */ export const allSkinsLol: Command = { data: new SlashCommandBuilder() - .setName('avatar') + .setName('skinlol') .setDescription( - 'Obtenha a URL do avatar do usuário selecionado ou do seu próprio avatar.' + 'Obtenha todas skins do personagem do jogo league of legends' ) - .addUserOption((options) => + .addStringOption((options) => options - .setName('user') - .setDescription('usuário para retornar') + .setName('champion') + .setDescription('Campeão do League retornar as skins') .setRequired(true) ), async executeMessageCommand(commandMessage: Message) { @@ -36,10 +38,109 @@ export const allSkinsLol: Command = { }, async executeSlashCommand(commandSlash: CommandInteraction | Interaction) { if (!commandSlash.isChatInputCommand()) return; - const user = commandSlash.options.getUser('user'); - if (user) { - return commandSlash.reply(user.displayAvatarURL({ extension: 'png' })); + const championName = commandSlash.options.getString('champion'); + if (championName) { + return loadinCreator( + commandSlash, + async () => { + return await LeagueOfLegendsSkins.SkinsBasedInChampName( + championName + ); + }, + undefined + ); } return; }, }; + +class LeagueOfLegendsSkins { + static async SkinsBasedInChampName(champName: string) { + try { + const version = await axios.get( + 'https://ddragon.leagueoflegends.com/api/versions.json' + ); + + const champ = capitalizeChampionName(champName); + + const json = `http://ddragon.leagueoflegends.com/cdn/${version['data'][0]}/data/pt_BR/champion/${champ}.json`; + + const responseApi = await axios.get(json); + const dataChampion = await responseApi.data.data; + const key = Object.keys(dataChampion)[0]; + const skinsArray: Skin[] = dataChampion[key].skins; + + for (let index = 0; index < skinsArray.length; index++) { + skinsArray[index].championName = dataChampion[key].name; + const num = skinsArray[index].num; + skinsArray[ + index + ].skinUrl = `https://ddragon.leagueoflegends.com/cdn/img/champion/splash/${key}_${num}.jpg`; + + skinsArray[ + index + ].loading = `https://ddragon.leagueoflegends.com/cdn/img/champion/loading/${key}_${num}.jpg`; + + if (skinsArray[index].chromas) { + skinsArray[index].chromas = 'A skin possui chromas'; + } else { + skinsArray[index].chromas = 'A skin não possui chromas'; + } + + if (skinsArray[index].name == 'default') { + skinsArray[index].name = + dataChampion[key].name + ' ' + dataChampion[key].title; + skinsArray[ + index + ].chromas = `${dataChampion[key].name} possui um total de ${skinsArray.length} skins`; + } + } + const icon = `http://ddragon.leagueoflegends.com/cdn/${version['data'][0]}/img/champion/${champ}.png`; + return { + icon, + skinsArray, + }; + } catch (error) { + return `Não foi possivel achar o Campeão **${champName}**`; + } + } +} +export type SkinChampToEmbed = { + icon: string; + skinsArray: Skin[]; +}; +type Skin = { + championName: string; + idSkin: string; + num: number; + name: string; + chromas: string; + skinUrl: string; + loading: string; +}; + +function capitalizeChampionName(champName: any) { + const nameChamp = names; + let x; + if (champName in names) { + let finder: keyof typeof names = champName; + x = nameChamp[finder]; + } + + function capitalizeFirstLetter(inputString: string) { + if (typeof inputString !== 'string' || inputString.length === 0) { + return inputString; + } + + return ( + inputString.charAt(0).toUpperCase() + + inputString.slice(1).toLowerCase() + ); + } + + let champ = capitalizeFirstLetter(champName); + if (x) { + champ = x; + } + return champ; +} diff --git a/src/command/commandAvatar.ts b/src/command/commandAvatar.ts index ad146cc..06b97ea 100644 --- a/src/command/commandAvatar.ts +++ b/src/command/commandAvatar.ts @@ -1,8 +1,8 @@ import { - CommandInteraction, - Interaction, - Message, - SlashCommandBuilder, + CommandInteraction, + Interaction, + Message, + SlashCommandBuilder, } from 'discord.js'; import { Command } from '../interfaces/Command'; diff --git a/src/command/commandBible.ts b/src/command/commandBible.ts index 0549c19..cd4fb1f 100644 --- a/src/command/commandBible.ts +++ b/src/command/commandBible.ts @@ -10,12 +10,7 @@ import * as fs from 'fs'; import { embedBuilder } from '../../src/util/getEmbed'; import { Command } from '../interfaces/Command'; -/** - * Don't forget to export - * Não esqueça de exportar - * @param Command - * @danielguirra - */ + export const bible: Command = { data: new SlashCommandBuilder() .setName('bible') @@ -53,10 +48,14 @@ export const bible: Command = { .setName('verse') .setRequired(true) .setDescription('verse for search') - ), + ), + + async executeMessageCommand(commandMessage: Message) { return commandMessage.reply('Use somente no slash'); - }, + }, + + async executeSlashCommand(commandSlash: CommandInteraction | Interaction) { if (!commandSlash.isChatInputCommand()) return; const BibleVersion = commandSlash.options.getString('version'); @@ -95,12 +94,11 @@ export const bible: Command = { }; export class Bible { - private urlForGet: string | undefined = - 'https://raw.githubusercontent.com/danielguirra/bible-json/main'; - version: string | undefined; - book: string | undefined; - chapter: number | undefined; - verse: number | undefined; + private urlForGet: string = 'https://raw.githubusercontent.com/danielguirra/bible-json/main'; + version!: string; + book!: string ; + chapter!: number ; + verse!: number ; static json: BibleJson = JSON.parse( fs.readFileSync('./data/json/newbible.json', 'utf-8') diff --git a/src/command/commandClearChannel.ts b/src/command/commandClearChannel.ts index 9936550..a9a90d7 100644 --- a/src/command/commandClearChannel.ts +++ b/src/command/commandClearChannel.ts @@ -26,7 +26,7 @@ export const clearChannel: Command = { .setRequired(true) ), async executeMessageCommand(commandMessage: Message) { - const numberMessageToDelete: number = stringForNumber( + const numberMessageToDelete: number = parseInt( commandMessage.content.replace('*cls ', '') ); const channel = await channelItsGuildTextChannel(commandMessage.channel); @@ -41,11 +41,10 @@ export const clearChannel: Command = { }, async executeSlashCommand(commandSlash: CommandInteraction | Interaction) { if (!commandSlash.isChatInputCommand()) return; - const numberMessageToDelete: number = stringForNumber( - commandSlash.options.get('value') - ); + const numberMessageToDelete = commandSlash.options.getInteger('value'); + const channel = await channelItsGuildTextChannel(commandSlash.channel); - if (channel) { + if (channel && numberMessageToDelete) { const del = await channel.bulkDelete(numberMessageToDelete); if (del) { commandSlash.reply('Foi apagado ' + numberMessageToDelete); @@ -56,8 +55,3 @@ export const clearChannel: Command = { return commandSlash.reply({ embeds: [embedBuilder('', '')] }); }, }; - -function stringForNumber(numberString: any) { - const number: number = numberString; - return number; -} diff --git a/src/command/commandDice.ts b/src/command/commandDice.ts index cb00aaa..1f86a77 100644 --- a/src/command/commandDice.ts +++ b/src/command/commandDice.ts @@ -20,7 +20,7 @@ export const dice: Command = { .setRequired(true) ), async executeMessageCommand(commandMessage: Message) { - const num: any = commandMessage.content.replace('*sorteio ', ''); + const num = parseInt(commandMessage.content.replace('*sorteio ', '')); if (num >= 2) { const resultado = sorteador(num); return commandMessage.reply({ @@ -35,8 +35,8 @@ export const dice: Command = { }, async executeSlashCommand(commandSlash) { if (!commandSlash.isChatInputCommand()) return; - const num: any = commandSlash.options.get('value'); - if (num >= 2) { + const num = commandSlash.options.getInteger('value'); + if (num && num >= 2) { const resultado = sorteador(num); return commandSlash.reply({ embeds: [embedBuilder('D20', `Seu valor foi:**${resultado}** `)], diff --git a/src/command/commandGoogleImage.ts b/src/command/commandGoogleImage.ts index 8e8de98..b1f1e0c 100644 --- a/src/command/commandGoogleImage.ts +++ b/src/command/commandGoogleImage.ts @@ -1,4 +1,9 @@ -import { CommandInteraction, Message, SlashCommandBuilder } from 'discord.js'; +import { + CommandInteraction, + Message, + SlashCommandBuilder, + TextBasedChannel, +} from 'discord.js'; import { googleImage } from '../util/googleImage'; import { channelItsGuildTextChannel } from '../util/channelItsGuildTextChannel'; @@ -20,7 +25,7 @@ export const ime: Command = { async executeSlashCommand(commandSlash) { if (!commandSlash.isChatInputCommand()) return; const text = commandSlash.options.getString('text'); - if (text) { + if (text && commandSlash.channel) { await sendSearch(text, commandSlash.channel, commandSlash); } }, @@ -28,7 +33,7 @@ export const ime: Command = { async function sendSearch( text: string, - channel: any, + channel: TextBasedChannel, command: CommandInteraction | Message ) { const channela = await channelItsGuildTextChannel(channel); diff --git a/src/command/commandHour.ts b/src/command/commandHour.ts index f86b2af..6882626 100644 --- a/src/command/commandHour.ts +++ b/src/command/commandHour.ts @@ -47,7 +47,7 @@ export function hourNow() { var dia_sem = data.getDay(); // 0-6 (zero=domingo) var mes = data.getMonth(); // 0-11 (zero=janeiro) var ano4 = data.getFullYear(); // 4 dígitos - var hora: any = data.getHours(); + var hora = data.getHours(); var min = data.getMinutes(); // 0-59 var seg = data.getSeconds(); // 0-59 @@ -57,7 +57,7 @@ export function hourNow() { return { getNameWeek, dia_sem, str_data, str_hora }; } -export const getNameWeek = (x: any) => { +export const getNameWeek = (x: number) => { return [ 'Domingo', 'Segunda-Feira', diff --git a/src/command/commandLoreLeagueOfLegends.ts b/src/command/commandLoreLeagueOfLegends.ts index b4bbd25..8536125 100644 --- a/src/command/commandLoreLeagueOfLegends.ts +++ b/src/command/commandLoreLeagueOfLegends.ts @@ -31,19 +31,22 @@ export const loreleagueoflegends: Command = { }, async executeSlashCommand(commandSlash) { if (!commandSlash.isChatInputCommand()) return; - const champ: any = commandSlash.options.get('champion'); + const champ = commandSlash.options.getString('champion'); if (champ) { - const lore = await getLoreChampionLeagueOfLegends( - champ.value.toLowerCase() - ); + const lore = await getLoreChampionLeagueOfLegends(champ.toLowerCase()); return commandSlash.reply({ embeds: [lore] }); } }, }; -async function getLoreChampionLeagueOfLegends(champ: string) { - const nameChamp: any = names; - const x = nameChamp[champ]; +async function getLoreChampionLeagueOfLegends(champName: any) { + const nameChamp = names; + let x; + if (champName in names) { + let finder: keyof typeof names = champName; + x = nameChamp[finder]; + } + function capitalizeFirstLetter(inputString: string) { if (typeof inputString !== 'string' || inputString.length === 0) { return inputString; @@ -55,7 +58,7 @@ async function getLoreChampionLeagueOfLegends(champ: string) { ); } - champ = capitalizeFirstLetter(champ); + let champ = capitalizeFirstLetter(champName); if (x) { champ = x; } diff --git a/src/service/guildMemberAdd.ts b/src/service/guildMemberAdd.ts index e05c541..2ab01c8 100644 --- a/src/service/guildMemberAdd.ts +++ b/src/service/guildMemberAdd.ts @@ -1,9 +1,6 @@ -import { RoleResolvable } from 'discord.js'; - import { client } from '../client/client'; import { channelItsGuildTextChannel } from '../util/channelItsGuildTextChannel'; import { embedBuilder } from '../util/getEmbed'; -import { env } from '../envs'; export const guildMemberAdd = client.on('guildMemberAdd', async (newMember) => { const bem = await channelItsGuildTextChannel( diff --git a/src/service/interactionCreate.ts b/src/service/interactionCreate.ts index 22f5bb7..1a5cd26 100644 --- a/src/service/interactionCreate.ts +++ b/src/service/interactionCreate.ts @@ -10,7 +10,7 @@ export const interactionCreate = client.on( async (interaction) => { if (interaction.type === InteractionType.ApplicationCommand) { if (!interaction.isChatInputCommand()) return; - const command = commands.get(interaction.commandName as any); + const command = commands.get(interaction.commandName); if (!command) return; try { await command.executeSlashCommand(interaction); diff --git a/src/service/messageCreate.ts b/src/service/messageCreate.ts index 1d8ccad..c3355bc 100644 --- a/src/service/messageCreate.ts +++ b/src/service/messageCreate.ts @@ -10,27 +10,26 @@ const prefix = env.PREFIX || '*'; export const messageCreate = client.on( 'messageCreate', async (message: Message) => { - const args: any = message.content - .slice(prefix?.length) - .trim() - .split(/ +/); - const command = args[0].toLowerCase() as string; + const args = message.content.slice(prefix?.length).trim().split(/ +/); + const command = (args[0].toLowerCase() as string) || undefined; - if (typeof command === 'undefined') return; - const commandExecutor = commands.get(command); - if (commandExecutor) - try { - commandExecutor.executeMessageCommand(message); + if (typeof command === 'string') { + const commandExecutor = commands.get(command); + if (commandExecutor) { + try { + commandExecutor.executeMessageCommand(message); - console.log( - logDate() + - 'Comando Message: ' + - commandExecutor.data.name + - ' foi usado pelo : ' + - message.author.id - ); - } catch (error) { - return; + console.log( + logDate() + + 'Comando Message: ' + + commandExecutor.data.name + + ' foi usado pelo : ' + + message.author.id + ); + } catch (error) { + return; + } } + } } ); diff --git a/src/service/on.ts b/src/service/on.ts index e1f19d9..8ec312b 100644 --- a/src/service/on.ts +++ b/src/service/on.ts @@ -43,7 +43,7 @@ export const on = client.on('ready', async () => { }); }).start(); } catch (error) { - console.log(error); + console.error(error); try { await userCheckSendClimate(); @@ -53,7 +53,7 @@ export const on = client.on('ready', async () => { channelDaily, }); } catch (error) { - console.log(logDate + `Erro ao enviar novamente`); + console.error(logDate + `Erro ao enviar novamente`); } console.log(logDate()); } diff --git a/src/util/loadin.ts b/src/util/loadin.ts index 80dd193..02a251d 100644 --- a/src/util/loadin.ts +++ b/src/util/loadin.ts @@ -2,13 +2,22 @@ import { AttachmentBuilder, ChatInputCommandInteraction, Embed, + EmbedBuilder, Message, } from 'discord.js'; +import { SkinChampToEmbed } from '../command/commandAllSkinsOfChampLol'; +import { embedBuilder } from './getEmbed'; export async function loadinCreator( command: Message | ChatInputCommandInteraction, exec: Function = function () {}, - sender: Embed | Embed[] | string | AttachmentBuilder | undefined + sender: + | Embed + | Embed[] + | string + | AttachmentBuilder + | undefined + | SkinChampToEmbed ) { if (command instanceof Message) { command.reply('Carregando...').then((messageToEdit) => { @@ -30,10 +39,17 @@ export async function loadinCreator( } async function send( message: Message, - sender: Embed | Embed[] | string | AttachmentBuilder | undefined, + sender: + | Embed + | Embed[] + | string + | AttachmentBuilder + | undefined + | SkinChampToEmbed, exec: Function ) { if (!sender) sender = await exec(); + if (typeof sender == 'string') { return await message.edit(sender); } @@ -43,5 +59,67 @@ async function send( if (sender instanceof Embed) { return await message.edit({ embeds: [sender] }); } + if (sender && 'icon' in sender) { + if (sender.skinsArray.length > 10) { + return await embedChunk(sender, message); + } + return await message.edit({ embeds: await embedChunk(sender) }); + } return await message.edit({ embeds: sender }); } + +async function embedChunk(skinChamp: SkinChampToEmbed, message?: Message) { + const response: { total: number; embeds: EmbedBuilder[] } = { + total: skinChamp.skinsArray.length, + embeds: [], + }; + + if (response.total > 10) { + const arrayIfMoreToTenSkins: any[] = []; + for (let index = 0; index < skinChamp.skinsArray.length; index++) { + const skin = skinChamp.skinsArray[index]; + arrayIfMoreToTenSkins.push( + embedBuilder( + skin.name, + skin.chromas, + skinChamp.icon, + skin.championName, + skin.loading, + skin.skinUrl, + undefined, + undefined + ) + ); + } + + await sendEmbedsInGroups(arrayIfMoreToTenSkins, message!); + return; + } + + async function sendEmbedsInGroups( + embeds: string | any[], + message: { channel: { send: (arg0: { embeds: any }) => any } } + ) { + const chunkSize = 10; + for (let i = 0; i < embeds.length; i += chunkSize) { + const embedChunk = embeds.slice(i, i + chunkSize); + await message.channel.send({ embeds: embedChunk }); + } + } + + for (const skin of skinChamp.skinsArray) { + response.embeds.push( + embedBuilder( + skin.name, + skin.chromas, + skinChamp.icon, + skin.championName, + skin.loading, + skin.skinUrl, + undefined, + undefined + ) + ); + } + return response.embeds; +}