all repos — simple-discord-music-bot @ 97d143480c5e930b650d03144851f59a790715c6

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