Discord.js TypeError: Cannot read properties of undefined (reading 'chaneld') - discord.js

This is my first question in discord.js . Here I am interested in why my code cannot read chanels that are located in Memory/Schems/guilds.js seems to be writing everything correctly, but nothing happens,
Error:
TypeError: Cannot read properties of undefined (reading 'chaneld')
at module.exports (D:\bots\Bot1\commands\channeld.js:20:56)
at Client.<anonymous> (D:\bots\Bot1\handlers\messageHandler.js:32:24)
at Client.emit (node:events:525:35)
at MessageCreateAction.handle (D:\bots\Bot1\node_modules\discord.js\src\client\actions\MessageCreate.js:23:14)
guilds.js
module.exports = (guild = {id: "!", name: "!"}) => {
return {
id: guild.id,
name: guild.name,
chaneld: "id",
members: {},
prefix: "p!"
}; };
channeld.js
const {PermissionsBitField} = require('discord.js');
module.exports = async(bot,message,args,argsF) =>{
const{content,member,author,guild} = message;
const{memGuild} = bot.Memory.guilds.get(guild.id);
if(member.permissions.has(PermissionsBitField.Flags.Administrator)){
if(args[0] == "set"){
if(!args[1]||!guild.channels.cache.get(args[1])) return message.reply("Send Channel ID");
memGuild.chaneld = args[1];
return message.reply("`The channel is installed, channel: ${guild.channels.cache.get(args[1])}`");
}
}
const Channel = guild.channels.cache.get(memGuild.chaneld);
if(!Channel) return message.reply("Channel not founded");
Channel.send({
embeds:[{
title: "Title ",
color: 0xFF001A, //Red color
description: "Description"
}]
});
};
module.exports.names = ["channeld"];
If you need anything else from my code, I will send you
Image of project files

Related

DISCORD BOT : `TypeError: Cannot read properties of undefined (reading 'permission')`

Its been a while since I programmed the Permissions Handler which all the perms will be handled each command. So I'm using Discord.Js v14 and it seems that this Permission handling is "deprecated"??? I really don't know so the error is TypeError: Cannot read properties of undefined (reading 'permission')
and here is my code
const ValidPerms = [
p.AddReactions,
p.Administrator,
p.AttachFiles,
p.BanMembers,
p.ChangeNickname,
p.Connect,
p.CreateInstantInvite,
p.CreatePrivateThreads,
p.CreatePublicThreads,
p.DeafenMembers,
p.EmbedLinks,
p.KickMembers,
p.ManageChannels,
p.ManageEmojisAndStickers,
p.ManageEvents,
p.ManageGuild,
p.ManageMessages,
p.ManageNicknames,
p.ManageRoles,
p.ManageThreads,
p.ManageWebhooks,
p.MentionEveryone,
p.ModerateMembers,
p.MoveMembers,
p.MuteMembers,
p.PrioritySpeaker,
p.ReadMessageHistory,
p.RequestToSpeak,
p.SendMessages,
p.SendMessagesInThreads,
p.SendTTSMessages,
p.Speak,
p.Stream,
p.UseApplicationCommands,
p.UseEmbeddedActivities,
p.UseExternalEmojis,
p.UseExternalStickers,
p.UseVAD,
p.ViewAuditLog,
p.ViewChannel,
p.ViewGuildInsights,
]
if (command.permissions) {
let invalidPerms = []
for (const permission of command.permissions) {
if (!ValidPerms.includes(permission)) {
console.log(`Invalid Perms`)
}
if (!message.members.permission.has(permission)) {
invalidPerms.push(permission)
}
}
if (invalidPerms.length) {
const noPermsEmbed = new ME()
.setColor(config.colors.no)
.setTitle("Aww~~~ You dont have have permss~")
.addField('Aweee~~~ you don\'t have permissions to run command:', `\`${command.name}\``)
.addField('Permission Required', `\`${invalidPerms}\``)
.setFooter({ text : client.user.username, iconURL : client.user.displayAvatarURL() })
.setTimestamp()
return message.channel.send(noPermsEmbed);
}
}
I tried using the "ADMINISTRATOR" like putting something like this in one like in the code and still the same error where did I go wrong?
Nvm I fixed it I have so many errors on creating the perms I didn't read the docs of so I fixed it by changing the p.[perms] to p.Flags.[perms] and I forgot to create a new function called :
`const ValidPerms = new PermissionsBitField(perms)`
and I fixed this function as well :
if (command.permissions) {
let invalidPerms = []
for (const permission1 of command.permissions) {
if (!ValidPerms.has(permission1)) {
console.log(`Invalid Perms`)
}
const member = message.member
if (!member.permissions.has(permission1)) {
invalidPerms.push(permission1)
}
}
if (invalidPerms.length) {
const noPermsEmbed = new ME()
.setColor('Random')
.setTitle("Aww~~~ You dont have have permss~")
.addFields(
{
name: 'Aweee~~~ you don\'t have permissions to run command:',
value: `\`${command.name}\``
}
)
.addFields(
{
name: 'Permission Required',
value: `\`${invalidPerms}\``
}
)
.setFooter({ text: client.user.username, iconURL: client.user.displayAvatarURL() })
.setTimestamp()
return message.channel.send({embeds : [noPermsEmbed]});
}
}
and on the command as well On Module.Exports :
permissions: ['BanMembers'],
I hope this answer will help you as well
reference here : https://discordjs.guide/popular-topics/permissions.html#converting-permission-numbers

