How do I stop playing bot music? (Discord.js) - discord

This code is for playing music, and I want to have a stop command on my bot. Could you help me?
const Discord = require("discord.js");
const client = new Discord.Client();
const config = require("./config.json")
const ytdl = require("ytdl-core")
const streamOptions = {seek:0, volume:1}
client.on("message", async message => {
if(message.author.bot) return
if(message.channel.type === "dm") return
if(!message.content.startsWith(config.prefix)) return
const args = message.content.slice(config.prefix.length).trim().split(/ +/g)
const comando = args.shift().toLocaleLowerCase()
if(comando === "play") {
var voiceChannel = message.guild.channels.cache.get("733122593019789314")
let file = args[0]
if(voiceChannel == null) {
console.log("Canal não encontrado.")
}
if(voiceChannel != null) {
console.log("Canal encontrado.")
await voiceChannel.join().then(connection => {
const stream = ytdl(file, {filter:"audioonly", quality:"highestaudio"})
const DJ = connection.play(stream, streamOptions)
DJ.on("end", end => {
voiceChannel.leave()
})
}).catch(console.error)
}
}/* I was trying to do the command this way:
else if(comando === "stop") {
voiceChannel.leave()
}*/
}
client.login(config.token);
Everything works, I just want to stop the music.
(I'm Brazilian, some words or sentences may be wrong.)
Thank you for your help! 😁

You can use StreamDispatcher.pause() and StreamDispatcher.resume().
Your StreamDispatcher is defined as DJ, so you can use:
DJ.pause(); // Pauses the stream.
DJ.resume(); // Resumes the stream.
DJ.destroy(); // Ends the stream.

Related

How do give only person that write i an specific discord channel xp

Here is the Code. I only want to give members xp when they write in a specific discord channel. How can i do that?
client.on('messageCreate', async message => {
if (!message.guild) return;
if (message.author.bot) return;
const prefix = '?'
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
const user = await Levels.fetch(message.author.id, message.guild.id);
if (!message.guild) return;
if (message.author.bot) return;
const randomAmountOfXp = Math.floor(Math.random() * 29) + 1; // Min 1, Max 30
const hasLeveledUp = await Levels.appendXp(message.author.id, message.guild.id, randomAmountOfXp);
if (hasLeveledUp) {
const user = await Levels.fetch(message.author.id, message.guild.id);
message.channel.send({ content: `${message.author}, congratulations! You have leveled up to **${user.level}**. :tada:` });
}
if (user.level === 5) {
message.member.roles.add("1022876270754791445");
} else if (user.level === 10) {
message.member.roles.add("1022876505132499054");
}else if (user.level === 10) {
message.member.roles.remove("1022876270754791445");
}
});
You can check message's channel id when event triggered.
if (message.channel.id !== "CHANNEL_ID") return;

How to create an embedded Queue list for discord bot the updates

I am making a discord bot that plays music. Currently, the embedded list works fine and every time I add a song to the queue, the list deletes itself and creates a new embedded queue list updated with the new song. However, I can't figure out how to make this queue list update itself when I use the skip button I have implemented (I'm new to programming).
Example of how it works now:
Pressing the button skips the song, but as stated before, how would I refresh the list every time I press the button?
const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
process.setMaxListeners(1000000000000);
const { MessageEmbed } = require('discord.js');
ffmpeg_options = {
'options': '-vn',
"before_options": "-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5"
}
//Global queue for your bot. Every server will have a key and value pair in this map. { guild.id, queue_constructor{} }
const queue = new Map();
module.exports = {
name: 'play',
aliases: ['skip', 'stop'], //We are using aliases to run the skip and stop command follow this tutorial if lost: https://www.youtube.com/watch?v=QBUJ3cdofqc
cooldown: 0,
description: 'Advanced music bot',
async execute(message, args, cmd, button, skip, client, Discord){
//Checking for the voicechannel and permissions (you can add more permissions if you like).
const voice_channel = message.member.voice.channel;
if (!voice_channel) return message.channel.send('You need to be in a channel to execute this command!');
const permissions = voice_channel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT')) return message.channel.send('You dont have the correct permissions.');
if (!permissions.has('SPEAK')) return message.channel.send('You dont have the correct permissions.');
//This is our server queue. We are getting this server queue from the global queue.
const server_queue = queue.get(message.guild.id);
let checker = false;
if (cmd === 'stop' && !server_queue){
return message.channel.send("The bot is not in the channel, you dont have to stop him.");
}
//If the user has used the play command
if (cmd === 'stop') stop_song(message, server_queue);
else if(skip === true) {
skip_song(message, server_queue);
}
else if (cmd === message.content){
//if (!args.length) return message.channel.send('You need to send the second argument!');
let song = {};
//If the first argument is a link. Set the song object to have two keys. Title and URl.
if (ytdl.validateURL(args[0])) {
const song_info = await ytdl.getInfo(args[0]);
song = { title: song_info.videoDetails.title, url: song_info.videoDetails.video_url }
message.delete({ timeout:1000 })
} else {
//If there was no link, we use keywords to search for a video. Set the song object to have two keys. Title and URl.
const video_finder = async (query) =>{
const video_result = await ytSearch(query);
return (video_result.videos.length > 1) ? video_result.videos[0] : null;
}
const video = await video_finder(args.join(' '));
if (video){
song = { title: video.title, url: video.url }
} else {
message.channel.send('Error finding video.');
}
message.delete({ timeout:1000 })
}
if (skip === true && server_queue) {
}
//If the server queue does not exist (which doesn't for the first video queued) then create a constructor to be added to our global queue.
if (!server_queue){
const queue_constructor = {
voice_channel: voice_channel,
text_channel: message.channel,
connection: null,
songs: []
}
//Add our key and value pair into the global queue. We then use this to get our server queue.
queue.set(message.guild.id, queue_constructor);
queue_constructor.songs.push(song);
//Establish a connection and play the song with the vide_player function.
try {
const connection = await voice_channel.join();
queue_constructor.connection = connection;
video_player(message.guild, queue_constructor.songs[0]);
} catch (err) {
queue.delete(message.guild.id);
message.channel.send('There was an error connecting!');
throw err;
}
} else {
server_queue.songs.push(song);
message.channel.bulkDelete(2)
.then(messages => console.log(`Bulk deleted ${messages.size} messages`))
.catch(console.error);
//where I actually make the embeded queue list
const queueList = server_queue.songs.map((song, i) => `[${++i}] - ${song.title}`);
const queueEmbed = new MessageEmbed()
.setDescription(queueList);
return message.channel.send(queueEmbed, button);
}
}
}
}
const video_player = async (guild, song) => {
const song_queue = queue.get(guild.id);
//If no song is left in the server queue. Leave the voice channel and delete the key and value pair from the global queue.
if (!song) {
song_queue.voice_channel.leave();
queue.delete(guild.id);
return;
}
const stream = ytdl(song.url, { filter: 'audioonly' });
song_queue.connection.play(stream, { seek: 0, volume: 0.5 })
.on('finish', () => {
song_queue.songs.shift();
video_player(guild, song_queue.songs[0]);
});
//await song_queue.text_channel.send(`🎶 Now playing **${song.title}**`)
}
const skip_song = (message, server_queue) => {
if (!message.member.voice.channel) return message.channel.send('You need to be in a channel to execute this command!');
if(!server_queue){
return message.channel.send(`There are no songs in queue 😔`,);
}
server_queue.connection.dispatcher.end();
//message.delete({ timeout:20000})
}
const stop_song = (message, server_queue) => {
if (!message.member.voice.channel) return message.channel.send('You need to be in a channel to execute this command!');
server_queue.songs = [];
server_queue.connection.dispatcher.end();
//message.delete({ timeout:20000})
}
return message.channel.send(queueEmbed, button);
That line above returns a Promise which resolves to a Message object. Change it to something like this:
const embeddedMessage = await message.channel.send(queueEmbed, button);
return embeddedMessage;
So when a user clicks the skip button you can simply call
embeddedMessage.edit(your_new_embed, button)

How to make a say embed command in Discord.js

I'm new to coding and am making a Discord bot for a friend. They are requesting a say command that could act as a confession command where it would look like this. An embed with a set Title, set color, and completely anonymous but with an editable description that would fill in with what they want to confess. As i'm new to coding I don't know how to do this. If anyone can help that would be really appreciated! Thank you!
(Edit) I realise that i wasn't through enough about what the code was so im making an edit with my main.js code.
const client = new Discord.Client();
const prefix = 'wtf ';
const fs = require('fs');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for(const file of commandFiles){
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
bot.once('ready', () => {
console.log('Tomoko is online!');
});
bot.on('message', async msg =>{
if(!msg.content.startsWith(prefix) || msg.author.bot) return;
const args = msg.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if(command === 'ping'){
client.commands.get('ping').execute(msg, args, Discord);
} else if (command === 'creator'){
client.commands.get('creator').execute(msg, args, Discord);
} else if (command === 'help'){
client.commands.get('help').execute(msg, args, Discord);
} else if (command === 'kick'){
client.commands.get('kick').execute(msg, args, Discord);
} else if (command === 'ban'){
client.commands.get('ban').execute(msg, args, Discord);
} else if (command === 'mute'){
client.commands.get('mute').execute(msg, args, Discord);
} else if (command === 'unmute'){
client.commands.get('unmute').execute(msg, args, Discord);
} else if (command === 'warn'){
client.commands.get('warn').execute(msg, args)
} else if (command === 'deletewarns'){
client.commands.get('deletewarns').execute(msg, args);
} else if (command === 'warnings'){
client.commands.get('warnings').execute(msg, args);
} if (args[0].toLowerCase() === 'confess') {
const description = args.splice(1).join(" ");
const embed = new MessageEmbed().setTitle('✦┊‧๑ ꒰<a:ccc:862524564457390150><a:ooo:862524674185101322><a:nnn:862524667368833024><a:fff:862524592202973244><a:eee:862524583802568714><a:sss:862524709782683648><a:sss:862524709782683648>꒱ ‧๑┊✧').setColor('ffaaaa').setDescription(description);
await msg.delete().catch(e => console.log(e));
msg.channel.send(embed);
} else if (command === "unban"){
client.commands.get('unban').execute(msg, args, Discord);
;}
});
client.login('DAMN YOU WISH I WOULD SHOW YOU');
So if possible can anyone give me the advanced command handler say embed command. Thank you!!
That depends on how you handle your commands. But in general: generate a new embed, and set the description to the contents of your message.
Check here on how to create an embed.
A simple bot to do your job
// importing dependencies
const { MessageEmbed, Client } = require('discord.js');
const prefix = '!';
const bot = new Client(); // init discord client
bot.on('ready', () => console.log('yee im on'));
// listening for messages
bot.on('message', async msg => {
if (!msg.content.startsWith(prefix)) return // dont run if the prefix is not used
const args = msg.content.substring(prefix.length).split(" "); // creating array of the message contents
if (args[0].toLowerCase() === 'say') { // a simple command handler
const description = args.splice(1).join(" ");
const embed = new MessageEmbed().setDescription(description); // setTitle and stuff according to your preference
await msg.delete().catch(e => console.log(e)); // deleting the user message since it should be anonymous
msg.channel.send(embed);
}
});
bot.login('yourtokenhere');
Make sure to replace token and prefix with your token and prefix
How to run the command :
!say ooh this is a confession

Prefix is changing

So in my config.json file I had put my prefix as "!". I was testing the bot in my friends server and the prefix was clashing with other bots. I changed it to ";". But now both the prefixs are functioning "!" and";". I saved all my files and restarted node too, but the commands are still responding to "!". Am I missing something?
The structure of my file system is -
1. index.js
2. config.json
3. commands folder (command files)
index.js
const Discord = require('discord.js');
const fs = require('fs');
const { prefix, token } = require('./config.json');
const profanity = require('profanities')
//console.log(profanity);
const client = new Discord.Client();
const cooldowns = new Discord.Collection();
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js')); //returns an array of all file anmes in a dir ['ping.js', beep.js, ....]; the filter is used to get only .js files.
const commandFiles_mod = fs.readdirSync('./commands/mod').filter(file => file.endsWith('.js')); //mod folder
const commandFiles_info = fs.readdirSync('./commands/info').filter(file => file.endsWith('.js')); //info folder
const commandFiles_extras = fs.readdirSync('./commands/extras').filter(file => file.endsWith('.js')); //
//file system
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
// set a new item in the Collection
// with the key as the command name and the value as the exported module
client.commands.set(command.name, command); //set takes the file name and the path to the file. //command is the path to file and command.name is the name of the file
}
for (const file of commandFiles_info) {
const command1 = require(`./commands/info/${file}`);
client.commands.set(command1.name, command1);
}
for (const file of commandFiles_mod) {
const command2 = require(`./commands/mod/${file}`);
client.commands.set(command2.name, command2);
}
for (const file of commandFiles_extras) {
const command3 = require(`./commands/extras/${file}`);
client.commands.set(command3.name, command3);
}
client.once('ready', () => {
client.user.setActivity(`${prefix}help`)
console.log(`Hello! ${client.user.username}-bot is now online!`)
});
client.on('message', message => {
//command handling
if (message.content === 'galaxy-prefix') {
const prefix_embed = new Discord.MessageEmbed()
.setTitle('Prefix')
.setDescription(`Use this ahead of comamnds for usage: **${prefix}**`)
.setColor('RANDOM')
.setTimestamp()
message.channel.send(prefix_embed);
}
if (message.content.startsWith(prefix) || !message.author.bot || !message.channel.type === 'dm') { //edit here
const args = message.content.slice(prefix.length).split(/ +/); //caveats
//console.log(args);
const messageArray = message.content.split(/ +/);
//console.log(messageArray);
const cmd = args[1];
//console.log(cmd);
const commandName = args.shift().toLowerCase();
//console.log(commandName);
/*if (!message.content.startsWith(prefix) && !message.author.bot) {
const messageArray = message.content.split(" ");
console.log(messageArray);
}*/
/*for (i=0; i < profanity.length; i++) {
if (messageArray.includes(profanity[i])) {
message.delete();
break;
}
}*/
const command = client.commands.get(commandName) || client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName)); //aliases
if (!command) return;
if (command.guildOnly && message.channel.type !== 'text') {
return message.reply('I can\'t execute that command inside DMs!'); //cannot dm this command
}
if (command.args && !args.length) {
let reply = `You didn't provide any arguments, ${message.author}!`;
if (command.usage) {
reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``; //usage check, in file as usage: '<...>'
}
return message.channel.send(reply);
}
if (!cooldowns.has(command.name)) { //cooldown
cooldowns.set(command.name, new Discord.Collection());
}
const now = Date.now();
//console.log(now);
const timestamps = cooldowns.get(command.name); // gets the collection for the triggered command
const cooldownAmount = (command.cooldown || 3) * 1000; //3 is default cooldown time, if cooldown isnt set in command files.
if (timestamps.has(message.author.id)) {
if (timestamps.has(message.author.id)) {
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
return message.reply(`please wait ${timeLeft.toFixed(1)} more second(s) before reusing the \`${command.name}\` command.`);
}
}
}
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
try {
command.execute(client, message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
}
});
client.on('shardError', error => {
console.error('A websocket connection encountered an error:', error);
});
process.on('unhandledRejection', error => {
console.error('Unhandled promise rejection:', error);
});
client.login(token);
config.json
{
"token": " ................. ",
"prefix": ";"
}
Your bot will respond to anything actually...
if (message.content.startsWith(prefix) || !message.author.bot || !message.channel.type === 'dm')
This means your bot will run if the message starts with the prefix OR the sender is not a bot OR the channel type is DM. You should try using ? - .... They will probs work too.
To use an and you use && instead of ||

