I try to detect in real-time whether each member is speaking or not on a voice channel using discord.js v13. In other words, I want to reproduce the green circle of discord in my application. However, I couldn't find a suitable code example or article. Could you give me some advice?
Edit:
Based on the advice, I was able to solve it. The example of Recorder BOT was useful. A code example is shown below.
const { Client, Intents, VoiceChannel } = require('discord.js')
const { joinVoiceChannel, getVoiceConnection, entersState, VoiceConnectionStatus } = require('@discordjs/voice');
const client = new Client({ intents: ['GUILD_VOICE_STATES', 'GUILD_MESSAGES', 'GUILDS'] });
client.on("messageCreate", async (message) => {
if(message.content.toLowerCase() === "test") {
var connection = getVoiceConnection(message.guildId)
if(!connection){
connection = joinVoiceChannel({
channelId: message.member.voice.channelId,
guildId: message.guildId,
adapterCreator: message.guild.voiceAdapterCreator,
selfDeaf: false,
selfMute: true,
});
}
try {
await entersState(connection, VoiceConnectionStatus.Ready, 20e3);
connection.receiver.speaking.on("start", (userId) => {
console.log( `${userId} start` );
});
connection.receiver.speaking.on("end", (userId) => {
console.log( `${userId} end` );
});
console.log( "Ready" );
} catch (error) {
console.warn(error);
}
}
});
client.login('YOUR-TOKEN')
Searching for this seems to suggest this used to be possible but was famously broken, because the event wouldn't fire, or would fire only once.
The client.voiceStateUpdate event used to give you a VoiceState that had a speaking property, which would tell you if someone was speaking (which seems like it never really worked).
The current discord.js documentation for VoiceState shows this property no longer exists, and you cannot do what you're asking using discord.js alone.
Edit: as per MrMythical's comment below, discord.js/voice has voiceRecievers, which exposes voiceReciever.speakingMap.users, a map of users currently speaking. you may get events for it by registering a listener.