Discord.js 无法检查“lastMessage.content”
Posted
技术标签:
【中文标题】Discord.js 无法检查“lastMessage.content”【英文标题】:Discord.js Can't Check 'lastMessage.content' 【发布时间】:2020-10-30 03:37:02 【问题描述】:function broadcast()
client.guilds.cache.forEach(g =>
g.channels.cache.find(c => c.name === 'chat' && c.lastMessage.content !== 'test').send('test')
)
;
setInterval(broadcast, 3000);
此代码不起作用。如果您不明白,我正在尝试获取所有名为“聊天”的频道,顺便说一下最后一条消息不是广播消息,然后向该频道发送一条消息。
2020-07-09T13:33:43.715482+00:00 app[worker.1]:
c.lastMessage.content !== 'test'
2020-07-09T13:33:43.715483+00:00 app[worker.1]: ^
2020-07-09T13:33:43.715483+00:00 app[worker.1]:
2020-07-09T13:33:43.715484+00:00 app[worker.1]: TypeError: Cannot read property 'content' of undefined
2020-07-09T13:33:43.715484+00:00 app[worker.1]: at /app/events/ready.js:22:27
2020-07-09T13:33:43.715485+00:00 app[worker.1]: at Map.find (/app/node_modules/@discordjs/collection/dist/index.js:160:17)
2020-07-09T13:33:43.715486+00:00 app[worker.1]: at /app/events/ready.js:20:28
2020-07-09T13:33:43.715486+00:00 app[worker.1]: at Map.forEach (<anonymous>)
2020-07-09T13:33:43.715486+00:00 app[worker.1]: at Timeout.broadcast [as _onTimeout] (/app/events/ready.js:19:29)
2020-07-09T13:33:43.715487+00:00 app[worker.1]: at listOnTimeout (internal/timers.js:549:17)
2020-07-09T13:33:43.715487+00:00 app[worker.1]: at processTimers (internal/timers.js:492:7)
这是我得到的错误。
【问题讨论】:
你能分享一个console.log(client.guilds.cache)
放在broadcast
函数开头的结果吗?显然,您收到的数据并不完全符合您的预期
【参考方案1】:
好的(我花了 5/10 分钟)我明白了
msg = 'Your message'
function broadcast()
// Check all servers
client.guilds.cache.forEach(g =>
// then all channels
g.channels.cache.find(c => c.name === 'chat').forEach(c =>
// if the last message on the channel is not not your message, it will send it
if(c.messages.cache.first().content !=== msg) c.send('test'):
)
)
;
// Interval you asked for
setInterval(broadcast, 3000);
【讨论】:
【参考方案2】:可能会出现通道中没有最后一条消息,导致c.lastMessage
成为undefined
,并在尝试访问不存在的content
键时关闭您的进程。
为了防止这种情况,您可以对此进行测试:
g.channels.cache.find(c => c.name === 'chat' && (c.lastMessage && c.lastMessage.content !== 'test'))
```
【讨论】:
它也不起作用,我相信我使用的 'lastMessage' 对象错误。【参考方案3】:这应该可行:
function broadcast()
client.guilds.cache.forEach(g =>
const channel = g.channels.cache.find(c => c.name === 'chat')
if (channel.lastMessage.content !== 'test') channel.send('test')
)
;
setInterval(broadcast, 3000);
【讨论】:
它没有,它说 2020-07-10T11:29:15.610164+00:00 app[worker.1]: TypeError: Cannot read property 'content' of null 看起来情况是关于 lastMessage 对象以上是关于Discord.js 无法检查“lastMessage.content”的主要内容,如果未能解决你的问题,请参考以下文章
Discord.js 空值检查在 TypeScript 中不起作用
Discord.js TypeError:无法读取 null 的属性“角色”