all repos — simple-discord-music-bot @ 142a67c1f9a5c30d9c4bebd699b8e8c012d0d5ee

A Discord bot making use of discord.js and play-yt.

commands/outro.js (view raw)

 1const path = require('node:path');
 2const { SlashCommandBuilder } = require('discord.js');
 3const { createAudioResource, createAudioPlayer, joinVoiceChannel, NoSubscriberBehavior, AudioPlayerStatus } = require('@discordjs/voice');
 4
 5const outros = [
 6	{ name: 'Random!', 							value: 'random' },
 7	{ name: 'TheFatRat - Xenogenesis', 			value: 'thefatrat_xenogenesis.mp3' },
 8	{ name: 'OMFG - Hello', 					value: 'omfg_hello.mp3' },
 9	{ name: 'Pegboard Nerds - Disconnected',	value: 'pegboard_nerds_disconnected.mp3' },
10];
11
12function get_player(resource, user_connection) {
13
14	const player = createAudioPlayer({ behaviors: { noSubscriber: NoSubscriberBehavior.Pause } });
15
16	player.on('error', error => console.error(`Error: ${error.message} with resource ${error.resource.metadata.title}`));
17	player.on(AudioPlayerStatus.Idle, () => {
18		player.stop();
19		player.subscribers.forEach(element => {
20			element.connection.disconnect();
21		});
22	});
23	player.on(AudioPlayerStatus.Playing, () => setTimeout(() => user_connection.disconnect(), 20_000));
24
25	player.play(createAudioResource(resource));
26	return player;
27}
28
29module.exports = {
30	data: new SlashCommandBuilder()
31		.setName('outro')
32		.setDescription('Leave with an outro.')
33		.addStringOption(option =>
34			option.setName('outro')
35				.setDescription('Select which outro to play')
36				.setRequired(false)
37				.addChoices(...outros)),
38
39	async execute(interaction) {
40		const member = interaction.member;
41		if (!member) return await interaction.reply({ content: 'Please use this in your current server.', ephemeral: true });
42
43		const user_connection = member.voice;
44		const channel = user_connection.channel;
45		if (!channel) return await interaction.reply({ content: 'You\'re not in a voice channel.', ephemeral: true });
46
47		const guild = channel.guild;
48		const bot_connection = joinVoiceChannel({ channelId: channel.id, guildId: guild.id, adapterCreator: guild.voiceAdapterCreator });
49
50		const outro = interaction.options.getString('outro');
51		let outro_file = outro ? outro : 'random';
52		if (outro_file == 'random')
53			outro_file = outros[Math.floor(Math.random() * (outros.length - 1)) + 1].value;
54
55		const song_path = path.join(process.cwd(), 'resources', outro_file);
56		bot_connection.subscribe(get_player(song_path, user_connection));
57
58		const outro_title = outros.find(element => element.value == outro_file).name;
59		return await interaction.reply({ content: `Prepare for takeoff with ${outro_title}!`, ephemeral: true });
60	},
61};