Error wtf UnMute Command: Cannot read property 'id' of undefined - node.js

const { MessageEmbed } = require("discord.js");
module.exports = {
name: 'unmute',
async execute (client, message, args) {
let user = message.guild.member(message.mentions.users.first());
let muteRole = message.guild.roles.cache.find(r => r.name === 'Muted');
if (!user.roles.cache.has(muteRole.id)) return message.reply("Is not Muted");
user.roles.remove(muteRole.id);
}
};
This code worked 2 weeks ago and now there is a bug, please help me!

It seems that there isn't any Muted role. The error clearly says Cannot find 'id' of undefined, and the only place I see .id used is on the Muted role.
Just saying, you also need to say where the console says the error is. Just saying, "This is the error" doesn't help.
You may want to use this:
const { MessageEmbed } = require("discord.js")
module.exports = {
name: 'unmute',
async execute(message, args) {
var user_to_mute = message.mentions.user.first()
.catch(err) {
console.error(err)
return message.reply("Could not find user in cache!")
}
var muted_role = message.guild.roles.cache.find(x => x.name == "Muted")
.catch(err) {
console.error(err)
return message.reply("Could not find role in cache!")
}
if (user_to_mute.has(muted_role)) return message.reply("User isn't muted!")
user_to_mute.removeRole(muted_role).catch(console.error)
}
};

Related

Play discord command

Hello I have been having a problem with a play command with discord. I am unsure of what the problem is and if it is possible please help. I will be honest I got this code from somewhere else but its for a private server. Please help fix this thank you. Anyway I have been trying to create a play, stop, skip, nowplaying command for ages and if this works it would be amazing thank you.
Console Error:
TypeError: Cannot read property 'get' of undefined
Code:
const ytdl = require("ytdl-core");
module.exports = {
name: "play",
description: "Play a song in your channel!",
async execute(message) {
try {
const args = message.content.split(" ");
const queue = message.client.queue;
const serverQueue = message.client.queue.get(message.guild.id);
const voiceChannel = message.member.voice.channel;
if (!voiceChannel)
return message.channel.send(
"You need to be in a voice channel to play music!"
);
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has("CONNECT") || !permissions.has("SPEAK")) {
return message.channel.send(
"I need the permissions to join and speak in your voice channel!"
);
}
const songInfo = await ytdl.getInfo(args[1]);
const song = {
title: songInfo.videoDetails.title,
url: songInfo.videoDetails.video_url
};
if (!serverQueue) {
const queueContruct = {
textChannel: message.channel,
voiceChannel: voiceChannel,
connection: null,
songs: [],
volume: 5,
playing: true
};
queue.set(message.guild.id, queueContruct);
queueContruct.songs.push(song);
try {
var connection = await voiceChannel.join();
queueContruct.connection = connection;
this.play(message, queueContruct.songs[0]);
} catch (err) {
console.log(err);
queue.delete(message.guild.id);
return message.channel.send(err);
}
} else {
serverQueue.songs.push(song);
return message.channel.send(
`${song.title} has been added to the queue!`
);
}
} catch (error) {
console.log(error);
message.channel.send(error.message);
}
},
play(message, song) {
const queue = message.client.queue;
const guild = message.guild;
const serverQueue = queue.get(message.guild.id);
if (!song) {
serverQueue.voiceChannel.leave();
queue.delete(guild.id);
return;
}
const dispatcher = serverQueue.connection
.play(ytdl(song.url))
.on("finish", () => {
serverQueue.songs.shift();
this.play(message, serverQueue.songs[0]);
})
.on("error", error => console.error(error));
dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
serverQueue.textChannel.send(`Start playing: **${song.title}**`);
}
};
You should look where you got the code from, maybe you missed a part?
specifically where they define client.queue
usually most of the people define it like
client.queue = new Map()
or discord.js collection class (Extended from map)
in your main bot file (index.js, bot.js etc).
You could either check where you got code from or try adding this to where you define client in your main bot file

Discord.js TypeError: Cannot read property 'prefix' of undefined

