Войдите на Портал разработчиков Discord
Нажмите «Новое приложение» в левом верхнем углу страницы.
Убедитесь, что установлен флажок «Все» в разделах намерений привилегированного шлюза.
После добавления бота давайте продолжим часть кода, мы рассмотрим этот раздел позже.
Создайте пустую папку и откройте с помощью vscode. Затем нам нужен js-проект узла инициализации.
Откройте терминал и выполните этот код =› npm init
Заполните эти обязательные вопросы, как я.
После этого запустите этот код на терминале => npm install
Затем выполните эти коды построчно =>
npm install @discordjs/[email protected]
npm install [email protected]
npm install [email protected]
npm install [email protected]
Создайте файл index.js в корне
И заполните эти строки кода
const { Client, GatewayIntentBits } = require("discord.js"); const { Player } = require("discord-music-player"); const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.MessageContent, ], }); const settings = { prefix: `!`, token: `discord_bot_token`, }; const player = new Player(client, { leaveOnEmpty: false, }); client.player = player; client.on("ready", () => { console.log("I am ready to Play Music!"); client.user.setActivity("Test Bot"); }); client.on("messageCreate", async (message) => { if (!message.content.startsWith(settings.prefix)) return; let command = message.content .slice(settings.prefix.length, message.content.length) .split(" ")[0]; let url = message.content.slice( settings.prefix.length + command.length + 1, message.content.length ); let guildQueue = client.player.getQueue(message.guild.id); if (command === "play") { let queue = client.player.createQueue(message.guild.id); message.channel.send('Playing `' + url +'` ...'); await queue.join(message.member.voice.channel); let song = await queue.play(url).catch((err) => { if (!guildQueue) queue.stop(); }); } if (command === "skip") { if (guildQueue) guildQueue.skip(); } if (command === "stop") { if (guildQueue) guildQueue.stop(); } if (command === "removeLoop") { if (guildQueue) guildQueue.setRepeatMode(RepeatMode.DISABLED); // or 0 instead of RepeatMode.DISABLED } if (command === "toggleLoop") { if (guildQueue) guildQueue.setRepeatMode(RepeatMode.SONG); // or 1 instead of RepeatMode.SONG } if (command === "toggleQueueLoop") { if (guildQueue) guildQueue.setRepeatMode(RepeatMode.QUEUE); // or 2 instead of RepeatMode.QUEUE } if (command === "setVolume") { if (guildQueue) guildQueue.setVolume(parseInt(args[0])); } if (command === "seek") { if (guildQueue) guildQueue.seek(parseInt(args[0]) * 1000); } if (command === "clearQueue") { if (guildQueue) guildQueue.clearQueue(); } if (command === "shuffle") { if (guildQueue) guildQueue.shuffle(); } if (command === "pause") { if (guildQueue) guildQueue.setPaused(true); } if (command === "resume") { if (guildQueue) guildQueue.setPaused(false); } if (command === "remove") { if (guildQueue) guildQueue.remove(parseInt(args[0])); } if (command === "createProgressBar") { const ProgressBar = guildQueue.createProgressBar(); } if (command === "move") { if (guildQueue) guildQueue.move(parseInt(args[0]), parseInt(args[1])); } }); client.login(settings.token);
Затем вернитесь на страницу разработчика бота Discord и сбросьте свой токен.
Меняем токен бота в коде на свой токен
Затем выполняется раздел кода
Теперь мы собираемся сгенерировать URL-адрес для присоединения к нашему серверу Discord.
И вот ваш сгенерированный URL!
Добавьте бота на один из ваших серверов, а затем присоединитесь к музыкальной комнате.
Запустите бота с этим кодом => узел index.js
Тогда наслаждайтесь своим музыкальным ботом Discord!
Вот пример этого бота =› Discordjs-Music-Bot
Спасибо, что читаете блог!