Cannot leave voice channel - javascript

My bot cannot leave a voicechannel, but it can join in anyone. I have 2 codes, one is "leave" and the other one is "stopstream", It said " Cannot read property 'channelID' of undefined" and "(node:11416) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'voiceChannel' of undefined" with one complex code
I tried to use different code, one more complex than the other. And put "const ytdl = require('ytdl-core');
const streamOptions = { seek: 0, volume: 1 };" in the complex one.
//leave
const ytdl = require('ytdl-core');
const streamOptions = { seek: 0, volume: 1 };
exports.run = async (client, message, args, ops) => {
if (!message.member.voiceChannel) return message.channel.send('Please connect to a voice chanel, don\'t be afraid my child. Share you beautiful voice.');
if (!message.guild.mne.voiceChannel) return message.channel.send('Sorry, I\'m not connected to the guild.');
if (message.guild.me.voiceChannelID !== message.member.voiceChannelID) return message.chanel.send('Sorry, you aren\t connected to the same channel, I\'ll give you some PeterFriffinCoins, for free.');
message.guild.me.voiceChannel.leave();
message.channel.send('Leaving Channel... I\'m a free elf...')
}
//stopstream
exports.run = (client, message, args) => {
client.leaveVoiceChannel(message.member.voiceState.channelID);
message.channel.send('Thanks for tuning in!');
}

Try this in leave channel command
let authorVoiceChannel = message.member.voiceChannel;
if(!authorVoiceChannel) return message.channel.send("You are not in a voice channel")
if(authorVoiceChannel.id !== client.voiceChannel.id) return message.channel.send("We're not in the same voice channel")
authorVoiceChannel.leave()
message.channel.send("I left voice channel")

Related

Discord.js Dev detector

I am making a discord bot and I have a few dev only commands. However, the system I use to detect if someone is a bot developer doesn't work.
My code:
const { MessageEmbed } = require("discord.js");
exports.execute = async (client, message, args) => {
if (!client.config.admins.includes(message.author.id)) return message.channel.send("Slow down, poke. This is devs only, poke?"); // return if author isn't bot owner
let user = message.mentions.users.first();
if (!user) return message.channel.send("Send money to who?");
let amount = args[1];
if (!amount || isNaN(amount)) return message.reply("That isn't a valid amount.");
let data = client.eco.addMoney(user.id, parseInt(amount));
const embed = new MessageEmbed()
.setTitle(`You'll be rich! The money has been added.`)
.addField(`User`, `<#${data.user}>`)
.addField(`Balance Given`, `${data.amount} 💸`)
.addField(`Total Amount`, data.after)
.setColor("#f54242")
.setThumbnail(user.displayAvatarURL)
.setTimestamp();
return message.channel.send(embed);
}
exports.help = {
name: "addmoney",
aliases: ["addbal"],
usage: `addmoney #user <amount>`
}
I shouldn't have received the devs only message, but when I tested in discord, I did.
Thought I'd just make this an answer than a comment, as I've had time to test.
This works, but it may be related to how you store your IDs in the admin array.
.includes() is type sensitive, so a string wont match a number. Discord IDs are a string, so your array has to match it.
Example:
const admins = [96876194712018944];
console.log(admins.includes("96876194712018944")); // false

Discord.js Ban Command with Command Handler

I made a Discord.js Ban Command with reason and stuff however i overcome an error whenever i try to use it. Here is my code :
const { MessageEmbed } = require('discord.js');
module.exports = {
name: 'ban',
description: 'Ban a user from the server by using mentioning them!',
guildOnly: true,
aliases: ['ban', 'banbanban'],
usage: `-ban <USER_MENTION> <OPTIONAL_REASON>`,
cooldown: 5,
async execute(message, args, client) {
const daidinevermantion = new MessageEmbed()
daidinevermantion.setTitle('Incorrect arguments provided!')
daidinevermantion.setDescription('Please Mention a user to ban ;-;. Make sure it a mention. The bot may not be able to ban users not in the server')
daidinevermantion.addField('Usage','``;ban <USER_MENTION> <OPTIONAL REASON>``')
daidinevermantion.addField('Example Usage', ';ban <#760773438775492610> Good Bot')
if(!message.member.hasPermission("BAN_MEMBERS")) return message.channel.send('You can\'t use that!')
if(!message.guild.me.hasPermission("BAN_MEMBERS")) return message.channel.send('I don\'t have the right permissions.')
const member = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if(!args[0]) return message.channel.send(daidinevermantion);
if(!member) return message.channel.send('Can\'t seem to find this user. Sorry \'bout that :/. Make sure you are mentioning the user and the user is in the server!');
if(!member.bannable) return message.channel.send('This user can\'t be banned. It is either because they are a mod/admin, or their highest role is higher than mine');
if(member.id === message.author.id) return message.channel.send('Bruh, you can\'t ban yourself!');
let reason = args.slice(1).join(" ");
if(!reason) reason = 'Unspecified';
member.ban({ days: 7, reason: reason }).catch(err => {
message.channel.send('Something went wrong')
console.log(err)
})
const banembed = new Discord.MessageEmbed()
.setTitle('Member Banned')
.setThumbnail(member.user.displayAvatarURL())
.addField('User Banned', member)
.addField('Banned by', message.author)
.addField('Reason', reason)
.setFooter('Banned On:', client.user.displayAvatarURL())
.setTimestamp()
message.channel.send(banembed);
}
}
Here whenever i send this command I this message in return "This user can't be banned. It is either because they are a mod/admin, or their highest role is higher than mine" regardless of whatever the case is whether its position is higher or lower. I'm a bit new to Discord.js please help me out thanks a lot!
You are getting that message because member.bannable is always false, and the reason for that is your bot doesn't have the required permissions to ban a user. Use this permission calculator and reinvite the bot to the server with required permissions i.e "Ban Members" or "Administrator".

