簡體   English   中英

未捕獲的 TypeError TypeError:無法讀取未定義 Discord.js 的屬性“緩存”

[英]Uncaught TypeError TypeError: Cannot read property 'cache' of undefined Discord.js

我對'cache'有疑問。 我之前修復了'guilds'有一個錯誤,但現在是'cache'有問題。

單擊網頁時,控制台中出現此錯誤

Uncaught TypeError TypeError: Cannot read property 'cache' of undefined
    at <anonymous> (c:\Users\elelo\OneDrive\Bureau\bot discord serv NFT\website\public\getUserGuilds.js:29:31)
    at run (c:\Users\elelo\OneDrive\Bureau\bot discord serv NFT\website\public\getUserGuilds.js:27:20)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

這是舊問題公會提出的舊問題的鏈接

代碼文件getUserGuilds.js

const { Permissions } = require('discord.js');
const client = require('../../index');
const schema = require('../../model/dashboard');
const jwt = require('jsonwebtoken');
const { jwt_secret } = require('../../config.json');

module.exports = {
 name: "/getUserGuilds/",
 run: async (req, res) => {
    delete require.cache[require.resolve("../html/getUserGuilds.ejs")];

    if (!req.cookies.token) return res.redirect('/login')
    let decoded;
    try { 
        decoded = jwt.verify(req.cookies.token, jwt_secret);
    } catch (e) { }
    if (!decoded) res.redirect('/login');

    let data = await schema.findOne({
        _id: decoded.uuid,
        userID: decoded.userID
    });
    if (!data) res.redirect('/login');

    let guildArray = await process.oauth.getUserGuilds(data.access_token);
    let mutualArray = [];
    guildArray.forEach(g => {
        g.avatar = `https://cdn.discordapp.com/avatars/${g.id}/${g.icon}.png`;
        if (client.guilds.cache.get(g.id)) {
            const bitPermissions = new Permissions(g.permissions_new);
            if (bitPermissions.has(Permissions.FLAGS.MANAGE_GUILD) || bitPermissions.has(Permissions.FLAGS.ADMINISTRATOR) || client.guilds.cache.get(g.id).ownerID == data.userID) g.hasPerm = true
            mutualArray.push(g);
        } else g.hasPerm = false;
    });
    let args = {
        avatar: `https://cdn.discordapp.com/avatars/${data.userID}/${data.user.avatar}.png`,
        username: data.user.username,
        discriminator: data.user.discriminator,
        id: data.user.userID,
        loggedIN: true,
        guilds: guildArray,
        adminGuilds: mutualArray
    };

    res.render('./website/html/getUserGuilds.ejs', args);
  }
}

代碼文件index.js

const Discord = require('discord.js');
const { Intents } = Discord;
const axios = require('axios');
const express = require("express");
const app = express()
const fs = require("fs");
const DiscordOauth2 = require('discord-oauth2');
const cookieParser = require('cookie-parser');
const mongoose = require('mongoose');
const { token, clientId, clientSecret } = require('./config.json');
const client = new Discord.Client({
  intents: 
  [
    Intents.FLAGS.GUILDS,
    Intents.FLAGS.GUILD_MESSAGES,
    Intents.FLAGS.GUILD_MEMBERS
  ]
});
require('dotenv').config();

const prefix = "k!";

mongoose.connect(process.env.DATABASE_URI, {
    autoIndex: false,
    maxPoolSize: 10,
    serverSelectionTimeoutMS: 5000,
    socketTimeoutMS: 45000,
    family: 4
}).then(() => { console.log('[Database] - La base de donnée est connectée') })
.catch(err => {console.log(err)})

app.enable("Trust proxy") // if this ip is ::1 it means localhost
app.set("etag", false) // disable cache
app.use(express.static(__dirname + "/website"))
app.set("views", __dirname)
app.set("view engine", "ejs")
app.use(cookieParser());
process.oauth = new DiscordOauth2({
    clientId: clientId,
    clientSecret: clientSecret,
    redirectUrl: "http://localhost:90/callback"
})

client.on("ready", () => {
    console.log("[BOT] - Le Bot est opérationnel");
    getGas();
});

我該如何解決?

有了這樣的事情,我發現使用client.guilds.fetch()可以更好,更順利地工作。

// async the forEach function param
guildArray.forEach(async g => {

  g.avatar = `https://cdn.discordapp.com/avatars/${g.id}/${g.icon}.png`;

  // awaits the fetching a the guild, for discord's sake
  await client.guilds.fetch(g.id)
    .catch(err => err) // caution of error
    .then(guild => {
    // bool based on if client was able to fetch guild
    if (guild !== undefined) {
      // if yes
      const bitPermissions = new Permissions(g.permissions_new)
      if (bitPermissions.has(Permissions.FLAGS.MANAGE_GUILD) || 
      bitPermissions.has(Permissions.FLAGS.ADMINISTRATOR) || 
      client.guilds.cache.get(g.id).ownerID == data.userID) g.hasPerm = true
      mutualArray.push(g)
    } else g.hasPerm = false; // if no
  })
});

為什么獲取而不獲取?

Fetch 函數允許您異步請求資源。 如果由於某些網絡問題導致請求失敗,則 Promise 被拒絕。 async/await 語法非常適合 fetch(),因為它簡化了 Promise 的工作。 意思是,我們等待不和諧的時間。 但出錯的可能性較小。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM