So i make a application system for a discord server and when testing it the bot worked fine till the questiosn for the application finished and it said application has been sent but it didnt send the application and i got a error saying
(node:11408) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'send' of undefined
Here is my code The error is on appsChannel.send(applicationembed);
const { Client, Message, MessageEmbed } = require('discord.js')
module.exports = {
name: "apply",
/**
* #param {Client} client
* #param {Message} message
* #param {string[]} args
*/
run: async (client, message, args) => {
const questions = [
"What is your IGN currently?",
"What is your discord Name and Tag?",
"Why do you want to join the guild?",
"What games stats are you applying with?",
"Is there anything else you want to tell us?"
];
let collectCounter = 0;
let endCounter = 0;
const filter = (m) => m.author.id === message.author.id;
const appStart = await message.author.send(questions[collectCounter++])
const channel = appStart.channel;
const collector = channel.createMessageCollector(filter);
collector.on("collect", () => {
if(collectCounter < questions.length) {
channel.send(questions[collectCounter++])
} else {
channel.send("You application has been sent!")
collector.stop("fulfilled")
}
})
const appsChannel = client.channels.cache.get('820355472635985991')
collector.on('end', (collected, reason) => {
if(reason === 'fulfilled') {
let index = 1;
const mappedResponses = collected.map((msg) => {
return `${index++}) ${questions[endCounter++]}\n-> ${msg.content}`;
})
.join('\n\n');
const applicationembed = new MessageEmbed()
.setAuthor(
message.author.tag,
message.author.displayAvatarURL({ dynamic: ture })
)
.setTitle('New Application!')
.setDescription(mappedResponses)
.setColor('RANDOM')
.setTimestamp()
appsChannel.send(applicationembed);
}
})
},
}
It's possible that the channel you're trying to get is not in the cache. It's always best to fetch rather than rely on the cache.
Change your appsChannel definition to this.
const appsChannel = await client.channels.cache.fetch('820355472635985991');
Can you try using await here?
const appsChannel = await client.channels.cache.get('820355472635985991')
Edit:
const applicationembed = await new MessageEmbed()
.setAuthor(
message.author.tag,
message.author.displayAvatarURL({ dynamic: ture })
)
.setTitle('New Application!')
.setDescription(mappedResponses)
.setColor('RANDOM')
.setTimestamp()
await appsChannel.send(applicationembed);
For your async to work:
collector.on('end', async (collected, reason) => {
Related
I've been trying to make a reaction role in my bot but I keep getting this error
interaction.guild.roles.fetch(mustard).then(role => member.roles.add(role)).catch(console.error())
^
TypeError: Cannot read properties of undefined (reading 'guild')
This is the full code:
const {
Client,
Message,
MessageEmbed,
MessageActionRow,
MessageButton,
} = require('discord.js');
const cooldown = new Set();
module.exports = {
name: "quickroles",
aliases: ["roles"],
permissions: ["ADMINISTRATOR"],
/**
* #param {Client} client
* #param {Message} message
* #param {String[]} args
*/
run: async (client, message, args, interaction) => {
if(cooldown.has(message.author.id)) {
message.reply(`Please wait! You're on a default cooldown of 5 seconds!`)
} else {
const row = new MessageActionRow().addComponents(
new MessageButton()
.setCustomId("pin")
.setLabel("Pink")
.setEmoji('🟥')
.setStyle("SECONDARY"),
new MessageButton()
.setCustomId("mus")
.setLabel("Mustard")
.setEmoji('🟨')
.setStyle("SECONDARY"),
new MessageButton()
.setCustomId("ski")
.setLabel("Sky")
.setEmoji('🟦')
.setStyle("SECONDARY")
)
let pink = '927403952348221449'
let mustard = '927403952427921412'
let sky = '927403952411140137'
let iuser = message.mentions.users.first() || message.author
let embed = new MessageEmbed()
.setTitle(`Color Roles`)
.setDescription('🟥 | Pink\n🟨 | Mustard\n🟦 | Sky')
.setURL("https://www.youtube.com/watch?v=rzVhR7ioqL4")
.setColor('#ffdb58')
const m = await message.channel.send({ embeds: [embed], components: [row] })
const filter = (interaction) => {
if(interaction.user.id === iuser.id) return true;
return interaction.reply({content: "This isn't for u", ephemeral: true})
}
const collector = message.channel.createMessageComponentCollector({
filter,
max: 1,
});
collector.on("end", (ButtonInteraction) => {
const id = ButtonInteraction.first().customId;
let pp = new MessageEmbed()
.setDescription(`You now have the <#&927403952348221449> role`)
.setColor('#ffc0cb')
m.edit(pp)
let mm = new MessageEmbed()
.setDescription(`You now have the <#&927403952427921412> role`)
.setColor('#ffdb58')
m.edit(mm)
let ss = new MessageEmbed()
.setDescription(`You now have the <#&927403952411140137> role`)
.setColor('#ffdb58')
m.edit(ss)
if(id === "pin") {
interaction.guild.roles.fetch(pink).then(role => member.roles.add(role)).catch(console.error())
return ButtonInteraction.first().reply({embeds: [pp]})
}else if(id === "mus") {
interaction.guild.roles.fetch(mustard).then(role => member.roles.add(role)).catch(console.error())
return ButtonInteraction.first().reply({embeds: [pp]})
}else if(id === "ski") {
interaction.guild.roles.fetch(sky).then(role => member.roles.add(role)).catch(console.error())
return ButtonInteraction.first().reply({embeds: [pp]})
}
})
} cooldown.add(message.author.id);
setTimeout(() => {
cooldown.delete(message.author.id)
}, 5000)}
};
I'm pretty much new in coding so hopefully, you could help me figure out the problem and make the code work fully 😄
I think you didn't define "guild",
try instead of
const {
Client,
Message,
MessageEmbed,
MessageActionRow,
MessageButton,
} = require('discord.js');
with the following:
const {
Client,
Guild,
guild
Message,
MessageEmbed,
MessageActionRow,
MessageButton,
} = require('discord.js');
I'm working on something and I need to add ban logging, I tried something but it doesn't send anything.
Any help would be appreciated!
client.on('guildBanAdd', async (guild, user) => {
let Banch = await client.channels.cache.get('ID')
const fetchedLogs = await guild.fetchAuditLogs({
limit: 1,
type: 'MEMBER_BAN_ADD',
});
const banLog = fetchedLogs.entries.first();
if (!banLog) return console.log(`${user.tag} was banned from ${guild.name} but no audit log could be found.`);
const embed = new Discord.MessageEmbed()
.setTitle(`Member Banned`)
.setDescription(`${guild.name}`)
.setColor("RED")
.addField(`Member`, `\n${username}`)
Banch.send(embed)
}
);
This should work
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('guildBanAdd', async (guild, user) => {
const banned = await guild.fetchAuditLogs({
type: 'MEMBER_BAN_ADD',
limit: 1
});
const channel = client.channels.cache.get('ID');
if(!channel) return console.log(`Channel was not found!`);
const userbanned = banned.entries.first();
const { executor, target } = userbanned; // get the user who banned the user and the user that got banned
if(target.id !== user.id) return console.log(`Invalid data in the audit logs!`); // check if the user that got banned in the Audit Logs is the user that is banned
const embed = new Discord.MessageEmbed()
.setTitle(`Member Banned`)
.setDescription(`${guild.name}`)
.setColor("RED")
.addField(`Member`, `${target.username}`);
channel.send(embed).catch(err => {
console.log(err);
});
});
I am working on an advanced suggestion command and here's my code so far:
if (command === 'accept') {
try {
const suggestionchan = bot.channels.cache.get('840493081659834403');
const acceptreason = message.content.split(' ')[2];
if(!acceptreason) return message.lineReply("Please provide the reason!")
const messageid = message.content.split(' ')[1];
console.log(messageid)
if(!messageid) return message.lineReply("Please provide the message id of the suggestion!")
const suggestionData = suggestionchan.messages.fetch(messageid)
const suggestionembed = suggestionData.embeds[0];
const acceptembed = new Discord.MessageEmbed()
.setAuthor(suggestionembed.author.name, suggestionembed.author.iconURL)
.setTitle("Suggestion!")
.setDescription(suggestionembed.description)
.setColor("GREEN")
.addFields(
{ name: `Accepted by ${message.author.tag}`, value: `**Reason:**\n${acceptreason}`}
)
.setFooter("Bot made by Sɱαɾƚx Gαɱιɳɠ YT")
suggestionembed.edit(acceptembed)
message.delete();
const user = bot.users.cache.find( (u) => u.tag === suggestionembed.author.name);
user.send(acceptembed)
} catch (err) { console.log(err)
message.lineReply("That message ID is not a valid ID!")}
}
I am getting an error on the part suggestionembed = suggestionData.embeds[0];
The error is TypeError: Cannot read property '0' of undefined at Client.<anonymous>
suggestionchan.messages.fetch returns a promise, so you'll need to resolve it first. You can either use the .then() method or the await keyword (as below).
It's also a good idea to check if the fetched message have any embeds.
if (command === 'accept') {
try {
const suggestionChannel = bot.channels.cache.get('840493081659834403');
const acceptReason = message.content.split(' ')[2];
if (!acceptReason)
return message.lineReply('Please provide the reason!');
const messageId = message.content.split(' ')[1];
if (!messageId)
return message.lineReply('Please provide the message id of the suggestion!');
const suggestionData = await suggestionChannel.messages.fetch(messageId);
const suggestionEmbed = suggestionData.embeds[0];
if (!suggestionEmbed)
return message.lineReply(`The message with ID ${messageId} doesn't have any embeds!`);
const acceptEmbed = new Discord.MessageEmbed()
.setAuthor(suggestionEmbed.author.name, suggestionEmbed.author.iconURL)
.setTitle('Suggestion!')
.setDescription(suggestionEmbed.description)
.setColor('GREEN')
.addFields({
name: `Accepted by ${message.author.tag}`,
value: `**Reason:**\n${acceptReason}`,
})
.setFooter('Bot made by Sɱαɾƚx Gαɱιɳɠ YT');
suggestionData.edit(acceptEmbed);
message.delete();
const user = bot.users.cache.find(
(u) => u.tag === suggestionEmbed.author.name,
);
user.send(acceptEmbed);
} catch (err) {
console.log(err);
message.lineReply('That message ID is not a valid ID!');
}
}
I am making a Discord bot for moderator applications for a server, and I followed a tutorial. The only issue is that when I run the command, nothing happens.
Code:
Apply.js
const { Message } = require('discord.js');
const Client = require('../client/Client');
module.exports = {
name: 'apply',
/**
* #param {Client} client
* #param {Message} message
* #param {String[]} args
*/
run: async(client, message, args) => {
const questions = [`What is your age?`, `What is your minecraft username?`, `Do you have a working mic?`, `What would you like to specialize in?`, `What experience do you have with previous discord/minecraft servers?`, `Why should we choose you?`, `Tell us about yourself!! What are your likes and dislikes, what do you find enjoyable, etc!`];
const dmChannel = await message.author.send('Welcome to your application!');
const collector = dmChannel.channel.createMessageCollector((msg) => msg.author.id == message.author.id);
let i = 0;
const res = [];
dmChannel.channel.send(questions[0]);
collector.on('collect', async(messag) => {
if(questions.length == i) return collector.stop('MAX');
const answer = msg.content;
res.push({ question: questions[i], answer });
i++;
if(questions.length == i) return collector.stop('MAX');
else {
dmChannel.channel.send(questions[i]);
}
});
collector.on('end', async(collected, reason) => {
if(reason == 'MAX') {
const data = message.guild.channels.cache.find(ch => ch.name.toLowerCase() == 'applications' && ch.type == 'text');
await data.send(`${message.member || message.author} (${message.author.tag}) submitted an application!\n${res.map(d => `${d.question} - ${d.answer}`).join("\n")}`)
}
})
}
}
Client.js
const { Client, Collection } = require('discord.js');
const { join } = require('path')
const { readdirSync } = require('fs');
class ApplicationClient extends Client {
constructor() {
super();
this.commands = new Collection();
};
start(token, cmd) {
this.prefix = 'a!'
this.login(token);
readdirSync(join(process.cwd(), cmd)).map((data) => {
const file = require(join(process.cwd(), cmd, data));
this.commands.set(file, file);
});
this.on('ready', () => console.log(``));
this.on('message', async(message) => {
if(message.author.bot ||!message.guild ||!message.content.toLowerCase().startsWith(this.prefix)) return;
const [ cmd, ...args] = message.content.slice(this.prefix.length).trim().split(/ +/g);
const command = this.commands.get(cmd.toLowerCase());
if(!command) return;
command.run(this, message, args).catch(console.error);
});
}
};
module.exports = ApplicationClient;
I've been trying this for 6 hours and have no clue what went wrong. In Node.js, everything works fine, the program runs. But if I type a!apply in Discord, nothing happens. Nothing shows up on the node.js console either. Any help would be appreciated.
I have a waifu command where it gets an image and a name and puts it in a embed, it also then reacts with the 💖 emoji. I wanted to make it so the first person who clicked the emoji would claim the waifu.
const { Client, MessageEmbed, ReactionCollector} = require('discord.js');
const {
prefix
} = require('../../config');
const superagent = require('superagent');
const {
urlencoded
} = require('body-parser');
module.exports = {
name: 'waifu',
category: 'waifu',
description: 'Random Waifu',
usage: `${prefix}waifu`,
perms: 'Send Messages',
cooldown: 5,
run: async (bot, message, args) => {
const rating1 = 10
const rating2 = Math.floor(Math.random() * rating1)
var rating = rating2
const decimals1 = 100
const decimals2 = Math.floor(Math.random() * decimals1)
var decimals = decimals2
const compatibility1 = 100
const compatibility2 = Math.floor(Math.random() * compatibility1)
var compatibility = compatibility2
const {
waifuID
} = require("../../Database/WaifuNameDB.json")
let randW = Math.floor(Math.random() * Object.keys(waifuID).length)
let randomWaifu = waifuID[randW]
let embed2 = new MessageEmbed()
.setTitle(`🎀${randomWaifu.names}🎀`)
.addField("Claims:", `${randomWaifu.claims}`)
.addField("Rating:", `${rating}.${decimals}/10 ⭐`)
.setImage(`${randomWaifu.img_url}`, innerHeight = '500', innerWidth = '500')
.setColor('#f095d1')
.setFooter(`| Powered by: #Twintails🎀 API `, `https://64.media.tumblr.com/1a1c3bcc08b5a048b90139a56fe7f415/tumblr_o9ku1rVS8z1vnqjx7o2_250.png`)
var mg = await message.channel.send(embed2);
mg.react('💖')
message.delete()
bot.on('messageReactionAdd', async (reaction, user) => {
if (reaction.mg) await reaction.mg.fetch();
if (reaction) await reaction.fetch()
if (user.bot) return;
if (reaction.emoji.name == "💖") {
message.channel.send(`${randomWaifu.names} was claimed!`)
mg.delete()
if(user = message.author) return;
}
})
}
}
It works, but if for example I do /waifu, it sends the embed and says (waifuname) was claimed, but whenever I do /waifu again, everything is the same, but when I click the react button, it says that the previous and the current waifu was claimed.
https://aws1.discourse-cdn.com/business6/uploads/glitch/original/2X/9/98363d9496747899fe23698cb0f98846b1e7136c.jpeg
(Umaru Doma was the previous waifu I rolled)
It also gives an error:
(node:9964) UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown Message
Please help if you can!
I have figured out a way to fix this everyone!
bot.on('messageReactionAdd', (messageReaction, user) => {
if(user.bot) return;
const {
message,
emoji
} = messageReaction;
if (emoji.name === "💖") {
if (!message.id === mg.id) return;
if (message.id === mg.id) {
mg.delete()
message.channel.send(`${randomWaifu.names} was claimed!`)
}
}
});