Need Assistance With My unmute command for discord.js

Basically This command is giving one major issue and that the fact that when the user is muted he won't be unmuted because of the command not responding back to the mute command
const Discord = require('discord.js');
const fs = module.require('fs');
module.exports.run = async (client, message, args) => {
if (!message.member.hasPermission('MANAGE_MESSAGES')) return;
let unMute = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if (!unMute) {
let exampleEmbed = new Discord.MessageEmbed()
.setDescription("__UNMUTE INFO__")
.setColor(client.colors.success)
.setThumbnail(client.user.displayAvatarURL())
.addField(`Unmute Command`, `Unmutes a mentioned user.`)
.addField(`Unmute Command`, `Unmutes User By Id.`)
.addField("Example", `${client.config.prefix}Unmutes #user`)
.addField("Example", `${client.config.prefix}Unmutes #id`)
message.channel.send(exampleEmbed);
return;
}
let role = message.guild.roles.cache.find(r => r.name === 'Muted');
message.channel.send(`Please Check roles to be sure user was unmuted`);
if (!role || !unMute.roles.cache.has(role.id)) return message.channel.send(`That user is not muted.`);
if (!role || !unMute.roles.cache.has(User.id)) return message.channel.send(`----`);
let guild = message.guild.id;
let member = client.mutes[unMute.id];
if (member) {
if (member === message.guild.id) {
delete client.mutes[unMute.id];
fs.writeFile("./mutes.json", JSON.stringify(client.mutes), err => {
if (err) throw err;
})
await unMute.roles.remove(role.id);
message.channel.send(`:white_check_mark: ${unMute} Has been unmuted.`);
}
return;
}
await unMute.roles.remove(role.id);
message.channel.send(`:white_check_mark: ${unMute} Has been unmuted.`);
message.delete();
}
module.exports.config = {
name: 'unmute',
description: 'Unmute a user.',
access: 'Manage Messages Permission',
usage: 'unmute #vision'
}
I'm Also getting an error message when manually unmuting the user
(node:6604) UnhandledPromiseRejectionWarning: ReferenceError: User is not defined
Any Form of help would be greatly appreciated and thank you for your time.
On the line if (!role || !unMute.roles.cache.has(User.id)) return message.channel.send('----'), you reference the variable User, but you haven't definied it anywhere, and even if it was defined, you need a role not a member or user. I'm pretty sure it should instead be Role.id. Also, not 100% sure on this, but I tnink it should just be Role not Role.id.

Temporary mute command returning error 'Cannot read property 'slice' of undefined'

I am trying to create a temporary mute command, that will unmute the muted user in the given time.
Here's my code:
const Discord = require("discord.js");
const ms = require("ms");
module.exports = {
name: 'mute',
description: 'mute a specific user',
usage: '[tagged user] [mute time]',
async execute(message, embed, args) {
let tomute = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[0]));
if (!tomute) return message.reply("Couldn't find user.");
const reason = args.slice(1).join(' ');
if (tomute.hasPermission("MANAGE_MESSAGES")) return message.reply("Can't mute them!");
const muterole = message.guild.roles.cache.find(muterole => muterole.name === "muted");
if (!muterole) {
try {
muterole = await message.guild.roles.create({
name: "muted",
color: "#000000",
permissions: []
})
message.guild.channels.cache.forEach(async (channel, id) => {
await channel.overwritePermissions(muterole, {
SEND_MESSAGES: false,
ADD_REACTIONS: false
});
});
} catch (e) {
console.log(e.stack);
}
}
const mutetime = args.slice(2).join(' ');
//here is the start of the error
await (tomute.roles.add(muterole.id));
message.reply(`<#${tomute.id}> has been muted for ${ms(ms(mutetime))} `);
setTimeout(function() {
tomute.roles.remove(muterole.id);
message.channel.send(`<#${tomute.id}> has been unmuted!`);
}, ms(mutetime));
}
}
Currently getting the following error: Cannot read property 'slice' of undefined
Do you have any idea on how to fix the command?
edit
this after a year and this is for future people who come here
the issue was here
async execute(message, embed, args) {
i never passed embed from my main file so args was undefined
embed part was where the args should have been, I was stupid at that time and was new to coding, but as I now have some experience, I decided to edit this to show what wrong
It means that somewhere in your code, you have a value which is undefined and you try to use the string/array function slice on it but undefined does not have this function : so it is a error.

How do I fix this to add a role mentioned in the command to the user?

I am coding a custom discord bot for my server and I ran into this issue. I want to add a role to a user that is not predefined. IE: I want to be able to &addrole #user anyrole and add that role to a user. Here is the code:
const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
//!addrole #andrew anyrole
if(!message.member.hasPermission("MANAGE_MEMBERS")) return
message.reply("Sorry pal, you can't do that.");
let rMember = message.guild.member(message.mentions.users.first()) ||
message.guild.members.get(args[0]);
if(!rMember) return message.reply("Couldn't find that user, yo.");
let role = args.join(" ").slice(22);
if(!role) return message.reply("Specify a role!");
let gRole = message.guild.roles.find('name', any);
if(!gRole) return message.reply("Couldn't find that role.");
if(rMember.roles.has(gRole.id)) return message.reply("They already have
that role.");
await(rMember.addRole(gRole.id));
try{
await rMember.send(`Congrats, you have been given the role
${gRole.name}`)
}catch(e){
message.channel.send(`Congrats to <#${rMember.id}>, they have been given
the role ${gRole.name}. We tried to DM them, but their DMs are locked.`)
}
}
module.exports.help = {
name: "addrole"
}

Categories

Resources