[英]TypeError: Cannot read property 'cache' of undefined in Discord.js
[英]Cannot read property 'cache' of undefined in discord.js
我正在編寫一些代碼來分析用於測量毒性的消息(使用 Perspective API),並為此采取行動。 我需要它的日志。 我有下面的代碼來測量所有消息和日志結果而不采取任何行動,但它給出了這個錯誤:
Cannot read property 'cache' of undefined
這是給出錯誤的代碼的一部分:
const {google} = require('googleapis');
const fs = require('fs');
client.on('message', (msg) => {
if(msg.author.id === client.user.id) return;
API_KEY = process.env['PERSPECTIVE_API_KEY'];
DISCOVERY_URL = 'https://commentanalyzer.googleapis.com/$discovery/rest?version=v1alpha1';
google.discoverAPI(DISCOVERY_URL)
.then(client => {
const analyzeRequest = {
"comment": {
"text": msg.content,
},
"requestedAttributes": {
"TOXICITY": {},
},
"doNotStore": true
};
client.comments.analyze(
{
key: API_KEY,
resource: analyzeRequest,
},
(err, response) => {
if (err) throw err;
let raw_analyzeResult = JSON.stringify(response.data, null, 2)
const analyzeResult = Math.round(JSON.parse(raw_analyzeResult).attributeScores.TOXICITY.summaryScore.value * 100)
console.log("Message: " + msg.content + "\nSent by: <@" + msg.author.id + ">\n Toxicity Level: %" + analyzeResult);
client.channels.cache.get("836242342872350790").send("Message: " + msg.content + "\nSent by: <@" + msg.author.id + ">\n Toxicity Level: %" + analyzeResult)
});
})
.catch(err => {
throw err;
});
});
另外,這是我的變量部分:
let discord = require("discord.js")
let client = new discord.Client()
let prefix = ";"
我該如何解決這個問題?
您正在混合兩個client
變量。 您將一個用於機器人( let client = new discord.Client()
)和一個用於 Google API ( .then .then(client => {
)。從discoverAPI
返回的client
沒有channels
屬性,只有機器人會。
由於client.channels
未定義,您會收到錯誤“無法讀取未定義的屬性‘緩存’”。
嘗試重命名其中之一,例如google.discoverAPI().then((discoveryClient) =>...)
:
client.on('message', (msg) => {
if (msg.author.id === client.user.id) return;
API_KEY = process.env['PERSPECTIVE_API_KEY'];
DISCOVERY_URL = 'https://commentanalyzer.googleapis.com/$discovery/rest?version=v1alpha1';
google
.discoverAPI(DISCOVERY_URL)
.then((discoveryClient) => {
const analyzeRequest = {
comment: { text: msg.content },
requestedAttributes: { TOXICITY: {} },
doNotStore: true,
};
discoveryClient.comments.analyze(
{
key: API_KEY,
resource: analyzeRequest,
},
(err, response) => {
if (err) throw err;
let raw_analyzeResult = JSON.stringify(response.data, null, 2);
const analyzeResult = Math.round(
JSON.parse(raw_analyzeResult).attributeScores.TOXICITY.summaryScore
.value * 100,
);
console.log(
'Message: ' +
msg.content +
'\nSent by: <@' +
msg.author.id +
'>\n Toxicity Level: %' +
analyzeResult,
);
client.channels.cache
.get('836242342872350790')
.send(
'Message: ' +
msg.content +
'\nSent by: <@' +
msg.author.id +
'>\n Toxicity Level: %' +
analyzeResult,
);
},
);
})
.catch((err) => {
throw err;
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.