add roles to discord member - javascript

it was not giving an error a few days ago, now it is giving an error strangely.
when i add code to add or remove a role, I get this error.
My code:
let member = message.mentions.members.first();
let role = message.guild.roles.get("707628035498836069");
let role1 = message.guild.roles.get("769919065551929385");
member.addRole(role);
member.removeRole(role1);
Error code:
(node:16668) UnhandledPromiseRejectionWarning: TypeError: Supplied parameter was neither a Role nor a Snowflake.
at GuildMember.removeRole (C:\Users\user\Desktop\discordjssss\node_modules\discord.js\src\structures\GuildMember.js:516:38)
at Object.module.exports.baslat (C:\Users\user\Desktop\discordjssss\komutlar\genel\jaildenm.js:22:10)
at AdvancedClient.<anonymous> (C:\Users\user\Desktop\discordjssss\node_modules\discordjs-advanced\src\client.js:549:5)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:16668) 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:16668) [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.

In discord.js v.12 you need to use a slighty different syntax for finding and adding roles.
You find the roles by accessing the new cache object.
message.guild.roles.cache.get('your ID here');
You now add or remove the roles within the GuildMemberRoleManager.
member.roles.add(role here);
member.roles.remove(role here);
It needs to be said that you don't need to get the role object first. You can simply use the ID. But if you get the role first you can check if it actually exists. But that is neither here nor there.
Note: Your original problem was that your role wasn't found. Either because the role doesn't exist or the ID was wrong.

Related

Getting a discord bot to set the role of a guild member from DM's

So i am trying to make my discord bot add roles to someone that dm-ed it, and i cant seem to make it work
Here is the code:
guild.members.fetch(message.author)
.then(member => {
member.roles.set(['roleID']);
});
This is the error that i get:
(node:5692) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'set' of undefined
at D:\Documents\GitHub\InfinitBotPrototip\index.js:48:24
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:5692) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise w
hich 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_unhand
led_rejections_mode). (rejection id: 1)
(node:5692) [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 e
xit code.

How do I get the most recent message in discord.js?

Every time a message is sent in a specific channel, I want to print it to the console (with console.log). I am also going to color it with npm install colors. I go everywhere, even on Stack Overflow, but I cannot seem to find any information. I am coding a Scholastic Bowl-helping bot. Below is the code I have tried (I found this on Stack Overflow.)
message.fetch({ limit: 1 }).then(messages => {
let lastMessage = message.first();
if (message.channel.lastMessage = 'channel-id'){
console.log(lastMessage.red);
}
})
(Note that when I say 'channel-id' I mean the actual ID of the channel.)
The error I am getting is that message.first is not a thing.
How do I fix this error, and how can I get the most recent message in discord.js?
Edit: The exact error I got is this:
(node:12352) UnhandledPromiseRejectionWarning: TypeError: messages.first is not a function
at C:\Users\[user redacted]\Desktop\SchoBot\index.js:57:32
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:12352) 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:12352) [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.
Below is the edit for the 3rd comment on this question (sorted by oldest):
message.channel.fetch({ limit: 1 }).then(messages => {
let lastMessage = message.channel.first();
if (message.channel.lastMessage = 'channel-id'){
console.log(lastMessage.red);
}
})
Use message.channel.messages.fetch() instead of message.channel.fetch().
I didn't find the message.first function in the discord.js documentation, so I am not sure if it works. But you don't really need that function to fetch a message. The fetch function already did that for you.
In your case, the option limit: 1 will only return the most recent message, which is the command you use to trigger the fetch. If you want to fetch the most recent message but not your command, you should use limit: 2 instead and remove your command in the object later.
The fetch function will return an object containing message id and the content.
I assume that message.fetch needs to be message.channel.fetch

MessageEmbed field values may not be empty

everytime I am trying to do like: !help command , if the command doesn't have any aliases, it gives me that error in the console, I tried the following method which if there is no aliases for the specific command, it should return 'None' , here's the code:
let command = helpArgs[0]
if(helpArgs[0]){
if(bot.commands.has(command)) {
command = bot.commands.get(command)
const embed = new Discord.MessageEmbed()
.setTitle(`${command.config.name}`)
.addField('Name', `${command.config.name}`)
.addField('Description', `${command.config.description}`)
.addField('Usage', `${command.config.usage}`)
.addField('Aliases', `${command.config.aliases !== undefined ? command.config.aliases : 'None'}`)
message.channel.send(embed)
And here is the error:
7:14 GMT+0300 (Eastern European Summer Time)
(node:11744) UnhandledPromiseRejectionWarning: RangeError [EMBED_FIELD_VALUE]: MessageEmbed field values may not be empty.
at Function.normalizeField (C:\Users\\OneDrive\Documents\GitHub\Fergus\node_modules\discord.js\src\structures\MessageEmbed.js:425:23)
at C:\Users\\OneDrive\Documents\GitHub\Fergus\node_modules\discord.js\src\structures\MessageEmbed.js:445:14
at Array.map (<anonymous>)
at Function.normalizeFields (C:\Users\\OneDrive\Documents\GitHub\Fergus\node_modules\discord.js\src\structures\MessageEmbed.js:444:8)
at MessageEmbed.addFields (C:\Users\\OneDrive\Documents\GitHub\Fergus\node_modules\discord.js\src\structures\MessageEmbed.js:259:42)
at MessageEmbed.addField (C:\Users\\OneDrive\Documents\GitHub\Fergus\node_modules\discord.js\src\structures\MessageEmbed.js:250:17)
at Object.module.exports.run (C:\Users\\OneDrive\Documents\GitHub\Fergus\commands\Information\help.js:115:18)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:11744) 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:11744) [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 error is at .addField('Aliases', ${command.config.aliases !== undefined ? command.config.aliases : 'None'}) , I checked each field.
I think the error may be, that the method you used in this field causes an error and because of this, the field is empty. To list the aliases in a string you can try the following method.
let aliases = command.config.aliases.toString();
if (aliases == "") {
aliases = "None";
}
.addField('Aliases', `${aliases}`)
With this method, you create a String from the aliases array of your command config. Then you look if there aren't any aliases. If yes the String is "None". After this, you need to replace your method in the embed with the variable aliases.
It seems like command.config.aliases is indeed empty, even though it is not undefined. You should modify the check. I do not know what the aliases field contains, so I cannot say what the check should be.

UnhandledPromiseRejectionWarning: Error: Script failed to execute- Electron execute script

i try to excuteJavaScript in electron
function createTestGmail(username, password){
username = '12344444444444444444444444asdasd44444444'
testGmail = new BrowserWindow({
width: 500,
height:300,
backgroundColor:'#ccc',
title:'Kiểm tra Gmail',
webPreferences: {
nodeIntegration: true,
nativeWindowOpen: true,
}
});
testGmail.loadURL('https://example.com');
testGmail.webContents.openDevTools();
testGmail.webContents.executeJavaScript(`
console.log(`+username+`)
`)
testGmail.on('closed',()=>{
testGmail = null;
})
}
if username is a number it work correctly, if username is a string, like below, it show error code
(node:3752) UnhandledPromiseRejectionWarning: Error: Script failed to execute, this normally means an error was thrown. Check the renderer console for the error.
at WebFrame.<computed> (C:\Users\Vy\Desktop\toolyoutube\node_modules\electron\dist\resources\electron.asar\renderer\api\web-frame.js:64:33)
at WebFrame.executeJavaScript (C:\Users\Vy\Desktop\toolyoutube\node_modules\electron\dist\resources\electron.asar\common\api\deprecate.js:114:32)
at C:\Users\Vy\Desktop\toolyoutube\node_modules\electron\dist\resources\electron.asar\renderer\web-frame-init.js:11:43
at C:\Users\Vy\Desktop\toolyoutube\node_modules\electron\dist\resources\electron.asar\renderer\ipc-renderer-internal-utils.js:7:40
at new Promise (<anonymous>)
at EventEmitter.<anonymous> (C:\Users\Vy\Desktop\toolyoutube\node_modules\electron\dist\resources\electron.asar\renderer\ipc-renderer-internal-utils.js:7:9)
at EventEmitter.emit (events.js:200:13)
at Object.onMessage (C:\Users\Vy\Desktop\toolyoutube\node_modules\electron\dist\resources\electron.asar\renderer\init.js:42:16)
(node:3752) 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(). (rejection id: 1)
(node:3752) 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(). (rejection id: 1)
(node:3752) [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.
(node:3752) [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.
i have try with tag and it have the same problem
I saw #Bravo answered your question through a comment, but just to improve it, since you're using a template string, you could just:
testGmail.webContents.executeJavaScript(`console.log('${username}')`)
It's cleaner that way (since this is the main purpose of a template string, not only allowing to have a multiline text) and you avoid doing string concatenation with the "+" operator.
Sometimes you will mess with single quote and quote mark.
I made an util function to log everywhere.
function logEverywhere(mainWindow, message) {
if (mainWindow && mainWindow.webContents) {
mainWindow.webContents.executeJavaScript(`console.log(\`${message}\`)`);
}
}
I was taking a UDEMY course called Master Electron: Desktop Apps with HTML, JavaScript & CSS, by Ray Viljoen
And in Lesson 3.17. Session: DownloadItem, I got this same error:
(node:9552) UnhandledPromiseRejectionWarning: Error: Script failed to execute, this normally means an error was thrown. Check the renderer console for the error.
at WebFrame.e.startsWith.e.startsWith.WebFrame.<computed> [as _executeJavaScript] (electron/js2c/renderer_init.js:87:1542)
at electron/js2c/renderer_init.js:139:429
at electron/js2c/renderer_init.js:123:361
at EventEmitter.<anonymous> (electron/js2c/renderer_init.js:127:872)
at EventEmitter.emit (events.js:223:5)
at Object.onMessage (electron/js2c/renderer_init.js:115:818)
(node:9552) 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(). (rejection id: 1)
(node:9552) [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.
In my case I tracked the bug/problem down to some code that had a divide by zero in the event handler for DownloadItem.on. The code snippet in question is:
ses.on('will-download', (e, downloadItem, webContents) => {
let fileName = downloadItem.getFilename()
let fileSize = downloadItem.getTotalBytes() // this was zero (which caused the bug)
downloadItem.on('updated', (e, state) => {
let received = downloadItem.getReceivedBytes()
if (state === 'progressing' && received) {
// THE NEXT LINE CAUSED the divide by zero exception because fileSize was zero.
let progress = Math.round((received/fileSize)*100)
webContents.executeJavaScript(`window.progress.value = ${progress}`)
}
})
})
So my takeaway is that Electron's stack didn't help me identify where the bug is but the but was a normal coding error. Not having an exception that included a line number of my code made this particularly difficult to debug/isolate.
The underlying problem was caused by the URL being used when the course was written no longer working. From site: https://file-examples.com/.

client.channels.get(id).send() not working

So a discord bot I'm creating has a twitch notifications, and it uses snekfetch to create a looping request function. On the return of the function I have client.channels.get(id).send(embed) however it doesn't message the channel id which I've given it.
const api = `https://api.twitch.tv/helix/streams?user_login=${streamer}`;
snekfetch.get(api).set('Client-ID', "XXXXXXXXXXXXXX").then(r => {
if (r.body.stream === null) {
setInterval(() => {
snekfetch.get(api).then(console.log(r.body))
}, 30000);
} else {
const embed = new discord.RichEmbed()
.setAuthor(
`${r.body.data.user_name} is live on Twitch`,
)
.setThumbnail(`http://static-cdn.jtvnw.net/ttv-boxart/live_user_${streamer}-500x500.jpg`)
.addField('Views', `${r.body.data.viewer_count}`, true)
return bot.channels.get(XXXXXXXXXXXX).send("TEST");
}
});
I have named my client bot so instead of client.channels it's bot.channels
It should in theory send the TEST message to whatever channel id I give it, however instead I get an error.
(node:62565) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'send' of undefined
at /Users/XXXXXXX/Desktop/HelperBot/main.js:61:50
at processTicksAndRejections (internal/process/task_queues.js:89:5)
(node:62565) 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(). (rejection id: 1)
(node:62565) [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.
your error has to do with that not all channels are text channels. Before you can send a message it has to be sure it can. so you could check if that's the case with the function .isText() when you have checked that it is the type should change to text channels which are dm text and news at this moment. those have the .send function
The error said it can't find the .send("Test") function of something that is not defined.
So the error come from bot.channels.get(XXXX)
bot.channels return a collection. If you search a specific item of this collection. You need to use .find and not .get
More info about .find here : https://discord.js.org/#/docs/main/stable/class/Collection?scrollTo=find

Categories

Resources