Home > Software design >  Typescript: Cannot read properties of null (reading "add")
Typescript: Cannot read properties of null (reading "add")

Time:03-12

I wanted to create a role command in discord.js v13.6, but... It cannot read the line with adding a role. It gives the Typescript: Cannot read properties of null (reading "add") error. How do I fix it?

exports.run = async (client, message, args) => {
    const ms = require("ms");


    //!tempmute @user 1s/m/h/d

    let tomute = message.mentions.users.first();
    if (!tomute) return message.reply("Couldn't find user.");
    let muterole = message.guild.roles.cache.find(role => role.name === "admin");
    //start of create role
    if (!muterole) {
        try {
            muterole = await message.guild.roles.create({
                name: "admin",
                color: "#ff0000",
                permissions: []
            })
            message.guild.channels.cache.forEach(async (muterole, id) => {
                await muterole.overwritePermissions({
                    ADMINISTRATOR: true
                })
            });
        } catch (e) {
            console.log(e.stack);
        }
    }

    await (tomute.roles.add(muterole));
    message.reply(`<@${tomute.id}> стал админом`);

}

CodePudding user response:

 let tomute = message.mentions.users.first();

This returns a user object which doesn't have role manager. You need a guild member object to be able to access the roles which can be obtained by replacing users with members in the above snippet

    let tomute = message.mentions.members.first();

read about it here

CodePudding user response:

Instead of using

let tomute = message.mentions.users.first();

Use

let tomute = message.mentions.members.first();

You can also use

let tomute = message.guild.members.cache.get(args[0]) //to use its ID

Or even use it at once

let tomute = message.mentions.members.first() || message.guild.members.cache.get(args[0])

as Arnav Mentioned. Using user return a user object which doesn't have role manager.

  • Related