I get the following error...
Error: connect ECONNREFUSED 127.0.0.1:5432
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16)
(node:8232) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'prefix' of undefined
When using a command from my bot. I think the issue is with the bot's main file.
The following code block is where I believe the error is coming from.
function startsWithPrefix(str, prefix) { if (str.slice(0, prefix.length).toLowerCase() == prefix.toLowerCase()) return true; }
// Execute when the bot sees a message
client.on('message', async msg => {
// Initialize guild settings on first message
if (msg.guild && !Settings[msg.guild.id]) {
const pool = new Pool();
try {
const res = await pool.query('SELECT prefix FROM settings WHERE guild_id = $1', [msg.guild.id]);
if (res.rows[0]) { Settings[msg.guild.id] = res.rows[0]; }
else {
Settings[msg.guild.id] = {
prefix: 'a!' // Default setting
};
}
} catch (err) { console.log(err.stack); }
finally { pool.end(); }
}
// Exit if msg doesn't start with prefix
if (msg.guild && !startsWithPrefix(msg.content, Settings[msg.guild.id].prefix)) { return; }
// Exit if msg was sent by a bot
if (msg.author.bot) { return; }
// Exit + Reply with a helpful message if msg was dm-ed to this bot
if (msg.channel.type == 'dm') { return await msg.reply(`I got nothin' for ya buddy :pensive:\nI think you meant to type that in the **Among Us LFG** server :+1:`); }
// Separate the command from the arguments
const words = msg.content.split(' ');
const cmdName = words[0].toLowerCase().slice(Settings[msg.guild.id].prefix.length);
const cmd = client.cmds.get(cmdName) || client.cmds.get(client.aliases.get(cmdName));
const args = words.slice(1);
// Run the command
if (cmd) cmd.run(client, msg, args);
});
// Start the bot
client.login(discordToken);
EDIT: seems like Settings[msg.guild.id] is undefined, However I define it as
let Settings = {};
exports.Settings = Settings;
at the start of the code dunno whats wrong
I think you can try to define the prefix with a const like this:
const prefix = '!'

Discord.js Per Server Prefix Error "TypeError: Cannot read property 'ID' of null"

