Halfbroken fixes

This commit is contained in:
Myx
2023-06-28 03:02:41 +02:00
parent 6a001604ab
commit f533e38333
18 changed files with 545 additions and 421 deletions

View File

@@ -1,44 +1,41 @@
const { StreamType } = require('@discordjs/voice');
const spotify = require('../music_sources/spotify');
const soundcloud = require('../music_sources/soundcloud');
const youtube = require('../music_sources/youtube');
const { StreamType } = require('@discordjs/voice');
async function getMusicStream(query) {
let stream;
let songTitle;
let songDuration;
let type = StreamType.Opus;
let userInput = query;
let stream;
let songTitle;
let songDuration;
let type = StreamType.Opus;
const userInput = query;
if (query.includes('spotify.com')) {
stream = await spotify.getStream(query);
songTitle = stream.title;
songDuration = stream.duration;
stream = stream.stream;
if (query.includes('spotify.com')) {
stream = await spotify.getStream(query);
songTitle = stream.title;
songDuration = stream.duration;
stream = stream.stream;
} else if (query.includes('soundcloud.com')) {
stream = await soundcloud.getStream(query);
songTitle = stream.title;
songDuration = stream.duration;
stream = stream.stream;
type = StreamType.OggOpus;
} else {
stream = await youtube.getStream(query);
songTitle = stream?.title ?? 'Unknown';
songDuration = stream?.duration ?? 'Unknown';
stream = stream?.stream;
type = StreamType.Opus;
}
} else if (query.includes('soundcloud.com')) {
stream = await soundcloud.getStream(query);
songTitle = stream.title;
songDuration = stream.duration;
stream = stream.stream;
type = StreamType.OggOpus;
} else {
stream = await youtube.getStream(query)
songTitle = stream?.title ?? 'Unknown';
songDuration = stream?.duration ?? 'Unknown';
stream = stream?.stream;
type = StreamType.Opus;
}
return {
title: songTitle,
duration: songDuration,
userInput: userInput,
stream: stream,
type: type
};
return {
title: songTitle,
duration: songDuration,
userInput,
stream,
type,
};
}
module.exports.getMusicStream = getMusicStream;
module.exports.getMusicStream = getMusicStream;

View File

