Discord JS problem get username & avatarURL by mention - javascript

i try to mention a member on my server discord and with this it's create a webhook with his username and avatarURL but it's not working, it's tell me my usermentioned don't have displayName
My code:
if (cmd === "say")
{
message.delete()
let usermentioned = message.mentions.members.first();
let msg = args.slice(1).join(" ");
message.channel.createWebhook(usermentioned.displayName,
usermentioned.user.displayAvatarURL).then(wb =>
{
var Hook = new hookcord.Hook()
.setLink(`https://discordapp.com/api/webhooks/${wb.id}/${wb.token}`)
.setPayload({
'title': usermentioned.displayName,
'avatar': usermentioned.user.displayAvatarURL,
'content': msg
})
.fire()
.then(function(response)
{
wb.delete();
})
.catch(function(e) {})
})
}
The error:
message.channel.createWebhook(usermentioned.displayName, usermentioned.user.displayAvatarURL).then(wb =>
^
TypeError: Cannot read property 'displayName' of undefined

at first you shoud try to run with debugger and track your variable usermentioned. Or make output this variable to console. It give to you information about structure of user's profile. May be you get wrong level of profile

Related

How can i get my discord.js v14 bot to stop saying "The application did not respond" if the slash command works?

i have multiple commands that work perfectly fine but i always get this message in return.
here is the code for that command. it works perfectly fine i guess it just doesn't respond to the interaction even though i feel like it should be?
how can i get it to ignore this message or reply properly?
const Discord = require('discord.js');
const { EmbedBuilder, SlashCommandBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
// command name
.setName('totalfrozencheckouts')
// command description
.setDescription('Add up every message in the frozen checkouts channel after a specific message ID')
.addStringOption(option =>
option.setName('messageid')
.setDescription('The message ID')
.setRequired(true)),
async execute(interaction) {
const channel = '<#' + process.env.FROZENCHECKOUTS + '>';
const messageId = interaction.options.getString("messageid");
// Check if the channel mention is valid
if (!channel.startsWith('<#') || !channel.endsWith('>')) {
return interaction.channel.send(`Invalid channel mention. Please use the format: ${this.usage}`);
}
// Extract the channel ID from the channel mention
const channelId = channel.slice(2, -1);
// Try to fetch the messages from the requested channel and message ID
interaction.guild.channels.cache.get(channelId).messages.fetch({ after: messageId })
.then(messages => {
// Create an array of the message contents that are numbers
const numbers = messages.map(message => message.content).filter(content => !isNaN(content));
// Check if there are any messages
if (numbers.length === 0) {
return interaction.channel.send(`No messages were found in ${channel} after message ID https://discord.com/channels/1059607354678726666/1060019655663689770/${messageId}`);
}
// Adds up the messages
const sum = numbers.reduce((accumulator) => accumulator + 1, 1);
// Create an embed object
const embed = new EmbedBuilder()
.setColor(0x4bd8c1)
.setTitle(`Total Checkouts in #frozen-checkouts for today is:`)
.addFields(
{name: 'Total Checkouts', value: sum.toString() , inline: true},
)
.setThumbnail('https://i.imgur.com/7cmn8uY.png')
.setTimestamp()
.setFooter({ text: 'Frozen ACO', iconURL: 'https://i.imgur.com/7cmn8uY.png' });
// Send the embed object
interaction.channel.send({embeds: [embed]});
})
.catch(error => {
console.error(error);
interaction.channel.send('An error occurred while trying to fetch the messages. Please try again later.');
});
}
}
I don't really know what to try because it literally works I just don't know how to get it to either ignore that message or respond with nothing. It doesn't break the bot its just annoying to look at.
Use interaction.reply instead of interaction.channel.send to reply.

Cannot read properties of undefined (reading 'fetchBans')

Im trying to make a command with in my Discord bot to make unban a person. When I finnished the code I got an error. The error is Cannot read properties of undefined (reading 'fetchBans'). The code I use to make it is
message.guild.cache.fetchBans().then(async bans => {
if (bans.size === 0) return message.channel.send("No one is banned on the server!")
let bannedUser = bans.find(ban => ban.user.id == userID)
if (!bannedUser) return message.channel.send("This user isn't banned!")
await message.guild.members.unban(bannedUser.user, reason).catch(err => {
return message.channel.send("Something went wrong!")
}).then(() => {
let embed = new MessageEmbed()
.setColor("GREEN")
.setTitle(`Member unbanned!`)
.setDescription("")
.setTimestamp()
.setFooter(this.client.user.username)
embed.addField(`member = ${target.username}`, `reason = ${reason}`, false)
message.channel.send({embeds: [embed]});
if (row[0].logs_channel != null) this.client.channels.cache.get(row[0].logs_channel).send({embeds: [embed]})
message.delete()
})
The line where it goes wrong is this line:
message.guild.cache.fetchBans().then(async bans => {
When I run this command it will give the error. I also tried to do something else. The code i tried else for that line is:
message.guild.fetchBans().then(async bans => {
This line also gave an error that says: TypeError: message.guild.fetchBans is not a function.
I don't know what i can do about this. I hope somebody can help me.
Node.js version: 16.9.1
discord.js version: 13.1.0
According to the documentation there is no fetchBans on Guild. Maybe you're looking for message.guild.bans.fetch().
It's also worth noting that message.guild is nullable - if the message was a direct message (not sent in a guild) it will be null.

I have the TypeError: Cannot read property 'toString' of undefined

I'm making a discord welcomer bot and there's a problem where when someone joins the server it sends this error:
TypeError: Cannot read property 'toString' of undefined
Here is the source code:
module.exports = (client) => {
const channelid = "865471665168580628";
client.on("guildMemberAdd", (member) => {
const serverid = member.guild.id
const guild = client.guilds.cache.get(serverid);
console.log("member");
const ruleschannel = guild.channels.cache.find(channel => channel.name === "rules");
const message = `welcome <#${member.id}> to music and chill! please read the ${member.guild.channels.cache.get(ruleschannel).toString()} before you start chatting.`;
const channel = member.guild.channels.cache.get(channelid);
channel.send(message);
})
}
Can someone please help me?
It means member.guild.channels.cache.get(ruleschannel) is undefined. As ruleschannel is a channel object, and the Collection#get() method needs a snowflake, you need to use its id property.
So member.guild.channels.cache.get(ruleschannel.id) should work.
A better way would be to check if the ruleschannel exists though. Also, you can just simply add rulesChannel inside the backticks and it gets converted to a channel link. Check out the code below:
client.on('guildMemberAdd', (member) => {
// not sure why not just: const { guild } = member
const guild = client.guilds.cache.get(member.guild.id);
const rulesChannel = guild.channels.cache.find((channel) => channel.name === 'rules');
if (!rulesChannel)
return console.log(`Can't find a channel named "rules"`);
const channel = guild.channels.cache.get(channelid);
const message = `Welcome <#${member.id}> to music and chill! Please, read the ${rulesChannel}.`;
channel.send(message);
});

How to log into the ban section of discord using discord.js v12?

I'm working on my ban command and it's fully functional, but I was wondering, how I would log the ban reason into the ban section of discord (example in the attachment)? My code looks like this:
const { DiscordAPIError } = require("discord.js");
const Discord = require('discord.js');
module.exports = {
name: 'ban',
description: "Mentioned user will be banned",
execute(message, args){
if (!message.member.hasPermission("BAN_MEMBERS")) return message.channel.send("Invalid Permissions")
let User = message.guild.member(message.mentions.members.first()) || message.guild.members.cache.get(args[0])
if (!User) return message.channel.send("Invalid User")
if (User.hasPermission("BAN_MEMBERS")) return message.reply("Invalid Permissions a")
let banReason = args.join(" ").slice(22);
if (!banReason) {
banReason = "None"
}
console.log(`USER = ${User}`)
User.ban
console.log(`Ban reason = ${banReason}`)
var UserID = User.id
console.log(`USER ID = ${UserID}`)
}
}
Any help? Thanks :)
It's actually quite easy, just add ({reason: banReason}) after the User.ban part, making it:
User.ban({reason: banReason})
That should log it there properly :)
You can use the reason property of the options parameter in the GuildMember.ban() method:
User.ban({ reason: 'real life danger' })
.then(member => console.log(`${member.name} was banned.`))
.catch(console.error)
Also, in your code, there's no reason for using the Guild.member() method when defining User. Guild.member(user) is used to turn a User object into a GuildMember object.
However, MessageMentions.members.first() already returns a GuildMember object, making it obsolete.

discord.js get message's id and delete it

When a user joins the server, the bot sends a welcome message, i want to take that welcome message's ID and make the bot delete it if the users leaves after he joins. I tried to save the message's id in a variable and make the bot delete the message when the user leaves but without success. I already took a look at the docs, but I really can't understand how to make it.
Define an object to hold the welcome messages by guild and user. You may want to use a JSON file or database (I'd highly recommend the latter) to store them more reliably.
When a user joins a guild...
Send your welcome message.
Pair the the message's ID with the user within the guild inside of the object.
When a member leaves the guild...
Fetch their welcome message.
Delete the message from Discord and the object.
Example setup:
const welcomeMessages = {};
client.on('guildMemberAdd', async member => {
const welcomeChannel = client.channels.get('channelIDHere');
if (!welcomeChannel) return console.error('Unable to find welcome channel.');
try {
const message = await welcomeChannel.send(`Welcome, ${member}.`);
if (!welcomeMessages[member.guild.id]) welcomeMessages[member.guild.id] = {};
welcomeMessages[member.guild.id][member.id] = message.id;
} catch(err) {
console.error('Error while sending welcome message...\n', err);
}
});
client.on('guildMemberRemove', async member => {
const welcomeChannel = client.channels.get('channelIDHere');
if (!welcomeChannel) return console.error('Unable to find welcome channel.');
try {
const message = await welcomeChannel.fetchMessage(welcomeMessages[member.guild.id][member.id]);
if (!message) return;
await message.delete();
delete welcomeMessages[member.guild.id][member.id];
} catch(err) {
console.error('Error while deleting existing welcome message...\n', err);
}
});
To do this you would have to store the id of the welcome message and the user that it is tied to (ideally put this in an object). And when the user leaves you would use those values to delete that message.
Example code:
const Discord = require('discord.js');
const client = new Discord.Client();
const welcomeChannel = client.channels.find("name","welcome"); // Welcome is just an example
let welcomes = [];
client.on('message', (message) => {
if(message.channel.name === 'welcome') {
const welcomeObj = { id: message.id, user: message.mentions.users.first().username };
welcomes.push(welcomeObj);
}
});
client.on('guildMemberRemove', (member) => {
welcomes.forEach(welcome, () => {
if(welcome.user === member.user.username) {
welcomeChannel.fetchMessage(welcome.id).delete();
}
});
});
This only works if the welcome message includes a mention to the user so make sure that's in the welcome message.
Also I can't test this code myself at the moment so let me know if you encounter any problems.

Categories

Resources