首页 > 解决方案 > JavaScript 中的 voiceStateUpdate 问题

问题描述

我正试图让这个不和谐的机器人工作。这个想法很简单,让机器人在有人加入语音聊天时发送通知。我在 Atom 上做这个,我得到的错误是这个:

TypeError: Cannot read property 'send' of undefined
at Client.client.on (C:\Users\Franco\Desktop\bot\bot.js:15:20)
at emitTwo (events.js:126:13)
at Client.emit (events.js:214:7)
at VoiceStateUpdateHandler.handle (C:\Users\Franco\Desktop\bot\node_modules\discord.js\src\client\websocket\packets\handlers\VoiceStateUpdate.js:39:16)
at WebSocketPacketManager.handle (C:\Users\Franco\Desktop\bot\node_modules\discord.js\src\client\websocket\packets\WebSocketPacketManager.js:103:65)
at WebSocketConnection.onPacket (C:\Users\Franco\Desktop\bot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:333:35)
at WebSocketConnection.onMessage (C:\Users\Franco\Desktop\bot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:296:17)
at WebSocket.onMessage (C:\Users\Franco\Desktop\bot\node_modules\ws\lib\event-target.js:120:16)
at emitOne (events.js:116:13)
at WebSocket.emit (events.js:211:7)

代码尝试:

client.on("message", function(message) {
  client.on('voiceStateUpdate', (oldMember, newMember) => {
    console.log('lol');
    let newUserChannel = newMember.voiceChannel
    let oldUserChannel = oldMember.voiceChannel
    var channel = client.channels.get('353996293154144259');
    if(oldUserChannel === 353996293154144260 && newUserChannel !== 489674797261783041) {
      channel.send('has joined a voice channel');
      // User Joins a voice channel
    } else if(newUserChannel === 489674797261783041){
       channel.send('has left a voice channel');
    // User leaves a voice channel
    }
  })
})

console.log 仅用于测试是否voiceStateUpdate正常工作。

当我尝试运行它时,我收到此错误:

“TypeError:无法读取未定义的属性‘发送’”

据我了解,错误是因为.send函数未定义

我从这里得到了几乎所有东西:

我尝试过的一切:

“当我将 client.on 移出时出现第二个错误:”(节点:18196)MaxListenersExceededWarning:检测到可能的 EventEmitter 内存泄漏。添加了 11 个消息侦听器。使用emitter.setMaxListeners() 增加限制”

也许一些无用的信息:

更新

好的,我解决了部分问题,我需要使用message.channel.send('has joined a voice channel');而不是channel.send('has joined a voice channel');但我无法让它按我的意愿工作。


特别感谢 YakovL。他帮助我使这篇文章更加完整和更好。

标签: javascriptbotsdiscord

解决方案


var channel = client.channels.get('353996293154144259');

这对我不起作用,所以我改用了这个:

const channel = client.channels.cache.filter((channel) => channel.name === 'name').first();

最好使用它但搜索ID:

const channel = client.channels.cache.filter((channel) => channel.id === '353996293154144259').first();

推荐阅读