@@ -1,74 +1,143 @@
/* eslint-disable max-len */
/* eslint-disable no-restricted-syntax */
const {
createAudioResource,
createAudioPlayer,
NoSubscriberBehavior,
AudioPlayerStatus,
createAudioResource,
createAudioPlayer,
NoSubscriberBehavior,
AudioPlayerStatus,
} = require('@discordjs/voice');
const process = require('dotenv').config();
const { clientId } = process.parsed;
const { EmbedBuilder } = require('discord.js');
const musicQueue = require('../musicQueue');
const { progressBar } = require('../utils/progress');
const { progressBar } = require('./progress');
const currentInteractionIds = new Map();
const currentInteractions = new Map();
const oldConnections = [];
const timeoutTimer = new Map();
// TODO FIX THIS SHIT!!! ISSUES WITH DISPLAYING NAME AND STATUS WHEN UPDATING
function nowPLayingMessage(interaction, song, oldInteractionId) {
progressBar(0, 0, true);
if (interaction.commandName === 'play') {
interaction.followUp('~🎵~').then((message) => {
const songTitle = song.title;
// const embed = new EmbedBuilder()
// .setColor('#E0B0FF')
// .setTitle(`Now playing: ${songTitle}`)
// .setDescription(
// progressBar(song.duration, 10).progressBarString,
// );
const embed = new EmbedBuilder()
.setColor('#E0B0FF')
.setTitle(`Now playing: ${songTitle}`);
message.edit({
embeds: [embed],
});
const inter = setInterval(async () => {
const { progressBarString, isDone } = progressBar(
song.duration,
10,
);
if (isDone || message.id !== oldInteractionId) {
// clearInterval(inter);
return;
}
if (message.id != null && interaction.guild.id !== oldInteractionId) {
interaction.channel.messages.fetch().then(async (channel) => {
const filter = channel.filter((msg) => msg.author.id === clientId);
const latestMessage = await interaction.channel.messages.fetch(filter.first().id);
latestMessage.edit({
embeds: [embed.setTitle(`Now playing: ${songTitle}`)],
});
});
}
}, 2000);
currentInteractionIds.set(interaction.guild.id, interaction);
currentInteractions.set(interaction.guild.id, interaction.id);
});
}
}
async function musicPlayer(guildId, connection, interaction) {
const serverQueue = musicQueue.getQueue(guildId);
try {
const oldInteractions = await currentInteractions.get(interaction.guild.id);
const oldInteractionId = await currentInteractionIds.get(interaction.guild.id);
const serverQueue = musicQueue.getQueue(guildId);
const oldConnection = oldConnections
.find((guidConnection) => guidConnection[0] === interaction.guild.id);
if (serverQueue.length === 0) {
connection.destroy();
return;
}
if (serverQueue.length === 0) {
oldConnection[1].destroy();
}
const song = serverQueue[0];
const song = serverQueue[0];
if (song.stream == null) {
musicQueue.removeFromQueue(guildId);
musicPlayer(guildId, connection);
return;
}
if (song.stream === undefined) {
musicQueue.removeFromQueue(guildId);
musicPlayer(guildId, connection);
return;
}
let resource = createAudioResource(song.stream, {
inputType: song.type
})
const resource = createAudioResource(song.stream, {
inputType: song.type,
});
let player = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Play
}
})
const player = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Play,
},
});
player.play(resource)
player.play(resource);
connection.subscribe(player)
connection.subscribe(player);
progressBar(0, 0, true)
nowPLayingMessage(interaction, song, oldInteractions);
if(interaction.commandName == "play") {
interaction.followUp(`~🎵~`).then(message => {
const embed = new EmbedBuilder()
.setColor("#E0B0FF")
.setTitle("Now playing: " + song.title)
.setDescription(progressBar(song.duration, 10).progressBarString);
message.edit({ embeds: [embed] });
inter = setInterval(() => {
const { progressBarString, isDone } = progressBar(song.duration, 10);
if (isDone) {
clearInterval(inter);
message.delete();
}
embed.setDescription(progressBarString);
message.edit({ embeds: [embed] });
}, 2000)
});
}
oldConnections.push([interaction.guild.id, connection]);
player.on(AudioPlayerStatus.Idle, async () => {
console.log('Song ended:', song.title);
await musicQueue.removeFromQueue(guildId)
musicPlayer(guildId, connection, interaction);
});
player.on(AudioPlayerStatus.Idle, async () => {
console.log('Song ended:', song.title);
if (serverQueue.length !== 1) {
await musicQueue.removeFromQueue(guildId);
musicPlayer(guildId, connection, interaction);
}
return player;
// timeoutTimer.set(guildId, setTimeout(async () => {
// await musicQueue.removeFromQueue(guildId);
// connection.destroy();
// }, 10000));
});
player.on(AudioPlayerStatus.Playing, () => {
console.log('pausing timer');
clearTimeout(
timeoutTimer.get(guildId),
);
});
if (oldInteractionId) {
oldInteractionId.channel.messages.fetch().then(async (channel) => {
const { lastMessage } = oldInteractionId.channel;
const filter = channel.filter((message) => message.author.id === clientId && message.id !== lastMessage.id);
setTimeout(() => {
oldInteractionId.channel.bulkDelete(filter);
}, 1000);
});
}
} catch (error) {
console.error(error);
interaction.followUp('There was an error playing the song.');
}
}
module.exports.musicPlayer = musicPlayer;

View File

