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 ;)
Related
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
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
I'm trying to set up a command that when mentioning a member gives them a specific role. However every time I get the same roles undefined error. Can anyone help me out?
My code:
client.on('messageCreate', (message) => {
if (message.content == '!brig'){
const role = message.guild.roles.cache.find(role => role.name === 'BRIG')
const target = message.mentions.members.first();
target.roles.add('757816527478325391')
}
})
I made a small modification to your code changing message.content === '!brig' to message.content.includes("!brig") and it seems like it works fine for me. You can try my code and let me know if anything changes:
const { Client } = require("discord.js");
const client = new Client({
intents: ["GUILDS", "GUILD_MESSAGES"],
});
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}`);
});
client.on("messageCreate", (message) => {
if (message.content.includes("!brig")) {
const role = message.guild.roles.cache.find(
(role) => role.name === "BRIG"
);
const target = message.mentions.members.first();
target.roles.add(role.id);
}
});
client.login("YOURTOKEN");
Edit: This code is working with discord.js#13.5.0 but I can't see why it wouldn't work with the latest version (13.6.0 at this moment).
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);
}
});
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
}