Discord.js command handler problems

I've been trying to fix a command handler for 3 hours now, but anytime I try to add a custom command nothing happens. It loads the command, but when the command is run it does nothing. Here's some code:
index.js:
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
console.log(`[LOG] Loaded command ${file}`);
client.commands.set(command.name, command);
}
commands/kick.js:
const fs = require('fs');
var moment = require('moment');
var logger = fs.createWriteStream(`./logs/${moment().format('MM-DD-YYYY')}.log`, {
flags: 'a'
});
module.exports = {
name: "kick",
category: "moderation",
description: "Kicks the mentioned user.",
usage: "<imputs>",
run: (client, message, args) => {
let reason = args.slice(1).join(' ');
let user = message.mentions.users.first();
if (message.mentions.users.size < 1) return message.reply('You must mention someone to kick them.').then(msg => { msg.delete(10000) }).catch(console.error);
if (user.id === message.author.id) return message.reply("You cannot kick yourself.").then(msg => { msg.delete(10000) });
if (user.id === client.user.id) return message.reply("You cannot kick me.").then(msg => { msg.delete(10000) });
if (!message.member.hasPermission("KICK_MEMBERS")) return message.reply("You don't have the **Kick Members** permission!").then(msg => { msg.delete(10000) });
if (reason.length < 1) reason = 'No reason supplied';
if (!message.guild.member(user).kickable) return message.reply('I could not kick that member').then(msg => { msg.delete(10000) });
message.delete();
message.guild.member(user).kick();
const embed = new Discord.RichEmbed()
.setColor(0x0000FF)
.setTimestamp()
.addField('Action:', 'Kick')
.addField('User:', `${user.username}#${user.discriminator} (${user.id})`)
.addField('Moderator:', `${message.author.username}#${message.author.discriminator}`)
.addField('Reason', reason)
.setFooter(`© NetSync by Towncraft Developers`);
let logchannel = message.guild.channels.find('name', 'logs');
if (!logchannel){
message.channel.send(`Successfully kicked ${user.username}#${user.discriminator}.`).then(msg => { msg.delete(10000) });
logger.log(`[LOG] [KICK] ${user.username}#${user.discriminator} (${user.id}) was kicked by ${message.author.username}#${message.author.discriminator}.`);
}else{
message.channel.send(`Successfully kicked ${user.username}#${user.discriminator}. I\'ve also logged the kick in <#${logchannel.id}>.`).then(msg => { msg.delete(10000) });
client.channels.get(logchannel.id).send({embed});
}
if(user.bot) return;
return message.mentions.users.first().send({embed}).catch(e =>{
if(e) return
});
}
}
Like I said, been trying to do this for 3 hours now, and I'm stumped. If someone could tell me what I did wrong that'd be awesome, thanks.
You need execute command in you main.js file on bot.on('message' block.
Like this:
client.on('message', message => {
if (message.channel.type === "dm") return;
let prefix = '!'
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
let args = messageArray.slice(1);
if (!message.content.startsWith(prefix)) return;
let commandfile = client.commands.get(cmd.slice(prefix.length));
if (commandfile) commandfile.run(client, message, args, botconfig);
})

Resources