Hi i was making a per server prefix thing for my discord.js v12 bot using quick.db everything was going well but when using a command it throws this error
C:\Users\Aoshey\Desktop\Taco Bot V2\tacobot.js:50
let prefix = db.get(`prefix_${message.guild.ID}`);
^
TypeError: Cannot read property 'ID' of null
i don't quite understand since i'm new to coding so sorry if it was something stupid
the main bot file's code:
client.on('message', message => {
let prefix = db.get(`prefix_${message.guild.ID}`);
if(prefix === null) prefix = default_prefix;
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName)
|| client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
if (!command) return;
if (command.guildOnly && message.channel.type === 'dm') {
return message.reply('I can\'t execute that command inside DMs!');
}
if (command.args && !args.length) {
let reply = `${message.author}, wrong usage`;
if (command.usage) {
reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
}
return message.channel.send(reply);
}
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command! Please tell Aro#1221 about this.');
}
});
i noticed that the error only occurs when its used on only 1 command meanwhile other commands work well (also yes i'm using the command in a guild)
the code for the command which causes the error i think?
const fsn = require("fs-nextra");
const colors = require("colors");
module.exports = {
name: 'deleteorder',
description: 'deleting/denying an order.',
args: 'true',
usage: '<order id> <reason>',
aliases: ['od', 'delorder', 'do'],
execute(message, args) {
if (message.member.roles.cache.find(r => r.id === '745410836901789749')) {
let ticketID = args[0];
let reason = args[1];
fsn.readJSON("./orders.json").then((orderDB) => {
const order = orderDB[ticketID];
if(order === undefined) {
message.reply(`Couldn't find order \`${args[0]}\` Try again.`);
return;
}
if(reason === "") {
reason = "None Provided";
}
delete orderDB[ticketID];
fsn.writeJSON("./orders.json", orderDB, {
replacer: null,
spaces: 4
});
message.reply(`You deleted order \`${args[0]}\` with reason \`${args[1]}\``)
// Sends a message to the customer.
let customer = message.guild.members.cache.find(m => m.id === order.userID)
//message.users.cache.get(order.userID).send(`Sorry, but your order was cancelled by **${message.author.username}** due to the following reason: \`${reason}\`.`);
customer.send(`Sorry, but your order was cancelled by **${message.author.username}** due to the following reason: \`${reason}\`.`)
// Logs in console.
console.log(colors.red(`${message.author.username} deleted order ${order.orderID}.`));
});
} else {
message.reply("You aren't an employee.");
console.log(colors.red(`${message.author.username} did not have access to the delorder command.`));
}
}
}
Its just id in lowercase letters. ID in uppercase letters doesn't exist.
let prefix = db.get(`prefix_${message.guild.id}`);

Discord.js command handler with user permission ,client permission and throttling

How can i check user permission ,client permission , add throttling and define args in exports like commando does
my message event looks like this
client.on('message', async (message) => {
if (message.author.bot) return;
if (!message.guild) return;
let prefix
await db.collection('guilds').doc(message.guild.id).get().then((q) => {
if (q.exists) {
prefix = q.data().prefix || config1.prefix_mention;
} else {
prefix = "." || config1.prefix_mention;
}
})
const prefixRegex = new RegExp(`^(<#!?${client.user.id}>|${escapeRegex(prefix)})\\s*`);
if (!prefixRegex.test(message.content)) return;
const [ matchedPrefix ] = message.content.match(prefixRegex);
const args = message.content.slice(matchedPrefix.length).trim().split(/ +/g);
const cmd = args.shift().toLowerCase();
if (cmd.length === 0) return;
let command = client.commands.get(cmd);
if (!command) command = client.commands.get(client.aliases.get(cmd));
if (!message.channel.permissionsFor(client.user).has("SEND_MESSAGES")) return;
if (command)
command.run(client, message, args, db);
})
how can i check other permission like example
name: 'osu',
group: 'search',
memberName: 'osu',
description: 'Responds with information on an osu! user.',
clientPermissions: ["EMBED_LINKS","SEND_MESSAGES"],
userPermissions:['VIEW_CHANNEL'],
args: [
{
key: 'user',
prompt: 'What user would you like to get information on?',
type: 'string'
}
],
async run(client ,message ,args) {
//some code here
}
You can get client.user permissions and message.member permissions for message.channel and then check it with has.
About throttling , you can use cooldowns. This is the nice guide how to use it.
const { Permissions } = require('discord.js');
if(command.clientPermissions.length > 0) {
let clientChannelPermissions = message.channel.permissionsFor(message.guild.me);
clientChannelPermissions = new Permissions(clientChannelPermissions.bitfield);
if(!clientChannelPermissions.has(command.clientPermissions)) {
let missingPermissions = command.clientPermissions.filter(perm => clientChannelPermissions.has(perm) === false).join(', ')
return message.reply(`I can`t execute this command, missing permissions for ${missingPermissions}`)
}
}
if(command.userPermissions.length > 0) {
let memberChannelPermissions = message.channel.permissionsFor(message.member);
memberChannelPermissions = new Permissions(memberChannelPermissions.bitfield);
if(!memberChannelPermissions.has(command.clientPermissions)) {
let missingPermissions = command.clientPermissions.filter(perm => memberChannelPermissions.has(perm) === false).join(', ')
return message.reply(`I can`t execute this command, you missing permissions for ${missingPermissions}`)
}
}

Why is Cloud Functions for Firebase taking 25 seconds?

For clarity I have other cloud functions that all run intermittently (i.e from 'cold' in around 2-6 seconds, and all use the same boilerplate set up of importing an admin instance and exporting the function as a module)
I've seen other similar posts but this is really bugging me. I have a cloud function like so:
const admin = require('../AdminConfig');
const { reportError } = require('../ReportError');
module.exports = (event) => {
const uid = event.params.uid;
const snapshot = event.data;
if (snapshot._newData === null ) {
return null;
}
console.log('Create org begin running: ', Date.now());
const organisation = event.data.val();
const rootRef = admin.database().ref();
const ref = rootRef.child('/organisations').push();
const oid = ref.key;
const userData = {
level: 'owner',
name: organisation.name,
};
const orgShiftInfo = {
name: organisation.name,
startDay: organisation.startDay || 'Monday',
};
const updatedData = {};
updatedData[`/users/${uid}/currentOrg`] = oid;
updatedData[`/users/${uid}/organisations/${oid}`] = userData;
updatedData[`/organisations/${oid}`] = organisation;
updatedData[`/org_shift_info/${oid}`] = orgShiftInfo;
rootRef.update(updatedData, (err) => {
if (err) {
return rootRef.child(`/users/${uid}/addOrgStatus`).set({ error: true })
.then(() => {
console.log(`error adding organisation for ${uid}: `, err);
return reportError(err, { uid });
});
}
console.log('Create org wrote succesfully: ', Date.now());
return rootRef.child(`/users/${uid}/addOrgStatus`).set({ success: true });
});
}
I understand the 'cold start' thing but I think something is seriously wrong that it's taking 25 seconds. The logs don't return any error and are as so:
Is there some deeper way I can debug this to try and figure out why it's taking so long? It's unusable at the moment. Thanks a lot.
Solved:
Sorry,
I misunderstood the API a bit. I should have watched the promise video first!
I needed to put
return rootRef.update...
instead of
rootRef.update...

Resources