when i kick a user with this command the audit logs show [object Onject] rather than the reason. if i were to replace all instances of kick in this command with ban it would work fine, but for some reason it's just kick where this issue occurs.
any ideas?
const caseInsensitive = message.content.toLowerCase();
const arguments = caseInsensitive.substring(prefix.length).split(` `);
const mention = message.mentions.users.first();
const member = message.guild.member(mention);
const reason = (!arguments[2]) ? `none` : `${arguments[2]}`
case `kick`:
if (!message.member.hasPermission(`KICK_MEMBERS`)) return;
if (!arguments[1]) return message.channel.send(`specify user`)
if (!mention) return message.channel.send(`couldn't find user`)
if (message.author === mention) return message.channel.send(`don't commit suicide`)
if (!member.kickable) return message.channel.send(`can't kick user`)
member.kick({ reason: `${reason}` }).then(
message.channel.send(`user has ben korked`))
break;
This is the problem.
You're passing an object into the member.kick() function.
According to the documentation, the parameters are supposed to be member.kick(reason), not member.kick({ reason }).
Hope this helps.
Related
client.on('message', async message => {
let guild = message.guild
if (!guild.me.hasPermission("ADMINISTRATOR")) return
})
When my bot join a server, there is this error
if (!guild.me.hasPermission("ADMINISTRATOR")) return
^
TypeError: Cannot read properties of null (reading 'me')
at Client.<anonymous> (/home/runner/Todoroki/index.js:236:16)```
That means that the command is runned on a server. Or you don't have the GUILDS intents enabled. simply
client.on('message',message =>{
if(!message.guild) return;
// Do whatever you want
})
Actually I found out how to do. I just added:
let guild = message.guild
if (!guild) return;
// rest of commands
Without much information, I could only deduce that me is null. To solve it, you could check if guild.me is truthy using Optional Chaining like so:
if (!guild?.me?.hasPermission ...
can someone please help me to retrieve username from user ID and send a message to the chat with that ID?
if (message.content.startsWith(prefix)) {
const [CMD_NAME, ...args] = message.content
.trim()
.substring(prefix.length)
.split(/\s+/);
if (CMD_NAME === "getid") {
const getid1 = new MessageEmbed()
.setDescription("❗️ | Please tag the member to retrieve the ID!")
.setColor(10181046);
if (args.length === 0) return message.reply(getid1);
const username = client.guilds.cache.get('<GUILD ID>');
const userid = client.users.cache.find(username => username.tag === 'Someone#1234').id
message.channel.send(`${username} id is ${userid}`);
}
}
});
When I type the command "d!getid #Username", it shows me this error:
C:\Users\USER\Desktop\DiscordBotas\index.js:152 const userid = client.users.cache.find(username => username.tag === 'Someone#1234').id TypeError: Cannot read property 'id' of undefined at Client. (C:\Users\USER\Desktop\DiscordBotas\index.js:152:90)
You are creating a lambda of a variable that you just defined above the actual lambda, this could probably mess with your code.
The const username = client.guilds.cache.get('<GUILD ID>'); is wrong.
The fetching of the userId should probably work if you fix the line above it.
You are trying to get the user the wrong way. Firstly, why are you trying to match a user's tag with a guild? Maybe you think guild.cache has users? Well actually, this is client.guilds.cache, which only has guilds in it, and it returns a guild, not a user. Secondly, to get a user, you can try this method:
const user = client.users.cache.find(u => u.tag === 'SomeUser#0000')
console.log(user.id);
Below is code to get user by ID, but it probably won’t help with this, considering you would already have access to the ID
const user = client.users.cache.get("<UserID>");
console.log(user);
Also, you should add code to see if user isn’t found (client can’t find user with the condition). Here is some code to check that:
//... the find user code I put
if(!user) return message.reply('User could not be found');
message.channel.send(user.id);
Purpose: To ban unauthorised users who kick members out of my server.
Code:
client.on("guildMemberRemove", async member => {
const FetchingLogs = await member.guild.fetchAuditLogs({
limit: 1,
type: "MEMBER_KICK",
});
const kickLog = FetchingLogs.entries.first();
if (!kickLog) {
return console.log(red(`${member.user.tag} was kicked in ${member.guild.name} but nothing was registered in the audit log...`));
}
const { executor, target, createdAt } = kickLog
if (target.id === member.id) {
console.log(greenBright(`${member.user.tag} got kicked in ${member.guild.name}, by ${executor.tag}`));
} else if (target.id === executor.id) {
return
}
if (executor.id !== client.user.id) {
member.guild.member(executor).ban({
reason: `Unauthorised Kick`
}).then(member.guild.owner.send(`**Unauthorised Kick By:** ${executor.tag} \n**Victim:** ${target.tag} \n**Time:** ${createdAt.toDateString()} \n**Sentence:** Ban.`)).catch();
}
})
Result: It bans the executor but it still throws this error:
(node:10272) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'ban' of null
Could you please tell me why this is happening and what I could to remove this error. All help appreciated ;)
This is the offending line:
member.guild.member(executor).ban(....
You supply member.guild.member an executor object and it returns null, then it tries to call the function ban on a null object and you get the error.
Maybe try sending it the executor.id instead, like so:
member.guild.member(executor.id).ban
If you want to ban somebody from a guild you can do this by writing:
member.guild.members.ban(executor.id, { reason: "/* Your reason */" })...
Sources:
https://discord.js.org/#/docs/main/stable/class/GuildMemberManager?scrollTo=ban
and my experience with discord.js
Aim: To ban every time a user is caught on the audit log attempting to create a channel
Code:
// Channel Create
client.on("channelCreate", async (channel) => {
const FetchingLogs = await client.guilds.cache.get(channel.guild.id).fetchAuditLogs({
limit: 1,
type: "CHANNEL_CREATE",
})
const ChannelLog = FetchingLogs.entries.first();
if (!ChannelLog) {
return console.log(red(`CHANNEL: ${channel.id} was created.`));
}
const { executor, target, createdAt } = ChannelLog;
if (target.id === channel.id) {
console.log(greenBright(`${channel.id} got created, by ${executor.tag}`));
} else if (target.id === executor.id) {
return
}
if (executor.id !== client.user.id) {
channel.guild.member(executor.id).ban({
reason: `Unauthorised Channel Created`
}).then(channel.guild.owner.send(`**Unauthorised Channel Created By:** ${executor.tag} \n**Channel ID:** ${channel.id} \n**Time:** ${createdAt.toDateString()} \n**Sentence:** Ban.`)).catch();
}
});
Result:
It bans the user successfully but still throws an error.
Error:
TypeError: Cannot read property 'id' of undefined
Code: Error Specified | Referring to channel.guild.id
const FetchingLogs = await client.guilds.cache.get(channel.guild.id).fetchAuditLogs({
limit: 1,
type: "CHANNEL_CREATE",
})
I'm guessing the reason for this is that the parameter ,channel, type is DMChannel and not GuildChannel
Is there any way to fix this or be able to change the parameter type to GuildChannel??? I've checked the Docs and I can't seem to find anything that indicates this is possible. Any help is appreciated ;)
Your assumption of why this error is occurring is correct. The channelCreate event does indeed handle the creation of both GuildChannel and DMChannel, and your code sends the guild owner a DM after banning the user. That's why the ban works but you get an error afterwards; because the DM creates a DMChannel with the owner, triggering the event handler again but with channel.guild being undefined since DMs do not have guilds.
So let me state the problem again. You are getting the error Cannot read property 'id' of undefined which you've figured out means channel.guild is undefined. You don't want the error to occur, so you don't want channel.guild to be undefined. But in your question you're asking:
Is there any way to fix this or be able to change the parameter type to GuildChannel???
That's not the approach you want to take. Doing that would mean users would get banned for DMing your bot because it would trigger your channelCreate event handler; plus, the bot would try to ban the guild owner since it sends the owner a DM. And you only want to ban users for creating channels in the guild.
When we put the problem that way, the solution is simple: check if the channel is a DMChannel, and discontinue if it is. Only allow users to get banned for creating a GuildChannel. So how do you do that? Well, as you've seen from your error already, channel.guild is undefined when the channel is a DMChannel. So simply check for this condition, and return if it is the case. Here's an example:
// Channel Create
client.on("channelCreate", async (channel) => {
if (!channel.guild) return; //<- added this
const FetchingLogs = await client.guilds.cache.get(channel.guild.id).fetchAuditLogs({
limit: 1,
type: "CHANNEL_CREATE",
})
const ChannelLog = FetchingLogs.entries.first();
if (!ChannelLog) {
return console.log(red(`CHANNEL: ${channel.id} was created.`));
}
const { executor, target, createdAt } = ChannelLog;
if (target.id === channel.id) {
console.log(greenBright(`${channel.id} got created, by ${executor.tag}`));
} else if (target.id === executor.id) {
return
}
if (executor.id !== client.user.id) {
channel.guild.member(executor.id).ban({
reason: `Unauthorised Channel Created`
}).then(channel.guild.owner.send(`**Unauthorised Channel Created By:** ${executor.tag} \n**Channel ID:** ${channel.id} \n**Time:** ${createdAt.toDateString()} \n**Sentence:** Ban.`)).catch();
}
});
This prevents the error from occurring, prevents users from getting banned for DMing the bot, and prevents the guild owner from being infinitely DM'd (if the DMChannel were to be somehow converted into a GuildChannel, the bot would DM the owner after banning the user that created the channel, which would trigger the event again and ban the user again, and DM the owner again, in an infinite loop).
Making a command to take a random photo of a waifu in this case, and posting it in the channel
Code here:
if (command === 'waifu') {
const waifu = new Discord.MessageEmbed()
got('https://waifu.pics/api/sfw/waifu').then(response => {
let content = JSON.parse(response.body);
let waifuUrl = content[0].data.children[0].data.url;
let waifuImage = content[0].data.children[0].data.url;
waifu.setImage(`${waifuImage}`)
waifu.setURL(`${waifuUrl}`)
waifu.setColor('#ffb9f4')
waifu.setFooter(`Requested by ${message.author.user}`)
waifu.setTimestamp()
waifu.setAuthor(`waifu.pics`, `https://waifu.pics/`)
message.channel.send(waifu)
});
};
The API should be correct. After a few small changes, I tried console logging the JSON and it did output the correct thing. But when running the code in discord, it outputted a TypeError: Cannot read property 'data' of undefined error. I cannot seem to figure out the problem
if (command === 'waifu') {
const waifu = new Discord.MessageEmbed()
get('https://waifu.pics/api/sfw/waifu').then(response => {
let content = response.body;
let waifuUrl = content.url;
let waifuImage = content.url;
waifu.setImage(`${waifuImage}`)
waifu.setURL(`${waifuUrl}`)
waifu.setColor('#ffb9f4')
waifu.setFooter(`Requested by ${message.author.username}`)
waifu.setTimestamp()
waifu.setAuthor(`waifu.pics`, `https://waifu.pics/`)
message.channel.send(waifu)
});
};
You thought a little bit complicated ^^ You had something with children and data, although the API just gives an URL. You don't even have to parse it. And you have used the function got(), which you have to replace with get().
I fixed your code just copy it from above.