Advertisement
VeNoM_1

Untitled

Jan 21st, 2024
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const { Client, GatewayIntentBits, ActivityType } = require("discord.js");
  2. const { REST } = require('@discordjs/rest');
  3. const { Routes } = require('discord-api-types/v9');
  4. const { joinVoiceChannel, createAudioPlayer, createAudioResource } = require('@discordjs/voice');
  5. const ytdl = require('ytdl-core-discord');
  6. const search = require('yt-search');
  7. const config = require("./config.json");
  8.  
  9. const client = new Client({
  10.     intents: [
  11.         GatewayIntentBits.Guilds,
  12.         GatewayIntentBits.GuildMembers,
  13.         GatewayIntentBits.GuildMessages,
  14.         GatewayIntentBits.GuildVoiceStates,
  15.     ],
  16. });
  17.  
  18. client.once("ready", () => {
  19.     console.log(`Logged in as ${client.user.tag}`);
  20.     client.user.setActivity({
  21.         name: 'Music',
  22.         type: ActivityType.Listening,
  23.     });
  24.  
  25.     // Register slash commands
  26.     registerCommands();
  27. });
  28.  
  29. const queues = new Map();
  30.  
  31. client.on("interactionCreate", async (interaction) => {
  32.     if (!interaction.isCommand()) return;
  33.  
  34.     const { commandName, options } = interaction;
  35.  
  36.     try {
  37.         if (commandName === "play") {
  38.             await interaction.deferReply();
  39.             const query = options.getString("query");
  40.             const connection = await JoinVoiceChannel(interaction);
  41.  
  42.             if (!connection) {
  43.                 return interaction.editReply({ content: "Could not join your voice channel!", ephemeral: true });
  44.             }
  45.  
  46.             const queue = getQueue(interaction.guild.id);
  47.  
  48.             const searchResult = await searchVideo(query);
  49.             if (!searchResult) {
  50.                 return interaction.editReply({ content: "No results were found!", ephemeral: true });
  51.             }
  52.  
  53.             queue.songs.push(searchResult);
  54.  
  55.             if (!queue.playing) {
  56.                 playSong(queue, interaction);
  57.             }
  58.             return interaction.editReply({ content: `⏱ | Loading your track...`, ephemeral: true });
  59.         } else if (commandName === "skip" || commandName === "stop") {
  60.             const queue = getQueue(interaction.guild.id);
  61.             if (!queue || !queue.playing) {
  62.                 return interaction.editReply({ content: "❌ | No music is being played!", ephemeral: true });
  63.             }
  64.  
  65.             if (commandName === "skip") {
  66.                 queue.connection.destroy();
  67.                 return interaction.editReply({ content: "🛑 | Skipped the current track!", ephemeral: true });
  68.             } else if (commandName === "stop") {
  69.                 queue.songs = [];
  70.                 queue.connection.destroy();
  71.                 return interaction.editReply({ content: "🛑 | Stopped the player!", ephemeral: true });
  72.             }
  73.         }
  74.     } catch (error) {
  75.         console.error(error);
  76.         interaction.followUp('An error occurred while processing your command.');
  77.     }
  78. });
  79.  
  80. async function JoinVoiceChannel(interaction) {
  81.     const member = interaction.guild.members.cache.get(interaction.user.id);
  82.     if (!member || !member.voice.channel) {
  83.         console.log('Member or voice channel not found', new Date());
  84.         return null;
  85.     }
  86.  
  87.     const channel = member.voice.channel;
  88.  
  89.     try {
  90.         console.log('Before joining voice channel', new Date());
  91.         const connection = joinVoiceChannel({
  92.             channelId: channel.id,
  93.             guildId: channel.guild.id,
  94.             adapterCreator: channel.guild.voiceAdapterCreator,
  95.             selfDeaf: false,
  96.         });
  97.         console.log('After joining voice channel', new Date());
  98.         return connection;
  99.     } catch (error) {
  100.         console.error(`Error connecting to voice channel: ${error.message}`, new Date());
  101.         return null;
  102.     }
  103. }
  104.  
  105. function getQueue(guildId) {
  106.     if (!queues.has(guildId)) {
  107.         queues.set(guildId, {
  108.             connection: null,
  109.             player: createAudioPlayer(),
  110.             songs: [],
  111.             playing: false,
  112.         });
  113.     }
  114.  
  115.     return queues.get(guildId);
  116. }
  117.  
  118. async function searchVideo(query) {
  119.     try {
  120.         const { videos } = await search(query);
  121.         if (!videos.length) return null;
  122.  
  123.         const firstVideo = videos[0];
  124.         return {
  125.             title: firstVideo.title,
  126.             url: firstVideo.url,
  127.         };
  128.     } catch (error) {
  129.         console.error(`Error searching for video: ${error.message}`);
  130.         return null;
  131.     }
  132. }
  133.  
  134. async function playSong(queue, interaction) {
  135.     if (!queue || !queue.connection || !queue.songs || queue.songs.length === 0) {
  136.         queue.playing = false;
  137.         return;
  138.     }
  139.  
  140.     const song = queue.songs[0];
  141.  
  142.     try {
  143.         const stream = await ytdl(song.url, { filter: "audioonly" });
  144.         const resource = createAudioResource(stream);
  145.  
  146.         resource.playStream.on('start', () => {
  147.             console.log("Song started playing:", song.title);
  148.             if (interaction && !interaction.deferred && !interaction.replied) {
  149.                 interaction.editReply({ content: `🎶 | Now playing: **${song.title}**`, ephemeral: true });
  150.             }
  151.         });
  152.  
  153.         resource.playStream.on('finish', () => {
  154.             queue.songs.shift();
  155.             playSong(queue, interaction);
  156.         });
  157.  
  158.         resource.playStream.on('error', (error) => {
  159.             console.error(`Error playing song: ${error.message}`);
  160.             playSong(queue, interaction);
  161.         });
  162.  
  163.         queue.playing = true;
  164.         queue.connection.play(resource);
  165.     } catch (error) {
  166.         console.error(`Error playing song: ${error.message}`);
  167.         playSong(queue, interaction);
  168.     }
  169. }
  170.  
  171. // Function to register slash commands
  172. async function registerCommands() {
  173.     const commands = [
  174.         {
  175.             name: 'play',
  176.             description: 'Play a song',
  177.             options: [
  178.                 {
  179.                     name: 'query',
  180.                     type: 3,
  181.                     description: 'The song you want to play',
  182.                     required: true,
  183.                 },
  184.             ],
  185.         },
  186.         {
  187.             name: 'skip',
  188.             description: 'Skip the current song',
  189.         },
  190.         {
  191.             name: 'stop',
  192.             description: 'Stop the player',
  193.         },
  194.     ];
  195.  
  196.     const rest = new REST({ version: '9' }).setToken(config.token);
  197.  
  198.     try {
  199.         console.log('Started refreshing application (/) commands.');
  200.  
  201.         await rest.put(
  202.             Routes.applicationGuildCommands(client.user.id, config.guildId),
  203.             { body: commands },
  204.         );
  205.  
  206.         console.log('Successfully reloaded application (/) commands.');
  207.     } catch (error) {
  208.         console.error(error);
  209.     }
  210. }
  211.  
  212. client.login(config.token);
  213.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement