Issues with voice state updates in JavaScript

I am currently working on setting up a discord bot to send notifications when someone joins a voice chat. While coding in Atom, I encountered the following error:

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)

This is the code snippet I attempted:

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');
    } else if(newUserChannel === 489674797261783041){
       channel.send('has left a voice channel');
    }
  })
})

The console.log statement was just for testing purposes.

When trying to run this code, I faced the error:

"TypeError: Cannot read property 'send' of undefined"

Upon my analysis, the issue lies with the undefined nature of the .send function.

I gathered most of my information from the following sources:

Here are the troubleshooting steps I have attempted:

  • Added

    client.on("message", function(message) {

  • Changed .send to .message and .sendMessage

  • Tried to define .send again

  • Modified client.channels.get to lient.channelid.get

  • Changed or removed

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

  • Moved

    client.on('voiceStateUpdate', (oldMember, newMember) => {
    outside of
    client.on("message", function(message) {
    . However, this resulted in another error.

"Second error I encountered after moving client.on out: "(node:18196) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 message listeners added. Use emitter.setMaxListeners() to increase limit"

Additional notes:

  • 353996293154144259 = id of General chat on discord server

  • 353996293154144260 = id of the first voice chat

  • 489674797261783041 = id of the second voice chat

UPDATE

Progress has been made by replacing

channel.send('has joined a voice channel');
with
message.channel.send('has joined a voice channel');
. However, the desired outcome is yet to be achieved.


Special thanks to YakovL for assisting in enhancing the quality of this post.

Answer №1

let specifiedChannel = client.channels.get('353996293154144259');

Unfortunately, the above method didn't work for me so I ended up using a different approach:

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

An even more efficient way would be to search for the channel by its ID:

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

Answer №2

Update

var channel = client.channelID.find('353996293154144259');

to

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

Correction: Starting from v12, it should be

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

Answer №3

I come from Brazil, and I speak Brazilian Portuguese!

const Discord = require('discord.js'),
  client = new Discord.Client(),
  colors = require('colors/safe');

client.on('voiceStateUpdate', (oldMember, newMember) => {
  
  let newUserChannel = newMember.channelID;
  let oldUserChannel = oldMember.channelID;
  let userid = newMember.id;

// ----------- verification --------------

  let selfmute = newMember.mute;
  let mute = newMember.selfMute;
  let selfmute1 = oldMember.mute;
  let mute1 = oldMember.selfMute;
  let selfdeaf = newMember.selfDeaf;
  let selfdeaf1 = oldMember.selfDeaf;  
  let selfvid = newMember.selfVideo;
  let selfvid1 = oldMember.selfVideo;
  let deaf = newMember.deaf;
  let deaf1 = oldMember.deaf;
  let servmute = newMember.serverMute;
  let servmute1 = oldMember.serverMute;

  if (selfmute == true) return;
  if (mute == true) return;
  if (selfmute1 == true) return;
  if (mute1 == true) return;
  if (selfdeaf == true) return;
  if (selfdeaf1 == true) return;
  if (selfvid == true) return;
  if (selfvid1 == true) return;
  if (deaf == true) return;
  if (deaf1 == true) return;
  if (servmute == true) return;
  if (servmute1 == true) return;

// -------- defining colors ----------

var a = colors.red('[-] ');
var b = colors.green('[+] ');
var c = colors.blue('[!] ');

// -------- message / log ----------

       if (newUserChannel === "827668874542579797") { //id voice channel

          console.log(c+"- id: "+userid)
          console.log(b+"- Joined: "+newUserChannel);   

       } else if (oldUserChannel === "827668874542579797") { //id voice channel
           
           console.log(c+"- id: "+userid)
           console.log(a+"- Left: "+oldUserChannel);

       } else {

           console.log(c+"- Rats are conversing...");

       }
    
})
//----------------Command to stay on-------------

client.login("TOKEN");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Acquiring JSON data within a JavaScript function using PHP

Requesting assistance on reading a JSON value using the code below, to retrieve data based on the $movieID. <script> function bookBTN(x) { <?php $url = 'http://movie.com/movieOne?seatNum=' . x; $jsonURL = file_get_ ...

Guide on utilizing personalized fonts with Handlebars and Puppeteer

I have a Handlebar template that I am converting to PDF using Puppeteer. My question is how can I incorporate custom fonts? Currently, I have a static folder declared in my app.js file like this: app.use(express.static(path.join(__dirname, 'assets&ap ...

Generating an interactive table using JSON data in ReactJS

I am a beginner in both React and UI development, and I would like to know how I can create a visually appealing table using the JSON data received from an AJAX call to the server. Any guidance or information on this topic would be greatly appreciated. v ...

When trying to load a php page2 into page1 via ajax, the Javascript code fails to execute

Currently, I am in the process of learning PHP and JavaScript. I have encountered a particular issue with a webpage setup. Let's say I have a page called page1 which consists of two input fields and a button labeled 'Go'. Upon clicking the & ...

Struggling to update state in React despite attempts to modify the state

Even though I have set the defaultAccount state to the metamask account, when trying to print it in the code below, it still shows null. The issue arises with fetching the value of defaultAccount. (Please see the error image below) class App extends Compo ...

Utilizing object UUID keys to associate products in VueJS

Hey there, I've gone ahead and created an object with UUIDs but now I'm looking for a way to link these UUIDs to specific items. It seems like there needs to be some separation between the UUID and the rest of the object, however, my main issue i ...

Calculate the total of the temporary information entered into the input field

I'm totally new to all of this and definitely not an expert, but there's something that really bothers me. I found a website where you have to complete a captcha to log in. It goes like this: <input type="text" class="form-contr ...

The initialization of a static member in a JS class occurs prior to the loading of the cdn

After declaring this class member, I encountered the issue stating that MenuItem is not defined. It appears that the class initialization occurs before React or Material-UI finishes loading (I am currently loading them from their CDN using straight < ...

Trouble with $sce in Angular.js causing limitations on passing desired content into my directive

I've successfully developed a directive that animates a PNG Sequence. Everything functions perfectly when I manually input the image url, but when attempting to pass a dynamic url, I encounter an error related to $sce disallowing it. Below is the cod ...

Is it possible to share a Vue.js component by "transferring" it rather than duplicating it?

In my comment system project using Vue.js, I have over 300 comments to manage. Each comment has an admin section that appears when the cursor hovers over it. Duplicating the admin section component for each comment is not ideal as it creates unnecessary l ...

What is the best way to access props from a different file in a React application?

I am facing a challenge with my two files: EnhancedTableHead and OrderDialog. I need to access the props data from EnhancedTabledHead in my OrderDialog file. Is there a way to achieve this? Here is how my files are structured: //OrderDialog.jsx import ...

How to delete an element from an array with UnderscoreJS

Here's a scenario: var arr = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}]; I'm looking to delete the element with id value of 3 from this array. Is there a method to achieve this without using splice? Perhap ...

Despite locating the button, Protractor still encounters difficulties when attempting to click on it

I've been having trouble clicking on a button using Protractor. The issue is that even though the driver can locate the element, it still won't click on it. Any assistance would be greatly appreciated. Thank you in advance. Here is the HTML for ...

Extract data from an API endpoint using JavaScript or React

I have the primary website link, which necessitates an authorization header for access every time. //console.log contains this information - accounts:[{categoryId:"some info"... }] api/v2/accounts To extract accountId and categoryId from the i ...

What is the reason for the failure of this react ternary return statement?

My slideboard is set up to show a warning component (currently just a "test" div) when the prop "columnsItem" exceeds 50. Everything works fine, but when I switch back to a slideboard with fewer columns, all I see is a blank white screen. Can you help me ...

Click to delete the <p> element

For the past few days, I've been struggling with this issue and have tried various approaches to solve it. However, I can't seem to remove the element for some reason. Can anyone offer some insight? My objective is to add the inputted markup on ...

Using Vue to iterate through elements

I am struggling to loop through an array in a Vue component without duplicating the element specified in the 'v-for' directive. I have consulted the official Vue.js API documentation, as well as various online articles, but haven't found a s ...

Incorporating Stripe into your Next.js 13 application: A step-by-step guide

Struggling to incorporate Stripe into my Next.js 13 app for a pre-built checkout form. So far, all attempts have fallen short. Seeking assistance from anyone who has conquered this integration successfully. Any tips or guidance would be highly valued. Pl ...

What is the best way to trigger a modal to appear when dynamically generated items are clicked?

My objective is to retrieve specific data from the server and present it in a list format on my webpage. The list displays correctly, but I want users to be able to view additional details for each list item by clicking on it, triggering a modal popup. How ...

What is the method for retrieving the index of an array from an HTML element?

Howdy! Within my Vue application, I have the ability to create multiple individuals: <div v-for="newContent in temp" :key="newContent.id" @click="showId(newContent.id)" v-show="true"> <!-- ...