Im trying to make a giveaway command based in a tutorial i saw and it says TypeError: Cannot read property 'start' of undefined

As i said in the title i am getting this error, and I don't know how to fix it, but tutorials use the same thing and don't get this error. Pls help me i dont know what to do.
error:
"Cannot read property 'start' of undefined"
const ms = require('ms')
const { MessageEmbed } = require('discord.js')
module.exports = {
name : 'giveaway',
execute : async(message, args ,client) => {
if(!message.member.hasPermission('MANAGE_MESSAGES')) return message.channel.send('You dont have manage messages permission.')
const channel = message.mentions.channels.first()
if(!channel) return message.channel.send('Please specify a channel')
const duration = args[1]
if(!duration) return message.channel.send('please enter a valid duration')
const winners = args[2]
if(!winners) return message.channel.send('Please specify an amount of winners')
const prize = args.slice(3).join(" ")
if(!prize) return message.channel.send('Please sepcify a prize to win')
client.giveaways.start(channel, {
time : ms(duration),
prize : prize,
winnerCount: winners,
hostedBy: message.author,
messages: {
giveaway: "Giveaway \#everyone",
giveawayEnd: "Giveaway Ended \#everyone",
timeRemaining: "Time Remaining **{duration}**",
inviteToParticipate: "React with 🎉 to join the giveaway",
winMessage: "Congrats {winners}, you have won the giveaway",
embedFooter: "Giveaway Time!",
noWinner: "Could not determine a winner",
hostedBy: 'Hosted by {user}',
winners: "winners",
endedAt: 'Ends at',
units: {
seconds: "seconds",
minutes: "minutes",
hours: 'hours',
days: 'days',
pluralS: false
}
},
})
message.channel.send(`Giveaway is starting in ${channel}`)
}
}
error line code: client.giveaways.start(channel, {
index.js:
client.giveaways = new GiveawaysManager(client, {
storage : './giveaways.json',
updateCountdownEvery : 5000,
embedColor: '#D03600',
reaction: '🎉'
})
giveaways.json: []
Execute:
try{
command.execute(message,args, cmd, client, Discord);
} catch (err){
message.reply("There was an error trying to execute this command!");
console.log(err);
}
}
In your command.execute() call, you are passing in client as the fourth parameter. But in your command file, where you export the giveaway command, client is the third parameter.
module.exports = {
name : 'giveaway',
// Add cmd parameter here, so client is passed in correctly as the fourth parameter
execute : async(message, args, cmd, client) => { ... }
}

How do I get the video url with ytdl-core?

const { YTSearcher } = require('ytsearcher');
const searcher = new YTSearcher({
key: config.YOUTUBE_API_KEY,
revealed: true
});
let result = await searcher.search(args.join(" "), { type: "video" })
var songInfo = await ytdl.getInfo(result.first.url)
var song = {
title: songInfo.videoDetails.title,
url: songInfo.videoDetails.video_url
};
I'm using ytdl-core to play music using a discord bot, when I try to play a song it sends the error "Cannot read property 'url' of underfined"

discord.js v12 | TypeError: Cannot read property 'send' of undefined

Here is my entire code for my ban command. Good to note I am using Discord.JS Commando as well I have been struggling with this error but literally cannot figure out why I am getting it everything looks fine unless I have used a deprecated function. Would really appreciate someone to help me on this one I've been getting along quite well creating a rich featured bot before this happened.
const { Command } = require('discord.js-commando');
const { MessageEmbed } = require('discord.js');
const db = require('quick.db');
module.exports = class banCommand extends Command {
constructor(client) {
super(client, {
name: 'ban',
memberName: "ban",
group: 'moderation',
guildOnly: true,
userPermissions: ['BAN_MEMBERS'],
description: 'Bans the mentioned user from the server with additional modlog info.'
});
}
async run(message, args) {
if (!args[0]) return message.channel.send('**Please Provide A User To Ban!**')
let banMember = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.guild.members.cache.find(r => r.user.username.toLowerCase() === args[0].toLocaleLowerCase()) || message.guild.members.cache.find(ro => ro.displayName.toLowerCase() === args[0].toLocaleLowerCase());
if (!banMember) return message.channel.send('**User Is Not In The Guild**');
if (banMember === message.member) return message.channel.send('**You Cannot Ban Yourself**')
var reason = args.slice(1).join(' ');
if (!banMember.bannable) return message.channel.send('**Cant Kick That User**')
banMember.send(`**Hello, You Have Been Banned From ${message.guild.name} for - ${reason || 'No Reason'}**`).then(() =>
message.guild.members.ban(banMember, { days: 7, reason: reason })).catch(() => null)
message.guild.members.ban(banMember, { days: 7, reason: reason })
if (reason) {
var sembed = new MessageEmbed()
.setColor('GREEN')
.setAuthor(message.guild.name, message.guild.iconURL())
.setDescription(`**${banMember.user.username}** has been banned for ${reason}`)
message.channel.send(sembed)
} else {
var sembed2 = new MessageEmbed()
.setColor('GREEN')
.setAuthor(message.guild.name, message.guild.iconURL())
.setDescription(`**${banMember.user.username}** has been banned`)
message.channel.send(sembed2)
}
let channel = db.fetch(`modlog_${message.guild.id}`)
if (channel == null) return;
if (!channel) return;
const embed = new MessageEmbed()
.setAuthor(`${message.guild.name} Modlogs`, message.guild.iconURL())
.setColor('#ff0000')
.setThumbnail(banMember.user.displayAvatarURL({ dynamic: true }))
.setFooter(message.guild.name, message.guild.iconURL())
.addField('**Moderation**', 'ban')
.addField('**Banned**', banMember.user.username)
.addField('**ID**', `${banMember.id}`)
.addField('**Banned By**', message.author.username)
.addField('**Reason**', `${reason || '**No Reason**'}`)
.addField('**Date**', message.createdAt.toLocaleString())
.setTimestamp();
var sChannel = message.guild.channels.cache.get(channel)
if (!sChannel) return;
sChannel.send(embed)
}
};
The reason you are getting the TypeError: args.slice(...).join is not a function error is because the slice method creates a new array of the sliced data, and so can not join(' ') since there is no space to join with. (i.e. it is not a string)
What you are looking for is args.slice(1).toString().replace(",", " ")
This removes the 2nd part of the args array object, then converts it to a string, then removes the commas in the string and replaces them with spaces.

TypeError: Cannot read property 'roles' of undefined at Object.module.exports.run

I am trying to make a tempmute command which saves data to JSON then reads it every 3 seconds to see is the time experied. I made the mute command but I recive an error TypeError: Cannot read property 'roles' of undefined. I delete the if(!message.member.roles.has("675376537272582154")) return message.channel.send('Bu komutu kullanabilmek için「🔪」Mute Premission rolüne sahip olmasınız.') but this time it said TypeError: Cannot read property 'members' of undefined. Can someone help me?
Information
Discord.js Version: v11.6.1
Node.js Version: 12.0.0
Code
const { RichEmbed } = require('discord.js');
const fs = require('fs');
module.exports.run = async (message, args, bot) => {
if(!message.member.roles.has("675376537272582154")) return message.channel.send(`Bu komutu kullanabilmek için \`「🔪」Mute Premission\` rolüne sahip olmasınız.`);
let toMute = message.mentions.member.first() || message.guild.members.get(args[0])
if(!toMute) return message.channel.send(`:x: Susturulacak kullanıcıyı etiketlemelisin!`)
let timeMute = args[1]
if(!timeMute) return message.channel.send(':x: Susturma süresini dakika cinsinden yazmalısın!')
if(isNaN(args[1])) return message.channel.send(':x: Senin de bildiğin gibi süre sadece sayı olabilir!')
let reason = args.slice(2).join(" ")
if(!reason) return message.channel.send(':x: Susturma sebebini yazmalısın!')
if(toMute.id === message.author.id) return message.channel.send(`:x: Kendini susturamazsın bea!`)
if(toMute.roles.has('675376537272582154')) return message.channel.send(`:x: \`「🔪」Mute Premission\` rolüne sahip olan birini susturamazsın!`)
let role = message.guild.roles.find(x => x.name === '「🔇」Muted')
if(!role) return message.channel.send(':x: `「🔇」Muted` adlı rolü bulamıyorum!')
if(toMute.roles.has(role.id)) return message.channel.send(':x: Bu kullanıcı zaten susturulmuş!')
let modlog = message.guild.channels.find(c => c.name === '『🔰』punishment')
if(!modlog) return message.channel.send(':x: Mod-Log kanalını bulamıyorum!')
const embed = new RichEmbed()
.setTitle('Susturma')
//.setThumbnail(`${toMute.avatarURL}`)
.setDescription(`**Susturlan Kişi: \`${toMute.tag}\`** \n **ID Numarası: \`${toMute.id}\`**\n **Susturan Yetkili: \`${message.author.tag}\`**\n **Süre: \`${timeMute}\`** **Sebep: \`${reason}\`** `)
.setColor("#ff0000")
.setFooter('Kurallara Uymayanın Sonu')
.setTimestamp();
bot.mutes[toMute.id] = {
guild: message.guild.id,
time: Date.now() + parseInt(args[1]) * 10000
}
await toMute.addRole(role)
fs.writeFile("./mutes.json", JSON.stringify(bot.mutes, null, 4), err => {
if(err) throw err;
modlog.send(embed)
})
}
module.exports.conf = {
enabled: true,
guildOnly: true,
aliases: ['sustur'],
permLevel: 0
};
module.exports.help = {
name: 'mute',
description: 'Sustur gitsin',
usage: '!sustur #kullanıcı süre sebep'
}
member and guild are most likely undefined because your bot is receiving a DM message. Check if the message is from a guild before continuing with your code:
module.exports.run = async (message, args, bot) => {
if(!message.guild) return
// rest of code
}

Resources