@@ -3,36 +3,35 @@ let current = 0;
let percentage;
const progressBar = (totalInMilliseconds, size, reset = false) => {
if (reset) {
startTime = Date.now();
current = 0;
}
if (reset) {
startTime = Date.now();
current = 0;
}
if (!startTime) {
startTime = Date.now();
}
if (!startTime) {
startTime = Date.now();
}
current = Date.now() - startTime;
current = Date.now() - startTime;
const totalInSeconds = totalInMilliseconds / 1000;
percentage = Math.min((current / 1000) / totalInSeconds, 1);
const progress = Math.round((size * percentage));
const emptyProgress = size - progress;
const totalInSeconds = totalInMilliseconds / 1000;
percentage = Math.min((current / 1000) / totalInSeconds, 1);
const progress = Math.round((size * percentage));
const emptyProgress = size - progress;
const progressText = '▇'.repeat(progress);
const emptyProgressText = '—'.repeat(emptyProgress);
const percentageText = Math.round(percentage * 100) + '%';
const progressText = '▇'.repeat(progress);
const emptyProgressText = '—'.repeat(emptyProgress);
let elapsedTimeText = new Date(current).toISOString().slice(11, -5);
let totalTimeText = new Date(totalInMilliseconds).toISOString().slice(11, -5);
let elapsedTimeText = new Date(current).toISOString().slice(11, -5);
let totalTimeText = new Date(totalInMilliseconds).toISOString().slice(11, -5);
if (totalTimeText.startsWith('00:')) {
elapsedTimeText = elapsedTimeText.slice(3);
totalTimeText = totalTimeText.slice(3);
}
if (totalTimeText.startsWith('00:')) {
elapsedTimeText = elapsedTimeText.slice(3);
totalTimeText = totalTimeText.slice(3);
}
const progressBarString = elapsedTimeText + ' [' + progressText + emptyProgressText + ']' + percentageText + ' ' + totalTimeText; // Creating and returning the bar
const progressBarString = `${elapsedTimeText} \`\`\`${progressText}${emptyProgressText}\`\`\` ${totalTimeText}`; // Creating and returning the bar
return { progressBarString, isDone: percentage === 1 };
}
module.exports.progressBar = progressBar;
return { progressBarString, isDone: percentage === 1 };
};
module.exports.progressBar = progressBar;

View File

@@ -1,59 +1,55 @@
const { SlashCommandBuilder } = require("@discordjs/builders");
const { REST } = require("@discordjs/rest");
const { Routes } = require("discord-api-types/v9");
const { SlashCommandBuilder } = require('@discordjs/builders');
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
async function registerCommands(clientId, token) {
const commands = [
new SlashCommandBuilder()
.setName("play")
.setDescription("Plays songs!")
.addStringOption((option) =>
option
.setName("input")
.setDescription("Play song from YouTube, Spotify, SoundCloud, etc.")
.setRequired(true)
),
new SlashCommandBuilder()
.setName("queue")
.setDescription("Adds a song to the queue!")
.addStringOption((option) =>
option
.setName("song")
.setDescription(
"Add song from YouTube, Spotify, SoundCloud, etc. to the queue"
)
.setRequired(true)
),
new SlashCommandBuilder()
.setName("pause")
.setDescription("Pauses the current song!"),
new SlashCommandBuilder()
.setName("resume")
.setDescription("Resumes the current song!"),
new SlashCommandBuilder()
.setName("loop")
.setDescription("Loops the current song! (toggle)"),
new SlashCommandBuilder()
.setName("stop")
.setDescription("Stops the current song!"),
];
const commands = [
new SlashCommandBuilder()
.setName('play')
.setDescription('Plays songs!')
.addStringOption((option) => option
.setName('input')
.setDescription('Play song from YouTube, Spotify, SoundCloud, etc.')
.setRequired(true)),
new SlashCommandBuilder()
.setName('queue')
.setDescription('Adds a song to the queue!')
.addStringOption((option) => option
.setName('song')
.setDescription(
'Add song from YouTube, Spotify, SoundCloud, etc. to the queue',
)
.setRequired(true)),
new SlashCommandBuilder()
.setName('pause')
.setDescription('Pauses the current song!'),
new SlashCommandBuilder()
.setName('resume')
.setDescription('Resumes the current song!'),
new SlashCommandBuilder()
.setName('loop')
.setDescription('Loops the current song! (toggle)'),
new SlashCommandBuilder()
.setName('stop')
.setDescription('Stops the current song!'),
];
const rest = new REST({
version: "9",
})
.setToken(token);
const rest = new REST({
version: '9',
})
.setToken(token);
try {
console.log("\x1b[35m", "Started refreshing application (/) commands.");
try {
console.log('\x1b[35m', 'Started refreshing application (/) commands.');
await rest.put(Routes.applicationCommands(clientId), {
body: commands,
});
await rest.put(Routes.applicationCommands(clientId), {
body: commands,
});
console.log("\x1b[35m", "Successfully reloaded application (/) commands.");
} catch (error) {
console.error(error);
}
console.log('\x1b[35m', 'Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
}
module.exports.registerCommands = registerCommands;