So I decided to start making a very simple Discord bot that should give a role to a member if a different member has the same role,
For example;
Person 1: I have the infected role
Person 2: I dont have the infected role.
Person 2: #Person1 blah blah blah
And now person 2 should receive the infected role, Instead that doesn't happen, And I cannot figure out a way to fix it.
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
console.log("rerararararrederasd")
var infectionStarted = true; client.on("message", message => {
if (infectionStarted) {
try{ let role = message.guild.roles.cache.find(r => r.name === 'infected');
client.users.cache.get(message.mentions.members.first().id).roles.add(role);}catch(e){console.log(e)};
}
});
client.login('my discord bots token ofc goes here i just removed for stackoverflow');
But in the console I get this issue report:
at Client.emit (events.js:196:13)
at MessageCreateAction.handle (/rbd/pnpm-volume/ec7e49f1-7b76-4ef8-9653-1982138496c7/node_modules/.registry.npmjs.org/discord.js/12.3.1/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (/rbd/pnpm-volume/ec7e49f1-7b76-4ef8-9653-1982138496c7/node_modules/.registry.npmjs.org/discord.js/12.3.1/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/rbd/pnpm-volume/ec7e49f1-7b76-4ef8-9653-1982138496c7/node_modules/.registry.npmjs.org/discord.js/12.3.1/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
at WebSocketShard.onPacket (/rbd/pnpm-volume/ec7e49f1-7b76-4ef8-9653-1982138496c7/node_modules/.registry.npmjs.org/discord.js/12.3.1/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
at WebSocketShard.onMessage (/rbd/pnpm-volume/ec7e49f1-7b76-4ef8-9653-1982138496c7/node_modules/.registry.npmjs.org/discord.js/12.3.1/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
at WebSocket.onMessage (/rbd/pnpm-volume/ec7e49f1-7b76-4ef8-9653-1982138496c7/node_modules/.registry.npmjs.org/ws/7.3.1/node_modules/ws/lib/event-target.js:125:16)
at WebSocket.emit (events.js:196:13)
at Receiver.receiverOnMessage (/rbd/pnpm-volume/ec7e49f1-7b76-4ef8-9653-1982138496c7/node_modules/.registry.npmjs.org/ws/7.3.1/node_modules/ws/lib/websocket.js:797:20)
TypeError: Cannot read property 'add' of undefined
It might be very obvious but i dont know how to solve this, If you could help me i would really appreciate it, Thank you!
EDIT:
I recommend structuring your code a little better as well as destructuring your variables.
The issue is that client.users.fetch() returns a user which unlike a member has no roles. Hence why it returned undefined
client.on("message", message => {
const infectionStarted = true
const role = message.guild.roles.cache.find(r => r.name === 'infected')
// have 'member' = the mentioned member
const member = message.mentions.members.first()
// If there was a mention, add the role to the mentioned
if (member) {
// Instead of fetching the user through Discord, I add the role directly to the member object like this
member.roles.cache.add(role)
}
}
Related
I am getting this error error when trying to add a role a member when they have an invite link in their status
Error:
C:\Users\Woody\Documents\Giveaway\node_modules\discord.js\src\managers\GuildMemberRoleManager.js:93
throw new TypeError('INVALID_TYPE', 'roles', 'Role, Snowflake or Array or Collection of Roles or Snowflakes');
^
TypeError [INVALID_TYPE]: Supplied roles is not a Role, Snowflake or Array or Collection of Roles or Snowflakes.
at GuildMemberRoleManager.add (C:\Users\Woody\Documents\Giveaway\node_modules\discord.js\src\managers\GuildMemberRoleManager.js:93:15)
at Client.<anonymous> (C:\Users\Woody\Documents\Giveaway\index.js:61:39)
at Client.emit (node:events:527:28)
at PresenceUpdateAction.handle (C:\Users\Woody\Documents\Giveaway\node_modules\discord.js\src\client\actions\PresenceUpdate.js:39:19)
at Object.module.exports [as PRESENCE_UPDATE] (C:\Users\Woody\Documents\Giveaway\node_modules\discord.js\src\client\websocket\handlers\PRESENCE_UPDATE.js:4:33)
at WebSocketManager.handlePacket (C:\Users\Woody\Documents\Giveaway\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (C:\Users\Woody\Documents\Giveaway\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocketShard.onMessage (C:\Users\Woody\Documents\Giveaway\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (C:\Users\Woody\Documents\Giveaway\node_modules\ws\lib\event-target.js:132:16)
at WebSocket.emit (node:events:527:28) {
[Symbol(code)]: 'INVALID_TYPE'
}
And this is my code:
client.on('presenceUpdate', async (oldPresence, newPresence) => {
const role = newPresence.guild.roles.cache.get("984959434256179221");
const member = newPresence.member
const activities = member.presence.activities[0];
if (activities && (activities.state.includes( ".gg/s7trZ2NF" ) || activities.state.includes("discord.gg/s7trZ2NF" ))) {
return newPresence.member.roles.add(role)
} else {
if(member.roles.cache.get(role.id)) {
newPresence.member.roles.remove(role)
}
}
})
Instead of using let role = roles.cache.get("roleId") just simply do member.roles.add(roleId); or make it let role = "roleId" instead
Currently you're trying to get a role from the cache, so chances are the role is uncached and returning nothing, hence the error.
Secondly in your if check, you only need the first includes(). Includes will check for any matches and not specific matches.
i.e. discord.gg/code and .gg/code will both return true in that condition
The error in the title seems to be completely unrelated to the error you've provided as well as the code, this answer only matches the actual descritpion of the problem.
My ban command checks if a user is bannable then bans them. My kick does the same thing but it actually works. The ban message sends so the user is bannable but doesn't actually get banned. Here's my code
if (memberTarget.bannable) {
if (
message.member.roles.highest.position >
message.guild.members.cache.get(target.id).roles.highest.position
) {
target.ban(reason);
let banReason = new Discord.MessageEmbed()
.setDescription(`**${target.user.tag}** has been banned.`)
.addField("Reason:", `${!reason ? "Unspecified" : `${reason}`}`)
.setFooter(
`banned by ${message.author.tag}`,
"https://cdn.discordapp.com/attachments/375020097431011328/881012463645126686/3dgifmaker15131.gif"
)
.setColor("#000000");
message.reply({ embeds: [banReason] }).catch((err) => {
message.channel.send({ embeds: [banReason] });
});
}
My problem with this is everytime I try to go and kick someone, I get my error:
if (!memberTarget.bannable) {
let lowPerms = new Discord.MessageEmbed()
.setDescription(
`<:role:887134365476335626> I lack the required permission to ban **${target.user.tag}**.`
)
.setColor("#000000");
message.reply({ embeds: [lowPerms] });
}
This happens even why I try to kick someone with no roles and my bot had administrative permissions.
The actual error itself:
C:\Users\\Documents\GitHub\omex\node_modules\discord.js\src\managers\GuildBanManager.js:142
if (typeof options !== 'object') throw new TypeError('INVALID_TYPE', 'options', 'object', true);
^
TypeError [INVALID_TYPE]: Supplied options is not an object.
at GuildBanManager.create (C:\Users\\Documents\GitHub\omex\node_modules\discord.js\src\managers\GuildBanManager.js:142:44)
at GuildMemberManager.ban (C:\Users\\Documents\GitHub\omex\node_modules\discord.js\src\managers\GuildMemberManager.js:364:28)
at GuildMember.ban (C:\Users\\Documents\GitHub\omex\node_modules\discord.js\src\structures\GuildMember.js:299:31)
at Object.execute (C:\Users\\Documents\GitHub\omex\commands\ban.js:32:22)
at Client.<anonymous> (C:\Users\\Documents\GitHub\omex\index.js:133:20)
at Client.emit (node:events:394:28)
at MessageCreateAction.handle (C:\Users\\Documents\GitHub\omex\node_modules\discord.js\src\client\actions\MessageCreate.js:23:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\\Documents\GitHub\omex\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\\Documents\GitHub\omex\node_modules\discord.js\src\client\websocket\WebSocketManager.js:345:31)
at WebSocketShard.onPacket (C:\Users\\Documents\GitHub\omex\node_modules\discord.js\src\client\websocket\WebSocketShard.js:443:22) {
[Symbol(code)]: 'INVALID_TYPE'
}
The error attached in question is originated via this specific line:
target.ban(reason)
The GuildMember#ban([options]) if needed to be called with options the options must be an array of options / object like so
target.ban({
reason: `${!reason ? "Unspecified" : `${reason}`}`
});
NodeJS is freaking out because I'm guessing the reason you passed into target.ban() is a string, not an object. In discord.js, you have to provide an object into the GuildMember#ban() method, like this:
target.ban({ reason });
You can also choose how many days (from 0-7) of messages to delete, like this:
target.ban({ days: 7, reason }); // Deletes all messages the member banned sent within the past 7 days
I am trying to find if my bot has a specific role so it can do something else. For example:
client.user.roles.cache.find(r => r.name === 'specific role');
My error:
TypeError: Cannot read property 'cache' of undefined
Let's start of by stating that users do not have roles, therefore you have to fetch the guildMember.
Fetching the guild member is easy;
First of all, you will have to fetch the guild the user is in. For example:
var guild = client.guilds.cache.get('guild-id');
Secondly, you will have to find the user in that guild. For example:
var member = guild.members.cache.get('user-id');
Then you will be able to move forward and fetch the roles
member.roles.cache.find(r => r.name === 'role-name');
The full example:
const Discord = require('discord.js'); //Define discord.js
const client = new Discord.Client(); //Define the client
client.on('message' message => { //Event listener
//Do something here
var guild = client.guilds.cache.get(message.guild.id);
var member = guild.members.cache.get(client.user.id);
member.roles.cache.find(r => r.name === 'role-name');
});
client.login('token'); //Login
So maybe I didnt explain my problem very well but here is what I found working for me message.guild.me.roles.cache.find(r=> r.name === 'a role') thanks to everyone for helping me !!!
You need to resolve the user into a GuildMember, since users don't have roles.
To do that you need a Guild class,after that you can use the guild.member() method to convert it to a member
const guild = client.guilds.cache.get('id of the guild'),
member = guild.member(client.user.id);
member.roles.cache.find(r=> r.name === 'name')
Another issue you might run into here is, the member constant being undefined, this can be solved by using guild.members.fetch(id) or enabling the Privileged Member intent in the Discord Developer Portal
What i am trying to achieve is having a very simple bot to give roles to people who have the role and only give it if the person they are mentioning has the role, Here is a example of what i mean;
Person1:hey i have a infected role
Person2:I dont have the infected role
Person2:blahblahblah #Person1 blahblahblah
and now Person2 Should get the infected role, But everytime someone pings someone else with the infected role i get errors, This is the current code i have;
const Discord = require('discord.js');
const client = new Discord.Client();
client.login('i have my token here but i removed it for the question');
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
console.log("logging in")
client.user.setActivity(`discord.gg/ypj9PSx`, {
type: "STREAMING",
url: "https://www.twitch.tv/ninja"})
.then(presence => console.log(`Your Status has been set to ${presence.game ? presence.game.none : 'none'}`))
.catch(console.error);
});
console.log("setting status")
client.on("message", message => {
const infectionStarted = true
const role = message.guild.roles.cache.find(r => r.name === 'infected')
const member = message.mentions.members.first()
if (member) {
member.guild.roles.cache.add(role)
}
})
But when i run this code it gives this error;
TypeError: member.guild.roles.cache.add is not a function
at Client.<anonymous> (/app/server.js:28:32)
at Client.emit (events.js:196:13)
at MessageCreateAction.handle (/rbd/pnpm-volume/ec7e49f1-7b76-4ef8-9653-1982138496c7/node_modules/.registry.npmjs.org/discord.js/12.3.1/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (/rbd/pnpm-volume/ec7e49f1-7b76-4ef8-9653-1982138496c7/node_modules/.registry.npmjs.org/discord.js/12.3.1/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/rbd/pnpm-volume/ec7e49f1-7b76-4ef8-9653-1982138496c7/node_modules/.registry.npmjs.org/discord.js/12.3.1/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
at WebSocketShard.onPacket (/rbd/pnpm-volume/ec7e49f1-7b76-4ef8-9653-1982138496c7/node_modules/.registry.npmjs.org/discord.js/12.3.1/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
at WebSocketShard.onMessage (/rbd/pnpm-volume/ec7e49f1-7b76-4ef8-9653-1982138496c7/node_modules/.registry.npmjs.org/discord.js/12.3.1/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
at WebSocket.onMessage (/rbd/pnpm-volume/ec7e49f1-7b76-4ef8-9653-1982138496c7/node_modules/.registry.npmjs.org/ws/7.3.1/node_modules/ws/lib/event-target.js:125:16)
at WebSocket.emit (events.js:196:13)
at Receiver.receiverOnMessage (/rbd/pnpm-volume/ec7e49f1-7b76-4ef8-9653-1982138496c7/node_modules/.registry.npmjs.org/ws/7.3.1/node_modules/ws/lib/websocket.js:797:20)
If anyone could help me that would be greatly appreciated
GuildMemberRoleManager.cache is a Collection, which has no method called add.
What you are looking for, is the method add of GuildMemberRoleManager.
member.roles.add(role)
Note: With member.guild.roles.cache you are actually accessing the cache of RoleManager. (The member's guild roles, which obviously you don't want to.)
I am trying to send a message to channel but I keep getting Error: send is not a function.I have been stuck on this problem for over an hour.
What I have tried:
using sendMessage
tried reading the discord.js documentation but it doesnt seem to be working at all.
Here is my code:
//Grab the Discord Library
const Discord = require("discord.js");
//What will connect to the server.
const bot = new Discord.Client();
//
bot.on('ready', () => {
console.log("Connected as " + bot.user.tag)
//Shows and set the activity of the user.
bot.user.setActivity("El Professor build me", {type: "Watching"})
//Inform you of the servers this bot is connected to.
bot.guilds.forEach((guild) => {
console.log(guild.name)
guild.channels.forEach((channel) => {
console.log(` - ${channel.name} ${channel.type} ${channel.id}`)
})
//Voice Channel ID =
})
var generalChannel = bot.channels.get("123456789").send("Hello World")
})
Error message:
C:\Users\F4_ALFA\documents\FirstDiscordBot\index.js:21
var generalChannel = bot.channels.get("123456789").send("Hello World")
^
TypeError: bot.channels.get(...).send is not a function
at Client.bot.on (C:\Users\F4_ALFA\documents\FirstDiscordBot\index.js:21:63)
at Client.emit (events.js:194:15)
at WebSocketConnection.triggerReady (C:\Users\F4_ALFA\documents\FirstDiscordBot\node_modules\discord.js\src\client\websocket\WebSocketConn
ection.js:125:17)
at WebSocketConnection.checkIfReady (C:\Users\F4_ALFA\documents\FirstDiscordBot\node_modules\discord.js\src\client\websocket\WebSocketConn
ection.js:141:61)
at GuildCreateHandler.handle (C:\Users\F4_ALFA\documents\FirstDiscordBot\node_modules\discord.js\src\client\websocket\packets\handlers\Gui
ldCreate.js:13:31)
at WebSocketPacketManager.handle (C:\Users\F4_ALFA\documents\FirstDiscordBot\node_modules\discord.js\src\client\websocket\packets\WebSocke
tPacketManager.js:103:65)
at WebSocketConnection.onPacket (C:\Users\F4_ALFA\documents\FirstDiscordBot\node_modules\discord.js\src\client\websocket\WebSocketConnecti
on.js:333:35)
at WebSocketConnection.onMessage (C:\Users\F4_ALFA\documents\FirstDiscordBot\node_modules\discord.js\src\client\websocket\WebSocketConnect
ion.js:296:17)
at WebSocket.onMessage (C:\Users\F4_ALFA\documents\FirstDiscordBot\node_modules\ws\lib\event-target.js:120:16)
at WebSocket.emit (events.js:189:13)
Discord.js uses cache and your code has no '.cache', you should try
bot.channels.cache.get('id').send('Hello world!')
The channels property returns a Collection with pair of ID and Channel object.
The Channel class could represent any channel in discord. You couldn't send any messages through it because it doesn't have send() method.
I’ve used this before client.guilds.find(x => x.name === "ChatLogs").channels.find(y => y.name === "server-testing1").send(botEmbed) try that