Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const { Client, GatewayIntentBits, ActivityType } = require("discord.js");
- const { REST } = require('@discordjs/rest');
- const { Routes } = require('discord-api-types/v9');
- const { joinVoiceChannel, createAudioPlayer, createAudioResource } = require('@discordjs/voice');
- const ytdl = require('ytdl-core-discord');
- const search = require('yt-search');
- const config = require("./config.json");
- const client = new Client({
- intents: [
- GatewayIntentBits.Guilds,
- GatewayIntentBits.GuildMembers,
- GatewayIntentBits.GuildMessages,
- GatewayIntentBits.GuildVoiceStates,
- ],
- });
- client.once("ready", () => {
- console.log(`Logged in as ${client.user.tag}`);
- client.user.setActivity({
- name: 'Music',
- type: ActivityType.Listening,
- });
- // Register slash commands
- registerCommands();
- });
- const queues = new Map();
- client.on("interactionCreate", async (interaction) => {
- if (!interaction.isCommand()) return;
- const { commandName, options } = interaction;
- try {
- if (commandName === "play") {
- await interaction.deferReply();
- const query = options.getString("query");
- const connection = await JoinVoiceChannel(interaction);
- if (!connection) {
- return interaction.editReply({ content: "Could not join your voice channel!", ephemeral: true });
- }
- const queue = getQueue(interaction.guild.id);
- const searchResult = await searchVideo(query);
- if (!searchResult) {
- return interaction.editReply({ content: "No results were found!", ephemeral: true });
- }
- queue.songs.push(searchResult);
- if (!queue.playing) {
- playSong(queue, interaction);
- }
- return interaction.editReply({ content: `⏱ | Loading your track...`, ephemeral: true });
- } else if (commandName === "skip" || commandName === "stop") {
- const queue = getQueue(interaction.guild.id);
- if (!queue || !queue.playing) {
- return interaction.editReply({ content: "❌ | No music is being played!", ephemeral: true });
- }
- if (commandName === "skip") {
- queue.connection.destroy();
- return interaction.editReply({ content: "🛑 | Skipped the current track!", ephemeral: true });
- } else if (commandName === "stop") {
- queue.songs = [];
- queue.connection.destroy();
- return interaction.editReply({ content: "🛑 | Stopped the player!", ephemeral: true });
- }
- }
- } catch (error) {
- console.error(error);
- interaction.followUp('An error occurred while processing your command.');
- }
- });
- async function JoinVoiceChannel(interaction) {
- const member = interaction.guild.members.cache.get(interaction.user.id);
- if (!member || !member.voice.channel) {
- console.log('Member or voice channel not found', new Date());
- return null;
- }
- const channel = member.voice.channel;
- try {
- console.log('Before joining voice channel', new Date());
- const connection = joinVoiceChannel({
- channelId: channel.id,
- guildId: channel.guild.id,
- adapterCreator: channel.guild.voiceAdapterCreator,
- selfDeaf: false,
- });
- console.log('After joining voice channel', new Date());
- return connection;
- } catch (error) {
- console.error(`Error connecting to voice channel: ${error.message}`, new Date());
- return null;
- }
- }
- function getQueue(guildId) {
- if (!queues.has(guildId)) {
- queues.set(guildId, {
- connection: null,
- player: createAudioPlayer(),
- songs: [],
- playing: false,
- });
- }
- return queues.get(guildId);
- }
- async function searchVideo(query) {
- try {
- const { videos } = await search(query);
- if (!videos.length) return null;
- const firstVideo = videos[0];
- return {
- title: firstVideo.title,
- url: firstVideo.url,
- };
- } catch (error) {
- console.error(`Error searching for video: ${error.message}`);
- return null;
- }
- }
- async function playSong(queue, interaction) {
- if (!queue || !queue.connection || !queue.songs || queue.songs.length === 0) {
- queue.playing = false;
- return;
- }
- const song = queue.songs[0];
- try {
- const stream = await ytdl(song.url, { filter: "audioonly" });
- const resource = createAudioResource(stream);
- resource.playStream.on('start', () => {
- console.log("Song started playing:", song.title);
- if (interaction && !interaction.deferred && !interaction.replied) {
- interaction.editReply({ content: `🎶 | Now playing: **${song.title}**`, ephemeral: true });
- }
- });
- resource.playStream.on('finish', () => {
- queue.songs.shift();
- playSong(queue, interaction);
- });
- resource.playStream.on('error', (error) => {
- console.error(`Error playing song: ${error.message}`);
- playSong(queue, interaction);
- });
- queue.playing = true;
- queue.connection.play(resource);
- } catch (error) {
- console.error(`Error playing song: ${error.message}`);
- playSong(queue, interaction);
- }
- }
- // Function to register slash commands
- async function registerCommands() {
- const commands = [
- {
- name: 'play',
- description: 'Play a song',
- options: [
- {
- name: 'query',
- type: 3,
- description: 'The song you want to play',
- required: true,
- },
- ],
- },
- {
- name: 'skip',
- description: 'Skip the current song',
- },
- {
- name: 'stop',
- description: 'Stop the player',
- },
- ];
- const rest = new REST({ version: '9' }).setToken(config.token);
- try {
- console.log('Started refreshing application (/) commands.');
- await rest.put(
- Routes.applicationGuildCommands(client.user.id, config.guildId),
- { body: commands },
- );
- console.log('Successfully reloaded application (/) commands.');
- } catch (error) {
- console.error(error);
- }
- }
- client.login(config.token);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement