Don’t have permission to read data on Onclick in React Firebase Firestore

I am creating a button that loads more documents from firestore database but the problem arises that I am able to do it in useEffect and set the state to the data. When I try to do the same thing in on click event handler it gives me the error that you don’t have sufficient access as I am logged in I have the access so I was able to get the data from firestore.
Here is some code::

import React, { useEffect, useState } from "react";
import Container from "@mui/material/Container";
import Box from "@mui/material/Box";
import Typography from "../../subcomponents/Typography";
import Adcard from "../../subcomponents/Marketplace/Adcard";
import Button from "@mui/material/Button";
import Pagination from "../../subcomponents/Marketplace/PaginationComponent";
import { db } from "../../config/Config";

function Adspace({ Products }) {
  const [data, setData] = useState(null);
  const [lastDoc, setlastDoc] = useState();
  useEffect(() => {
    return db
      .collection("Products")
      .orderBy("MonthlyRate", "asc")
      .limit(2)
      .get()
      .then((snapshot) => {
        const ProductData = snapshot.docs.map((doc) => doc.data());
        /* snapshot.docs.forEach((doc) => {
          ProductData.push({ ...doc.data(), id: doc.id });
          setData(ProductData);
        }); */
        setData(ProductData);

        const lastDoc = snapshot.docs[snapshot.docs.length - 1];
        setlastDoc(lastDoc);
      });
  }, []);
  console.log(data);
  console.log(Products);
  const fetchData = () => {
    db.collection(Products)
      .orderBy("MonthlyRate", "asc")
      .startAfter(lastDoc)
      .limit(1)
      .get()
      .then((snapshot) => {
        const ProductData = snapshot.docs.map((doc) => doc.data());
        setData((PrevData) => [...PrevData, ProductData]);
        const lastDoc = snapshot.docs[snapshot.docs.length - 1];
        setlastDoc(lastDoc);
      });
  };
  return (
    <div>
      <Container component="section" sx={{ mt: 8, mb: 4 }}>
        <Typography variant="h4" marked="center" align="center" component="h2">
          Rent Machines
        </Typography>
      </Container>
      <Box
        sx={{
          m: 8,
          display: "flex",
          flexWrap: "wrap",
          justifyContent: "flex-start",
        }}
      ></Box>
      <Container
        component="section"
        sx={{ mt: 8, mb: 4, display: "flex", justifyContent: "center" }}
      >
        {/*  {data !== null ? <Adcard /> : ""} */}

        {data !== null
          ? data.map((doc) => {
              if (doc.Type === Products) {
                return <Adcard data={doc} state={Products} key={doc.id} />;
              } else if (Products === "All") {
                return <Adcard data={doc} state={Products} />;
              }
            })
          : ""}
      </Container>
      <Box textAlign="center">
        <Button variant="contained" onClick={fetchData}>
          Load More
        </Button>
      </Box>
    </div>
  );
}

export default Adspace;

And here is firestore database rules for this collection

 match /Products/{userid}{
        allow create:if request.auth.uid!=null
      allow read: if request.auth.uid!=null
      allow write:if request.auth.uid==userid
      allow delete:if request.auth.uid!=null
    }

AJAX, using onreadystatechange() but still not working

I have been working on a XML, HTTP communication , and I do not understand why my code seems to have some type of error. When sending a get request, sometimes it fails to get response or even to send to the server(I believe, as no message is shown). When I include alerts it does work. I understand this is due to asynchronous programming, as the alerts give more time to the operation. But even so, I am working with onreadystatechange() so I do not understand. Here is the code:

<script  type ="text/javascript">

const xhr = new XMLHttpRequest();
function sendData() {
const getEnter = document.getElementById('p_input').value;
const cont = document.getElementById('cont');
var url = "http://192.168.1.132:4344?";
url += getEnter;

xhr.onreadystatechange = () => {
    if(xhr.readyState==4 && xhr.status==200){
        console.log("success");

    }
}
xhr.open('GET',url,true);
cont.textContent ="processing";
xhr.send();
}
</script> 

I am calling this function on the onClicked event of a button. It would be excellent if someone knew how to fix this

return value remains undefined even when timed out for 10 seconds

I had an issue where I needed to return the response of an async function which kept being returned as undefined. So I decided to use setTimeout() before trying to use it. It still doesn’t seem to work. Can someone explain why?

My attempt:

insertUser = (req,res) => {
    var record = {
        'handle': req.body.handle,
        'name': req.body.name,
        'password': req.body.password
    };
    var response;
    createUser(record, response)
    setTimeout(() => {
        console.log(response);
    },10000)
};

createUser = (record, response) => {
    users.insertOne(record, function(err, result){
        if(err){
            response = {'code': 404, 'message': 'Something went wrong. Message: ', err} 
        }else{
            response = {'code': 200, 'message': result.insertedId}
        }
    })
    setTimeout(() => {
        console.log(response)
    }, 1000);
};

Why unary operator before exponentiation expression in JavaScript cannot be evaluated? [duplicate]

I noticed that expression like “-3**2” is considered ambiguous in JavaScript. For example, in Chrome, the error is thrown as “Uncaught SyntaxError: Unary operator used immediately before exponentiation expression. Parenthesis must be used to disambiguate operator precedence.”

From the perspective of compiler (specifically, parser I think) or syntax designer, why this input is not allowed? If I were the designer of the compiler, maybe I would just assign a higher precedence to unary operator, or the other way, instead of throw an error.

how to change navigation focus view of v-date-picker with manual trigger

i made vue date range picker manually using v-list and v-date-picker :

<v-card width="600" elevation="1" rounded>
    <v-container class="pa-0" fluid>
      <v-row dense no-gutters>
        <v-col cols="3" style="height: 100%">
          <v-list>
            <v-list-item-group v-model="select">
              <v-list-item v-for="(item, i) in items" :key="i">
                <v-list-item-content>
                  <v-list-item-title v-text="item.time" @click="tes(item.duration)"></v-list-item-title>
                </v-list-item-content>
              </v-list-item>
            </v-list-item-group>
          </v-list>
        </v-col>
        <v-divider></v-divider>
        <v-col cols="9">
          <v-date-picker ref="tes" v-model="dates" range full-width>
            <template>
              <v-container class="pa-0">
                <v-row>
                  <v-col cols="6"><YBtn block secondary>Cancel</YBtn></v-col>
                  <v-col cols="6"><YBtn block>Apply</YBtn></v-col>
                </v-row>
              </v-container>
            </template>
          </v-date-picker>
        </v-col>
      </v-row>
    </v-container>
</v-card>

and my script :

export default {
data() {
    return {
    select: { time: 'Today', duration: 'today' },
    items: [
        { time: 'Today', duration: 'today' },
        { time: 'Yesterday', duration: 'yesterday' },
        { time: 'This Month', duration: 'thismonth' },
        { time: 'This Year', duration: 'year' },
        { time: 'Previous Month', duration: 'previousmonth' }
    ],
    dates: [this.$moment().format('YYYY-MM-DD')]
    }
},

methods: {
    tes(e) {
    switch (e) {
        case 'yesterday':
        this.dates = this.$moment().subtract(1, 'days').format('YYYY-MM-DD')
        break
        case 'thismonth':
        this.dates = [
            this.$moment().startOf('month').format('YYYY-MM-DD'),
            this.$moment().endOf('month').format('YYYY-MM-DD')
        ]
        console.log(this.dates)
        break
        case 'year':
        this.dates = [
            this.$moment().startOf('year').format('YYYY-MM-DD'),
            this.$moment().endOf('year').format('YYYY-MM-DD')
        ]
        console.log(this.dates)
        break
        case 'previousmonth':
        this.dates = []
        this.dates = [
            this.$moment().startOf('month').subtract(1, 'months').format('YYYY-MM-DD'),
            this.$moment().endOf('month').subtract(1, 'months').format('YYYY-MM-DD')
        ]
        console.log(this.dates)
        break
        default:
        this.dates = this.$moment().format('YYYY-MM-DD')
        break
    }
    }
}
}

when i click on previous month, it succesfully change v-date-picker value to the selected previous month. but, the navigation still in current month. how do i change v-date-picker navigation focus to selected previous month?

as you can see there, the focus navigation at december. what i want when i click prevous month. it showing november, which is the previous selected month

How do I create a custom Form with FormData and upload to a server as PHP

If you wanted to upload randomText - 5994 text to a PHP server without the client using a <form> and data was sent in the background, how would you do it?
I guess this should be my code…

let xhr = new XMLHttpRequest();
xhr.open("log.php","POST");
//correct after this line.
xhr.send('{"name":"Sample Form Data","age":".."}');
xhr.close();

The code should send a request + data and the PHP code will do the rest.
This is the PHP code.

$name = $_POST["name"];
$age = $_POST["age"];
echo "client: ".$name."age".$age."yrs";

Native Javascript click event not working on icon in button

I have a button in my HTML + Tailwindcss page like so:

<div class="fixed bottom-4 right-4 z-10">

    <button
        id="button-fab-anchor"
        class="z-50 whitespace-nowrap flex items-center px-3.5 py-2 rounded-full shadow-xl
           outline-none focus:outline-none border-t border-b border-transparent
           combo-primary hover:bg-primary-contrast active:bg-primary-contrast"
    >
        <span class="z-40 icon-inverse-primary text-lg text-center">
            <i id="up-icon" class="fal fa-chevron-up"></i>
            <i id="down-icon" class="fal fa-chevron-down hidden"></i>
        </span>

    </button>

    <ul id="button-fab-list" class="absolute bottom-full right-0 flex flex-col justify-end hidden">
        <li> Buttons here... </li>
    </ul>

</div>

On the page I have the following JS:

document.addEventListener("DOMContentLoaded", function(event) {

    const btnAnchor = document.getElementById('button-fab-anchor');

    if (btnAnchor) {

        const btnList = document.getElementById("button-fab-list");
        const upIcon = document.getElementById("up-icon");
        const downIcon = document.getElementById("down-icon");

        btnAnchor.addEventListener("click",  function(event) {
            if (event.target == btnAnchor) {
                btnList.classList.toggle('hidden');
                upIcon.classList.toggle('hidden');
                downIcon.classList.toggle('hidden');
            }
        });

    }

});

This works fine if I click on the button but not on the icon in the button. I have tried using z-index to place the button parent at z-50 and the icon as z-10 so the parent is stacked above the child.

What sis I miss / How do I set up the event to work on the button parent and all its children (i.e.: the icon)?

How do I access a constructor “this” variable? [duplicate]

In my updateCamera(event) function, I am trying to access this.camera as can be shown in my constructor. Unfortunately, it’s undefined in that function, I assume it’s a scope issue, but I’m not sure how to solve it. Any ideas? Thank you.

export default class Experience {
    constructor(options = {}) {
        this.camera = new Camera();
        // removed unnecessary stuff
        this.onMouseDrag();
    }

    updateCamera(event) {
        console.log(this.camera); //Prints "undefined" in the console
        this.camera.position.x = (event.clientX / window.innerWidth) * 2 - 1;
    }

    onMouseDrag() {
        window.addEventListener("mousedown", () => {
            window.addEventListener("mousemove", this.updateCamera);
        });
        window.addEventListener("mouseup", () => {
            window.removeEventListener("mousemove", this.updateCamera);
        });
    }

Javascript single quote inside string for exported text file [duplicate]

I am creating a node.js file that creates and readme file where the install directions need to be displayed as shell or javascript type font. However, I have not been able to use the single quotes required to make that work since they close out the string.

function generateExport(data) {
  const { username, ...title} = data;

  return `
    ```shell <--- how would you do this ?
    ${data.title} 
    ```  <----- and this?
`;
}

“Error : Cannot use ‘in’ operator to search for ‘length’ in [{“ID”:”2″,”Name”:”EAA2″}]” when performing $.each

What ever I do, I keep getting the same error. The only thing I have found that might of helped is the JSON.parse, but I still get the same problem. console log gives data as [{"ID":"2","Name":"EAA2"}]

I split it into two functions as I didn’t want to keep going back to the api everytime a user selects/de-selects an option.

I have also tried the following:

  1. Changing vars to lets
  2. Passing data.d from the update to the populate
function populateAvailableAuthorities() {
            var list = $('#availableAA');
            var data = JSON.parse($('#AAJSON').val());
            var auths = $('#tbSelectedAA').val();

            list.empty();
            
            $.each(data, function (key, entry) {
                if (!~auths.indexOf(entry.ID + ';')) {
                    list.append($('<option></option>').attr('value', entry.ID).text(entry.Name));
                }
            });
            
        }

        function updateListboxes() {
            var teams = '';
            let aa = $('#AAJSON');

            aa.empty();

            $('#cblTeams input:checked').each(function () {
                teams += $(this).attr('value') + ',';
            });

            if (teams.length > 1) {
                teams = teams.substr(0, teams.length - 1);

                $.ajax({
                    type: "POST",
                    url: '<%# ResolveUrl("~/api/Authorities.asmx/FetchByTeam") %>',
                    data: '{teams: "' + teams + '"}',
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        aa.val(JSON.stringify(data.d));
                        populateAvailableAuthorities();
                    }
                });
            }
        }

