I'm trying to make verification channel where users will verify themselves using reactions.
I tried fetching messages from the verify channel and trying to do this code:
const mReaction = new Discord.MessageReaction();
const message = mReaction.message;
const verified = 'verifiedID';
const unverified = 'unverifiedID';
if(message.reactions.cache.find(r => r.emoji === '✅') || message.channel.id == 'channelID'){
message.member.roles.add(verified);
message.member.roles.remove(unverified);
}
When I run the code I keep getting:
TypeError: Cannot read property 'me' of undefined
at new MessageReaction (D:\Users\Rastik\Desktop\discord bot\node_modules\discord.js\src\structures\MessageReaction.js:35:20)
at Object.<anonymous> (D:\Users\Rastik\Desktop\discord bot\main.js:98:20)
at Module._compile (internal/modules/cjs/loader.js:1200:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1220:10)
at Module.load (internal/modules/cjs/loader.js:1049:32)
at Function.Module._load (internal/modules/cjs/loader.js:937:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
So I would like to ask you guys to help me, If anyone would be that awesome to try help me I would really appreciated.
The error is that you are creating a MessageReaction out of thin air,
const mReaction = new Discord.MessageReaction();
If you look at the docs, it shows you would need the client, the data and the message.
https://discord.js.org/#/docs/main/stable/class/MessageReaction
const message = mReaction.message how would it know which message the reaction refers to? You don't define anything
All in all this code makes no sense.
If you want to do a verification message reaction system you will need to listen to the messageReactionAdd event, but since that event listens to only cached messages you will need to either use raw event or partials
I will show the partial way.
Main file:
const client = new Client({ partials: ["REACTION", "MESSAGE"]});
And then you will need to handle the messageReactionAdd event somehow,
client.on("messageReactionAdd", async (reaction, user) => {
if(reaction.partial) await reaction.fetch();
//you should have one message with the checkmark emoji, that users need to press
//to join, insert the msg id here
if(reaction.message.id !== "id") return;
//now you validate the user, if they have the role already return if not add.
});
Related
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
Recently I saw another question that had a answer but it doesn't fully satisfy me. I would like to use the bot in the usage of /invite [invitelink]
Found this code that works using puppeteer but I would like it instead of setting the url by hand in code to use a var or something. I tried just changing the url to a var called url but that just gives a error
>(node:32664) UnhandledPromiseRejectionWarning: Error: Evaluation failed: ReferenceError: invite is not defined
at __puppeteer_evaluation_script__:3:62
at ExecutionContext._evaluateInternal (E:\Folders\DiscordBot\v2\node_modules\puppeteer\lib\cjs\puppeteer\common\ExecutionContext.js:218:19)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async ExecutionContext.evaluate (E:\Folders\DiscordBot\v2\node_modules\puppeteer\lib\cjs\puppeteer\common\ExecutionContext.js:107:16)
at async invite4 (E:\Folders\DiscordBot\v2\app.js:91:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:32664) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:32664) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
The code I use is:
const invite = async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://discord.com/');
await page.evaluate(async () => {
const x = new XMLHttpRequest();
x.open('POST', `https://discord.com/api/v6/invites/${invite}`);
x.setRequestHeader('Authorization', token);
x.send();
});
//Maybe good idea to close browser after executing
};
Got the code from here: How do I make a selfbot join a server?
Can anyone help me?
So in the Error is stated, that evaluation failed, because invite is not defined. Evaluation is the part of the code, that gets injected into the website you're trying to access.
>(node:32664) UnhandledPromiseRejectionWarning: Error: Evaluation failed: ReferenceError: invite is not defined
at __puppeteer_evaluation_script ...
You need to pass the inviteCode to the page.evaluate() function. In your case, you also need to pass the token to the function.
To pass variables inside the page.evaluate() function in puppeteer, I found an answer here:
How can I pass variable into an evaluate function?
So for your example, it'd look like that:
const invite = async (inviteCode, token) => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://discord.com/');
await page.evaluate(({inviteCode, token}) => {
const x = new XMLHttpRequest();
console.log(inviteCode);
x.open('POST', `https://discord.com/api/v6/invites/${inviteCode}`);
x.setRequestHeader('Authorization', token);
x.send();
},{inviteCode, token});
//Maybe good idea to close browser after executing
};
Like that, you can pass the arguments directly to your function like that: invite(inviteCode, token);
I have some code for discord.js that sends a user a DM when they join the server. They then have to enter the password given to them, and it will then give them a role that allows them access to channels.
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
client.on('guildMemberAdd', guildMember => {
console.log("Joined");
guildMember.send("Welcome to the server! Please enter the password given to you to gain access to the server:")
.then(function(){
guildMember.awaitMessages(response => message.content, {
max: 1,
time: 300000000,
errors: ['time'],
})
.then((collected) => {
if(response.content === "Pass"){
guildMember.send("Correct password! You now have access to the server.");
}
else{
guildMember.send("Incorrect password! Please try again.");
}
})
.catch(function(){
guildMember.send('You didnt input the password in time.');
});
});
});
client.login("token");
The thing is, I don't really know how to use the awaitResponses function. I do not know how to call it, because all the tutorials I find use it with message.member.
When I run my code, I get these three errors:
UnhandledPromiseRejectionWarning: TypeError: guildMember.awaitMessages is not a function
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.
I do not know what lines these are referring to, so I am very confused.
Here's a quick rundown on how awaitMessages works:
First of all, the .awaitMessages() function extends GuildChannel, meaning you had already messed up a little bit by extending the GuildMember object instead. - You could easily fetch a channel using
const channelObject = guildMember.guild.channels.cache.get('Channel ID Here'); // Gets a channel object based on it's ID
const channelObject = guildMember.guild.channels.cache.find(ch => ch.name === 'channel name here') // Gets a channel object based on it's name
awaitMessages() also gives you the ability to add a filter for a certain condition an input must have.
Let's take the freshly new member as an example. We could simply tell the client to only accept input from members who have the same id as the guildMember object, so basically only the new Member.
const filter = m => m.author.id === guildMember.id
Now, finally, after we've gathered all of the resources needed, this should be our final code to await Messages.
const channelObject = guildMember.guild.channels.cache.get('Channel ID Here');
const filter = m => m.author.id === guildMember.id
channelObject.awaitMessages(filter, {
max: 1, // Requires only one message input
time: 300000000, // Maximum amount of time the bot will await messages for
errors: 'time' // would give us the error incase time runs out.
})
To read more about awaitMessages(), click here!
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)
}
}
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