From da37e6b6344351760efcec9ffb0c679489c7ecb4 Mon Sep 17 00:00:00 2001 From: Lucas Gabriel Date: Wed, 25 Sep 2024 00:02:41 -0300 Subject: [PATCH] Database implemented for the Last.fm command instead of specifying the user + help --- .gitignore | 3 +- commands/help.js | 9 ++++-- commands/lastfm.js | 65 +++++++++++++++++++++++++++++++++++++---- locales/english.json | 10 +++++-- locales/portuguese.json | 10 +++++-- nodemon.json | 3 ++ 6 files changed, 85 insertions(+), 15 deletions(-) create mode 100644 nodemon.json diff --git a/.gitignore b/.gitignore index 93b1dfe..60ce1a0 100644 --- a/.gitignore +++ b/.gitignore @@ -4,4 +4,5 @@ node_modules __pycache__ !requirements.txt -props/config.json \ No newline at end of file +props/config.json +props/lastfm.json \ No newline at end of file diff --git a/commands/help.js b/commands/help.js index 85b833d..26620cb 100644 --- a/commands/help.js +++ b/commands/help.js @@ -9,7 +9,8 @@ async function sendHelpMessage(ctx, isEditing) { reply_markup: { inline_keyboard: [ [{ text: Strings.mainCommands, callback_data: '1' }, { text: Strings.usefulCommands, callback_data: '2' }], - [{ text: Strings.interactiveEmojis, callback_data: '3' }, { text: Strings.funnyCommands, callback_data: '4' }] + [{ text: Strings.interactiveEmojis, callback_data: '3' }, { text: Strings.funnyCommands, callback_data: '4' }], + [{ text: Strings.lastFm, callback_data: '5' }] ] } }; @@ -33,7 +34,7 @@ module.exports = (bot) => { parse_mode: 'Markdown', reply_markup: JSON.stringify({ inline_keyboard: [ - [{ text: Strings.goBack, callback_data: '5' }], + [{ text: Strings.goBack, callback_data: '6' }], ] }) }; @@ -56,6 +57,10 @@ module.exports = (bot) => { await ctx.editMessageText(Strings.funnyCommandsDesc, options); break; case '5': + await ctx.answerCbQuery(); + await ctx.editMessageText(Strings.lastFmDesc, options); + break; + case '6': await ctx.answerCbQuery(); await sendHelpMessage(ctx, true); break; diff --git a/commands/lastfm.js b/commands/lastfm.js index 4e523c0..b8f1228 100644 --- a/commands/lastfm.js +++ b/commands/lastfm.js @@ -1,3 +1,4 @@ +const fs = require('fs'); const axios = require('axios'); const Config = require('../props/config.json'); const { getStrings } = require('../plugins/checklang.js'); @@ -7,14 +8,66 @@ const spamwatchMiddleware = require('../plugins/lib-spamwatch/Middleware.js')(is const scrobbler_url = 'http://ws.audioscrobbler.com/2.0/'; const api_key = Config.lastKey; +const dbFile = 'props/lastfm.json'; +let users = {}; + +function loadUsers() { + if (!fs.existsSync(dbFile)) { + console.log(`WARN: Last.fm user database ${dbFile} not found. Creating a new one.`); + saveUsers(); + return; + } + + try { + const data = fs.readFileSync(dbFile, 'utf-8'); + users = JSON.parse(data); + } catch (err) { + console.log("WARN: Error loading the Last.fm user database:", err); + users = {}; + } +} + +function saveUsers() { + try { + fs.writeFileSync(dbFile, JSON.stringify(users, null, 2), 'utf-8'); + } catch (err) { + console.error("WARN: Error saving Last.fm users:", err); + } +} + module.exports = (bot) => { - bot.command(['lt', 'lmu', 'last', 'lfm'], spamwatchMiddleware, async (ctx) => { + loadUsers(); + + bot.command('setuser', (ctx) => { + const userId = ctx.from.id; const Strings = getStrings(ctx.from.language_code); - const userInput = ctx.message.text.split(" "); - const lastfmUser = userInput[1]; + const lastUser = ctx.message.text.split(' ')[1]; + + if (!lastUser) { + return ctx.reply(Strings.lastFmNoUser, { + parse_mode: "Markdown", + reply_to_message_id: ctx.message.message_id + }); + }; + + users[userId] = lastUser; + saveUsers(); + + const message = Strings.lastFmUserSet.replace('{lastUser}', lastUser); + + ctx.reply(message, { + parse_mode: "Markdown", + reply_to_message_id: ctx.message.message_id + }); + }); + + bot.command(['lt', 'lmu', 'last', 'lfm'], spamwatchMiddleware, async (ctx) => { + const userId = ctx.from.id; + const Strings = getStrings(ctx.from.language_code); + const lastfmUser = users[userId]; if (!lastfmUser) { - return ctx.reply(Strings.lastFmNoUser, { + return ctx.reply(Strings.lastFmNoSet, { parse_mode: "Markdown", reply_to_message_id: ctx.message.message_id }); @@ -51,7 +104,7 @@ module.exports = (bot) => { const imageExtralarge = track.image.find(img => img.size === 'extralarge'); const imageMega = track.image.find(img => img.size === 'mega'); const imageUrl = (imageExtralarge && imageExtralarge['#text']) || (imageMega && imageMega['#text']) || ''; - + const trackUrl = `https://www.last.fm/music/${encodeURIComponent(artistName)}/_/${encodeURIComponent(trackName)}`; const artistUrl = `https://www.last.fm/music/${encodeURIComponent(artistName)}`; const userUrl = `https://www.last.fm/user/${encodeURIComponent(lastfmUser)}`; @@ -82,7 +135,7 @@ module.exports = (bot) => { reply_to_message_id: ctx.message.message_id }); }; - + const message = Strings.lastFmStatusFor .replace("{lastfmUser}", `[${lastfmUser}](${userUrl})`) .replace("{nowPlaying}", nowPlaying) diff --git a/locales/english.json b/locales/english.json index ab6d7e3..e6035eb 100644 --- a/locales/english.json +++ b/locales/english.json @@ -31,12 +31,16 @@ "chatInfo": "*Chat info*\n\n*Name:* `{chatName}`\n*Chat ID:* `{chatId}`\n*Handle:* `{chatHandle}`\n*Type:* `{chatType}`\n*Members:* `{chatMembersCount}`\n*Is a forum:* `{isForum}`", "funEmojiResult": "*You rolled {emoji} and got* `{value}`*!*\nYou don't know what that means? Me neither!", "gifErr": "*Something went wrong while sending the GIF. Please try again later.*\n\n{err}", - "lastFmNoUser": "*Please provide a Last.fm username.*\nExample: `/lt username`", + "lastFm": "Last.fm", + "lastFmDesc": "*Last.fm*\n\n- /lt | /lmu | /last | /lfm: Shows the last song from your Last.fm profile + the number of plays.\n- /setuser ``: Sets the user for the command above.", + "lastFmNoUser": "*Please provide a Last.fm username.*\nExample: `/setuser `", + "lastFmNoSet": "*You haven't set your Last.fm username yet.*\nUse the command /setuser to set.\n\nExample: `/setuser `", "lastFmNoRecent": "*No recent tracks found for Last.fm user* `{lastfmUser}`*.*", "lastFmListeningNow": "Listening now", + "lastFmUserSet": "*Your Last.fm username has been set to:* `{lastUser}`.", "lastFmLastPlayed": "Last played", "lastFmStatusFor": "*Last.fm status for user* {lastfmUser}*:*\n\n*{nowPlaying}*: {trackName} by {artistName} \n\n*Number of plays*: {plays}", - "lastFmErr": "*Error retrieving data for Last.fm user* {lastfmUser}.", + "lastFmErr": "*Error retrieving data for Last.fm user* {lastfmUser}.\n\n`{err}`", "currentCommit": "*Current commit:* `{commitHash}`", "errorRetrievingCommit": "*Error retrieving commit:* {error}", "provideLocation": "*Please provide a location.*", @@ -46,7 +50,7 @@ "mainCommands": "Main commands", "mainCommandsDesc": "*Main commands*\n\n- /help: Show bot's help\n- /start: Start the bot\n- /privacy: Read the bot's Privacy Policy", "usefulCommands": "Useful commands", - "usefulCommandsDesc": "*Useful commands*\n\n- /chatinfo: Send information about the group\n- /userinfo: Send information about yourself\n- /d | /device ``: Search for a device on GSMArena and show its specs.\n- /lt | /lmu | /last | /lfm ``: Show the last song from a specified Last.fm profile + number of plays.\n- /weather | /clima ``: See weather status for a specific location.\n- /modarchive | /tma ``: Download a module from The Mod Archive", + "usefulCommandsDesc": "*Useful commands*\n\n- /chatinfo: Send information about the group\n- /userinfo: Send information about yourself\n- /d | /device ``: Search for a device on GSMArena and show its specs.\n- /weather | /clima ``: See weather status for a specific location.\n- /modarchive | /tma ``: Download a module from The Mod Archive", "funnyCommands": "Funny commands", "funnyCommandsDesc": "*Funny commands*\n\n- /gay: Check if you are gay\n- /furry: Check if you are a furry\n- /random: Pick a random number between 0-10", "interactiveEmojis": "Interactive emojis", diff --git a/locales/portuguese.json b/locales/portuguese.json index 8f01d19..372f99c 100644 --- a/locales/portuguese.json +++ b/locales/portuguese.json @@ -31,12 +31,16 @@ "chatInfo": "*Informações do chat*\n\n*Nome:* `{chatName}`\n*ID do chat:* `{chatId}`\n*Identificador:* `{chatHandle}`\n*Tipo:* `{chatType}`\n*Membros:* `{chatMembersCount}`\n*É um fórum:* `{isForum}`", "funEmojiResult": "*Você lançou {emoji} e obteve *`{value}`*!*\nVocê não sabe o que isso significa? Nem eu!", "gifErr": "*Algo deu errado ao enviar o GIF. Tente novamente mais tarde.*\n\n{err}", - "lastFmNoUser": "*Por favor, forneça um nome de usuário do Last.fm.*\nExemplo: `/lt username`", + "lastFm": "Last.fm", + "lastFmDesc": "*Last.fm*\n\n- /lt | /lmu | /last | /lfm: Mostra a última música do seu perfil no Last.fm + o número de reproduções.\n- /setuser ``: Define o usuário para o comando acima.", + "lastFmNoUser": "*Por favor, forneça um nome de usuário do Last.fm.*\nExemplo: `/setuser `", + "lastFmNoSet": "*Você ainda não definiu seu nome de usuário do Last.fm.*\nUse o comando /setuser para definir.\n\nExemplo: `/set `", "lastFmNoRecent": "*Nenhuma faixa recente encontrada para o usuário do Last.fm* `{lastfmUser}`*.*", "lastFmListeningNow": "Ouvindo agora", + "lastFmUserSet": "*Seu nome de usuário do Last.fm foi definido como:* `{lastUser}`.", "lastFmLastPlayed": "Última reprodução", "lastFmStatusFor": "*Status do Last.fm para o usuário* {lastfmUser}*:*\n\n*{nowPlaying}*: {trackName} por {artistName}\n\n*Número de reproduções*: {plays}", - "lastFmErr": "*Erro ao recuperar dados para o usuário do Last.fm* {lastfmUser}.", + "lastFmErr": "*Erro ao recuperar dados para o usuário do Last.fm* {lastfmUser}.\n\n`{err}`", "currentCommit": "*Commit atual:* `{commitHash}`", "errorRetrievingCommit": "*Erro ao obter o commit:*\n\n`{error}`", "provideLocation": "*Por favor, forneça uma localização.*", @@ -46,7 +50,7 @@ "mainCommands": "Comandos principais", "mainCommandsDesc": "*Comandos principais*\n\n- /help: Exibe a ajuda do bot\n- /start: Inicia o bot\n- /privacy: Leia a política de privacidade do bot", "usefulCommands": "Comandos úteis", - "usefulCommandsDesc": "*Comandos úteis*\n\n- /chatinfo: Envia informações sobre o grupo\n- /userinfo: Envia informações sobre você\n- /d | /device ``: Pesquisa um dispositivo no GSMArena e mostra suas especificações.\n- /lt | /lmu | /last | /lfm ``: Mostra a última música de um perfil especificado no Last.fm + o número de reproduções.\n- /weather | /clima ``: Veja o status do clima para uma localização específica\n- /modarchive | /tma ``: Baixa um módulo do The Mod Archive", + "usefulCommandsDesc": "*Comandos úteis*\n\n- /chatinfo: Envia informações sobre o grupo\n- /userinfo: Envia informações sobre você\n- /d | /device ``: Pesquisa um dispositivo no GSMArena e mostra suas especificações.\n- /weather | /clima ``: Veja o status do clima para uma localização específica\n- /modarchive | /tma ``: Baixa um módulo do The Mod Archive", "funnyCommands": "Comandos engraçados", "funnyCommandsDesc": "*Comandos engraçados*\n\n- /gay: Verifique se você é gay\n- /furry: Verifique se você é furry\n- /random: Escolhe um número aleatório entre 0-10", "interactiveEmojis": "Emojis interativos", diff --git a/nodemon.json b/nodemon.json new file mode 100644 index 0000000..35b7bb0 --- /dev/null +++ b/nodemon.json @@ -0,0 +1,3 @@ +{ + "ignore": ["props"] +} \ No newline at end of file