简体   繁体   中英

Discord.JS TypeError: Cannot read property 'roles' of undefined while trying to add roles

   const Discord = require('discord.js');
   const client = new Discord.Client();
   const config = require('./config.json');


   client.once('ready', () => {
       console.log('Ready!');
   });

   client.on('message', message => {
       if (message.content.includes('jail')) {
               let muteUser = message.guild.members.cache.get('832168644230381609');
               let mainRole = message.guild.roles.cache.get('845217593970786314');
               let muteRole = message.guild.roles.cache.get('845217665906638868');

               muteUser.roles.remove(mainRole).catch(console.error);
               muteUser.roles.add(muteRole).catch(console.error);
               console.log('User muted');
      }
   })

   client.login('');

I created this as a test, that is why I have a constant id for the roles and for the user.

Error: TypeError: Cannot read property 'roles' of undefined The error is for the "muteUser.roles.remove(mainRole).catch(console.error);"

After studying the docs I couldn't find out how can I make it work with the latest version.

let muteUser = await message.guild.members.fetch('832168644230381609');
let mainRole = await message.guild.roles.cache.get('845217593970786314');
let muteRole = await message.guild.roles.cache.get('845217665906638868');

//Muting the user
await muteUser.roles.remove(mainRole).catch(console.error);
await muteUser.roles.add(muteRole).catch(console.error);

I should have use fetch and NOT cache for the muteUser one, also I had to resolve my promise with the asyncs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM