discord bot audio playing undefined channel error - discord.js

i try to playing music in discord voice channel. but i got some error
message in terminal
i don't know why....
already try to changed voice channel id . but it show same error....
ho can i solve it??
[![enter image description here][1]][1]
TypeError: Cannot read properties of undefined (reading 'channels')
at Object.execute (C:\discordbot\music\commands\play.js:13:31)
at Client.<anonymous> (C:\discordbot\music\index.js:34:17)
at Client.emit (node:events:527:28)
at InteractionCreateAction.handle (C:\discordbot\music\node_modules\discord.js\src\client\actions\InteractionCreate.js:81:12)
at Object.module.exports [as INTERACTION_CREATE] (C:\discordbot\music\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36)
at WebSocketManager.handlePacket (C:\discordbot\music\node_modules\discord.js\src\client\websocket\WebSocketManager.js:352:31)
at WebSocketShard.onPacket (C:\discordbot\music\node_modules\discord.js\src\client\websocket\WebSocketShard.js:481:22)
at WebSocketShard.onMessage (C:\discordbot\music\node_modules\discord.js\src\client\websocket\WebSocketShard.js:321:10)
at WebSocket.onMessage (C:\discordbot\music\node_modules\ws\lib\event-target.js:199:18)
at WebSocket.emit (node:events:527:28)
and this is my code
const { generateDependencyReport, AudioPlayerStatus, joinVoiceChannel, createAudioPlayer, createAudioResource } = require('#discordjs/voice');
const config = require('../config.json');
module.exports = {
data: new SlashCommandBuilder()
.setName('play')
.setDescription('Plays audio in the music VC'),
async execute(interaction, client) {
//get the voice channel ids
const voiceChannelId = config.musicChannelId;
const voiceChannel = client.channels.cache.get(voiceChannelId);
const guildId = config.guildId;
//create audio player
const player = createAudioPlayer();
player.on(AudioPlayerStatus.Playing, () => {
console.log('The audio player has started playing!');
});
player.on('error', error => {
console.error(`Error: ${error.message} with resource`);
});
//create and play audio
const resource = createAudioResource('C:\\discordbot\\music\\temp\\.mp3');
player.play(resource);
//create the connection to the voice channel
const connection = joinVoiceChannel({
channelId: voiceChannelId,
guildId: guildId,
adapterCreator: voiceChannel.guild.voiceAdapterCreator,
});
interaction.reply("created voice connection")
// Subscribe the connection to the audio player (will play audio on the voice connection)
const subscription = connection.subscribe(player);
// subscription could be undefined if the connection is destroyed!
if (subscription) {
// Unsubscribe after 5 seconds (stop playing audio on the voice connection)
setTimeout(() => subscription.unsubscribe(), 30_000);
}
},
};```
[1]: https://i.stack.imgur.com/a9d9t.png

Related

Discord.js struggling to add a role to a discord member through id's

const { SlashCommandBuilder } = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("mute")
.setDescription("Mute a Member in secret")
.addUserOption((option) =>
option.setName("target").setDescription("Select a user").setRequired(true)
),
async execute(interaction, client) {
const message = await interaction.deferReply({
fetchReply: true,
});
const guild = client.guilds.cache.get("872567903839453215");
const userId = interaction.options.getUser("target").id;
console.log(userId);
const user = interaction.guild.roles.cache.get(userId);
console.log(user);
const newMessage = `Muted : ${user}`;
let fRole = message.guild.roles.cache.get("1005988662472888370");
let rRole = message.guild.roles.cache.get("1004543262884888636");
user.roles.add(fRole);
await interaction.editReply({
content: newMessage,
});
},
};
in the code i grab the user mentioned in the message and try to convert to something that would be recognised in user.roles.add(frole);
does anyone know a way to do this?
TypeError: Cannot read properties of undefined (reading 'add')
at Object.execute (DiscordBot\src\commands\tools\MuteMember.js:25:16)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Object.execute (DiscordBot\src\events\client\interactionCreate.js:11:9)
node:events:505
throw er; // Unhandled 'error' event
^
Error [InteractionAlreadyReplied]: The reply to this interaction has already been sent or deferred.
at ChatInputCommandInteraction.reply (discord.js\src\structures\interfaces\InteractionResponses.js:101:46)
at Object.execute (DiscordBot\src\events\client\interactionCreate.js:14:27)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
Emitted 'error' event on Client instance at:
at emitUnhandledRejectionOrErr (node:events:384:10)
at processTicksAndRejections (node:internal/process/task_queues:85:21) {
code: 'InteractionAlreadyReplied'
}
this is the error message i get when i do /mute #user
i have no idea what it means please help :)
You're searching for the user ID using interaction.guild.roles.cache instead of searching for members.
Change that to:
const user = interaction.guild.members.cache.get(userId);
A better way of mute can be through the usage of the new timeout feature.
Read more here

Discord.js Trying to send a message if a user joins a voice channel

I'm trying to make my bot mention my server staff in a specific text channel when someone enters in the voice support waiting room.
Here's the script I use:
const { DiscordAPIError } = require('discord.js');
const BaseEvent = require('../../utils/structures/BaseEvent');
const Discord = require("discord.js");
const client = new Discord.Client();
module.exports = class ReadyEvent extends BaseEvent {
constructor() {
super('ready');
}
async run (client) {
console.log(`Bot prêt, connecté en tant qu'${client.user.username}!`);
}
}
client.on('voiceStateUpdate', (newMember) => {
const newUserChannel = newMember.voice.channelID
const textChannel = client.channels.cache.get('815316823275995139')
if(newUserChannel === '815316796067414016') {
textChannel.send(`worked`)
}
})
There's no error in the console and when I'm joining the voice support channel, nothing happens.
This:
textChannel.send(`worked`)
is for test purposes, the line I use is
textChannel.send(`Hey ! Le <#&${753367852299321404}>, ${newMember.user.username} (${newMember.id}) est en Attente de Support !`)
The first part of the script that logs me the script is working ... is working, so I'm sure the script is correctly loaded, the bot is on my server and have all the permissions he needs.
Console and script screen
My discord.js version is 12.5.3
EDIT:
Yes, now I can see the log, so I put back my script to detect and send a message:
const { DiscordAPIError } = require('discord.js');
const BaseEvent = require('../../utils/structures/BaseEvent');
const Discord = require("discord.js");
const client = new Discord.Client();
module.exports = class ReadyEvent extends BaseEvent {
constructor() {
super('ready');
}
async run (client) {
console.log(`Bot prêt, connecté en tant qu'${client.user.username}!`);
client.on('voiceStateUpdate', (newState) => {
const newUserChannel = newState.voice.channelID
const textChannel = client.channels.cache.get('815316823275995139')
if(newUserChannel === '815316796067414016') {
textChannel.send(`working`)
}
});
}
}
but I have this error:
D:\DiscordBot\Ariabot\src\events\ready\ReadyEvent.js:13
const newUserChannel = newState.voice.channelID
^
TypeError: Cannot read property 'channelID' of undefined
at Client.<anonymous> (D:\DiscordBot\Ariabot\src\events\ready\ReadyEvent.js:13:43)
at Client.emit (events.js:376:20)
at VoiceStateUpdate.handle (D:\DiscordBot\Ariabot\node_modules\discord.js\src\client\actions\VoiceStateUpdate.js:40:14)
at Object.module.exports [as VOICE_STATE_UPDATE] (D:\DiscordBot\Ariabot\node_modules\discord.js\src\client\websocket\handlers\VOICE_STATE_UPDATE.js:4:35)
at WebSocketManager.handlePacket (D:\DiscordBot\Ariabot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (D:\DiscordBot\Ariabot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocketShard.onMessage (D:\DiscordBot\Ariabot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (D:\DiscordBot\Ariabot\node_modules\ws\lib\event-target.js:132:16)
at WebSocket.emit (events.js:376:20)
at Receiver.receiverOnMessage (D:\DiscordBot\Ariabot\node_modules\ws\lib\websocket.js:834:20)
[nodemon] app crashed - waiting for file changes before starting...
The voiceStateUpdate event calls the callback with two VoiceStates. (oldState and newState)
You should use the newState property for this purpose.
A VoiceState does not contain a voice property but does contain a channelID property.
Thus, your code should look something like this:
const { DiscordAPIError } = require('discord.js');
const BaseEvent = require('../../utils/structures/BaseEvent');
const Discord = require("discord.js");
const client = new Discord.Client();
module.exports = class ReadyEvent extends BaseEvent {
constructor() {
super('ready');
}
async run (client) {
console.log(`Bot prêt, connecté en tant qu'${client.user.username}!`);
// use 2 parameters
client.on('voiceStateUpdate', (oldState, newState) => {
// use the .channelID property (.voice doesn't exist)
const newUserChannel = newState.channelID;
const textChannel = client.channels.cache.get('815316823275995139');
if(newUserChannel === '815316796067414016') {
textChannel.send("working");
}
});
}
}
When calling functions, the name of the parameter does not matter, the position determines what is assigned to those variables.
For example, in the code above, I could have named the variables foo and bar (instead of oldState and newState), and it would have still worked.
Thank you so much to you two it's now working fine.
If the script can be usefull to someone passing-by:
const { DiscordAPIError } = require('discord.js');
const BaseEvent = require('../../utils/structures/BaseEvent');
const Discord = require("discord.js");
const client = new Discord.Client();
module.exports = class ReadyEvent extends BaseEvent {
constructor() {
super('ready');
}
async run (client) {
console.log(`Bot ready, connected as ${client.user.username}!`);
client.on('voiceStateUpdate', (oldState, newState) => {
const newUserChannel = newState.channelID;
const textChannel = client.channels.cache.get('852643030477307995');
// 852643030477307995 = ID of the text channel, I use, where the message will be posted
if(newUserChannel === '759339336663040020') {
// 759339336663040020 = ID of the voice channel I want to lookup
textChannel.send(`Hey <#&752168551103856700> ! ${newState.member} is waiting for help !`);
// <#&752168551103856700> = ID of the role I want to tag
}
});
}
}

How to add roles when user send message

I want to give a role when users send messages any text channel. But I am making mistake somewhere.
const Discord = require('discord.js');
const client = new Discord.Client();
const config = require('./config.json');
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("message", msg => {
var sender = msg.author;
var message= msg.content;
const guild = client.guilds.cache.get("847874027149721680");
let role = message.guilds.roles.cache.find("848033734909231156");
if (message) {
message.author.addRole(role).catch(console.error);
}
});
client.login(process.env.DISCORD_TOKEN);
And i constantly get this error
/home/runner/Project/index.js:23
let role = message.guilds.roles.cache.find("848033734909231156");
^
TypeError: Cannot read property 'roles' of undefined
at Client.<anonymous> (/home/runner/Project/index.js:23:29)
at Client.emit (events.js:314:20)
at Client.EventEmitter.emit (domain.js:483:12)
at MessageCreateAction.handle (/home/runner/Project/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (/home/runner/Project/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/home/runner/Project/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
at WebSocketShard.onPacket (/home/runner/Project/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
at WebSocketShard.onMessage (/home/runner/Project/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
at WebSocket.onMessage (/home/runner/Project/node_modules/ws/lib/event-target.js:132:16)
at WebSocket.emit (events.js:314:20)
Im new so i may be dumb. sorry
It’s message.guild.roles.cache.get(), not message.guilds.roles.cache.get().
As japanballdev noted, you are committing a spelling error. The reason it still persists after you fix it is because you make this error in two places:
client.on("message", msg => {
var sender = msg.author;
var message= msg.content;
const guild = client.guild.cache.get("847874027149721680"); //ERROR WAS HERE
let role = message.guild.roles.cache.find("848033734909231156"); //ERROR WAS HERE TOO
if (message) {
message.author.addRole(role).catch(console.error);
}
});

How can I add a role to a member

So I am trying to make a verify script so when a member join he/she has to write !verify and then he/she will get a rank on the discord so we won't get raided by bot's
const Discord = require("discord.js");
const bot = new Discord.Client();
module.exports.run = async (bot, message, args) => {
message.delete()
const member = message.author
let myRole = message.guild.roles.cache.get("791724979435470889")
if (!message.channel.name.startsWith(`⚜ʙɪᴇɴ`)) return message.channel.send(`you have already been verified`).then(msg => msg.delete({ timeout: 5000 }));
message.channel.send(`${member} have been verifyed`).then(member.roles.add(myRole).tehn(msg => msg.delete({ timeout: 5000 })));
}
module.exports.help = {
name: "verify" //Name of the command
}
And when I try this code out I get this error And I have tried to research it but I can't find anything on it
This is my error
message.channel.send(`${member} have been verifyed`).then(member.roles.add(myRole).tehn(msg => msg.delete({ timeout: 5000 })));
^
TypeError: Cannot read property 'add' of undefined
at Object.module.exports.run (C:\Users\lauri\Desktop\QuebecCity\utility\verify.js:12:76)
at Client.<anonymous> (C:\Users\lauri\Desktop\QuebecCity\index.js:257:33)
at Client.emit (node:events:376:20)
at MessageCreateAction.handle (C:\Users\lauri\Desktop\QuebecCity\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\lauri\Desktop\QuebecCity\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\lauri\Desktop\QuebecCity\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (C:\Users\lauri\Desktop\QuebecCity\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocketShard.onMessage (C:\Users\lauri\Desktop\QuebecCity\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (C:\Users\lauri\Desktop\QuebecCity\node_modules\ws\lib\event-target.js:132:16)
at WebSocket.emit (node:events:376:20)
roles is a property of the GuildMember object. You are unable to add roles to a User object (AKA message.author that returns the user object of the author of a message). From that instance, we would simply want to instead use the member property of the message object, resulting in message.member.
Final Code
const Discord = require("discord.js");
const bot = new Discord.Client();
module.exports.run = async (bot, message, args) => {
message.delete()
const member = message.member
let myRole = message.guild.roles.cache.get("791724979435470889")
if (!message.channel.name.startsWith(`⚜ʙɪᴇɴ`)) return message.channel.send(`you have already been verified`).then(msg => msg.delete({ timeout: 5000 }));
message.channel.send(`${member} have been verifyed`).then(msg => msg.delete({ timeout: 5000 }));
member.roles.add(myRole)
}
module.exports.help = {
name: "verify" //Name of the command
}

trying to make a bot that counts members in a voice channel

Please don't comment if think that what I'm asking is stupid.
I am completely new to this. I tried searching up solutions but couldn't find helpful ones or ones that a noob in discord.js would understand. Thank you for your help in advance!
const express = require ("express")
var app = require('express')();
app.get("/", (req, res) => {
res.send("hello hell!")
})
app.listen(3000, () => {
console.log("Project is ready")
})
let Discord = require("discord.js")
let client = new Discord.Client()
client.on('voiceStateUpdate', (oldVoiceState, newVoiceState) => {
let newUserChannel = newVoiceState.voiceChannel
let oldUserChannel = oldVoiceState.voiceChannel
if(oldUserChannel === undefined && newUserChannel !== undefined) {
// User Joins a voice channel
console.log(client.voiceConnections.size)
} else if(newUserChannel === undefined){
// User leaves a voice channel
console.log(client.voiceConnections.size)
}
})
client.login("token")
repl.it
outcome when someone joins
Project is ready
console.log(client.voiceConnections.size)
^
TypeError: Cannot read property 'size' of undefined
at Client.<anonymous> (/home/runner/VCC-Bot/index.js:30:37)
at Client.emit (events.js:315:20)
at Client.EventEmitter.emit (domain.js:483:12)
at VoiceStateUpdate.handle (/home/runner/VCC-Bot/node_modules/discord.js/src/client/actions/VoiceStateUpdate.js:40:14)
at Object.module.exports [as VOICE_STATE_UPDATE] (/home/runner/VCC-Bot/node_modules/discord.js/src/client/websocket/handlers/VOICE_STATE_UPDATE.js:4:35)
at WebSocketManager.handlePacket (/home/runner/VCC-Bot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
at WebSocketShard.onPacket (/home/runner/VCC-Bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
at WebSocketShard.onMessage (/home/runner/VCC-Bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
at WebSocket.onMessage (/home/runner/VCC-Bot/node_modules/ws/lib/event-target.js:132:16)
at WebSocket.emit (events.js:315:20)
Not sure if i'm too late here, but you need to give the bot the intent to it.
You can add the intent like this:
const { Client, Intents } = require("discord.js");
const client = new Client({
intents: [Intents.FLAGS.GUILD_VOICE_STATES],
});
Change
let newUserChannel = newVoiceState.voiceChannel
To
let newUserChannel = newVoiceState.channel
And change
let oldUserChannel = oldVoiceState.voiceChannel
To
let oldUserChannel = oldVoiceState.channel
client.voiceConnections doesn't exists so, if you want this to work, try oldUserChannel.users.size ;)

Resources