Vue : How to use async await accordingly in a function array of which can have two functions for Promise.all?

I want to use await where I marked [here] in 1.vue. However, if I use await there then it emits error Unexpected reserved word 'await'. If I want to use async useFunctionToAllServers() sequentially after [Promise.all] then, where to put async or how to change async useFunctionToAllServers()? Or need to change submitToTheOthers()?

1.vue

<template>
  <div>
    <label for="imgUpload">
      <button class="point">upload</button>
    </label>
    <input
      type="file"
      class="input-file"
      ref="logo1"
      id="imgUpload"
      @change="sendFile('logo')"
    />
    <div v-if="imageData" class="imgBox">
      <img :src="imageData" />
    </div>

    <label for="imgUpload">
      <button class="point">upload1</button>
    </label>
    <input
      type="file"
      class="input-file"
      ref="logo1"
      id="imgUpload"
      @change="sendFile('logo1')"
    />
    <div v-if="imageData1" class="imgBox">
      <img :src="imageData1" />
    </div>
    <button @click="useFunctionToAllServers">BUTTON</button>
  </div>
</template>
<script>
import {
  updateGeneralInfo,
  createUploadToOther,
  updateGeneralInfoToOther,
} from '@/2'

export default {
  data() {
    return {
      filename: '',
      filename1: '',
      originalFilename: '',
      originalFilename1: '',
      imageData: '',
      imageData1: '',
      serverNames: ['a server', 'b server'],
      idxs: [0, 1],
      serverFullAddress:['http://a.url', 'http://b.url'],
      serverResCheck:[],
      isLogoChanged:false,
      isLogo1Changed:false,
    }
  },
  methods: {  
    sendFile(type) {
      let file = ''
      if (type == 'logo') {
        file = this.$refs.logo.files[0]
      } else {
        file = this.$refs.logo1.files[0]
      }
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = (e) => {
        if (type == 'logo') {
        this.imageData = e.target.result
        } else {
        this.imageData1 = e.target.result
        }
      }
    },
    sendFileToOther(type, serverFullURL) {
      let file = ''
      if (type == 'logo') {
        file = this.$refs.logo.files[0]
        this.originalFilename = this.$refs.logo.files[0].name
      } else {
        file = this.$refs.logo1.files[0]
        this.originalFilename1 = this.$refs.logo1.files[0].name
      }
      const reader = new FileReader()
      reader.readAsDataURL(file)
      const formdata = new FormData()
      formdata.append('logo', file)
      
      formdata.append('serverURL', serverFullURL)

      return createUploadToOther(formdata)
    },
    
    async useFunctionToAllServers() {
      
        let data = {
          foo: this.foo,
          bar: this.bar,
        }
        
        await updateGeneralInfo(data).then().catch()
      
        await Promise.all(this.submitToTheOthers()).catch((err) =>{ // [Promise.all]
          console.log('Promise.all err>>', err)
        });  
        
        let notWorkingServers = []
        for(let i=0; i< this.idxs.length ; i++){
          if(!this.serverResCheck[i]){
          notWorkingServers.push(this.serverNames[i])
          }
        }
        if(Array.isArray(notWorkingServers) && notWorkingServers.length == 0){
          alert('not working : ', notWorkingServers)
        }else{
          alert('all server works')
        }      
    },
    submitToTheOthers(){
      let data = {
        foo: this.foo,
        bar: this.bar,
      }
      let logoData ={}
      if(this.originalFilename){
        data.logo = this.originalFilename
        logoData.logo = true
      }else if(this.isLogoChanged){
        data.logo = this.logo
      }
      if(this.originalFilename1){
        data.logo1 = this.originalFilename1
        logoData.logo1 = true
      }else if(this.isLogo1Changed){
        data.logo1 = this.logo1
      }
      
      return this.idxs.map( (_entry, i) => {
        return updateGeneralInfoToOther(1, data, this.serverFullAddress[i]).then((res) => { // [here2]
          if (res.status == 200) {
            this.serverResCheck[i] = true
            if(logoData.logo){
              this.sendFileToOther('logo', this.serverFullAddress[i]).then((res) => { // [here]
              }).catch((err) => {
                this.serverResCheck[i] = false
              })
            }
            if(logoData.logo1){
              this.sendFileToOther('logo1', this.serverFullAddress[i]).then((res) =>{ // [here]
              }).catch((err) => {
                this.serverResCheck[i] = false
              })
            }
          }else{
            this.serverResCheck[i] = false            
          }
        }).catch((err) => {
          this.serverResCheck[i] = false
        })
      })
    },
  },
}
</script>

