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 ...
Related
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).
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.
I develop a bot with discord.js that uses things like msg.member.hasPermission("ADMINISTRATOR") or msg.member.roles.cache.has(teacherRoleID). Everything worked fine until I tried webhooks. By adding these two lines :
client.on('ready', () => {
client.user.setStatus("online")
client.user.setActivity("!help", {
type: "PLAYING",
});
superConsole(`Logged in as ${client.user.tag} in ${client.guilds.size} guilds!`);
const hook = new Discord.WebhookClient("ID", "secret token"); // THESE
hook.send("I am now alive!"); // LINES
});
(btw superConsole is a function)
Since then, the program did not work any more and always returned the same errors: (node:20736) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'hasPermission' of null & (node:20736) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'roles' of null
When I delete these 2 lines for the webhook, it works again. Why? I don't understand.
The permission and role things are in a message listener:
client.on('message', async msg => {
if (msg.member.hasPermission('ADMINISTRATOR') {
// some stuff here
}
if (msg.member.roles.cache.has(teacherRoleID) {
// some stuff here
}
});
The issue is that when you send a message from hook, it triggers the client's message event. Because a webhook isn't a guild member, msg.member will get undefined for messages sent from a webhook.
You would have to use something like this:
if (msg.member) {
if (msg.member.permissions.has('ADMINISTRATOR') {
// some stuff here
}
if (msg.member.roles.cache.has(teacherRoleID) {
// some stuff here
}
}
When I try
message.member.roles.add('695699359634817094');
I get the following error:
TypeError: Cannot read property 'add' of undefined
Is there a specific way to add my guild ID and update their role to that specific server through DM?
My function works within the guild by calling the command, however, through DM it doesn't.
You could do this by using message.author.id to get the user's ID and then using guild.get(guild_ID).members.fetch(user_ID) to access the GuildMember of that user.
You also mentioned that you give users the ability to run that command either in DM or a text channel in your guild.
If that is the case I would suggest adding a check to see if the command is being sent to a text channel or dm channel.
if (message.channel.type === "dm") {
const member = await client.guilds.get(guild_ID).members.fetch(message.author.id);
member.roles.add(role_ID);
} else {
message.member.roles.add('695699359634817094');
}
Ignore the if statement if you intend on having the command only run from dm.
By using the info given from Syntle and tipakA this is the solution.
if (message.channel.type === "dm") {
client.guilds.get('[SeverId]').members.fetch(message.author.id).then(async () => {
await client.guilds.get('[ServerId]').members.fetch(message.author.id).then((memberid) => {
memberid.roles.add('[roleid]');
}).catch((err) => {
console.log("ERROR");
});
});
}
else
{
message.member.roles.add('[roleid]');
}