Does fetching embeds through messages from msg.reference.messageID not work? - javascript

I am coding a discord bot, and I am trying to get the content of embeds through the command user replying to the message and using a prefix. When I try running the command, it says that fetchedMsg.embeds[0] isn't a thing. Is there anything wrong with my code?
if (msg.reference) {
const fetchedMsg = await msg.channel.messages.fetch(msg.reference.messageID)
console.log(fetchedMsg)
console.log(fetchedMsg.embeds[0])
}
The error is on the line console.log(fetchedMsg.embeds[0]), and looking at the log from the code before it includes embeds: [ [MessageEmbed] ],.
The error reads TypeError: Cannot read properties of undefined (reading '0'), and when I remove the [0], it's undefined. This whole thing is in a module.exports.run, if that helps.
module.exports.run = async (client, msg, args) => {
const { MessageActionRow, MessageButton, MessageEmbed } = require('discord.js');
if (args.length === 5) {
if (msg.reference) {
const fetchedMsg = await msg.channel.messages.fetch(await msg.reference.messageID)
console.log(fetchedMsg)
console.log(fetchedMsg.embeds[0])
}
//do things with fetchedMsg

You can get the MessageEmbed() same as normal Message using:
const messages = args[0]
if(!messages) return message.reply("Provide an ID for message.")
if(isNaN(messages)) return message.reply("Message ID should be
number, not a letter")
message.channel.messages.fetch(`${messages}`)
.then(msg => {
console.log(msg.content) || console.log(msg.embeds)
})
You can find more here about fetching a message

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 'channels')

I'm trying to make an event that when someone added my bot it will send a message embed on a channel that my bot can send the message embed.
discord.js: v13.6.0
Node: v17.7.2
events/guildCreate.js
const client = require("../index");
const discord = require("discord.js")
client.on("guildCreate", async (client, guild) => {
let channel = guild.channels.cache.find(
channel =>
channel.type === "text" &&
channel.permissionsFor(guild.me).has("SEND_MESSAGES")
);
channel.send( new discord.MessageEmbed()
.setDescription("**Thank you for adding me!**")
.setColor("#fcba03"))
})
edit:
I kinda of fix my problem with the reading channels:
const client = require("../index");
const { MessageEmbed } = require("discord.js")
client.on("guildCreate", async (guild, message) => {
let channel = guild.channels.cache.find(
channel =>
channel.type === "text" &&
channel.permissionsFor(guild.me).has("SEND_MESSAGES")
);
const embed = new MessageEmbed()
embed.setDescription("Thank you for adding me!")
embed.setColor("#2f3136")
message.guild.channels.cache.get(channel).send(embed)
})
but then again got new error:
TypeError: Cannot read properties of undefined (reading 'guild')
I think your “channel” is an array instead of a channel object, because you're filtering all text channels. Make sure to select the first channel of the array/collection.
Try to show what shows up when you log the “channel”

Discord bot failing to call username of person who calls it

I'm trying to make my bot say a simple message whenever someone tells it 'hello'. Currently, the code of the command itself looks like this:
const { SlashCommandBuilder } = require('#discordjs/builders');
const greeter = "default";
const greetOptions = [
`Hello, ${greeter}. It's very nice to hear from you today.`
]
module.exports = {
data: new SlashCommandBuilder()
.setName('hello')
.setDescription('say hi to Hal!'),
execute(message, args) {
let greeter = message.user.username;
msg.channel.send(greetOptions[Math.floor(Math.random() * greetOptions.length)]);
},
};
The code I am using to manage when commands are typed looks as follows:
let prefix = "hal, ";
client.on('messageCreate', message => {
if (!message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length);
const command = args.toLowerCase();
console.log(`${message.author.tag} called ${command}`);
if (!client.commands.has(command)) return;
try {
client.commands.get(command).execute(message, args);
} catch (error) {
console.error(error);
message.channel.send({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
When I run it, it throws the error, "Cannot read properties of undefined (reading 'username').
If You want to mention a user you can do ${message.author}. But if you want to say for ex. Hello, Brandon then you need to do ${message.author.username}. The message ${message.author.tag} does not always function and also I recommend you const user = message.mentions.users.first() || message.author or just const user = message.author for short so then you can do ${user.username}. Maybe this might fix the bot failing to respond otherwise if it doesn't tell me.
Fix the first code and change msg.channel.send to message.channel.send.

Need Assistance With My unmute command for discord.js

Basically This command is giving one major issue and that the fact that when the user is muted he won't be unmuted because of the command not responding back to the mute command
const Discord = require('discord.js');
const fs = module.require('fs');
module.exports.run = async (client, message, args) => {
if (!message.member.hasPermission('MANAGE_MESSAGES')) return;
let unMute = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if (!unMute) {
let exampleEmbed = new Discord.MessageEmbed()
.setDescription("__UNMUTE INFO__")
.setColor(client.colors.success)
.setThumbnail(client.user.displayAvatarURL())
.addField(`Unmute Command`, `Unmutes a mentioned user.`)
.addField(`Unmute Command`, `Unmutes User By Id.`)
.addField("Example", `${client.config.prefix}Unmutes #user`)
.addField("Example", `${client.config.prefix}Unmutes #id`)
message.channel.send(exampleEmbed);
return;
}
let role = message.guild.roles.cache.find(r => r.name === 'Muted');
message.channel.send(`Please Check roles to be sure user was unmuted`);
if (!role || !unMute.roles.cache.has(role.id)) return message.channel.send(`That user is not muted.`);
if (!role || !unMute.roles.cache.has(User.id)) return message.channel.send(`----`);
let guild = message.guild.id;
let member = client.mutes[unMute.id];
if (member) {
if (member === message.guild.id) {
delete client.mutes[unMute.id];
fs.writeFile("./mutes.json", JSON.stringify(client.mutes), err => {
if (err) throw err;
})
await unMute.roles.remove(role.id);
message.channel.send(`:white_check_mark: ${unMute} Has been unmuted.`);
}
return;
}
await unMute.roles.remove(role.id);
message.channel.send(`:white_check_mark: ${unMute} Has been unmuted.`);
message.delete();
}
module.exports.config = {
name: 'unmute',
description: 'Unmute a user.',
access: 'Manage Messages Permission',
usage: 'unmute #vision'
}
I'm Also getting an error message when manually unmuting the user
(node:6604) UnhandledPromiseRejectionWarning: ReferenceError: User is not defined
Any Form of help would be greatly appreciated and thank you for your time.
On the line if (!role || !unMute.roles.cache.has(User.id)) return message.channel.send('----'), you reference the variable User, but you haven't definied it anywhere, and even if it was defined, you need a role not a member or user. I'm pretty sure it should instead be Role.id. Also, not 100% sure on this, but I tnink it should just be Role not Role.id.

discord.js UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'kickable' of undefined

Yesterday I could run this scrip.
Today I get the error
(node:29568) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'kickable' of undefined
I'm running version "discord.js": 12.1.1 - I hope someone can spot what I'm doing wrong here... because it's drive me nuts.
Bellow you can find my kickuser.js - script
+ my index.js script -> https://pastebin.com/7tLkuU5p
const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
if (message.member.hasPermission("KICK_MEMBERS")) {
if (!message.mentions.users) return message.reply('You must tag 1 user.');
else {
const channel = message.guild.channels.cache.get(696692048543088691);
const member = message.mentions.members.first();
let reason = message.content.split(" ").slice(2).join(' ');
if (member.kickable == false) return message.channel.send("That user cannot be kicked!")
else {
if (!reason) reason = (`No reason provided.`);
await member.send(`You have been kicked from **${message.guild.name}** with the reason: **${reason}**`)
.catch(err => message.channel.send(`⚠ Unable to contact **${member}**.`));
await member.kick(reason);
const kickEmbed = new MessageEmbed()
.setAuthor(member.user.tag, member.user())
.setThumbnail(member.user.avatarURL())
.setColor("#ee0000")
.setTimestamp()
.addField("Kicked By", message.author.tag)
.addField("Reason", reason);
await channel.send(kickEmbed);
console.log(`${message.author.tag} kicked ${member.user.tag} from '${message.guild.name}' with the reason: '${reason}'.`);
}
}
} else {
message.channel.send("You do not have permission to use kick.");
return;
}
}
module.exports.help = {
name: "kickuser"
}
I hope someone can help me.
Thanks in advance.
message.mentions.users always evaluates to true because it is an object, and to check if the message has any mentions, you can do:
if(!message.mentions.members.first()) return message.reply('You must tag 1 user.');
instead of:
if(!message.mentions.users) ...

Categories

Resources