diff --git a/.editorconfig b/.editorconfig index 311c301..edb2837 100644 --- a/.editorconfig +++ b/.editorconfig @@ -6,3 +6,4 @@ end_of_line = crlf insert_final_newline = true indent_style = space indent_size = 4 +max_line_legnth = 120 diff --git a/.env.example b/.env.example index a8c32bf..3c7feaa 100644 --- a/.env.example +++ b/.env.example @@ -1,8 +1,26 @@ +# This file contains all the environment variables that are used by the bot. + +# For production use, set NODE_ENV to production +# For development use, set NODE_ENV to development NODE_ENV=development -MINIMUM_LOG_LEVEL=debug -MINIMUM_LOG_LEVEL_CONSOLE=info + +# Required: Login credentials for the bot +# Retrieve your bot token and application id from https://discordapp.com/developers/applications/me DISCORD_BOT_TOKEN=YOUR_DISCORD_BOT_TOKEN -DISCORD_CLIENT_ID=YOUR_DISCOR_BOT_CLIENT_ID -UV_THREADPOOL_SIZE=4 -NODE_OPTIONS= +DISCORD_APPLICATION_ID=YOUR_DISCORD_BOT_APPLICATION_ID + +# Optional: Set a YouTube cookie to reduce the chance of getting rate limited / 429 Too Many Requests YOUTUBE_COOKIE= + +# Optional: Authentication tokens for botlist websites to automatically update server count, etc. +# See /src/utils/postBotStats.js for more information +BOTLIST_TOP_GG_API_TOKEN= +BOTLIST_DISCORD_BOT_LIST_COM_API_TOKEN= +BOTLIST_DISCORDS_COM_API_TOKEN= +BOTLIST_DISCORD_BOTS_GG_API_TOKEN= +BOTLIST_BOTLIST_ME_API_TOKEN= +BOTLIST_DISCORDLIST_GG_API_TOKEN= + +# Optional: Only change this if you know what you are doing +NODE_OPTIONS= +UV_THREADPOOL_SIZE= diff --git a/.eslintrc.json b/.eslintrc.json index 8967c60..853c74b 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -8,7 +8,18 @@ "ecmaVersion": "latest" }, "rules": { - "indent": ["error", 4], + "indent": ["error", 4, { "SwitchCase": 1 }], + "max-len": [ + "error", + { + "code": 120, + "ignoreTemplateLiterals": true, + "ignoreStrings": true, + "ignoreComments": true, + "ignoreRegExpLiterals": true, + "ignoreUrls": true + } + ], "linebreak-style": ["error", "windows"], "quotes": ["error", "single"], "semi": ["error", "always"], diff --git a/.gitignore b/.gitignore index a0596c3..d64da02 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ /node_modules /config.json +/src/config.js /.env /app-*.log /logs diff --git a/.prettierrc b/.prettierrc index 3b68416..f723216 100644 --- a/.prettierrc +++ b/.prettierrc @@ -7,5 +7,6 @@ "trailingComma": "none", "arrowParens": "always", "endOfLine": "auto", - "tabWidth": 4 + "tabWidth": 4, + "printWidth": 120 } diff --git a/config.json.example b/config.json.example deleted file mode 100644 index 1008754..0000000 --- a/config.json.example +++ /dev/null @@ -1,130 +0,0 @@ -{ - "botInfo": { - "name": "Cadence", - "websiteUrl": "Unknown", - "botInviteUrl": "Unknown", - "supportServerInviteUrl": "Unknown" - }, - "systemServerGuildIds": [ - "Server id where system commands can be used", - "Another server id where system commands can be used" - ], - "embedColors": { - "colorSuccess": "#23A55A", - "colorWarning": "#F0B232", - "colorError": "#F23F43", - "colorInfo": "#5865F2", - "colorNote": "#80848E" - }, - "playerOptions": { - "leaveOnEmpty": true, - "leaveOnEmptyCooldown": 60000, - "leaveOnEnd": true, - "leaveonEndCooldown": 60000, - "leaveOnStop": true, - "leaveOnStopCooldown": 60000, - "defaultVolume": 50, - "maxQueueSize": 1000, - "maxHistorySize": 100 - }, - "progressBarOptions": { - "length": 14, - "timecodes": false, - "separator": "┃", - "indicator": "🔘", - "leftChar": "▬", - "rightChar": "▬" - }, - "embedIcons": { - "logo": "🤖", - "beta": "`beta`", - "new": "`new`", - "rule": "📒", - "support": "❓", - "bot": "🤖", - "audioPlaying": "🎶", - "audioStartedPlaying": "🎶", - "success": "✅", - "error": "⚠️", - "warning": "⚠️", - "disable": "🚫", - "enable": "✅", - "disabled": "✅", - "enabled": "✅", - "nextTrack": "⏭️", - "previousTrack": "⏮️", - "pauseResumeTrack": "⏯️", - "shuffleQueue": "🔀", - "loop": "🔁", - "loopAction": "🔁", - "autoplay": "♾️", - "autoplayAction": "♾️", - "looping": "🔁", - "autoplaying": "♾️", - "skipped": "⏭️", - "back": "⏮️", - "pauseResumed": "⏯️", - "shuffled": "🔀", - "volume": "🔊", - "volumeIsMuted": "🔇", - "volumeChanged": "🔊", - "volumeMuted": "🔇", - "queue": "🎶", - "sourceArbitrary": "🎵", - "sourceAppleMusic": "🎵", - "sourceYouTube": "🎵", - "sourceSoundCloud": "🎵", - "sourceSpotify": "🎵" - }, - "filterThreadAmount": "2", - "filterList": [ - { - "label": "Bass boost", - "value": "bassboost_low", - "description": "Boost the bass of the audio.", - "emoji": "🔉" - }, - { - "label": "Bass boost high", - "value": "bassboost", - "description": "Boost the bass of the audio a lot.", - "emoji": "🔊" - }, - { - "label": "Night core", - "value": "nightcore", - "description": "Speed up the audio (higher pitch).", - "emoji": "🐱" - }, - { - "label": "Lo-fi", - "value": "lofi", - "description": "Low fidelity effect (lower quality).", - "emoji": "📻" - }, - { - "label": "Vaporwave", - "value": "vaporwave", - "description": "Slow down the audio (lower pitch).", - "emoji": "🌸" - }, - { - "label": "Ear rape", - "value": "earrape", - "description": "Extremely loud and distorted audio.", - "emoji": "👂" - }, - { - "label": "8D", - "value": "8D", - "description": "Simulate 8D audio effect (surround).", - "emoji": "🎧" - }, - { - "label": "Treble", - "value": "treble", - "description": "Increase the high frequencies.", - "emoji": "🎼" - } - ] -} diff --git a/package.json b/package.json index a87bd1a..1e7cb21 100644 --- a/package.json +++ b/package.json @@ -21,8 +21,8 @@ "test": "echo \"Error: no test specified\" && exit 1", "start": "node ./src/index.js", "start-pretty": "node ./src/index.js | pino-pretty", - "deploy": "node ./src/deploy-commands.js && node ./src/deploy-system-commands.js", - "deploy-pretty": "node ./src/deploy-commands.js | pino-pretty && node ./src/deploy-system-commands.js | pino-pretty", + "deploy": "node ./src/utils/deploySlashCommands.js", + "deploy-pretty": "node ./src/utils/deploySlashCommands.js | pino-pretty", "eslint": "eslint ./" }, "dependencies": { diff --git a/src/commands/help.js b/src/commands/info/help.js similarity index 60% rename from src/commands/help.js rename to src/commands/info/help.js index 2d4002d..373f3fe 100644 --- a/src/commands/help.js +++ b/src/commands/info/help.js @@ -1,34 +1,32 @@ -const path = require('path'); -const { SlashCommandBuilder } = require('@discordjs/builders'); -const { EmbedBuilder } = require('discord.js'); -const { embedColors, embedIcons, botInfo } = require(path.resolve('./config.json')); +const { embedOptions, botOptions } = require('../../config'); +const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); module.exports = { data: new SlashCommandBuilder() .setName('help') .setDescription('Show a list of commands and their usage.') .setDMPermission(false), - run: async ({ interaction }) => { + execute: async ({ interaction }) => { return await interaction.editReply({ embeds: [ new EmbedBuilder() .setDescription( - `${embedIcons.rule} **List of commands**\n` + + `${embedOptions.icons.rule} **List of commands**\n` + '- **`/play` `query`** - Add a track or playlist to the queue by url or search.\n' + '- **`/pause`** - Pause or resume the current track.\n' + '- **`/queue` `[page]`** - Show the list of tracks added to the queue.\n' + '- **`/nowplaying`** - Show information about the track currently playing.\n' + - `- **\`/seek\` \`duration\`** - ${embedIcons.new} Seek to a specified duration in the current track.\n` + - `- **\`/loop\` \`mode\`** - ${embedIcons.beta} Toggle looping a track, the whole queue or autoplay.\n` + + `- **\`/seek\` \`duration\`** - ${embedOptions.icons.new} Seek to a specified duration in the current track.\n` + + `- **\`/loop\` \`mode\`** - ${embedOptions.icons.beta} Toggle looping a track, the whole queue or autoplay.\n` + '- **`/filters`** - Toggle various audio filters during playback.\n' + '- **`/volume` `[percentage]`** - Show or set the playback volume for tracks.\n' + '- **`/skip` `[tracknumber]`** - Skip to next or specified track.\n' + '- **`/remove` `tracknumber`** - Remove specified track from the queue.\n' + '- **`/leave`** - Clear the queue and remove the bot from voice channel.\n\n' + - `${embedIcons.support} **Support server**\nJoin the support server for help or suggestions: \n**${botInfo.supportServerInviteUrl}**\n\n` + - `${embedIcons.bot} **Enjoying ${botInfo.name}?**\nAdd me to another server: \n**[Click me!](${botInfo.botInviteUrl})**` + `${embedOptions.icons.support} **Support server**\nJoin the support server for help or suggestions: \n**${botOptions.serverInviteUrl}**\n\n` + + `${embedOptions.icons.bot} **Enjoying ${botOptions.name}?**\nAdd me to another server: \n**[Click me!](${botOptions.botInviteUrl})**` ) - .setColor(embedColors.colorInfo) + .setColor(embedOptions.colors.info) ] }); } diff --git a/src/commands/play.js b/src/commands/play.js deleted file mode 100644 index 0ada85c..0000000 --- a/src/commands/play.js +++ /dev/null @@ -1,232 +0,0 @@ -const path = require('path'); -const { SlashCommandBuilder } = require('@discordjs/builders'); -const { useMainPlayer, useQueue } = require('discord-player'); -const { EmbedBuilder } = require('discord.js'); -const { - embedColors, - embedIcons, - playerOptions, - botInfo -} = require(path.resolve('./config.json')); - -module.exports = { - data: new SlashCommandBuilder() - .setName('play') - .setDescription( - 'Add a track or playlist to the queue by searching or url.' - ) - .setDMPermission(false) - .addStringOption((option) => - option - .setName('query') - .setDescription('Search query or URL.') - .setRequired(true) - ), - run: async ({ interaction }) => { - if (!interaction.member.voice.channel) { - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedIcons.warning} Oops!**\nYou need to be in a voice channel to use this command.` - ) - .setColor(embedColors.colorWarning) - ] - }); - } - - const player = useMainPlayer(); - const query = interaction.options.getString('query'); - - const searchResult = await player.search(query, { - requestedBy: interaction.user - }); - - if (!searchResult || searchResult.tracks.length === 0) { - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedIcons.warning} No track found**\nNo results found for \`${query}\`.\n\nIf you specified a URL, please make sure it is valid and public.` - ) - .setColor(embedColors.colorWarning) - ] - }); - } - - if ( - searchResult.tracks[0].raw.live && - searchResult.tracks[0].raw.duration === 0 && - searchResult.tracks[0].source === 'youtube' - ) { - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedIcons.warning} Unsupported audio source**\nYouTube live streams are currently not supported. This is due to issues with extracting audio from the livestream.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botInfo.supportServerInviteUrl})**._` - ) - .setColor(embedColors.colorWarning) - ] - }); - } - - let track; - - try { - ({ track } = await player.play( - interaction.member.voice.channel, - searchResult, - { - requestedBy: interaction.user, - nodeOptions: { - leaveOnEmpty: playerOptions.leaveOnEmpty ?? true, - leaveOnEmptyCooldown: - playerOptions.leaveOnEmptyCooldown ?? 60000, - leaveOnEnd: playerOptions.leaveOnEnd ?? true, - leaveOnEndCooldown: - playerOptions.leaveOnEndCooldown ?? 60000, - leaveOnStop: playerOptions.leaveOnStop ?? true, - leaveOnStopCooldown: - playerOptions.leaveOnStopCooldown ?? 60000, - maxSize: playerOptions.maxQueueSize ?? 1000, - maxHistorySize: playerOptions.maxHistorySize ?? 100, - volume: playerOptions.defaultVolume ?? 50 - } - } - )); - } catch (error) { - if (error.message.includes('Sign in to confirm your age')) { - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedIcons.warning} Cannot retrieve audio for track**\nThis audio source is age restricted and requires login to access. Because of this I cannot retrieve the audio for the track.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botInfo.supportServerInviteUrl})**._` - ) - .setColor(embedColors.colorWarning) - ] - }); - } - - if ( - (error.type === 'TypeError' && - (error.message.includes( - 'Cannot read properties of null (reading \'createStream\')' - ) || - error.message.includes( - 'Failed to fetch resources for ytdl streaming' - ))) || - error.message.includes( - 'Could not extract stream for this track' - ) - ) { - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedIcons.error} Uh-oh... Failed to add track!**\nAfter finding a result, I was unable to retrieve audio for the track.\n\nYou can try to perform the command again.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botInfo.supportServerInviteUrl})**._` - ) - .setColor(embedColors.colorError) - ] - }); - } - - if (error.message === 'Cancelled') { - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedIcons.error} Uh-oh... Failed to add track!**\nSomething unexpected happened and the operation was cancelled.\n\nYou can try to perform the command again.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botInfo.supportServerInviteUrl})**._` - ) - .setColor(embedColors.colorError) - ] - }); - } - } - - let queue = useQueue(interaction.guild.id); - - if (!queue) { - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedIcons.error} Uh-oh... Failed to add track!**\nThere was an issue adding this track to the queue.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botInfo.supportServerInviteUrl})**._` - ) - .setColor(embedColors.colorError) - ] - }); - } - - if (track.source === 'arbitrary') { - track.thumbnail = - 'https://raw.githubusercontent.com/mariusbegby/cadence-discord-bot/main/assets/logo-rounded-128px.png'; - } - - let durationFormat = - track.raw.duration === 0 || track.duration === '0:00' - ? '' - : `\`${track.duration}\``; - - if (searchResult.playlist && searchResult.tracks.length > 1) { - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setAuthor({ - name: - interaction.member.nickname || - interaction.user.username, - iconURL: interaction.user.avatarURL() - }) - .setDescription( - `**${ - embedIcons.success - } Added playlist to queue**\n**${durationFormat} [${ - track.title - }](${track.url})**\n\nAnd **${ - searchResult.tracks.length - 1 - }** more tracks... **\`/queue\`** to view all.` - ) - .setThumbnail(track.thumbnail) - .setColor(embedColors.colorSuccess) - ] - }); - } - - if (queue.currentTrack === track) { - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setAuthor({ - name: - interaction.member.nickname || - interaction.member.nickname || - interaction.user.username, - iconURL: interaction.user.avatarURL() - }) - .setDescription( - `**${embedIcons.audioStartedPlaying} Started playing**\n**${durationFormat} [${track.title}](${track.url})**` - ) - .setThumbnail(track.thumbnail) - .setColor(embedColors.colorSuccess) - ] - }); - } - - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setAuthor({ - name: - interaction.member.nickname || - interaction.user.username, - iconURL: interaction.user.avatarURL() - }) - .setDescription( - `${embedIcons.success} **Added to queue**\n**${durationFormat} [${track.title}](${track.url})**` - ) - .setThumbnail(track.thumbnail) - .setColor(embedColors.colorSuccess) - ] - }); - } -}; diff --git a/src/commands/filters.js b/src/commands/player/filters.js similarity index 70% rename from src/commands/filters.js rename to src/commands/player/filters.js index 5bfb2ee..a7e3d71 100644 --- a/src/commands/filters.js +++ b/src/commands/player/filters.js @@ -1,34 +1,28 @@ -const path = require('path'); -const { SlashCommandBuilder } = require('@discordjs/builders'); -const { useQueue } = require('discord-player'); +const { embedOptions, ffmpegFilterOptions } = require('../../config'); const { + SlashCommandBuilder, EmbedBuilder, + ActionRowBuilder, StringSelectMenuBuilder, StringSelectMenuOptionBuilder, - ActionRowBuilder, ButtonBuilder } = require('discord.js'); -const { - embedColors, - embedIcons, - filterList, - filterThreadAmount -} = require(path.resolve('./config.json')); +const { useQueue } = require('discord-player'); module.exports = { data: new SlashCommandBuilder() .setName('filters') .setDescription('Toggle various audio filters during playback.') .setDMPermission(false), - run: async ({ interaction }) => { + execute: async ({ interaction }) => { if (!interaction.member.voice.channel) { return await interaction.editReply({ embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nYou need to be in a voice channel to use this command.` + `**${embedOptions.icons.warning} Oops!**\nYou need to be in a voice channel to use this command.` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } @@ -40,16 +34,16 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nThere are no tracks in the queue. First add some tracks with **\`/play\`**!` + `**${embedOptions.icons.warning} Oops!**\nThere are no tracks in the queue. First add some tracks with **\`/play\`**!` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } let filterOptions = []; - filterList.forEach((filter) => { + ffmpegFilterOptions.availableFilters.forEach((filter) => { let isEnabled = false; if (queue.filters.ffmpeg.filters.includes(filter.value)) { @@ -73,25 +67,23 @@ module.exports = { .setMaxValues(filterOptions.length) .addOptions(filterOptions); - const filterActionRow = new ActionRowBuilder().addComponents( - filterSelect - ); + const filterActionRow = new ActionRowBuilder().addComponents(filterSelect); const disableFiltersActionRow = new ActionRowBuilder().addComponents( new ButtonBuilder() .setCustomId('disable-filters') .setLabel('Disable all filters') .setStyle('Secondary') - .setEmoji(embedIcons.disable) + .setEmoji(embedOptions.icons.disable) ); const response = await interaction.editReply({ embeds: [ new EmbedBuilder() .setDescription( - `**Toggle filters** ${embedIcons.beta}\nEnable or disable audio filters for playback from the menu.` + `**Toggle filters** ${embedOptions.icons.beta}\nEnable or disable audio filters for playback from the menu.` ) - .setColor(embedColors.colorInfo) + .setColor(embedOptions.colors.info) ], components: [filterActionRow, disableFiltersActionRow] }); @@ -107,7 +99,7 @@ module.exports = { queue.filters.ffmpeg.setInputArgs([ '-threads', - filterThreadAmount, + ffmpegFilterOptions.threadAmount, '-reconnect', '1', '-reconnect_streamed', @@ -122,23 +114,18 @@ module.exports = { queue.filters.ffmpeg.setFilters(false); } - if ( - confirmation.customId === 'disable-filters' || - confirmation.values.length === 0 - ) { + if (confirmation.customId === 'disable-filters' || confirmation.values.length === 0) { return await interaction.editReply({ embeds: [ new EmbedBuilder() .setAuthor({ - name: - interaction.member.nickname || - interaction.user.username, + name: interaction.member.nickname || interaction.user.username, iconURL: interaction.user.avatarURL() }) .setDescription( - `**${embedIcons.success} Disabled filters**\nAll audio filters have been disabled.` + `**${embedOptions.icons.success} Disabled filters**\nAll audio filters have been disabled.` ) - .setColor(embedColors.colorSuccess) + .setColor(embedOptions.colors.success) ], components: [] }); @@ -151,27 +138,24 @@ module.exports = { embeds: [ new EmbedBuilder() .setAuthor({ - name: - interaction.member.nickname || - interaction.user.username, + name: interaction.member.nickname || interaction.user.username, iconURL: interaction.user.avatarURL() }) .setDescription( `**${ - embedIcons.success + embedOptions.icons.success } Filters toggled**\nNow using these filters:\n${confirmation.values .map( (enabled) => `\`${ - filterList.find( - (filter) => - enabled == filter.value + ffmpegFilterOptions.availableFilters.find( + (filter) => enabled == filter.value ).label }\`` ) .join(', ')}.` ) - .setColor(embedColors.colorSuccess) + .setColor(embedOptions.colors.success) ], components: [] }); diff --git a/src/commands/leave.js b/src/commands/player/leave.js similarity index 53% rename from src/commands/leave.js rename to src/commands/player/leave.js index f8c2a52..9b994a4 100644 --- a/src/commands/leave.js +++ b/src/commands/player/leave.js @@ -1,27 +1,23 @@ -const path = require('path'); -const { SlashCommandBuilder } = require('@discordjs/builders'); +const { embedOptions } = require('../../config'); +const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); const { useQueue } = require('discord-player'); -const { EmbedBuilder } = require('discord.js'); -const { embedColors, embedIcons } = require(path.resolve('./config.json')); module.exports = { data: new SlashCommandBuilder() .setName('leave') - .setDescription( - 'Clear the track queue and remove the bot from voice channel.' - ) + .setDescription('Clear the track queue and remove the bot from voice channel.') .setDMPermission(false), // todo, allow command to be executed if bot is only member in voice channel - run: async ({ interaction }) => { + execute: async ({ interaction }) => { if (!interaction.member.voice.channel) { return await interaction.editReply({ embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nYou need to be in a voice channel to use this command.` + `**${embedOptions.icons.warning} Oops!**\nYou need to be in a voice channel to use this command.` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } @@ -33,9 +29,9 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\n_Hmm.._ It seems I am not in a voice channel!` + `**${embedOptions.icons.warning} Oops!**\n_Hmm.._ It seems I am not in a voice channel!` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } @@ -47,15 +43,13 @@ module.exports = { embeds: [ new EmbedBuilder() .setAuthor({ - name: - interaction.member.nickname || - interaction.user.username, + name: interaction.member.nickname || interaction.user.username, iconURL: interaction.user.avatarURL() }) .setDescription( - `**${embedIcons.success} Leaving channel**\nCleared the track queue and left voice channel.\n\nTo play more music, use the **\`/play\`** command!` + `**${embedOptions.icons.success} Leaving channel**\nCleared the track queue and left voice channel.\n\nTo play more music, use the **\`/play\`** command!` ) - .setColor(embedColors.colorSuccess) + .setColor(embedOptions.colors.success) ] }); } diff --git a/src/commands/loop.js b/src/commands/player/loop.js similarity index 58% rename from src/commands/loop.js rename to src/commands/player/loop.js index 582db6d..2566c8d 100644 --- a/src/commands/loop.js +++ b/src/commands/player/loop.js @@ -1,8 +1,6 @@ -const path = require('path'); -const { SlashCommandBuilder } = require('@discordjs/builders'); +const { embedOptions, botOptions } = require('../../config'); +const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); const { useQueue } = require('discord-player'); -const { EmbedBuilder } = require('discord.js'); -const { embedColors, embedIcons, botInfo } = require(path.resolve('./config.json')); module.exports = { data: new SlashCommandBuilder() @@ -21,15 +19,15 @@ module.exports = { { name: 'Disabled', value: '0' } ) ), - run: async ({ interaction }) => { + execute: async ({ interaction }) => { if (!interaction.member.voice.channel) { return await interaction.editReply({ embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nYou need to be in a voice channel to use this command.` + `**${embedOptions.icons.warning} Oops!**\nYou need to be in a voice channel to use this command.` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } @@ -41,9 +39,9 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nThere are no tracks in the queue and nothing currently playing. First add some tracks with **\`/play\`**!` + `**${embedOptions.icons.warning} Oops!**\nThere are no tracks in the queue and nothing currently playing. First add some tracks with **\`/play\`**!` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } @@ -66,12 +64,10 @@ module.exports = { new EmbedBuilder() .setDescription( `**${ - currentMode === 3 - ? embedIcons.autoplay - : embedIcons.loop + currentMode === 3 ? embedOptions.icons.autoplay : embedOptions.icons.loop } Current loop mode**\nThe looping mode is currently set to \`${currentModeUserString}\`.` ) - .setColor(embedColors.colorInfo) + .setColor(embedOptions.colors.info) ] }); } @@ -81,9 +77,9 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nLoop mode is already \`${modeUserString}\`.` + `**${embedOptions.icons.warning} Oops!**\nLoop mode is already \`${modeUserString}\`.` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } @@ -95,9 +91,9 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.error} Uh-oh... Failed to change loop mode!**\nI tried to change the loop mode to \`${modeUserString}\`, but something went wrong.\n\nYou can try to perform the command again.\n\n_If you think this message is incorrect or the issue persists, please submit a bug report in the **[support server](${botInfo.supportServerInviteUrl})**._` + `**${embedOptions.icons.error} Uh-oh... Failed to change loop mode!**\nI tried to change the loop mode to \`${modeUserString}\`, but something went wrong.\n\nYou can try to perform the command again.\n\n_If you think this message is incorrect or the issue persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` ) - .setColor(embedColors.colorError) + .setColor(embedOptions.colors.error) ] }); } @@ -107,15 +103,13 @@ module.exports = { embeds: [ new EmbedBuilder() .setAuthor({ - name: - interaction.member.nickname || - interaction.user.username, + name: interaction.member.nickname || interaction.user.username, iconURL: interaction.user.avatarURL() }) .setDescription( - `**${embedIcons.success} Loop mode disabled**\nChanging loop mode from \`${currentModeUserString}\` to \`${modeUserString}\`.\n\nThe ${currentModeUserString} will no longer play on repeat!` + `**${embedOptions.icons.success} Loop mode disabled**\nChanging loop mode from \`${currentModeUserString}\` to \`${modeUserString}\`.\n\nThe ${currentModeUserString} will no longer play on repeat!` ) - .setColor(embedColors.colorSuccess) + .setColor(embedOptions.colors.success) ] }); } @@ -125,15 +119,13 @@ module.exports = { embeds: [ new EmbedBuilder() .setAuthor({ - name: - interaction.member.nickname || - interaction.user.username, + name: interaction.member.nickname || interaction.user.username, iconURL: interaction.user.avatarURL() }) .setDescription( - `**${embedIcons.autoplaying} Loop mode changed**\nChanging loop mode from \`${currentModeUserString}\` to \`${modeUserString}\`.\n\nWhen the queue is empty, similar tracks will start playing!` + `**${embedOptions.icons.autoplaying} Loop mode changed**\nChanging loop mode from \`${currentModeUserString}\` to \`${modeUserString}\`.\n\nWhen the queue is empty, similar tracks will start playing!` ) - .setColor(embedColors.colorSuccess) + .setColor(embedOptions.colors.success) ] }); } @@ -142,15 +134,13 @@ module.exports = { embeds: [ new EmbedBuilder() .setAuthor({ - name: - interaction.member.nickname || - interaction.user.username, + name: interaction.member.nickname || interaction.user.username, iconURL: interaction.user.avatarURL() }) .setDescription( - `**${embedIcons.looping} Loop mode changed**\nChanging loop mode from \`${currentModeUserString}\` to \`${modeUserString}\`.\n\nThe ${modeUserString} will now play on repeat!` + `**${embedOptions.icons.looping} Loop mode changed**\nChanging loop mode from \`${currentModeUserString}\` to \`${modeUserString}\`.\n\nThe ${modeUserString} will now play on repeat!` ) - .setColor(embedColors.colorSuccess) + .setColor(embedOptions.colors.success) ] }); } diff --git a/src/commands/nowplaying.js b/src/commands/player/nowplaying.js similarity index 65% rename from src/commands/nowplaying.js rename to src/commands/player/nowplaying.js index e540b6a..991cdc3 100644 --- a/src/commands/nowplaying.js +++ b/src/commands/player/nowplaying.js @@ -1,27 +1,21 @@ -const path = require('path'); -const { SlashCommandBuilder } = require('@discordjs/builders'); +const { embedOptions, playerOptions } = require('../../config'); +const { SlashCommandBuilder, EmbedBuilder, ActionRowBuilder, ButtonBuilder } = require('discord.js'); const { useQueue } = require('discord-player'); -const { EmbedBuilder, ActionRowBuilder, ButtonBuilder } = require('discord.js'); -const { - embedColors, - embedIcons, - progressBarOptions -} = require(path.resolve('./config.json')); module.exports = { data: new SlashCommandBuilder() .setName('nowplaying') .setDescription('Show information about the track currently playing.') .setDMPermission(false), - run: async ({ interaction }) => { + execute: async ({ interaction }) => { if (!interaction.member.voice.channel) { return await interaction.editReply({ embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nYou need to be in a voice channel to use this command.` + `**${embedOptions.icons.warning} Oops!**\nYou need to be in a voice channel to use this command.` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } @@ -33,9 +27,9 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nThere are no tracks in the queue and nothing currently playing. First add some tracks with **\`/play\`**!` + `**${embedOptions.icons.warning} Oops!**\nThere are no tracks in the queue and nothing currently playing. First add some tracks with **\`/play\`**!` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } @@ -45,9 +39,9 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nThere is nothing currently playing. First add some tracks with **\`/play\`**!` + `**${embedOptions.icons.warning} Oops!**\nThere is nothing currently playing. First add some tracks with **\`/play\`**!` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } @@ -61,11 +55,11 @@ module.exports = { ]); const sourceIcons = new Map([ - ['youtube', embedIcons.sourceYouTube], - ['soundcloud', embedIcons.sourceSoundCloud], - ['spotify', embedIcons.sourceSpotify], - ['apple_music', embedIcons.sourceAppleMusic], - ['arbitrary', embedIcons.sourceArbitrary] + ['youtube', embedOptions.icons.sourceYouTube], + ['soundcloud', embedOptions.icons.sourceSoundCloud], + ['spotify', embedOptions.icons.sourceSpotify], + ['apple_music', embedOptions.icons.sourceAppleMusic], + ['arbitrary', embedOptions.icons.sourceArbitrary] ]); const currentTrack = queue.currentTrack; @@ -87,26 +81,19 @@ module.exports = { plays = 'Unavailable'; } - const source = - sourceStringsFormatted.get(currentTrack.raw.source) ?? - 'Unavailable'; + const source = sourceStringsFormatted.get(currentTrack.raw.source) ?? 'Unavailable'; const queueLength = queue.tracks.data.length; const timestamp = queue.node.getTimestamp(); - let bar = `**\`${ - timestamp.current.label - }\`** ${queue.node.createProgressBar({ + let bar = `**\`${timestamp.current.label}\`** ${queue.node.createProgressBar({ queue: false, - length: progressBarOptions.length ?? 12, - timecodes: progressBarOptions.timecodes ?? false, - indicator: progressBarOptions.indicator ?? '🔘', - leftChar: progressBarOptions.leftChar ?? '▬', - rightChar: progressBarOptions.rightChar ?? '▬' + length: playerOptions.progressBar.length ?? 12, + timecodes: playerOptions.progressBar.timecodes ?? false, + indicator: playerOptions.progressBar.indicator ?? '🔘', + leftChar: playerOptions.progressBar.leftChar ?? '▬', + rightChar: playerOptions.progressBar.rightChar ?? '▬' })} **\`${timestamp.total.label}\`**`; - if ( - currentTrack.raw.duration === 0 || - currentTrack.duration === '0:00' - ) { + if (currentTrack.raw.duration === 0 || currentTrack.duration === '0:00') { bar = 'No duration available.'; } @@ -115,7 +102,7 @@ module.exports = { .setCustomId('nowplaying-skip') .setLabel('Skip track') .setStyle('Secondary') - .setEmoji(embedIcons.nextTrack) + .setEmoji(embedOptions.icons.nextTrack) ); const loopModesFormatted = new Map([ @@ -131,15 +118,13 @@ module.exports = { embeds: [ new EmbedBuilder() .setAuthor({ - name: `Channel: ${queue.channel.name} (${ - queue.channel.bitrate / 1000 - }kbps)`, + name: `Channel: ${queue.channel.name} (${queue.channel.bitrate / 1000}kbps)`, iconURL: interaction.guild.iconURL() }) .setDescription( (queue.node.isPaused() ? '**Currently Paused**\n' - : `**${embedIcons.audioPlaying} Now Playing**\n`) + + : `**${embedOptions.icons.audioPlaying} Now Playing**\n`) + `**[${currentTrack.title}](${currentTrack.url})**` + `\nRequested by: <@${currentTrack.requestedBy.id}>` + `\n ${bar}\n\n` + @@ -147,9 +132,7 @@ module.exports = { queue.repeatMode === 0 ? '' : `**${ - queue.repeatMode === 3 - ? embedIcons.autoplay - : embedIcons.loop + queue.repeatMode === 3 ? embedOptions.icons.autoplay : embedOptions.icons.loop } Looping**\nLoop mode is set to ${loopModeUserString}. You can change it with **\`/loop\`**.` }` ) @@ -166,19 +149,15 @@ module.exports = { }, { name: '**Audio source**', - value: `**${sourceIcons.get( - currentTrack.raw.source - )} [${source}](${currentTrack.url})**`, + value: `**${sourceIcons.get(currentTrack.raw.source)} [${source}](${currentTrack.url})**`, inline: true } ) .setFooter({ - text: queueLength - ? `${queueLength} other tracks in the queue...` - : ' ' + text: queueLength ? `${queueLength} other tracks in the queue...` : ' ' }) .setThumbnail(queue.currentTrack.thumbnail) - .setColor(embedColors.colorInfo) + .setColor(embedOptions.colors.info) ], components: [nowPlayingActionRow] }); @@ -193,17 +172,14 @@ module.exports = { confirmation.deferUpdate(); if (confirmation.customId === 'nowplaying-skip') { - if ( - !queue || - (queue.tracks.data.length === 0 && !queue.currentTrack) - ) { + if (!queue || (queue.tracks.data.length === 0 && !queue.currentTrack)) { return await interaction.followUp({ embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nThere is nothing currently playing. First add some tracks with **\`/play\`**!` + `**${embedOptions.icons.warning} Oops!**\nThere is nothing currently playing. First add some tracks with **\`/play\`**!` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ], components: [] }); @@ -214,9 +190,9 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nThis track has already been skipped or is no longer playing.` + `**${embedOptions.icons.warning} Oops!**\nThis track has already been skipped or is no longer playing.` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ], components: [] }); @@ -224,39 +200,34 @@ module.exports = { const skippedTrack = queue.currentTrack; let durationFormat = - skippedTrack.raw.duration === 0 || - skippedTrack.duration === '0:00' + skippedTrack.raw.duration === 0 || skippedTrack.duration === '0:00' ? '' : `\`${skippedTrack.duration}\``; queue.node.skip(); - const repeatModeUserString = loopModesFormatted.get( - queue.repeatMode - ); + const repeatModeUserString = loopModesFormatted.get(queue.repeatMode); return await interaction.followUp({ embeds: [ new EmbedBuilder() .setAuthor({ - name: - interaction.member.nickname || - interaction.user.username, + name: interaction.member.nickname || interaction.user.username, iconURL: interaction.user.avatarURL() }) .setDescription( - `**${embedIcons.skipped} Skipped track**\n**${durationFormat} [${skippedTrack.title}](${skippedTrack.url})**` + + `**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${skippedTrack.title}](${skippedTrack.url})**` + `${ queue.repeatMode === 0 ? '' : `\n\n**${ queue.repeatMode === 3 - ? embedIcons.autoplaying - : embedIcons.looping + ? embedOptions.icons.autoplaying + : embedOptions.icons.looping } Looping**\nLoop mode is set to ${repeatModeUserString}. You can change it with **\`/loop\`**.` }` ) .setThumbnail(skippedTrack.thumbnail) - .setColor(embedColors.colorSuccess) + .setColor(embedOptions.colors.success) ], components: [] }); diff --git a/src/commands/pause.js b/src/commands/player/pause.js similarity index 51% rename from src/commands/pause.js rename to src/commands/player/pause.js index e6856a2..787f1c6 100644 --- a/src/commands/pause.js +++ b/src/commands/player/pause.js @@ -1,23 +1,21 @@ -const path = require('path'); -const { SlashCommandBuilder } = require('@discordjs/builders'); +const { embedOptions } = require('../../config'); +const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); const { useQueue } = require('discord-player'); -const { EmbedBuilder } = require('discord.js'); -const { embedColors, embedIcons } = require(path.resolve('./config.json')); module.exports = { data: new SlashCommandBuilder() .setName('pause') .setDescription('Pause or resume the current track.') .setDMPermission(false), - run: async ({ interaction }) => { + execute: async ({ interaction }) => { if (!interaction.member.voice.channel) { return await interaction.editReply({ embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nYou need to be in a voice channel to use this command.` + `**${embedOptions.icons.warning} Oops!**\nYou need to be in a voice channel to use this command.` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } @@ -29,9 +27,9 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nThere are no tracks in the queue and nothing currently playing. First add some tracks with **\`/play\`**!` + `**${embedOptions.icons.warning} Oops!**\nThere are no tracks in the queue and nothing currently playing. First add some tracks with **\`/play\`**!` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } @@ -41,16 +39,15 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nThere is nothing currently playing. First add some tracks with **\`/play\`**!` + `**${embedOptions.icons.warning} Oops!**\nThere is nothing currently playing. First add some tracks with **\`/play\`**!` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } let durationFormat = - queue.currentTrack.raw.duration === 0 || - queue.currentTrack.duration === '0:00' + queue.currentTrack.raw.duration === 0 || queue.currentTrack.duration === '0:00' ? '' : `\`${queue.currentTrack.duration}\``; @@ -61,22 +58,16 @@ module.exports = { embeds: [ new EmbedBuilder() .setAuthor({ - name: - interaction.member.nickname || - interaction.user.username, + name: interaction.member.nickname || interaction.user.username, iconURL: interaction.user.avatarURL() }) .setDescription( - `**${embedIcons.pauseResumed} ${ - queue.node.isPaused() - ? 'Paused Track' - : 'Resumed track' - }**\n**${durationFormat} [${ - queue.currentTrack.title - }](${queue.currentTrack.url})**` + `**${embedOptions.icons.pauseResumed} ${ + queue.node.isPaused() ? 'Paused Track' : 'Resumed track' + }**\n**${durationFormat} [${queue.currentTrack.title}](${queue.currentTrack.url})**` ) .setThumbnail(queue.currentTrack.thumbnail) - .setColor(embedColors.colorSuccess) + .setColor(embedOptions.colors.success) ] }); } diff --git a/src/commands/player/play.js b/src/commands/player/play.js new file mode 100644 index 0000000..a66db10 --- /dev/null +++ b/src/commands/player/play.js @@ -0,0 +1,194 @@ +const { embedOptions, playerOptions, botOptions } = require('../../config'); +const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); +const { useMainPlayer, useQueue } = require('discord-player'); + +module.exports = { + data: new SlashCommandBuilder() + .setName('play') + .setDescription('Add a track or playlist to the queue by searching or url.') + .setDMPermission(false) + .addStringOption((option) => option.setName('query').setDescription('Search query or URL.').setRequired(true)), + execute: async ({ interaction }) => { + if (!interaction.member.voice.channel) { + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.warning} Oops!**\nYou need to be in a voice channel to use this command.` + ) + .setColor(embedOptions.colors.warning) + ] + }); + } + + const player = useMainPlayer(); + const query = interaction.options.getString('query'); + + const searchResult = await player.search(query, { + requestedBy: interaction.user + }); + + if (!searchResult || searchResult.tracks.length === 0) { + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.warning} No track found**\nNo results found for \`${query}\`.\n\nIf you specified a URL, please make sure it is valid and public.` + ) + .setColor(embedOptions.colors.warning) + ] + }); + } + + if ( + searchResult.tracks[0].raw.live && + searchResult.tracks[0].raw.duration === 0 && + searchResult.tracks[0].source === 'youtube' + ) { + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.warning} Unsupported audio source**\nYouTube live streams are currently not supported. This is due to issues with extracting audio from the livestream.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + ) + .setColor(embedOptions.colors.warning) + ] + }); + } + + let track; + + try { + ({ track } = await player.play(interaction.member.voice.channel, searchResult, { + requestedBy: interaction.user, + nodeOptions: { + leaveOnEmpty: playerOptions.leaveOnEmpty ?? true, + leaveOnEmptyCooldown: playerOptions.leaveOnEmptyCooldown ?? 60000, + leaveOnEnd: playerOptions.leaveOnEnd ?? true, + leaveOnEndCooldown: playerOptions.leaveOnEndCooldown ?? 60000, + leaveOnStop: playerOptions.leaveOnStop ?? true, + leaveOnStopCooldown: playerOptions.leaveOnStopCooldown ?? 60000, + maxSize: playerOptions.maxQueueSize ?? 1000, + maxHistorySize: playerOptions.maxHistorySize ?? 100, + volume: playerOptions.defaultVolume ?? 50 + } + })); + } catch (error) { + if (error.message.includes('Sign in to confirm your age')) { + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.warning} Cannot retrieve audio for track**\nThis audio source is age restricted and requires login to access. Because of this I cannot retrieve the audio for the track.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + ) + .setColor(embedOptions.colors.warning) + ] + }); + } + + if ( + (error.type === 'TypeError' && + (error.message.includes('Cannot read properties of null (reading \'createStream\')') || + error.message.includes('Failed to fetch resources for ytdl streaming'))) || + error.message.includes('Could not extract stream for this track') + ) { + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.error} Uh-oh... Failed to add track!**\nAfter finding a result, I was unable to retrieve audio for the track.\n\nYou can try to perform the command again.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + ) + .setColor(embedOptions.colors.error) + ] + }); + } + + if (error.message === 'Cancelled') { + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.error} Uh-oh... Failed to add track!**\nSomething unexpected happened and the operation was cancelled.\n\nYou can try to perform the command again.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + ) + .setColor(embedOptions.colors.error) + ] + }); + } + } + + let queue = useQueue(interaction.guild.id); + + if (!queue) { + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.error} Uh-oh... Failed to add track!**\nThere was an issue adding this track to the queue.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + ) + .setColor(embedOptions.colors.error) + ] + }); + } + + if (track.source === 'arbitrary') { + track.thumbnail = + 'https://raw.githubusercontent.com/mariusbegby/cadence-discord-bot/main/assets/logo-rounded-128px.png'; + } + + let durationFormat = track.raw.duration === 0 || track.duration === '0:00' ? '' : `\`${track.duration}\``; + + if (searchResult.playlist && searchResult.tracks.length > 1) { + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setAuthor({ + name: interaction.member.nickname || interaction.user.username, + iconURL: interaction.user.avatarURL() + }) + .setDescription( + `**${embedOptions.icons.success} Added playlist to queue**\n**${durationFormat} [${ + track.title + }](${track.url})**\n\nAnd **${ + searchResult.tracks.length - 1 + }** more tracks... **\`/queue\`** to view all.` + ) + .setThumbnail(track.thumbnail) + .setColor(embedOptions.colors.success) + ] + }); + } + + if (queue.currentTrack === track) { + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setAuthor({ + name: + interaction.member.nickname || interaction.member.nickname || interaction.user.username, + iconURL: interaction.user.avatarURL() + }) + .setDescription( + `**${embedOptions.icons.audioStartedPlaying} Started playing**\n**${durationFormat} [${track.title}](${track.url})**` + ) + .setThumbnail(track.thumbnail) + .setColor(embedOptions.colors.success) + ] + }); + } + + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setAuthor({ + name: interaction.member.nickname || interaction.user.username, + iconURL: interaction.user.avatarURL() + }) + .setDescription( + `${embedOptions.icons.success} **Added to queue**\n**${durationFormat} [${track.title}](${track.url})**` + ) + .setThumbnail(track.thumbnail) + .setColor(embedOptions.colors.success) + ] + }); + } +}; diff --git a/src/commands/queue.js b/src/commands/player/queue.js similarity index 62% rename from src/commands/queue.js rename to src/commands/player/queue.js index 2ac624d..c7875f1 100644 --- a/src/commands/queue.js +++ b/src/commands/player/queue.js @@ -1,33 +1,22 @@ -const path = require('path'); -const { SlashCommandBuilder } = require('@discordjs/builders'); +const { embedOptions, playerOptions } = require('../../config'); +const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); const { useQueue } = require('discord-player'); -const { EmbedBuilder } = require('discord.js'); -const { - embedColors, - embedIcons, - progressBarOptions -} = require(path.resolve('./config.json')); module.exports = { data: new SlashCommandBuilder() .setName('queue') .setDescription('Show the list of tracks added to the queue.') .setDMPermission(false) - .addNumberOption((option) => - option - .setName('page') - .setDescription('Page number of the queue') - .setMinValue(1) - ), - run: async ({ interaction }) => { + .addNumberOption((option) => option.setName('page').setDescription('Page number of the queue').setMinValue(1)), + execute: async ({ interaction }) => { if (!interaction.member.voice.channel) { return await interaction.editReply({ embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nYou need to be in a voice channel to use this command.` + `**${embedOptions.icons.warning} Oops!**\nYou need to be in a voice channel to use this command.` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } @@ -42,11 +31,11 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nPage \`${ + `**${embedOptions.icons.warning} Oops!**\nPage \`${ pageIndex + 1 }\` is not a valid page number.\n\nThe queue is currently empty, first add some tracks with **\`/play\`**!` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } @@ -59,10 +48,8 @@ module.exports = { name: interaction.guild.name, iconURL: interaction.guild.iconURL() }) - .setDescription( - `**${embedIcons.queue} Tracks in queue**\n${queueString}` - ) - .setColor(embedColors.colorInfo) + .setDescription(`**${embedOptions.icons.queue} Tracks in queue**\n${queueString}`) + .setColor(embedOptions.colors.info) .setFooter({ text: 'Page 1 of 1' }) @@ -77,11 +64,11 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nPage \`${ + `**${embedOptions.icons.warning} Oops!**\nPage \`${ pageIndex + 1 }\` is not a valid page number.\n\nThere are only a total of \`${totalPages}\` pages in the queue.` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } @@ -93,13 +80,9 @@ module.exports = { .slice(pageIndex * 10, pageIndex * 10 + 10) .map((track, index) => { let durationFormat = - track.raw.duration === 0 || track.duration === '0:00' - ? '' - : `\`${track.duration}\``; + track.raw.duration === 0 || track.duration === '0:00' ? '' : `\`${track.duration}\``; - return `**${ - pageIndex * 10 + index + 1 - }.** **${durationFormat} [${track.title}](${track.url})**`; + return `**${pageIndex * 10 + index + 1}.** **${durationFormat} [${track.title}](${track.url})**`; }) .join('\n'); } @@ -119,9 +102,7 @@ module.exports = { queue.repeatMode === 0 ? '' : `**${ - queue.repeatMode === 3 - ? embedIcons.autoplay - : embedIcons.loop + queue.repeatMode === 3 ? embedOptions.icons.autoplay : embedOptions.icons.loop } Looping**\nLoop mode is set to ${loopModeUserString}. You can change it with **\`/loop\`**.\n\n` }`; @@ -130,38 +111,30 @@ module.exports = { embeds: [ new EmbedBuilder() .setAuthor({ - name: `Channel: ${queue.channel.name} (${ - queue.channel.bitrate / 1000 - }kbps)`, + name: `Channel: ${queue.channel.name} (${queue.channel.bitrate / 1000}kbps)`, iconURL: interaction.guild.iconURL() }) .setDescription( - `${repeatModeString}` + - `**${embedIcons.queue} Tracks in queue**\n${queueString}` + `${repeatModeString}` + `**${embedOptions.icons.queue} Tracks in queue**\n${queueString}` ) .setFooter({ text: `Page ${pageIndex + 1} of ${totalPages}` }) - .setColor(embedColors.colorInfo) + .setColor(embedOptions.colors.info) ] }); } else { const timestamp = queue.node.getTimestamp(); - let bar = `**\`${ - timestamp.current.label - }\`** ${queue.node.createProgressBar({ + let bar = `**\`${timestamp.current.label}\`** ${queue.node.createProgressBar({ queue: false, - length: progressBarOptions.length ?? 12, - timecodes: progressBarOptions.timecodes ?? false, - indicator: progressBarOptions.indicator ?? '🔘', - leftChar: progressBarOptions.leftChar ?? '▬', - rightChar: progressBarOptions.rightChar ?? '▬' + length: playerOptions.progressBar.length ?? 12, + timecodes: playerOptions.progressBar.timecodes ?? false, + indicator: playerOptions.progressBar.indicator ?? '🔘', + leftChar: playerOptions.progressBar.leftChar ?? '▬', + rightChar: playerOptions.progressBar.rightChar ?? '▬' })} **\`${timestamp.total.label}\`**`; - if ( - currentTrack.raw.duration === 0 || - currentTrack.duration === '0:00' - ) { + if (currentTrack.raw.duration === 0 || currentTrack.duration === '0:00') { bar = '_No duration available._'; } @@ -169,26 +142,22 @@ module.exports = { embeds: [ new EmbedBuilder() .setAuthor({ - name: `Channel: ${queue.channel.name} (${ - queue.channel.bitrate / 1000 - }kbps)`, + name: `Channel: ${queue.channel.name} (${queue.channel.bitrate / 1000}kbps)`, iconURL: interaction.guild.iconURL() }) .setDescription( - `**${embedIcons.audioPlaying} Now playing**\n` + - (currentTrack - ? `**[${currentTrack.title}](${currentTrack.url})**` - : 'None') + + `**${embedOptions.icons.audioPlaying} Now playing**\n` + + (currentTrack ? `**[${currentTrack.title}](${currentTrack.url})**` : 'None') + `\nRequested by: <@${currentTrack.requestedBy.id}>` + `\n ${bar}\n\n` + `${repeatModeString}` + - `**${embedIcons.queue} Tracks in queue**\n${queueString}` + `**${embedOptions.icons.queue} Tracks in queue**\n${queueString}` ) .setThumbnail(queue.currentTrack.thumbnail) .setFooter({ text: `Page ${pageIndex + 1} of ${totalPages}` }) - .setColor(embedColors.colorInfo) + .setColor(embedOptions.colors.info) ] }); } diff --git a/src/commands/remove.js b/src/commands/player/remove.js similarity index 59% rename from src/commands/remove.js rename to src/commands/player/remove.js index 8419685..6ea818f 100644 --- a/src/commands/remove.js +++ b/src/commands/player/remove.js @@ -1,8 +1,6 @@ -const path = require('path'); -const { SlashCommandBuilder } = require('@discordjs/builders'); +const { embedOptions } = require('../../config'); +const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); const { useQueue } = require('discord-player'); -const { EmbedBuilder } = require('discord.js'); -const { embedColors, embedIcons } = require(path.resolve('./config.json')); module.exports = { data: new SlashCommandBuilder() @@ -16,15 +14,15 @@ module.exports = { .setMinValue(1) .setRequired(true) ), - run: async ({ interaction }) => { + execute: async ({ interaction }) => { if (!interaction.member.voice.channel) { return await interaction.editReply({ embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nYou need to be in a voice channel to use this command.` + `**${embedOptions.icons.warning} Oops!**\nYou need to be in a voice channel to use this command.` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } @@ -36,9 +34,9 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nThere are no tracks in the queue and nothing currently playing. First add some tracks with **\`/play\`**!` + `**${embedOptions.icons.warning} Oops!**\nThere are no tracks in the queue and nothing currently playing. First add some tracks with **\`/play\`**!` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } @@ -50,9 +48,9 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nTrack \`${removeTrackNumber}\` is not a valid track number. There are a total of\`${queue.tracks.data.length}\` tracks in the queue.\n\nView tracks added to the queue with **\`/queue\`**.` + `**${embedOptions.icons.warning} Oops!**\nTrack \`${removeTrackNumber}\` is not a valid track number. There are a total of\`${queue.tracks.data.length}\` tracks in the queue.\n\nView tracks added to the queue with **\`/queue\`**.` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } @@ -60,24 +58,20 @@ module.exports = { // Remove specified track number from queue const removedTrack = queue.node.remove(removeTrackNumber - 1); let durationFormat = - removedTrack.raw.duration === 0 || removedTrack.duration === '0:00' - ? '' - : `\`${removedTrack.duration}\``; + removedTrack.raw.duration === 0 || removedTrack.duration === '0:00' ? '' : `\`${removedTrack.duration}\``; return await interaction.editReply({ embeds: [ new EmbedBuilder() .setAuthor({ - name: - interaction.member.nickname || - interaction.user.username, + name: interaction.member.nickname || interaction.user.username, iconURL: interaction.user.avatarURL() }) .setDescription( - `**${embedIcons.success} Removed track**\n**${durationFormat} [${removedTrack.title}](${removedTrack.url})**` + `**${embedOptions.icons.success} Removed track**\n**${durationFormat} [${removedTrack.title}](${removedTrack.url})**` ) .setThumbnail(removedTrack.thumbnail) - .setColor(embedColors.colorSuccess) + .setColor(embedOptions.colors.success) ] }); } diff --git a/src/commands/seek.js b/src/commands/player/seek.js similarity index 60% rename from src/commands/seek.js rename to src/commands/player/seek.js index 3821ac2..13a2119 100644 --- a/src/commands/seek.js +++ b/src/commands/player/seek.js @@ -1,8 +1,6 @@ -const path = require('path'); -const { SlashCommandBuilder } = require('@discordjs/builders'); +const { embedOptions } = require('../../config'); +const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); const { useQueue } = require('discord-player'); -const { EmbedBuilder } = require('discord.js'); -const { embedColors, embedIcons } = require(path.resolve('./config.json')); module.exports = { data: new SlashCommandBuilder() @@ -12,20 +10,18 @@ module.exports = { .addStringOption((option) => option .setName('duration') - .setDescription( - 'Duration in format 00:00:00 (HH:mm:ss) to seek to.' - ) + .setDescription('Duration in format 00:00:00 (HH:mm:ss) to seek to.') .setRequired(true) ), - run: async ({ interaction }) => { + execute: async ({ interaction }) => { if (!interaction.member.voice.channel) { return await interaction.editReply({ embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nYou need to be in a voice channel to use this command.` + `**${embedOptions.icons.warning} Oops!**\nYou need to be in a voice channel to use this command.` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } @@ -37,9 +33,9 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nThere are no tracks in the queue and nothing currently playing. First add some tracks with **\`/play\`**!` + `**${embedOptions.icons.warning} Oops!**\nThere are no tracks in the queue and nothing currently playing. First add some tracks with **\`/play\`**!` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } @@ -49,9 +45,9 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nThere is nothing currently playing. First add some tracks with **\`/play\`**!` + `**${embedOptions.icons.warning} Oops!**\nThere is nothing currently playing. First add some tracks with **\`/play\`**!` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } @@ -60,14 +56,14 @@ module.exports = { let durationArray = durationInput.split(':'); switch (durationArray.length) { - case 1: - durationArray.unshift('00', '00'); - break; - case 2: - durationArray.unshift('00'); - break; - default: - break; + case 1: + durationArray.unshift('00', '00'); + break; + case 2: + durationArray.unshift('00'); + break; + default: + break; } if (durationArray.length === 0 || durationArray.length > 3) { @@ -75,12 +71,12 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nYou entered an invalid duration format, \`${durationString}\`.\n\nPlease use the format \`HH:mm:ss\`, \`mm:ss\` or \`ss\`, where \`HH\` is hours, \`mm\` is minutes and \`ss\` is seconds.\n\n**Examples:**\n` + + `**${embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, \`${durationString}\`.\n\nPlease use the format \`HH:mm:ss\`, \`mm:ss\` or \`ss\`, where \`HH\` is hours, \`mm\` is minutes and \`ss\` is seconds.\n\n**Examples:**\n` + '- `/seek` **`1:24:12`** - Seek to 1 hour, 24 minutes and 12 seconds.\n' + '- `/seek` **`3:27`** - Seek to 3 minutes and 27 seconds.\n' + '- `/seek` **`42`** - Seek to 42 seconds.' ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } @@ -100,12 +96,12 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nYou entered an invalid duration format, \`${durationString}\`.\n\nPlease use the format \`HH:mm:ss\`, \`mm:ss\` or \`ss\`, where \`HH\` is hours, \`mm\` is minutes and \`ss\` is seconds.\n\n**Examples:**\n` + + `**${embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, \`${durationString}\`.\n\nPlease use the format \`HH:mm:ss\`, \`mm:ss\` or \`ss\`, where \`HH\` is hours, \`mm\` is minutes and \`ss\` is seconds.\n\n**Examples:**\n` + '- `/seek` **`1:24:12`** - Seek to 1 hour, 24 minutes and 12 seconds.\n' + '- `/seek` **`3:27`** - Seek to 3 minutes and 27 seconds.\n' + '- `/seek` **`42`** - Seek to 42 seconds.' ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } @@ -120,30 +116,27 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nYou entered an invalid duration format, \`${durationString}\`.\n\nPlease use the format \`HH:mm:ss\`, \`mm:ss\` or \`ss\`, where \`HH\` is hours, \`mm\` is minutes and \`ss\` is seconds.\n\n**Examples:**\n` + + `**${embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, \`${durationString}\`.\n\nPlease use the format \`HH:mm:ss\`, \`mm:ss\` or \`ss\`, where \`HH\` is hours, \`mm\` is minutes and \`ss\` is seconds.\n\n**Examples:**\n` + '- `/seek` **`1:24:12`** - Seek to 1 hour, 24 minutes and 12 seconds.\n' + '- `/seek` **`3:27`** - Seek to 3 minutes and 27 seconds.\n' + '- `/seek` **`42`** - Seek to 42 seconds.' ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } const currentTrackMaxDurationInMs = queue.currentTrack.durationMS; - const durationInMilliseconds = - durationArray[0] * 3600000 + - durationArray[1] * 60000 + - durationArray[2] * 1000; + const durationInMilliseconds = durationArray[0] * 3600000 + durationArray[1] * 60000 + durationArray[2] * 1000; if (durationInMilliseconds > currentTrackMaxDurationInMs - 1000) { return await interaction.editReply({ embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nYou entered **\`${durationString}\`**, which is a duration that is longer than the duration for the current track.\n\nPlease try a duration that is less than the duration of the track (**\`${queue.currentTrack.duration}\`**).` + `**${embedOptions.icons.warning} Oops!**\nYou entered **\`${durationString}\`**, which is a duration that is longer than the duration for the current track.\n\nPlease try a duration that is less than the duration of the track (**\`${queue.currentTrack.duration}\`**).` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } @@ -153,16 +146,14 @@ module.exports = { embeds: [ new EmbedBuilder() .setAuthor({ - name: - interaction.member.nickname || - interaction.user.username, + name: interaction.member.nickname || interaction.user.username, iconURL: interaction.user.avatarURL() }) .setDescription( - `**${embedIcons.success} Seeking to duration**\nSeeking to **\`${durationString}\`** in current track.` + `**${embedOptions.icons.success} Seeking to duration**\nSeeking to **\`${durationString}\`** in current track.` ) .setThumbnail(queue.currentTrack.thumbnail) - .setColor(embedColors.colorSuccess) + .setColor(embedOptions.colors.success) ] }); } diff --git a/src/commands/skip.js b/src/commands/player/skip.js similarity index 60% rename from src/commands/skip.js rename to src/commands/player/skip.js index 96f418c..6ba871d 100644 --- a/src/commands/skip.js +++ b/src/commands/player/skip.js @@ -1,8 +1,6 @@ -const path = require('path'); -const { SlashCommandBuilder } = require('@discordjs/builders'); +const { embedOptions } = require('../../config'); +const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); const { useQueue } = require('discord-player'); -const { EmbedBuilder } = require('discord.js'); -const { embedColors, embedIcons } = require(path.resolve('./config.json')); module.exports = { data: new SlashCommandBuilder() @@ -10,20 +8,17 @@ module.exports = { .setDescription('Skip current or specified track.') .setDMPermission(false) .addNumberOption((option) => - option - .setName('tracknumber') - .setDescription('Track number to skip to in the queue.') - .setMinValue(1) + option.setName('tracknumber').setDescription('Track number to skip to in the queue.').setMinValue(1) ), - run: async ({ interaction }) => { + execute: async ({ interaction }) => { if (!interaction.member.voice.channel) { return await interaction.editReply({ embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nYou need to be in a voice channel to use this command.` + `**${embedOptions.icons.warning} Oops!**\nYou need to be in a voice channel to use this command.` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } @@ -35,9 +30,9 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nThere are no tracks in the queue and nothing currently playing. First add some tracks with **\`/play\`**!` + `**${embedOptions.icons.warning} Oops!**\nThere are no tracks in the queue and nothing currently playing. First add some tracks with **\`/play\`**!` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } @@ -50,16 +45,15 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nThere are only \`${queue.tracks.data.length}\` tracks in the queue. You cannot skip to track \`${skipToTrack}\`.\n\nView tracks added to the queue with **\`/queue\`**.` + `**${embedOptions.icons.warning} Oops!**\nThere are only \`${queue.tracks.data.length}\` tracks in the queue. You cannot skip to track \`${skipToTrack}\`.\n\nView tracks added to the queue with **\`/queue\`**.` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } else { const skippedTrack = queue.currentTrack; let durationFormat = - skippedTrack.raw.duration === 0 || - skippedTrack.duration === '0:00' + skippedTrack.raw.duration === 0 || skippedTrack.duration === '0:00' ? '' : `\`${skippedTrack.duration}\``; queue.node.skipTo(skipToTrack - 1); @@ -68,16 +62,14 @@ module.exports = { embeds: [ new EmbedBuilder() .setAuthor({ - name: - interaction.member.nickname || - interaction.user.username, + name: interaction.member.nickname || interaction.user.username, iconURL: interaction.user.avatarURL() }) .setDescription( - `**${embedIcons.skipped} Skipped track**\n**${durationFormat} [${skippedTrack.title}](${skippedTrack.url})**` + `**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${skippedTrack.title}](${skippedTrack.url})**` ) .setThumbnail(skippedTrack.thumbnail) - .setColor(embedColors.colorSuccess) + .setColor(embedOptions.colors.success) ] }); } @@ -87,17 +79,16 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nThere is nothing currently playing. First add some tracks with **\`/play\`**!` + `**${embedOptions.icons.warning} Oops!**\nThere is nothing currently playing. First add some tracks with **\`/play\`**!` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } const skippedTrack = queue.currentTrack; let durationFormat = - skippedTrack.raw.duration === 0 || - skippedTrack.duration === '0:00' + skippedTrack.raw.duration === 0 || skippedTrack.duration === '0:00' ? '' : `\`${skippedTrack.duration}\``; queue.node.skip(); @@ -115,25 +106,23 @@ module.exports = { embeds: [ new EmbedBuilder() .setAuthor({ - name: - interaction.member.nickname || - interaction.user.username, + name: interaction.member.nickname || interaction.user.username, iconURL: interaction.user.avatarURL() }) .setDescription( - `**${embedIcons.skipped} Skipped track**\n**${durationFormat} [${skippedTrack.title}](${skippedTrack.url})**` + + `**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${skippedTrack.title}](${skippedTrack.url})**` + `${ queue.repeatMode === 0 ? '' : `\n\n**${ queue.repeatMode === 3 - ? embedIcons.autoplaying - : embedIcons.looping + ? embedOptions.icons.autoplaying + : embedOptions.icons.looping } Looping**\nLoop mode is set to ${loopModeUserString}. You can change it with **\`/loop\`**.` }` ) .setThumbnail(skippedTrack.thumbnail) - .setColor(embedColors.colorSuccess) + .setColor(embedOptions.colors.success) ] }); } diff --git a/src/commands/volume.js b/src/commands/player/volume.js similarity index 59% rename from src/commands/volume.js rename to src/commands/player/volume.js index 2d45fc5..28ba226 100644 --- a/src/commands/volume.js +++ b/src/commands/player/volume.js @@ -1,8 +1,6 @@ -const path = require('path'); -const { SlashCommandBuilder } = require('@discordjs/builders'); +const { embedOptions } = require('../../config'); +const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); const { useQueue } = require('discord-player'); -const { EmbedBuilder } = require('discord.js'); -const { embedColors, embedIcons } = require(path.resolve('./config.json')); module.exports = { data: new SlashCommandBuilder() @@ -16,15 +14,15 @@ module.exports = { .setMinValue(0) .setMaxValue(100) ), - run: async ({ interaction }) => { + execute: async ({ interaction }) => { if (!interaction.member.voice.channel) { return await interaction.editReply({ embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nYou need to be in a voice channel to use this command.` + `**${embedOptions.icons.warning} Oops!**\nYou need to be in a voice channel to use this command.` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } @@ -36,9 +34,9 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nThere are no tracks in the queue and nothing currently playing. First add some tracks with **\`/play\`**!` + `**${embedOptions.icons.warning} Oops!**\nThere are no tracks in the queue and nothing currently playing. First add some tracks with **\`/play\`**!` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } @@ -53,12 +51,10 @@ module.exports = { new EmbedBuilder() .setDescription( `**${ - currentVolume === 0 - ? embedIcons.volumeIsMuted - : embedIcons.volume + currentVolume === 0 ? embedOptions.icons.volumeIsMuted : embedOptions.icons.volume } Playback volume**\nThe playback volume is currently set to \`${currentVolume}%\`.` ) - .setColor(embedColors.colorInfo) + .setColor(embedOptions.colors.info) ] }); } else if (volume > 100 || volume < 0) { @@ -66,9 +62,9 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nYou cannot set the volume to \`${volume}\`, please pick a value betwen \`1\`% and \`100\`%.` + `**${embedOptions.icons.warning} Oops!**\nYou cannot set the volume to \`${volume}\`, please pick a value betwen \`1\`% and \`100\`%.` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } else { @@ -79,15 +75,13 @@ module.exports = { embeds: [ new EmbedBuilder() .setAuthor({ - name: - interaction.member.nickname || - interaction.user.username, + name: interaction.member.nickname || interaction.user.username, iconURL: interaction.user.avatarURL() }) .setDescription( - `**${embedIcons.volumeMuted} Audio muted**\nPlayback audio has been muted, because volume was set to \`${volume}%\`.` + `**${embedOptions.icons.volumeMuted} Audio muted**\nPlayback audio has been muted, because volume was set to \`${volume}%\`.` ) - .setColor(embedColors.colorSuccess) + .setColor(embedOptions.colors.success) ] }); } @@ -96,15 +90,13 @@ module.exports = { embeds: [ new EmbedBuilder() .setAuthor({ - name: - interaction.member.nickname || - interaction.user.username, + name: interaction.member.nickname || interaction.user.username, iconURL: interaction.user.avatarURL() }) .setDescription( - `**${embedIcons.volumeChanged} Volume changed**\nPlayback volume has been changed to \`${volume}%\`.` + `**${embedOptions.icons.volumeChanged} Volume changed**\nPlayback volume has been changed to \`${volume}%\`.` ) - .setColor(embedColors.colorSuccess) + .setColor(embedOptions.colors.success) ] }); } diff --git a/src/commands/system/guilds.js b/src/commands/system/guilds.js new file mode 100644 index 0000000..7bac512 --- /dev/null +++ b/src/commands/system/guilds.js @@ -0,0 +1,51 @@ +const { embedOptions, systemOptions } = require('../../config'); +const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); + +module.exports = { + isSystemCommand: true, + data: new SlashCommandBuilder() + .setName('guilds') + .setDescription('Show list of guilds where bot is added.') + .setDMPermission(false), + execute: async ({ interaction, client }) => { + if (!systemOptions.systemGuildIds.includes(interaction.guildId)) { + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.warning} Oops!**\nNo permission to execute this command.\n\nThe command \`${interaction.commandName}\` cannot be executed in this server.` + ) + .setColor(embedOptions.colors.warning) + ] + }); + } + + let guildsList = client.guilds.cache + .map((guild) => { + return { + name: guild.name, + memberCount: guild.memberCount + }; + }) + .sort((a, b) => b.memberCount - a.memberCount) + .slice(0, 50) + .map((guild, index) => `${index + 1}. \`${guild.name} (#${guild.memberCount})\``) + .join('\n'); + + const totalMemberCount = client.guilds.cache.reduce((a, b) => a + b.memberCount, 0); + + let embedDescription = + `**${embedOptions.icons.bot} ${ + client.guilds.cache.size < 50 ? `Top ${client.guilds.cache.size} guilds` : 'Top 50 guilds' + } by member count (${client.guilds.cache.size} total)**\n${guildsList}` + + `\n\n**Total members:** \`${totalMemberCount}\``; + + if (embedDescription.length >= 4000) { + embedDescription = `${embedDescription.slice(0, 3996)}...`; + } + + return await interaction.editReply({ + embeds: [new EmbedBuilder().setDescription(embedDescription).setColor(embedOptions.colors.info)] + }); + } +}; diff --git a/src/system-commands/status.js b/src/commands/system/status.js similarity index 62% rename from src/system-commands/status.js rename to src/commands/system/status.js index f472ff2..09dec62 100644 --- a/src/system-commands/status.js +++ b/src/commands/system/status.js @@ -1,29 +1,21 @@ -const path = require('path'); -const { SlashCommandBuilder } = require('@discordjs/builders'); -const { EmbedBuilder } = require('discord.js'); +const { embedOptions, systemOptions } = require('../../config'); +const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); const { useQueue } = require('discord-player'); -const { - embedColors, - embedIcons, - systemServerGuildIds -} = require(path.resolve('./config.json')); const osu = require('node-os-utils'); -const packageJson = require(path.resolve('./package.json')); +const { version, dependencies } = require('../../../package.json'); module.exports = { - data: new SlashCommandBuilder() - .setName('status') - .setDescription('Show bot status.') - .setDMPermission(false), - run: async ({ interaction, client }) => { - if (!systemServerGuildIds.includes(interaction.guildId)) { + isSystemCommand: true, + data: new SlashCommandBuilder().setName('status').setDescription('Show bot status.').setDMPermission(false), + execute: async ({ interaction, client }) => { + if (!systemOptions.systemGuildIds.includes(interaction.guildId)) { return await interaction.editReply({ embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.warning} Oops!**\nNo permission to execute this command.\n\nThe command \`${interaction.commandName}\` cannot be executed in this server.` + `**${embedOptions.icons.warning} Oops!**\nNo permission to execute this command.\n\nThe command \`${interaction.commandName}\` cannot be executed in this server.` ) - .setColor(embedColors.colorWarning) + .setColor(embedOptions.colors.warning) ] }); } @@ -33,20 +25,14 @@ module.exports = { let uptimeDate = new Date(0); uptimeDate.setSeconds(uptimeInSeconds.toFixed(0)); const uptimeString = uptimeDate.toISOString().substring(11, 19); - const nodeProcessMemUsageInMb = ( - process.memoryUsage().heapUsed / - 1024 / - 1024 - ).toFixed(2); - const usedMemoryInMB = Math.ceil( - (await osu.mem.info()).usedMemMb - ).toLocaleString('en-US'); + const nodeProcessMemUsageInMb = (process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2); + const usedMemoryInMB = Math.ceil((await osu.mem.info()).usedMemMb).toLocaleString('en-US'); const cpuUsage = await osu.cpu.usage(); const cpuCores = await osu.cpu.count(); const platform = await osu.os.platform(); - const releaseVersion = packageJson.version; - const discordJsVersion = packageJson.dependencies['discord.js']; - const discordPlayerVersion = packageJson.dependencies['discord-player']; + const releaseVersion = version; + const discordJsVersion = dependencies['discord.js']; + const discordPlayerVersion = dependencies['discord-player']; const discordApiLatency = client.ws.ping; let activeVoiceConnections = 0; client.guilds.cache.forEach((guild) => { @@ -61,7 +47,7 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedIcons.bot} System and bot status**\n` + + `**${embedOptions.icons.bot} System and bot status**\n` + `Uptime: \`${uptimeString}\`\n` + `Platform: \`${platform}\`\n` + `CPU cores: \`${cpuCores}\`\n` + @@ -77,7 +63,7 @@ module.exports = { `Active voice connections: \`${activeVoiceConnections}\`\n` + `Joined guilds: \`${client.guilds.cache.size}\`` ) - .setColor(embedColors.colorInfo) + .setColor(embedOptions.colors.info) ] }); } diff --git a/src/config_example.js b/src/config_example.js new file mode 100644 index 0000000..bf6f918 --- /dev/null +++ b/src/config_example.js @@ -0,0 +1,152 @@ +// Description: Config file for Cadence Discord bot. + +// General options for information about the bot. +module.exports.botOptions = { + name: 'Cadence', + websiteUrl: 'Unknown', + botInviteUrl: 'Unknown', + serverInviteUrl: 'Unknown' +}; + +// Logging options for the bot, can set logging level to file and console separately. +module.exports.loggerOptions = { + minimumLogLevel: 'debug', + minimumLogLevelConsole: 'info' +}; + +// systemGuildIds: Array of guild ids where system commands should be available. +// systemMessageChannelId: Channel id where system messages should be sent, such as error events. +// systemUserId: User id of the system administrator, used for pining on certain system messages. +module.exports.systemOptions = { + systemGuildIds: ['Guild id where system commands can be used'], + systemMessageChannelId: 'Channel id where system messages will be sent', + systemUserId: 'User id of the system administrator which will receive pings on certain system messages' +}; + +// Options for embed messages, like colors and custom emojis. +module.exports.embedOptions = { + colors: { + success: '#23A55A', + warning: '#F0B232', + error: '#F23F43', + info: '#5865F2', + note: '#80848E' + }, + icons: { + logo: '🤖', + beta: '`beta`', + new: '`new`', + rule: '📒', + support: '❓', + bot: '🤖', + audioPlaying: '🎶', + audioStartedPlaying: '🎶', + success: '✅', + error: '⚠️', + warning: '⚠️', + disable: '🚫', + enable: '✅', + disabled: '✅', + enabled: '✅', + nextTrack: '⏭️', + previousTrack: '⏮️', + pauseResumeTrack: '⏯️', + shuffleQueue: '🔀', + loop: '🔁', + loopAction: '🔁', + autoplay: '♾️', + autoplayAction: '♾️', + looping: '🔁', + autoplaying: '♾️', + skipped: '⏭️', + back: '⏮️', + pauseResumed: '⏯️', + shuffled: '🔀', + volume: '🔊', + volumeIsMuted: '🔇', + volumeChanged: '🔊', + volumeMuted: '🔇', + queue: '🎶', + sourceArbitrary: '🎵', + sourceAppleMusic: '🎵', + sourceYouTube: '🎵', + sourceSoundCloud: '🎵', + sourceSpotify: '🎵' + } +}; + +// Options for the discord-player player. +module.exports.playerOptions = { + leaveOnEmpty: true, + leaveOnEmptyCooldown: 300000, + leaveOnEnd: true, + leaveonEndCooldown: 300000, + leaveOnStop: true, + leaveOnStopCooldown: 300000, + defaultVolume: 50, + maxQueueSize: 1000, + maxHistorySize: 100, + progressBar: { + length: 14, + timecodes: false, + separator: '┃', + indicator: '🔘', + leftChar: '▬', + rightChar: '▬' + } +}; + +// Options to be used by the ffmpeg, and available ffmpeg filters shown in filter commands. +module.exports.ffmpegFilterOptions = { + threadAmount: '2', + filterList: [ + { + label: 'Bass boost', + value: 'bassboost_low', + description: 'Boost the bass of the audio.', + emoji: '🔉' + }, + { + label: 'Bass boost high', + value: 'bassboost', + description: 'Boost the bass of the audio a lot.', + emoji: '🔊' + }, + { + label: 'Night core', + value: 'nightcore', + description: 'Speed up the audio (higher pitch).', + emoji: '🐱' + }, + { + label: 'Lo-fi', + value: 'lofi', + description: 'Low fidelity effect (lower quality).', + emoji: '📻' + }, + { + label: 'Vaporwave', + value: 'vaporwave', + description: 'Slow down the audio (lower pitch).', + emoji: '🌸' + }, + { + label: 'Ear rape', + value: 'earrape', + description: 'Extremely loud and distorted audio.', + emoji: '👂' + }, + { + label: '8D', + value: '8D', + description: 'Simulate 8D audio effect (surround).', + emoji: '🎧' + }, + { + label: 'Treble', + value: 'treble', + description: 'Increase the high frequencies.', + emoji: '🎼' + } + ] +}; diff --git a/src/deploy-commands.js b/src/deploy-commands.js deleted file mode 100644 index 0d1c205..0000000 --- a/src/deploy-commands.js +++ /dev/null @@ -1,44 +0,0 @@ -const path = require('path'); -const fs = require('node:fs'); -const logger = require(path.resolve('./src/services/logger.js')); -const { REST, Routes } = require('discord.js'); -require('dotenv').config(); - -const commands = []; -const commandFiles = fs - .readdirSync(path.resolve('./src/commands')) - .filter((file) => file.endsWith('.js')); - -for (const file of commandFiles) { - const command = require(path.resolve(`./src/commands/${file}`)); - commands.push(command.data.toJSON()); -} - -const rest = new REST({ version: '10' }).setToken( - process.env.DISCORD_BOT_TOKEN -); - -(async () => { - try { - logger.info('DEPLOYING BOT SLASH COMMANDS'); - logger.info( - commands.map((commands) => { - return commands.name; - }), - 'Bot commands found:' - ); - - logger.info('Started refreshing application (/) bot commands.'); - - await rest.put( - Routes.applicationCommands(process.env.DISCORD_CLIENT_ID), - { - body: commands - } - ); - - logger.info('Successfully refreshed application (/) bot commands.'); - } catch (error) { - logger.error(error, 'Failed to refresh application (/) bot commands.'); - } -})(); diff --git a/src/deploy-system-commands.js b/src/deploy-system-commands.js deleted file mode 100644 index f352aca..0000000 --- a/src/deploy-system-commands.js +++ /dev/null @@ -1,53 +0,0 @@ -const path = require('path'); -const fs = require('node:fs'); -const logger = require(path.resolve('./src/services/logger.js')); -const { REST, Routes } = require('discord.js'); -const { systemServerGuildIds } = require(path.resolve('./config.json')); -require('dotenv').config(); - -const systemCommands = []; -const systemCommandFiles = fs - .readdirSync(path.resolve('./src/system-commands')) - .filter((file) => file.endsWith('.js')); - -for (const file of systemCommandFiles) { - const systemCommand = require(path.resolve(`./src/system-commands/${file}`)); - systemCommands.push(systemCommand.data.toJSON()); -} - -const rest = new REST({ version: '10' }).setToken( - process.env.DISCORD_BOT_TOKEN -); - -(async () => { - try { - logger.info('DEPLOYING SYSTEM SLASH COMMANDS'); - logger.info( - systemCommands.map((systemCommand) => { - return systemCommand.name; - }), - 'System commands found:' - ); - - logger.info('Started refreshing application (/) system commands.'); - - for (const systemServerGuildId of systemServerGuildIds) { - await rest.put( - Routes.applicationGuildCommands( - process.env.DISCORD_CLIENT_ID, - systemServerGuildId - ), - { - body: systemCommands - } - ); - } - - logger.info('Successfully refreshed application (/) system commands.'); - } catch (error) { - logger.error( - error, - 'Failed to refresh application (/) system commands.' - ); - } -})(); diff --git a/src/events/client/debug.js b/src/events/client/debug.js new file mode 100644 index 0000000..0416747 --- /dev/null +++ b/src/events/client/debug.js @@ -0,0 +1,11 @@ +const logger = require('../../services/logger'); +const { Events } = require('discord.js'); + +module.exports = { + name: Events.Debug, + isDebug: true, + once: false, + execute: async (message) => { + logger.debug(message); + } +}; diff --git a/src/events/client/disconnect.js b/src/events/client/disconnect.js new file mode 100644 index 0000000..bad4645 --- /dev/null +++ b/src/events/client/disconnect.js @@ -0,0 +1,26 @@ +const logger = require('../../services/logger'); +const { embedOptions, systemOptions } = require('../../config'); +const { EmbedBuilder } = require('discord.js'); + +module.exports = { + name: 'disconnect', + isDebug: false, + once: false, + execute: async (client) => { + logger.warn(`${client.user.tag} lost connection to Discord APIs. Disconnected.`); + + // send message to system message channel for event + if (systemOptions.systemMessageChannelId && systemOptions.systemUserId) { + await client.channels.cache.get(systemOptions.systemMessageChannelId).send({ + embeds: [ + new EmbedBuilder() + .setDescription( + `${embedOptions.icons.warning} **${client.user.tag}** is **\`disconnected\`**!` + + `\n<@${systemOptions.systemUserId}>` + ) + .setColor(embedOptions.colors.warning) + ] + }); + } + } +}; diff --git a/src/events/client/error.js b/src/events/client/error.js new file mode 100644 index 0000000..f182933 --- /dev/null +++ b/src/events/client/error.js @@ -0,0 +1,11 @@ +const logger = require('../../services/logger'); +const { Events } = require('discord.js'); + +module.exports = { + name: Events.Error, + isDebug: false, + once: false, + execute: async (error) => { + logger.error(error); + } +}; diff --git a/src/events/client/guildCreate.js b/src/events/client/guildCreate.js new file mode 100644 index 0000000..819882d --- /dev/null +++ b/src/events/client/guildCreate.js @@ -0,0 +1,11 @@ +const logger = require('../../services/logger'); +const { Events } = require('discord.js'); + +module.exports = { + name: Events.GuildCreate, + isDebug: false, + once: false, + execute: async (guild) => { + logger.info(`Added to guild '${guild.name}' with ${guild.memberCount} members.`); + } +}; diff --git a/src/events/client/guildDelete.js b/src/events/client/guildDelete.js new file mode 100644 index 0000000..4656580 --- /dev/null +++ b/src/events/client/guildDelete.js @@ -0,0 +1,11 @@ +const logger = require('../../services/logger'); +const { Events } = require('discord.js'); + +module.exports = { + name: Events.GuildDelete, + isDebug: false, + once: false, + execute: async (guild) => { + logger.info(`Removed from guild '${guild.name}' with ${guild.memberCount} members.`); + } +}; diff --git a/src/events/client/ready.js b/src/events/client/ready.js new file mode 100644 index 0000000..2813bcf --- /dev/null +++ b/src/events/client/ready.js @@ -0,0 +1,36 @@ +const logger = require('../../services/logger'); +const { embedOptions, systemOptions } = require('../../config'); +const { Events, ActivityType, PresenceUpdateStatus, EmbedBuilder } = require('discord.js'); +const { postBotStats } = require('../../utils/postBotStats.js'); + +module.exports = { + name: Events.ClientReady, + isDebug: false, + once: true, + execute: async (client) => { + logger.info(`Client logged in successfully as ${client.user.tag}!`); + await client.user.setPresence({ + status: PresenceUpdateStatus.Online, + activities: [ + { + name: '/help', + type: ActivityType.Watching + } + ] + }); + + // Post bot stats to bot lists in production + process.env.NODE_ENV === 'production' ? postBotStats(client) : null; + + // send message to system message channel for event + if (systemOptions.systemMessageChannelId) { + await client.channels.cache.get(systemOptions.systemMessageChannelId).send({ + embeds: [ + new EmbedBuilder() + .setDescription(`${embedOptions.icons.success} **${client.user.tag}** is now **\`online\`**!`) + .setColor(embedOptions.colors.success) + ] + }); + } + } +}; diff --git a/src/events/client/reconnecting.js b/src/events/client/reconnecting.js new file mode 100644 index 0000000..e2f3184 --- /dev/null +++ b/src/events/client/reconnecting.js @@ -0,0 +1,26 @@ +const logger = require('../../services/logger'); +const { embedOptions, systemOptions } = require('../../config'); +const { EmbedBuilder } = require('discord.js'); + +module.exports = { + name: 'reconnecting', + isDebug: false, + once: false, + execute: async (client) => { + logger.warn(`${client.user.tag} is reconnecting to Discord APIs.`); + + // send message to system message channel for event + if (systemOptions.systemMessageChannelId && systemOptions.systemUserId) { + await client.channels.cache.get(systemOptions.systemMessageChannelId).send({ + embeds: [ + new EmbedBuilder() + .setDescription( + `${embedOptions.icons.warning} **${client.user.tag}** is **\`reconnecting\`**!` + + `\n<@${systemOptions.systemUserId}>` + ) + .setColor(embedOptions.colors.warning) + ] + }); + } + } +}; diff --git a/src/events/client/warn.js b/src/events/client/warn.js new file mode 100644 index 0000000..33e63a0 --- /dev/null +++ b/src/events/client/warn.js @@ -0,0 +1,11 @@ +const logger = require('../../services/logger'); +const { Events } = require('discord.js'); + +module.exports = { + name: Events.Warn, + isDebug: false, + once: false, + execute: async (warning) => { + logger.warn(warning); + } +}; diff --git a/src/events/interactions/interactionCreate.js b/src/events/interactions/interactionCreate.js new file mode 100644 index 0000000..bfe4da7 --- /dev/null +++ b/src/events/interactions/interactionCreate.js @@ -0,0 +1,77 @@ +const logger = require('../../services/logger'); +const { embedOptions, botOptions } = require('../../config'); +const { Events, EmbedBuilder } = require('discord.js'); + +module.exports = { + name: Events.InteractionCreate, + isDebug: false, + execute: async (interaction, { client }) => { + if (!interaction.isCommand()) { + return; + } + + const command = client.commands.get(interaction.commandName); + if (!command) { + logger.warn(`Interaction created but command '${interaction.commandName}' was not found.`); + return; + } + + try { + const inputTime = new Date(); + + await interaction.deferReply(); + await command.execute({ interaction, client }); + + const outputTime = new Date(); + const executionTime = outputTime - inputTime; + + if (executionTime > 20000) { + // don't send warning message for commands with collector timeouts, as collector timeout happens after 60 seconds + if ( + (interaction.commandName === 'filters' || interaction.commandName === 'nowplaying') && + executionTime > 55000 + ) { + logger.info( + `(${interaction.guild.memberCount}) ${interaction.guild.name}> Command '${interaction}' executed in ${executionTime} ms.` + ); + return; + } + + logger.warn( + `(${interaction.guild.memberCount}) ${interaction.guild.name}> Command '${interaction}' took ${executionTime} ms to execute.` + ); + + return await interaction.followUp({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.warning} Warning**\nThis command took ${ + executionTime / 1000 + } seconds to execute.\n\n_If you experienced problems with the command, please try again._` + ) + .setColor(embedOptions.colors.warning) + ] + }); + } else { + logger.info( + `(${interaction.guild.memberCount}) ${interaction.guild.name}> Command '${interaction}' executed in ${executionTime} ms.` + ); + } + } catch (error) { + logger.error( + error, + `(${interaction.guild.memberCount}) ${interaction.guild.name}> Command '${interaction}' failed to execute.` + ); + + await interaction.followUp({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + ) + .setColor(embedOptions.colors.error) + ] + }); + } + } +}; diff --git a/src/events/player/error.js b/src/events/player/error.js new file mode 100644 index 0000000..8a1c23a --- /dev/null +++ b/src/events/player/error.js @@ -0,0 +1,12 @@ +const logger = require('../../services/logger'); + +// Emitted when the player queue encounters error +module.exports = { + name: 'error', + isDebug: false, + isPlayerEvent: true, + execute: async (queue, error) => { + logger.error(error, 'Player queue error event'); + process.env.NODE_ENV === 'development' ? logger.trace(queue) : null; + } +}; diff --git a/src/events/player/generalDebug.js b/src/events/player/generalDebug.js new file mode 100644 index 0000000..1a42b06 --- /dev/null +++ b/src/events/player/generalDebug.js @@ -0,0 +1,10 @@ +const logger = require('../../services/logger'); + +module.exports = { + name: 'debug', + isDebug: true, + isPlayerEvent: false, + execute: async (message) => { + logger.debug(message); + } +}; diff --git a/src/events/player/playerDebug.js b/src/events/player/playerDebug.js new file mode 100644 index 0000000..be15191 --- /dev/null +++ b/src/events/player/playerDebug.js @@ -0,0 +1,10 @@ +const logger = require('../../services/logger'); + +module.exports = { + name: 'error', + isDebug: true, + isPlayerEvent: true, + execute: async (message) => { + logger.trace(message); + } +}; diff --git a/src/events/player/playerError.js b/src/events/player/playerError.js new file mode 100644 index 0000000..0393e37 --- /dev/null +++ b/src/events/player/playerError.js @@ -0,0 +1,11 @@ +const logger = require('../../services/logger'); + +module.exports = { + name: 'error', + isDebug: false, + isPlayerEvent: true, + execute: async (queue, error) => { + logger.error(error, 'Player queue error event'); + process.env.NODE_ENV === 'development' ? logger.trace(queue) : null; + } +}; diff --git a/src/events/player/playerSkip.js b/src/events/player/playerSkip.js new file mode 100644 index 0000000..096057d --- /dev/null +++ b/src/events/player/playerSkip.js @@ -0,0 +1,11 @@ +const logger = require('../../services/logger'); + +module.exports = { + name: 'playerSkip', + isDebug: false, + isPlayerEvent: true, + execute: async (queue, track) => { + logger.warn(`playerSkip event: Failed to play '${track.raw.source}'.`); + process.env.NODE_ENV === 'development' ? logger.trace(queue) : null; + } +}; diff --git a/src/events/player/playerStart.js b/src/events/player/playerStart.js new file mode 100644 index 0000000..11bec27 --- /dev/null +++ b/src/events/player/playerStart.js @@ -0,0 +1,11 @@ +const logger = require('../../services/logger'); + +module.exports = { + name: 'playerStart', + isDebug: true, + isPlayerEvent: true, + execute: async (queue, track) => { + logger.debug(`playerStart event: Started playing '${track.raw.source}'.`); + process.env.NODE_ENV === 'development' ? logger.trace(queue) : null; + } +}; diff --git a/src/events/process/uncaughtException.js b/src/events/process/uncaughtException.js new file mode 100644 index 0000000..0612b84 --- /dev/null +++ b/src/events/process/uncaughtException.js @@ -0,0 +1,10 @@ +const logger = require('../../services/logger'); + +module.exports = { + name: 'uncaughtException', + isDebug: false, + execute: async (error) => { + logger.fatal(error, 'UNCAUGHT EXCEPTION ERROR:'); + return; + } +}; diff --git a/src/events/process/unhandledRejection.js b/src/events/process/unhandledRejection.js new file mode 100644 index 0000000..b7a95fb --- /dev/null +++ b/src/events/process/unhandledRejection.js @@ -0,0 +1,10 @@ +const logger = require('../../services/logger'); + +module.exports = { + name: 'unhandledRejection', + isDebug: false, + execute: async (error) => { + logger.fatal(error, 'UNHANDLED REJECTION ERROR:'); + return; + } +}; diff --git a/src/index.js b/src/index.js index 481b426..e7c897f 100644 --- a/src/index.js +++ b/src/index.js @@ -1,215 +1,18 @@ -const fs = require('node:fs'); -const path = require('path'); -const Discord = require('discord.js'); -const logger = require(path.resolve('./src/services/logger.js')); -const { EmbedBuilder } = require('discord.js'); -const { Player, onBeforeCreateStream } = require('discord-player'); -const { stream } = require('yt-stream'); -const { embedColors, embedIcons, botInfo } = require(path.resolve( - './config.json' -)); require('dotenv').config(); +const logger = require('./services/logger'); +const { registerEventListeners } = require('./utils/registerEventListeners.js'); +const { registerClientCommands } = require('./utils/registerClientCommands.js'); +const { createClient } = require('./utils/createClient.js'); +const { createPlayer } = require('./utils/createPlayer.js'); -// Setup required permissions for the bot to work -const client = new Discord.Client({ - intents: [ - Discord.GatewayIntentBits.Guilds, - Discord.GatewayIntentBits.GuildVoiceStates - ] +(async () => { + const client = await createClient(); + const player = await createPlayer(client); + + registerEventListeners(client, player); + registerClientCommands(client); + + client.login(process.env.DISCORD_BOT_TOKEN); +})().catch((error) => { + logger.error(error); }); - -// Setup commands collection and load commands -// todo: extract this logic to a separate file -client.commands = new Discord.Collection(); -const commandFiles = fs - .readdirSync(path.resolve('./src/commands')) - .filter((file) => file.endsWith('.js')); -for (const file of commandFiles) { - const command = require(path.resolve(`./src/commands/${file}`)); - client.commands.set(command.data.name, command); -} - -const systemCommandFiles = fs - .readdirSync(path.resolve('./src/system-commands')) - .filter((file) => file.endsWith('.js')); -for (const file of systemCommandFiles) { - const systemCommand = require(path.resolve( - `./src/system-commands/${file}` - )); - client.commands.set(systemCommand.data.name, systemCommand); -} - -const player = new Player(client, { - useLegacyFFmpeg: false, - ytdlOptions: { - quality: 'highestaudio', - highWaterMark: 1 << 25, - requestOptions: { - headers: { - cookie: process.env.YOUTUBE_COOKIE || '' - } - } - } -}); - -onBeforeCreateStream(async (track) => { - if (track.source === 'youtube') { - return ( - await stream(track.url, { - type: 'audio', - quality: 'high', - highWaterMark: 1 << 25, - cookie: process.env.YOUTUBE_COOKIE || '' - }) - ).stream; - } - - return null; -}); - -if (process.env.NODE_ENV === 'development') { - player.on('debug', (message) => { - logger.debug(message); - }); - - player.events.on('debug', (message) => { - logger.trace(message); - }); -} - -player.events.on('error', (queue, error) => { - // Emitted when the player queue encounters error - logger.error(error, 'Player queue error event'); -}); - -player.events.on('playerError', (queue, error) => { - // Emitted when the audio player errors while streaming audio track - logger.error(error, 'Player audio stream error event'); -}); - -player.events.on('playerStart', (queue, track) => { - logger.debug(`playerStart event: Started playing '${track.title}'.`); -}); - -player.events.on('playerSkip', (queue, track) => { - logger.debug(`playerSkip event: Failed to play '${track.title}'.`); -}); - -client.once('ready', async () => { - // This method will load all the extractors from the @discord-player/extractor package - await player.extractors.loadDefault(); - - logger.info(`discord-player loaded dependencies:\n${player.scanDeps()}`); - logger.info(`Logged in as ${client.user.tag}!`); - logger.info( - `${client.user.tag} is currently added in ${client.guilds.cache.size} guilds` - ); - - // Set Discord presence status for bot - client.user.setActivity('/help', { - type: Discord.ActivityType.Watching, - name: '/help' - }); -}); - -client.once('reconnecting', () => { - logger.warn('${client.user.tag} is reconnecting to Discord APIs.'); -}); - -client.once('disconnect', () => { - logger.warn( - '${client.user.tag} lost connection to Discord APIs. Disconnected.' - ); -}); - -client.on('warn', (warning) => { - logger.warn(warning, 'Discord client warning event'); -}); - -client.on('error', (error) => { - logger.error(error, 'Discord client error event'); -}); - -client.on('guildCreate', (guild) => { - logger.info( - `Added to guild '${guild.name}' with ${guild.memberCount} members.` - ); -}); - -client.on('guildDelete', (guild) => { - logger.info( - `Removed from guild '${guild.name}' with ${guild.memberCount} members.` - ); -}); - -client.on('interactionCreate', async (interaction) => { - if (!interaction.isCommand()) { - return; - } - - const command = client.commands.get(interaction.commandName); - if (!command) { - return; - } - - try { - const inputTime = new Date(); - await interaction.deferReply(); - await command.run({ interaction, client }); - const outputTime = new Date(); - const executionTime = outputTime - inputTime; - - if (executionTime > 20000) { - // don't send warning message for commands with collector timeouts, as collector timeout happens after 60 seconds - if ( - (interaction.commandName === 'filters' || - interaction.commandName === 'nowplaying') && - executionTime > 55000 - ) { - logger.info( - `(${interaction.guild.memberCount}) ${interaction.guild.name}> Command '${interaction}' executed in ${executionTime} ms.` - ); - return; - } - - logger.warn( - `(${interaction.guild.memberCount}) ${interaction.guild.name}> Command '${interaction}' took ${executionTime} ms to execute.` - ); - - return await interaction.followUp({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${ - embedIcons.warning - } Warning**\nThis command took ${ - executionTime / 1000 - } seconds to execute.\n\n_If you experienced problems with the command, please try again._` - ) - .setColor(embedColors.colorWarning) - ] - }); - } else { - logger.info( - `(${interaction.guild.memberCount}) ${interaction.guild.name}> Command '${interaction}' executed in ${executionTime} ms.` - ); - } - } catch (error) { - logger.error( - error, - `(${interaction.guild.memberCount}) ${interaction.guild.name}> Command '${interaction}' failed to execute.` - ); - - await interaction.followUp({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedIcons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botInfo.supportServerInviteUrl})**._` - ) - .setColor(embedColors.colorError) - ] - }); - } -}); - -client.login(process.env.DISCORD_BOT_TOKEN); diff --git a/src/services/logger.js b/src/services/logger.js index b79ae01..2d81ede 100644 --- a/src/services/logger.js +++ b/src/services/logger.js @@ -1,11 +1,11 @@ const pino = require('pino'); -require('dotenv').config(); +const { loggerOptions } = require('../config'); const transport = pino.transport({ targets: [ { target: 'pino/file', - level: process.env.MINIMUM_LOG_LEVEL, + level: loggerOptions.minimumLogLevel, options: { destination: './logs/app-all.log', mkdir: true, @@ -34,7 +34,7 @@ const transport = pino.transport({ }, { target: 'pino/file', - level: process.env.MINIMUM_LOG_LEVEL_CONSOLE, + level: loggerOptions.minimumLogLevelConsole, options: { colorize: true, sync: false @@ -45,7 +45,7 @@ const transport = pino.transport({ module.exports = pino( { - level: process.env.MINIMUM_LOG_LEVEL, + level: loggerOptions.minimumLogLevel, timestamp: () => `,"timestamp":"${new Date(Date.now()).toISOString()}"`, base: undefined }, diff --git a/src/system-commands/guilds.js b/src/system-commands/guilds.js deleted file mode 100644 index a288e4a..0000000 --- a/src/system-commands/guilds.js +++ /dev/null @@ -1,61 +0,0 @@ -const path = require('path'); -const { SlashCommandBuilder } = require('@discordjs/builders'); -const { EmbedBuilder } = require('discord.js'); -const { - embedColors, - embedIcons, - systemServerGuildIds -} = require(path.resolve('./config.json')); - -module.exports = { - data: new SlashCommandBuilder() - .setName('guilds') - .setDescription('Show list of guilds where bot is added.') - .setDMPermission(false), - run: async ({ interaction, client }) => { - if (!systemServerGuildIds.includes(interaction.guildId)) { - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedIcons.warning} Oops!**\nNo permission to execute this command.\n\nThe command \`${interaction.commandName}\` cannot be executed in this server.` - ) - .setColor(embedColors.colorWarning) - ] - }); - } - - let guildsList = client.guilds.cache - .map((guild) => { - return { - name: guild.name, - memberCount: guild.memberCount - }; - }) - .sort((a, b) => b.memberCount - a.memberCount) - .slice(0, 50) - .map( - (guild, index) => - `${index + 1}. \`${guild.name} (#${guild.memberCount})\`` - ) - .join('\n'); - - let embedDescription = `**${embedIcons.bot} ${ - client.guilds.cache.size < 50 - ? `Top ${client.guilds.cache.size} guilds` - : 'Top 50 guilds' - } by member count (${client.guilds.cache.size} total)**\n${guildsList}`; - - if (embedDescription.length >= 4000) { - embedDescription = `${embedDescription.slice(0, 3996)}...`; - } - - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription(embedDescription) - .setColor(embedColors.colorInfo) - ] - }); - } -}; diff --git a/src/utils/createClient.js b/src/utils/createClient.js new file mode 100644 index 0000000..88ea339 --- /dev/null +++ b/src/utils/createClient.js @@ -0,0 +1,34 @@ +const logger = require('../services/logger'); +const Discord = require('discord.js'); + +exports.createClient = async () => { + logger.debug('Creating Discord.js client...'); + + const client = new Discord.Client({ + intents: [Discord.GatewayIntentBits.Guilds, Discord.GatewayIntentBits.GuildVoiceStates], + makeCache: Discord.Options.cacheWithLimits({ + ...Discord.Options.DefaultMakeCacheSettings, + MessageManager: 25, + ThreadManager: 25, + PresenceManager: 0, + ReactionManager: 0, + GuildMemberManager: { + maxSize: 50, + keepOverLimit: (member) => member.id === client.user.id + } + }), + sweepers: { + ...Discord.Options.DefaultSweeperSettings, + messages: { + interval: 3600, + lifetime: 1800 + }, + users: { + interval: 3600, + filter: () => (user) => user.id !== client.user.id + } + } + }); + + return client; +}; diff --git a/src/utils/createPlayer.js b/src/utils/createPlayer.js new file mode 100644 index 0000000..22f2564 --- /dev/null +++ b/src/utils/createPlayer.js @@ -0,0 +1,40 @@ +const logger = require('../services/logger'); +const { Player, onBeforeCreateStream } = require('discord-player'); +const { stream } = require('yt-stream'); + +exports.createPlayer = async (client) => { + logger.debug('Creating discord-player player...'); + + const player = new Player(client, { + useLegacyFFmpeg: false, + ytdlOptions: { + quality: 'highestaudio', + highWaterMark: 1 << 25, + requestOptions: { + headers: { + cookie: process.env.YOUTUBE_COOKIE || '' + } + } + } + }); + + onBeforeCreateStream(async (track) => { + if (track.source === 'youtube') { + return ( + await stream(track.url, { + type: 'audio', + quality: 'high', + highWaterMark: 1 << 25, + cookie: process.env.YOUTUBE_COOKIE || '' + }) + ).stream; + } + + return null; + }); + + await player.extractors.loadDefault(); + logger.debug(`discord-player loaded dependencies:\n${player.scanDeps()}`); + + return player; +}; diff --git a/src/utils/deploySlashCommands.js b/src/utils/deploySlashCommands.js new file mode 100644 index 0000000..7b18160 --- /dev/null +++ b/src/utils/deploySlashCommands.js @@ -0,0 +1,64 @@ +require('dotenv').config(); +const logger = require('../services/logger'); +const fs = require('node:fs'); +const { REST, Routes } = require('discord.js'); +const { systemOptions } = require('../config'); + +const slashCommands = []; +const systemCommands = []; +const commandFolders = fs.readdirSync('./src/commands'); +for (const folder of commandFolders) { + const commandFiles = fs.readdirSync(`./src/commands/${folder}`).filter((file) => file.endsWith('.js')); + + for (const file of commandFiles) { + const command = require(`../commands/${folder}/${file}`); + command.isSystemCommand + ? systemCommands.push(command.data.toJSON()) + : slashCommands.push(command.data.toJSON()); + } +} + +const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_BOT_TOKEN); + +(async () => { + try { + logger.info('DEPLOYING BOT SLASH COMMANDS'); + logger.info( + slashCommands.map((command) => { + return command.name; + }), + 'Bot commands found:' + ); + + logger.info('Started refreshing application (/) bot commands.'); + await rest.put(Routes.applicationCommands(process.env.DISCORD_APPLICATION_ID), { + body: slashCommands + }); + + logger.info('Successfully refreshed application (/) bot commands.'); + } catch (error) { + logger.error(error, 'Failed to refresh application (/) bot commands.'); + } + + try { + logger.info('DEPLOYING SYSTEM SLASH COMMANDS'); + logger.info( + systemCommands.map((systemCommand) => { + return systemCommand.name; + }), + 'System commands found:' + ); + + logger.info('Started refreshing application (/) system commands.'); + for (const systemGuildId of systemOptions.systemGuildIds) { + logger.info(`Refreshing system commands for guild id ${systemGuildId}.`); + await rest.put(Routes.applicationGuildCommands(process.env.DISCORD_APPLICATION_ID, systemGuildId), { + body: systemCommands + }); + } + + logger.info('Successfully refreshed application (/) system commands.'); + } catch (error) { + logger.error(error, 'Failed to refresh application (/) system commands.'); + } +})(); diff --git a/src/utils/postBotStats.js b/src/utils/postBotStats.js new file mode 100644 index 0000000..7d40435 --- /dev/null +++ b/src/utils/postBotStats.js @@ -0,0 +1,80 @@ +const logger = require('../services/logger'); +const https = require('node:https'); + +exports.postBotStats = (client) => { + try { + const guildCount = client.guilds.cache.size; + + /* eslint-disable camelcase */ + const sites = [ + { + hostname: 'top.gg', + path: `/api/bots/${process.env.DISCORD_APPLICATION_ID}/stats`, + method: 'POST', + body: { server_count: guildCount }, + token: process.env.BOTLIST_TOP_GG_API_TOKEN + }, + { + hostname: 'discordbotlist.com', + path: `/api/v1/bots/${process.env.DISCORD_APPLICATION_ID}/stats`, + method: 'POST', + body: { guilds: guildCount }, + token: process.env.BOTLIST_DISCORD_BOT_LIST_COM_API_TOKEN + }, + { + hostname: 'discords.com', + path: `/bots/api/bot/${process.env.DISCORD_APPLICATION_ID}`, + method: 'POST', + body: { server_count: guildCount }, + token: process.env.BOTLIST_DISCORDS_COM_API_TOKEN + }, + { + hostname: 'discord.bots.gg', + path: `/api/v1/bots/${process.env.DISCORD_APPLICATION_ID}/stats`, + method: 'POST', + body: { guildCount: guildCount }, + token: process.env.BOTLIST_DISCORD_BOTS_GG_API_TOKEN + }, + { + hostname: 'api.botlist.me', + path: `/api/v1/bots/${process.env.DISCORD_APPLICATION_ID}/stats`, + method: 'POST', + body: { server_count: guildCount }, + token: process.env.BOTLIST_BOTLIST_ME_API_TOKEN + }, + { + hostname: 'api.discordlist.gg', + path: `/v0/bots/${process.env.DISCORD_APPLICATION_ID}/guilds?count=${guildCount}`, + method: 'PUT', + body: {}, + token: `Bearer ${process.env.BOTLIST_DISCORDLIST_GG_API_TOKEN}` + } + ]; + + logger.info(`Posting stats to bot lists with guildCount ${guildCount}...`); + sites.map((site) => { + let options = { + protocol: 'https:', + hostname: site.hostname, + port: 443, + path: site.path, + method: site.method, + headers: { + 'Content-Type': 'application/json', + Authorization: site.token + } + }; + + let request = https.request(options, (res) => { + res.statusCode === 200 + ? logger.info(`Request to ${site.hostname}: statusCode: ${res.statusCode}`) + : logger.warn(`Request to ${site.hostname}: statusCode: ${res.statusCode}`); + }); + + request.write(JSON.stringify(site.body)); + request.end(); + }); + } catch (error) { + logger.error(error, 'Failed to post stats to bot lists'); + } +}; diff --git a/src/utils/registerClientCommands.js b/src/utils/registerClientCommands.js new file mode 100644 index 0000000..98524b0 --- /dev/null +++ b/src/utils/registerClientCommands.js @@ -0,0 +1,19 @@ +const logger = require('../services/logger'); +const fs = require('node:fs'); +const { Collection } = require('discord.js'); + +exports.registerClientCommands = (client) => { + logger.debug('Registering client commands...'); + + client.commands = new Collection(); + const commandFolders = fs.readdirSync('./src/commands'); + for (const folder of commandFolders) { + const commandFiles = fs.readdirSync(`./src/commands/${folder}`).filter((file) => file.endsWith('.js')); + + for (const file of commandFiles) { + logger.debug(`Registering command ${folder}/${file}...`); + const command = require(`../commands/${folder}/${file}`); + client.commands.set(command.data.name, command); + } + } +}; diff --git a/src/utils/registerEventListeners.js b/src/utils/registerEventListeners.js new file mode 100644 index 0000000..18f91d4 --- /dev/null +++ b/src/utils/registerEventListeners.js @@ -0,0 +1,60 @@ +const logger = require('../services/logger'); +const fs = require('node:fs'); + +exports.registerEventListeners = (client, player) => { + logger.debug('Registering event listeners...'); + + const eventFolders = fs.readdirSync('./src/events'); + for (const folder of eventFolders) { + const eventFiles = fs.readdirSync(`./src/events/${folder}`).filter((file) => file.endsWith('.js')); + + for (const file of eventFiles) { + const event = require(`../events/${folder}/${file}`); + switch (folder) { + case 'client': + logger.debug(`Registering client event listener ${event.name}...`); + if (event.once) { + client.once(event.name, (...args) => event.execute(...args)); + } else { + if ( + !event.isDebug || + process.env.NODE_ENV === 'development' || + process.env.MINIMUM_LOG_LEVEL === 'debug' + ) { + client.on(event.name, (...args) => event.execute(...args)); + } + } + break; + + case 'interactions': + logger.debug(`Registering interactions event listener ${event.name}...`); + client.on(event.name, (...args) => event.execute(...args, { client })); + break; + + case 'process': + logger.debug(`Registering process event listener ${event.name}...`); + process.on(event.name, (...args) => event.execute(...args)); + break; + + case 'player': + logger.debug(`Registering player event listener ${event.name}...`); + if ( + !event.isDebug || + process.env.NODE_ENV === 'development' || + process.env.MINIMUM_LOG_LEVEL === 'debug' + ) { + if (event.isPlayerEvent) { + player.events.on(event.name, (...args) => event.execute(...args)); + break; + } else { + player.on(event.name, (...args) => event.execute(...args)); + } + } + break; + + default: + logger.error(`Unknown event folder '${folder}' while trying to register events.`); + } + } + } +};