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

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) => { ... }
}

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

Cannot update or save data on second or next user in mongodb

May I know what is the problem with my code for the backend. I try to create a place and update it in the user database. The problem is If I only have 1 user. The database can create and update the data but if I have more than 2 then, the data cannot be updated or created. Here is my code. I have been working on this part for so long, that I cannot find the solution.
const createFile = async (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return next(
new HttpError('Invalid inputs passed, please check your data.', 422)
);
}
const { userId, Dataset } = req.body;
const createdFile = new File({
userId,
Dataset,
});
let user;
try {
user = await User.findById(userId);
} catch (err) {
const error = new HttpError(
'Creating place failed, please try again 1',
500
);
return next(error);
}
if (!user) {
const error = new HttpError('Could not find user for provided id', 404);
return next(error);
}
try {
const sess = await mongoose.startSession();
sess.startTransaction();
await createdFile.save({ session: sess });
user.Dataset.push(createdFile);
await user.save({ session: sess });
await sess.commitTransaction();
} catch (err) {
const error = new HttpError(
'Creating place failed, please try again.2',
500
);
return next(error);
}
res.status(201).json({ files: createdFile });
};
The error message that I got
Error: User validation failed: _id: Error, expected `_id` to be unique. Value: `62c661c629d1cb99768efd05`
at ValidationError.inspect (C:\Users\acit\Desktop\FYP Code\FYP Code\backend2\node_modules\mongoose\lib\error\validation.js:48:26)
at internal/per_context/primordials.js:23:32
at formatValue (internal/util/inspect.js:783:19)
at inspect (internal/util/inspect.js:337:10)
at formatWithOptionsInternal (internal/util/inspect.js:2016:40)
at formatWithOptions (internal/util/inspect.js:1898:10)
at console.value (internal/console/constructor.js:323:14)
at console.log (internal/console/constructor.js:358:61)
at createFile (C:\Users\acit\Desktop\FYP Code\FYP Code\backend2\controllers\files-controller.js:102:13)
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
errors: {
_id: ValidatorError: Error, expected `_id` to be unique. Value: `62c661c629d1cb99768efd05`
at validate (C:\Users\acit\Desktop\FYP Code\FYP Code\backend2\node_modules\mongoose\lib\schematype.js:1321:13)
at C:\Users\acit\Desktop\FYP Code\FYP Code\backend2\node_modules\mongoose\lib\schematype.js:1297:24
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
properties: [Object],
kind: 'unique',
path: '_id',
value: new ObjectId("62c661c629d1cb99768efd05"),
reason: undefined,
[Symbol(mongoose:validatorError)]: true
}
},
_message: 'User validation failed'
}
It already settle, I reroll the mongoose-unique-validator to 2.0.3 version
I use this command
npm install mongoose-unique-validator#2.0.3 --legacy-peer-deps
hope that someone with same issues as mine find my post and can help them to solve the same issues

MessageEmbed description must be a string

This is my code and im getting this error: RangeError [EMBED_DESCRIPTION]: MessageEmbed description must be a string can can someone help me please? I updated from v12 to v13 and now this error happens, haven't found a solution yet.
const { MessageEmbed } = require('discord.js');
const Command = require('../../Structures/Command');
module.exports = class extends Command {
constructor(...args) {
super(...args, {
aliases: ['halp'],
description: 'Displays all the commands in the bot',
category: 'Utilities',
usage: '[command]'
});
}
async run(message, [command]) {
const embed = new MessageEmbed()
.setColor('BLUE')
.setAuthor(`${message.guild.name} Help Menu`, message.guild.iconURL({ dynamic: true }))
.setThumbnail(this.client.user.displayAvatarURL())
.setFooter(`Requested by ${message.author.username}`, message.author.displayAvatarURL({ dynamic: true }))
.setTimestamp();
if (command) {
const cmd = this.client.commands.get(command) || this.client.commands.get(this.client.aliases.get(command));
if (!cmd) return message.channel.send(`Invalid Command named. \`${command}\``);
embed.setAuthor(`${this.client.utils.capitalise(cmd.name)} Command Help`, this.client.user.displayAvatarURL());
embed.setDescription([
`**❯ Aliases:** ${cmd.aliases.length ? cmd.aliases.map(alias => `\`${alias}\``).join(' ') : 'No Aliases'}`,
`**❯ Description:** ${cmd.description}`,
`**❯ Category:** ${cmd.category}`,
`**❯ Usage:** ${cmd.usage}`
]);
return message.channel.send(embed);
} else {
embed.setDescription([
`These are the available commands for ${message.guild.name}`,
`The bot's prefix is: ${this.client.prefix}`,
`Command Parameters: \`<>\` is strict & \`[]\` is optional`
]);
let categories;
if (!this.client.owners.includes(message.author.id)) {
categories = this.client.utils.removeDuplicates(this.client.commands.filter(cmd => cmd.category !== 'Owner').map(cmd => cmd.category));
} else {
categories = this.client.utils.removeDuplicates(this.client.commands.map(cmd => cmd.category));
}
for (const category of categories) {
embed.addField(`**${this.client.utils.capitalise(category)}**`, this.client.commands.filter(cmd =>
cmd.category === category).map(cmd => `\`${cmd.name}\``).join(' '));
}
return message.channel.send(embed);
}
}
};
Since you updated discord.js to v13, <MessageEmbed>.setDescription no longer accepts arrays, you need to put a string or use <Array>.join like this:
embed.setDescription([
`These are the available commands for ${message.guild.name}`,
`The bot's prefix is: ${this.client.prefix}`,
`Command Parameters: \`<>\` is strict & \`[]\` is optional`
].join('\n'));
Discord.js is expecting a string but you give it an array.
I would remove the array brackets [ ] and the commas from the setDescriptions

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.

Call Exports.run async from a member phrase

Please help me understand how can i call that ping.js from user input, like if a user type ping it will Trigger cuz of the aliases but if a user types a full phrase it won't trigger.
Or in a non headic question how can i implent this to work -> if (message.content.includes('ping'))
Sorry in advance and thanks a lot
ping.js
const Discord = require('discord.js')
const colors = require('../lib/colors.json')
exports.run = async (client, message, args, level) => {
try {
const pingEmbed = new Discord.RichEmbed()
.setColor(colors.default)
.setFooter('ping)
.addField(`${message.author.id}`, 'hey')
const msg = await message.channel.send(pingEmbed)
const embed = new Discord.RichEmbed()
.setColor(colors.default)
.addField('...',
`${msg.createdTimestamp - message.createdTimestamp}ms`)
msg.edit(embed)
} catch (err) {
message.channel.send('There was an error!\n' + err).catch()
}
}
exports.conf = {
enabled: true,
aliases: ['ping'],
guildOnly: false,
permLevel: 'User'
}
exports.help = {
name: 'ping,
category: 'tools,
description: 'ping pong',
usage: 'ping'
}
If you want to check whether a message contains any of the aliases you can just use Array.some() like this:
let aliases = ['your', 'command', 'aliases']
client.on('message', message => {
if (aliases.some(trigger => message.content.includes(trigger))) {
// The message includes at least one of your keywords
}
})
In this example is just declared aliases, but you can use the array from your command and integrate this method in your normal command handler.

Resources