From 7126a760379c2e44706e87aabfb9c5a425082632 Mon Sep 17 00:00:00 2001 From: Francisco Pessano Date: Mon, 14 Nov 2022 21:00:10 -0300 Subject: [PATCH] added customTextSuggest and some ajustments in the bot --- app.js | 9 +++- commands/price.js | 28 ++--------- commands/suggestCustomText.js | 41 +++++++++++++++ .../{suggest.js => suggestPriceOption.js} | 25 +++++----- constants.js | 50 +++++++++++++++++++ deploy-commands.js | 8 +-- 6 files changed, 122 insertions(+), 39 deletions(-) create mode 100644 commands/suggestCustomText.js rename commands/{suggest.js => suggestPriceOption.js} (73%) create mode 100644 constants.js diff --git a/app.js b/app.js index 5470d1f..2641a4d 100644 --- a/app.js +++ b/app.js @@ -1,15 +1,18 @@ const fs = require('fs'); const path = require('path'); const { Collection, Client, GatewayIntentBits, Events } = require('discord.js'); +const { getRandomElementFromArray } = require('./constants'); require('dotenv').config(); +const enviroment = process.env.NODE_ENV; + const client = new Client({ intents: [GatewayIntentBits.Guilds] }); client.on('ready', () => { console.log('working'); }); -client.login(process.env.BOT_TOKEN); +client.login(enviroment === 'production' ? process.env.PROD_BOT_TOKEN : process.env.DEV_BOT_TOKEN); client.commands = new Collection(); @@ -28,6 +31,10 @@ for (const file of commandFiles) { } client.on(Events.InteractionCreate, async interaction => { + if (enviroment !== 'production' && interaction.user.id !== process.env.MY_DISCORD_USER_ID) { + interaction.reply(`The dev instance of this bot is only for ${getRandomElementFromArray([`<@${process.env.MY_DISCORD_USER_ID}>`, 'the king'])}`); + return; + } const command = interaction.client.commands.get(interaction.commandName); if (interaction.isChatInputCommand()) { try { diff --git a/commands/price.js b/commands/price.js index 9b0cbac..c7c1c5f 100644 --- a/commands/price.js +++ b/commands/price.js @@ -1,6 +1,7 @@ const { SlashCommandSubcommandBuilder, hyperlink, bold, ActionRowBuilder, ButtonBuilder, ButtonStyle } = require('discord.js'); const puppeteer = require('puppeteer'); const jsdom = require('jsdom'); +const { responses } = require('../constants'); function truncateText(text, max) { return text.substr(0, max - 1).trim() + (text.length > max ? '...' : ''); @@ -62,25 +63,6 @@ const countryData = { const pages = Object.values(countryData).map((country) => country.pages).flat(1); -const responses = { - 'extractedFrom': { - 'en-US': 'Prices extracted from:', - 'es-ES': 'Precios extraídos de:', - }, - 'missingPlatform': { - 'en-US': 'ERROR: Platform don\'t found!!', - 'es-ES': 'ERROR: Plataforma no encontrada!!', - }, - 'platformInBrowser': { - 'en-US': 'Search in %P on browser', - 'es-ES': 'Buscar en %P en el buscador', - }, - 'errorScrapping': { - 'en-US': 'No products could be found in:', - 'es-ES': 'No se pudieron encontrar productos en:', - }, -}; - const ELEMENTS_LIMIT = 3; module.exports = { @@ -146,7 +128,7 @@ module.exports = { const product = interaction.options.getString('product'); const platform = interaction.options.getString('platform'); if (platform && !pages.some(page => (page.name === platform))) { - await interaction.editReply(responses.missingPlatform[userLanguage]); + await interaction.editReply(responses(userLanguage).missingPlatform); return; } const country = interaction.options.getString('country') || @@ -213,17 +195,17 @@ module.exports = { (new ActionRowBuilder() .addComponents( new ButtonBuilder() - .setLabel(responses.platformInBrowser[userLanguage].replace('%P', page.name)) + .setLabel(responses(userLanguage).platformInBrowser.replace('%P', page.name)) .setURL(page.searchUrl) .setStyle(ButtonStyle.Link), )), ); const replyTexts = [ pagesScraped.length && - `${responses.extractedFrom[userLanguage]} ${pagesScraped.map(({ name }) => name).join(' ')}`, + `${responses(userLanguage).extractedFrom} ${pagesScraped.map(({ name }) => name).join(' ')}`, `${productPrices.join('\n')}`, pagesWithErrorScrapping.length && - `${responses.errorScrapping[userLanguage]} ${pagesWithErrorScrapping.map((name) => name).join(' ')}`, + `${responses(userLanguage).errorScrapping} ${pagesWithErrorScrapping.map((name) => name).join(' ')}`, ].filter(a => a); await interaction.editReply({ content: replyTexts.join('\n\n'), components: [...buttons] }); }, diff --git a/commands/suggestCustomText.js b/commands/suggestCustomText.js new file mode 100644 index 0000000..f8e539d --- /dev/null +++ b/commands/suggestCustomText.js @@ -0,0 +1,41 @@ +const { SlashCommandSubcommandBuilder } = require('discord.js'); +const { urlRegex, responses } = require('../constants'); +require('dotenv').config(); + +module.exports = { + data: new SlashCommandSubcommandBuilder() + .setName('suggest-custom') + .setNameLocalizations({ + 'es-ES': 'sugerencia-custom', + }) + .setDescription('Suggest a new feature or idea for the bot') + .setDescriptionLocalizations({ + 'es-ES': 'Sugiera una nueva funcionalidad o una idea para el bot', + }) + .addStringOption(option => option + .setName('text') + .setNameLocalizations({ + 'es-ES': 'texto', + }) + .setDescription('Add your suggest/idea') + .setDescriptionLocalizations({ + 'es-ES': 'Introduce tu sugerencia/idea', + }) + .setMaxLength(1800)), + async execute(interaction) { + const userLanguage = interaction.locale || 'en-US'; + const suggestion = interaction.options.getString('text'); + if (!suggestion) { + interaction.reply(responses(userLanguage).notSuggest); + return; + } + if (urlRegex.test(suggestion)) { + interaction.reply(responses(userLanguage).linksNotAllowed); + return; + } + + const notificationsChannel = interaction.client.channels.cache.get(process.env.NOTIFICATION_DISCORD_CHANNEL_ID); + notificationsChannel.send(`SUGGESTION: ${suggestion}`); + await interaction.reply(responses(userLanguage).suggestionSended); + }, +}; \ No newline at end of file diff --git a/commands/suggest.js b/commands/suggestPriceOption.js similarity index 73% rename from commands/suggest.js rename to commands/suggestPriceOption.js index 41459cf..7c07a0c 100644 --- a/commands/suggest.js +++ b/commands/suggestPriceOption.js @@ -1,18 +1,12 @@ const { SlashCommandSubcommandBuilder } = require('discord.js'); +const { urlRegex, responses } = require('../constants'); require('dotenv').config(); -const responses = { - 'suggestionSended': { - 'en-US': `Suggestion sended to <@${process.env.MY_DISCORD_USER_ID}>`, - 'es-ES': `Sugerencia enviada a <@${process.env.MY_DISCORD_USER_ID}>`, - }, -}; - module.exports = { data: new SlashCommandSubcommandBuilder() - .setName('suggest') + .setName('suggest-option') .setNameLocalizations({ - 'es-ES': 'sugerir', + 'es-ES': 'sugerir-opción', }) .setDescription('Suggest a new country and/or platform for add to the bot') .setDescriptionLocalizations({ @@ -42,9 +36,16 @@ module.exports = { const country = interaction.options.getString('country'); const platform = interaction.options.getString('platform'); const suggestion = [country, platform].filter(a => a).join(' - '); - + if (!country && !platform) { + interaction.reply(responses(userLanguage).notSuggest); + return; + } + if (urlRegex.test(suggestion)) { + interaction.reply(responses(userLanguage).linksNotAllowed); + return; + } const notificationsChannel = interaction.client.channels.cache.get(process.env.NOTIFICATION_DISCORD_CHANNEL_ID); - notificationsChannel.send(`SUGGESTION: ${suggestion}`); - await interaction.reply(responses.suggestionSended[userLanguage]); + notificationsChannel.send(`SUGGESTION of country: ${suggestion}`); + await interaction.reply(responses(userLanguage).suggestionSended); }, }; \ No newline at end of file diff --git a/constants.js b/constants.js new file mode 100644 index 0000000..36b4cc4 --- /dev/null +++ b/constants.js @@ -0,0 +1,50 @@ +require('dotenv').config(); + +const urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g; +function getRandomElementFromArray(arr) { + return arr[Math.floor((Math.random() * arr.length))]; +} +const responsesTexts = { + suggestionSended: { + 'en-US': `Suggestion sended to <@${process.env.MY_DISCORD_USER_ID}>`, + 'es-ES': `Sugerencia enviada a <@${process.env.MY_DISCORD_USER_ID}>`, + }, + extractedFrom: { + 'en-US': 'Prices extracted from:', + 'es-ES': 'Precios extraídos de:', + }, + missingPlatform: { + 'en-US': 'ERROR: Platform don\'t found!!', + 'es-ES': 'ERROR: Plataforma no encontrada!!', + }, + platformInBrowser: { + 'en-US': 'Search in %P on browser', + 'es-ES': 'Buscar en %P en el buscador', + }, + errorScrapping: { + 'en-US': 'No products could be found in:', + 'es-ES': 'No se pudieron encontrar productos en:', + }, + notSuggest: { + 'en-US': 'Please suggest someting :tired_face:', + 'es-ES': 'Por favor, sugiere algo :tired_face:', + }, + linksNotAllowed: { + 'en-US': 'Links aren\'t allowed :/', + 'es-ES': 'No esta permitido enviar links :/', + }, +}; +function responses(userLanguage) { + const responsesEntries = Object.entries(responsesTexts); + const localizatedResponses = {}; + responsesEntries.forEach(([responseName, responseTexts]) => { + localizatedResponses[responseName] = Object.entries(responseTexts).find(responseText => responseText[0] === userLanguage)[1]; + }); + return localizatedResponses; +} + +module.exports = { + urlRegex, + getRandomElementFromArray, + responses, +}; \ No newline at end of file diff --git a/deploy-commands.js b/deploy-commands.js index e720396..d1d8b4a 100644 --- a/deploy-commands.js +++ b/deploy-commands.js @@ -2,6 +2,8 @@ const { REST, Routes } = require('discord.js'); const fs = require('node:fs'); require('dotenv').config(); +const enviroment = process.env.NODE_ENV; + const commands = []; const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js')); @@ -10,15 +12,15 @@ for (const file of commandFiles) { commands.push(command.data.toJSON()); } -const rest = new REST({ version: '10' }).setToken(process.env.BOT_TOKEN); +const rest = new REST({ version: '10' }).setToken(enviroment === 'production' ? process.env.PROD_BOT_TOKEN : process.env.DEV_BOT_TOKEN); (async () => { try { console.log(`Started refreshing ${commands.length} application (/) commands.`); const data = await rest.put( - process.env.NODE_ENV === 'production' ? Routes.applicationCommands(process.env.DISCORD_CLIENT_ID) : - Routes.applicationGuildCommands(process.env.DISCORD_CLIENT_ID, process.env.TEST_DISCORD_SERVER_ID), + enviroment === 'production' ? Routes.applicationCommands(process.env.PROD_DISCORD_CLIENT_ID) : + Routes.applicationGuildCommands(process.env.DEV_DISCORD_CLIENT_ID, process.env.TEST_DISCORD_SERVER_ID), { body: commands }, );