Search code examples
node.jsdiscord.js

Send DM when a user joins a VC using Discord.JS


Stack Overflow (I apologize if this question has already been asked, I don't believe it has, but in advance, just in case):

I'm making a discord bot using Discord.JS and Node.JS. I want to make a bot to detect when a user joins a VC, and then sends said user a DM. I have the detection code figured out:

const Discord = require('discord.js');
const bot = new Discord.Client();

bot.login("token");

bot.once('ready', () =>{
    console.log(`Bot ready, logged in as ${bot.user.tag}!`);
})

bot.on('voiceStateUpdate', (oldMember, newMember) => {
    let newUserChannel = newMember.channelID;
    let oldUserChannel = oldMember.channelID;
 
    if(newUserChannel === "channel id")
    { 
        // User Joins a voice channel
        console.log("User joined vc with id "+newUserChannel)
        
    }
    else{
        // User leaves a voice channel
        console.log("Left vc");
    }
 });

But I'm having trouble sending the user (who i assume is represented by newMember) a DM. Can someone kindly provide some assistance? Thanks!


Solution

  • You can use the .member property of the VoiceState instance you get to get the user who has joined the voice channel. Then simply call the .send() method on the voice channel user to send them a DM. Take a look at the example code below:

    bot.on('voiceStateUpdate', (oldState, newState) => {
      const newChannelID = newState.channelID;
    
      if (newChannelID === "channel id") {
        console.log("User has joined voice channel with id " + newChannelID);
    
        const member = newState.member;
    
        member.send('Hi there! Welcome to the voice channel!');
      } else {
        console.log("User left or didn't join the channel matching the given ID");
      }
    });
    

    Give it a try and see how it goes