无法读取不和谐中未定义的属性'cache'.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(client => {(。从discoverAPI返回的client没有channels属性,只有bot有。

由于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;
});
});

最新更新