[英]TypeError: Cannot read properties of undefined (reading 'send') | Discord JS v14
I am making a discord bot that will automatically post a message once a document is added or modified in Firebase Firestore.我正在制作一个 discord 机器人,它会在 Firebase Firestore 中添加或修改文档后自动发布消息。 I have run into an error, saying
TypeError: Cannot read properties of undefined (reading 'send')
when trying to send a message to the channel.我遇到了一个错误,说
TypeError: Cannot read properties of undefined (reading 'send')
试图向频道发送消息时。
How can I get the channel with the ID stored in channelID
?如何获取带有存储在
channelID
中的 ID 的频道? I have tried the solution in the docs, but with no luck.我已经尝试过文档中的解决方案,但没有成功。 The channel exists, so I don't understand why this error keeps coming.
该频道存在,所以我不明白为什么这个错误不断出现。
Here is my code:这是我的代码:
const channelID = "1043109494625935387"
let botChannel
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
botChannel = client.channels.cache.fetch().find(channel => channel.id === channelID)
});
const doc = db.collection('announcements');
const observer = doc.onSnapshot(docSnapshot => {
docSnapshot.forEach(async (doc) => {
if (doc.data().published === false) {
await botChannel.send(doc.data().title)
}
})
}, err => {
console.log(`Encountered error: ${err}`);
});
It's because everything inside client.on('ready')
runs after you set doc.onSnapshot
这是因为
client.on('ready')
中的所有内容在您设置doc.onSnapshot
后运行
When you set the onSnapshot
listener, Firestore sends your listener an initial snapshot of the data (when botChannel
is still undefined
), and then another snapshot each time the document changes.当您设置
onSnapshot
侦听器时,Firestore 会向您的侦听器发送数据的初始快照(当botChannel
仍为undefined
时),然后在每次文档更改时发送另一个快照。
To solve this, you can move all this inside your callback.要解决这个问题,您可以将所有这些移动到回调中。 Also, you can fetch the channel instead.
此外,您可以改为获取频道。
client.on('ready', async () => {
console.log(`Logged in as ${client.user.tag}!`);
const channelID = '1043109494625935387';
const botChannel = await client.channels.fetch(channelID);
db.collection('announcements').onSnapshot(
(docSnapshot) => {
docSnapshot.forEach(async (doc) => {
if (doc.data().published === false) {
await botChannel.send(doc.data().title);
}
});
},
(err) => {
console.log(`Encountered error: ${err}`);
},
);
});
It's not recommended to fetch all channels at once.不建议一次获取所有频道。 Instead, try fetching a single channel at once like so:
相反,尝试像这样一次获取单个频道:
<client>.channels.fetch(SNOWFLAKE_ID)
Alternatively if you have the guild object, this will be faster或者,如果你有公会 object,这会更快
<guild>.channels.fetch(SNOWFLAKE_ID)
Do keep in mind that these methods both return a Promise , you might have to resolve it.请记住,这些方法都返回Promise ,您可能必须解决它。
These solutions will work because the cache is not always up-to-date.这些解决方案将起作用,因为缓存并不总是最新的。 If you want to get a channel it is highly recommended to just fetch it.
如果你想获得一个频道,强烈建议只获取它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.