2.js

import axios from 'axios'
export const headers = {
  'Content-Type': 'application/json',
  'header1' : 'header1',
  'header2' : 'header2',
}

export function updateGeneralInfoToOther(id, data, serverAddress) {
  data.serverAddress = serverAddress
  return axios.put(`/u/r/l/${id}`, data, { headers })
}

export function updateGeneralInfo(id, data) {
  return axios.put(`/extra/u/r/l/${id}`, data, { headers })
}

export function createUploadToOther(data) {
  return axios.post('/u/r/l', data, { headers })
}

How to validate a Cloned form fields by javascript?

// Cloning Form
  var id_count = 1;
  $('.add').on('click', function() {
    var source = $('.form-holder:first'), clone = source.clone();
    clone.find(':input').val("").attr('name', function(i, val) {
      return val + '-'+id_count;
    });

    clone.appendTo('.form-holder-append');
      id_count++;

  });

  // Removing Form Field
  $('body').on('click', '.remove', function() {
    var closest = $(this).closest('.form-holder').remove();
  });
.remove
{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-folder">

 <input type="file" name="variant_images" id="upload_file" required multiple>
  
 
  
  <button class="remove">remove -</button>
</div>



  <div class="form-holder-append"></div><br>
  <button class="add">Add +</butoon>
  
// Cloning Form
  var id_count = 1;
  $('.add').on('click', function() {
    var source = $('.form-holder:first'), clone = source.clone();
    clone.find(':input').val("").attr('name', function(i, val) {
      return val + '-'+id_count;
    });

    clone.appendTo('.form-holder-append');
      id_count++;

  });

  // Removing Form Field
  $('body').on('click', '.remove', function() {
    var closest = $(this).closest('.form-holder').remove();
  });





//Image upload restriction
$(document).ready(function(){
  $('#upload_file').change(function(){
   //get the input and the file list
    var images = document.getElementById('upload_file');
      if(images.files.length<4){
          alert ("Please Upload minimum 4 images.");
          $("#upload_file").val('');

      }
   });
});
.remove
{
display:none;
}
.form-holder-append .remove {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-holder">

  <input type="file" name="variant_images" id="upload_file" required multiple>
 <button class="remove">remove - </button>

</div>
<div class="form-holder-append"></div><br>
<button class="add">add + </button>

I want to validate a each cloned forms input file, the validation is –>minimum 4 images should be uploaded otherwise the field returns empty value. But I have got this for fist form. After cloned, the id would be same and this is not working. How to write this for unlimited clone forms?

(Beginner Coder. Entry Entry Level) Save/Load function on HTML clicker game not working

Beginner learning from forums websites and youtube, bear with me pls.
(plus im dumb)

I’m making a stupid clicker game just to see if i can do it (clearly not).
I’ve got some buttons with onclick functions and multipliers setup whatever everything works fine.

Until Saving/Loading.

I followed a tutorial i found for the save function, to save/load your progress via localStorage/cookies, and it’s saving the total “money” (score) upon refresh, but my “scorepersecond” and every upgrade via button doesn’t save, even though i’ve included their cost and name values to tell which variables i want to save. I’m using VS Code with Live Server extension to test (firefox).

    function loadGame() {
            var savedGame = JSON.parse(localStorage.getItem("gameSave", "score", "scorepersecond", "cursors", "cursorcost", "lighters", "lightercost", "grinders", "grindercost", "devils", "devilcost", "trays", "traycost", "dealers", "dealercost"));
            if (typeof savedGame.score !== "undefined") score = savedGame.score;
        }
         function saveGame() {
             
            var gameSave = {
                 score: score,
                 scorepersecond: scorepersecond,
                 clickingPower: clickingPower,
                 cursors: cursors,
                 cursorcost: cursorcost,
                 lighters: lighters,
                 lightercost: lightercost,
                 grinders: grinders,                
                 grindercost: grindercost,
                 devils: devils,
                 devilcost: devilcost,
                 trays: trays,
                 traycost: traycost,
                 dealers: dealers,
                 dealercost: dealercost,
                        
             };
             localStorage.setItem("gameSave", JSON.stringify(gameSave));
            document.getElementById("score").innerHTML = score;
        document.getElementById("scorepersecond").innerHTML = scorepersecond;
            document.getElementById("cursorcost").innerHTML = cursorcost;
            document.getElementById("cursors").innerHTML = cursors;
            document.getElementById("lightercost").innerHTML = lightercost;
            document.getElementById("lighters").innerHTML = lighters;
            document.getElementById("grindercost").innerHTML = grindercost;
            document.getElementById("grinders").innerHTML = grinders;
            document.getElementById("devilcost").innerHTML = devilcost;
            document.getElementById("devils").innerHTML = devils;
            document.getElementById("traycost").innerHTML = traycost;
            document.getElementById("trays").innerHTML = trays;
            document.getElementById("dealercost").innerHTML = dealercost;
            document.getElementById("dealers").innerHTML = dealers;
         }
         window.onload = function() {
            loadGame();
            updatescorepersecond();
            document.getElementById("score").innerHTML = score;
            document.getElementById("cursorcost").innerHTML = cursorcost;
            document.getElementById("cursors").innerHTML = cursors;
            document.getElementById("lightercost").innerHTML = lightercost;
            document.getElementById("lighters").innerHTML = lighters;
            document.getElementById("grindercost").innerHTML = grindercost;
            document.getElementById("grinders").innerHTML = grinders;
            document.getElementById("devilcost").innerHTML = devilcost;
            document.getElementById("devils").innerHTML = devils;
            document.getElementById("traycost").innerHTML = traycost;
            document.getElementById("trays").innerHTML = trays;
            document.getElementById("dealercost").innerHTML = dealercost;
            document.getElementById("dealers").innerHTML = dealers;
            
         };

Thing’s I’ve Tried.

        var savedGame = JSON.parse(localStorage.getItem("gameSave"));
        if (typeof savedGame.score !== "undefined") score = savedGame.score;
    }```

```function loadGame() {
        var savedGame = JSON.parse(localStorage.getItem("gameSave"));
        if (typeof savedGame.score !== "undefined") score = savedGame.score;
        if (typeof savedGame.scorepersecond!== "undefined") scorepersecond = savedGame.scorepersecond;
    }

along with other variables i want to save, in the form of “(typeof ” which have also failed.

Not sure if this bit literally means anything, but if i inspect element on the page and access local storage it updates accordingly every 30 seconds with proper values, but upon page refresh it poof’s (except for total “money” (score) on top of the page).

Not sure what people need to see or if i shared enough, but if anyone could help without being a d-bag that’d be cool 🙂 even if not to solve it but a general idea of where i f’d up besides the whole thing. thanks in advance and lmk if you need to see more of my poopy clicker game.

Finding the creation date of the guild in the correct format, using discord.js

I’m trying to make a serverinfo command, and I wanted to add Server CreationDate.

This should give the Date, Time and How long ago.

But the issue is when I use message.guild.createdAt the output looks like this:

Sat Sep 04 2021 09:44:44 GMT+0000 (Coordinated Universal Time)

It’s too long AND it looks bad, I’m wondering if I can have the output look something like this?

09/04/2021 11:44 (3 months and 10 days ago)

Here is my code:

const { MessageEmbed } = require('discord.js');

module.exports = {
    name: 'serverinfo',
    category: 'Info',
    description: 'Shows info about the server.',
    aliases: [],
    usage: 'Serverinfo',
    userperms: [],
    botperms: [],
    run: async (client, message, args) => {
  if(message.author.bot) return;

  let staffcount = message.guild.roles.cache.get(process.env.ROLE_STAFF).members.size;
  let botcount = message.guild.roles.cache.get(process.env.ROLE_BOT).members.size;
  let membercount = message.guild.memberCount - botcount
  let verifiedcount = message.guild.roles.cache.get(process.env.ROLE_MEMBER).members.size - staffcount

    const embed = new MessageEmbed()
      .setThumbnail(client.user.displayAvatarURL({ dynamic: true, size: 512 }))
      .setColor("BLUE")
      .setTitle(':desktop: SERVER INFORMATION :desktop:')
      .addField('Server Name', '```' + message.guild.name + '```',true)
      .addField('Server Owner', '```SirDevinci#1998```',true)
      .addField('Server Members ['+ membercount +']', '```' + verifiedcount + ' Verified Members | ' + staffcount + ' Staff Members```',false)
      .addField('Server Tier','```' + message.guild.premiumTier + '```',true)
      .addField('Server Boosts','```' + message.guild.premiumSubscriptionCount + '```',true)
      .addField('Server CreationDate','```' + message.guild.createdAt + '```',false)
      message.channel.send(embed);
  }
}

thanks.