Discord JS - Embed Footer Text - discord.js

I'm trying to make a starboard so here is my code:
const starChannel = bot.channels.cache.find(channel => channel.name.toLowerCase() === 'test-logs');
const fetchedMessages = await starChannel.messages.fetch({ limit: 100 });
const stars = fetchedMessages.filter((m) => m.embeds.length != 0).find((m) => m.embeds[0].footer.text.includes(message.id));
const image = message.attachment.size > 0 ? await(reaction, message.attachment.array()[0].url) : '';
const embed = new Discord.MessageEmbed()
.setAuthor(message.author.tag, message.author.displayAvatarURL({ format: 'png', dynamic: true }))
.setDescription(message.content)
.addField("Original:", `[**Jump to message**](https://discordapp.com/channels/${message.guild.id}/${message.channel.id}/${message.id})`)
.setFooter(`Message ID: ${message.id}`)
.setTimestamp()
Then I got this rejection error: UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'text' of undefined

embed.footer can be null, so you need check if embed has footer.
Like this
const fetchedMessages = await starChannel.messages.fetch({ limit: 100 });
const stars = fetchedMessages.filter((m) => m.embeds.length != 0).find((m) => m.embeds[0].footer && m.embeds[0].footer.text.includes(message.id));
const image = message.attachment.size > 0 ? await (reaction, message.attachment.array()[0].url) : '';
const embed = new Discord.MessageEmbed()
.setAuthor(message.author.tag, message.author.displayAvatarURL({ format: 'png', dynamic: true }))
.setDescription(message.content)
.addField("Original:", `[**Jump to message**](https://discordapp.com/channels/${message.guild.id}/${message.channel.id}/${message.id})`)
.setFooter(`Message ID: ${message.id}`)
.setTimestamp()

Related

discord interaction.deferUpdate() is not a function

I'm creating a message with buttons as reaction roles but do the reaction role handling in another file so it stays loaded after a reset but it either says "interaction.deferUpdate() is not a function, or in discord it says "this interaction failed" but it gave/removed the role
my code for creating the message:
const { ApplicationCommandType, ActionRowBuilder, ButtonBuilder, EmbedBuilder } = require('discord.js');
module.exports = {
name: 'role',
description: "reactionroles",
cooldown: 3000,
userPerms: ['Administrator'],
botPerms: ['Administrator'],
run: async (client, message, args) => {
const getButtons = (toggle = false, choice) => {
const row = new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setLabel('member')
.setCustomId('member')
.setStyle(toggle == true && choice == 'blue' ? 'Secondary' : 'Primary')
.setDisabled(toggle),
new ButtonBuilder()
.setLabel('member2')
.setCustomId('member2')
.setStyle(toggle == true && choice == 'blue' ? 'Secondary' : 'Primary')
.setDisabled(toggle),
);
return row;
}
const embed = new EmbedBuilder()
.setTitle('Wähle eine rolle')
.setDescription('Wähle die rolle, die du gern haben möchtest')
.setColor('Aqua')
message.channel.send({ embeds: [embed], components: [getButtons()] })
.then((m) => {
const collector = m.createMessageComponentCollector();
collector.on('collect', async (i) => {
if (!i.isButton()) return;
await i.deferUpdate();
});
});
}
};
code for the reaction role:
const fs = require('fs');
const chalk = require('chalk')
var AsciiTable = require('ascii-table')
var table = new AsciiTable()
const discord = require("discord.js");
table.setHeading('Events', 'Stats').setBorder('|', '=', "0", "0")
module.exports = (client) => {
client.ws.on("INTERACTION_CREATE", async (i) => {
let guild = client.guilds.cache.get('934096845762879508');
let member = await guild.members.fetch(i.member.user.id)
let role = guild.roles.cache.find(role => role.name === i.data.custom_id);
if (!member.roles.cache.has(role.id)) {
member.roles.add(role);
} else {
member.roles.remove(role);
}
return i.deferUpdate()
})
};
The client.ws events give raw data (not discord.js objects), so the .deferUpdate() method doesn't exist there. You should be using client.on("interactionCreate")
client.on("interactionCreate", async (i) => {
// ...
return i.deferUpdate()
})

DiscordAPIError: Cannot send an empty message (discord.js v13)

I am coding a bot with the below command and it throws an error, but i don't know where is the error
i tried my best
const Discord = require("discord.js");
const client = new Discord.Client({
allowedMentions: {
parse: ["roles", "users", "everyone"],
},
intents: [
Discord.Intents.FLAGS.GUILDS,
Discord.Intents.FLAGS.GUILD_MESSAGES,
Discord.Intents.FLAGS.DIRECT_MESSAGES
]
});
const config = require("../config.json");
module.exports = {
name: "quar",
run: async (client, message, args) => {
if (!message.member.permissions.has("ADMINISTRATOR")) return;
let role = message.guild.roles.cache.find(role => role.name === "Quarantined" || role.name === "Quarantine")
let member = message.mentions.members.first() || message.guild.members.cache.get(args[0])
let reason = message.content.split(" ").slice(2).join(" ")
if(!reason) reason = "No reason given."
if(!role) return message.channel.send("❌ This server doesn't have a quarantine role!")
if(!member) return message.channel.send("❌ You didn't mention a member!")
if(member.roles.cache.has(role.id)) return message.channel.send(`❌ That user already quarantined!`)
member.roles.add(role)
.then (() => {
const embed = new Discord.MessageEmbed()
.setTitle(`✅ ${member.user.tag} was quarantined!`)
.setColor("RANDOM")
.setTimestamp()
embed.setFooter(`Requested by ${message.author.username}`)
message.channel.send(embed)
member.send(`You were quarantined in \`${message.guild.name}\`. Reason: ${reason} `).catch(error => {
message.channel.send(`❌ Can't send DM to ${member.user.tag}!`);
});
})
}
}
If I have made a mistake, please help me out
Sorry I don't speak English well
Try the below code out, I made notes along the way to explain as well as improved a small bit of code. I assume this is a collection of 2 separate files which is why they are separated. If they aren't 2 separate files, you do not need the top section, just the bottom.
const {
Client,
Intents,
MessageEmbed
} = require("discord.js");
const client = new Client({
allowedMentions: {
parse: ["roles", "users", "everyone"],
},
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.DIRECT_MESSAGES
]
});
const config = require("../config.json");
const {
MessageEmbed,
Permissions
} = require("discord.js");
module.exports = {
name: "quar",
run: async (client, message, args) => {
if (!message.member.permissions.has(Permissions.FLAGS.ADMINISTRATOR)) return;
let role = message.guild.roles.cache.find(role => role.name === "Quarantined" || role.name === "Quarantine")
let member = message.mentions.members.first() || message.guild.members.cache.get(args[0])
let reason = message.content.split(" ").slice(2).join(" ")
if (!reason) reason = "No reason given."
if (!role) return message.channel.send("❌ This server doesn't have a quarantine role!")
if (!member) return message.channel.send("❌ You didn't mention a member!")
if (member.roles.cache.has(role.id)) return message.channel.send(`❌ That user already quarantined!`)
member.roles.add(role)
.then(() => {
const embed = new MessageEmbed()
.setTitle(`✅ ${member.user.tag} was quarantined!`)
.setColor("RANDOM")
.setTimestamp()
.setFooter({
text: `Requested by ${message.author.username}`
})
// author and footer are now structured like this
// .setAuthor({
// name: 'Some name',
// icon_url: 'https://i.imgur.com/AfFp7pu.png',
// url: 'https://discord.js.org',
// })
// .setFooter({
// text: 'Some footer text here',
// icon_url: 'https://i.imgur.com/AfFp7pu.png',
// })
message.channel.send({
embeds: [embed]
}) //embeds must be sent as an object and this was the actual line that was causing the error.
member.send(`You were quarantined in \`${message.guild.name}\`. Reason: ${reason} `).catch(() => { // if error is not used, it is not required to be stated
message.channel.send(`❌ Can't send DM to ${member.user.tag}!`);
});
})
}
}

How can I read MongoDB data using discord.js?

I've made a coin system and am trying to read how many coins the user has, but for some reason it's coming back as 'undefined', done anyone know why?
else if (command === 'coins') {
const userData = await CoinSystem.find({userID : message.member.user.id});
if (!userData.length) {
const createdData = new CoinSystem({
userID : message.member.user.id,
userName : message.member.user.tag,
coins : 0
})
await createdData.save().catch(e => console.log(e));
await message.channel.send("You have 0 coins.");
return;
}
if (userData.length) {
await message.channel.send(await userData.find(coins));
}
Creating the data.
const mongoose = require('mongoose');
const coinSchema = new mongoose.Schema({
userID : {
type : mongoose.SchemaTypes.String,
required : true
},
userName : {
type : mongoose.SchemaTypes.String,
required : true
},
coins : {
type : mongoose.SchemaTypes.Number,
required : true,
default : 0
}
})
module.exports = mongoose.model('CoinSystem', coinSchema)
First, try using await CoinSystem.findOne({userID : message.member.user.id}); instead of await CoinSystem.find({userID : message.member.user.id});
Second, try using (!userData) and (userData) instead of (!userData.length) and (userData.length)
Third, try using
await message.channel.send({ content: `${userData.coins}` });
instead of await message.channel.send(await userData.find(coins));
The final code is:
const userData = await CoinSystem.findOne({userID : message.member.user.id});
if (!userData) {
const createdData = new CoinSystem({
userID : message.member.user.id,
userName : message.member.user.tag,
coins : 0
})
await createdData.save().catch(e => console.log(e));
await message.channel.send({ content: "You have 0 coins."});
return;
}
if (userData) {
await message.channel.send({ content: `You have ${userData.coins} coins` });
}
Notes --> the reason of using:
message.channel.send({ content: `You have ${userData.coins} coins` })
instead of:
message.channel.send(`You have ${userData.coins} coins`)
is because of Discord.js v13.
If yours is discord.js v12, then u should use:
message.channel.send(`You have ${userData.coins} coins`)

doesn't get an embed doesn't come out

I'm going to make a discord.js. When I enter !otherhelp, I try to get an embed, but it doesn't get an embed doesn't come out.
this is my code...
const { Client, Intents, DiscordAPIError } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const {prefix, token} = require('./config.json')
const fs = require('fs')
const { MessageEmbed } = require('discord.js');
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`)
});
const convertEmoji = (who) => {
if(who === "!가위바위보 가위"){
return "✌";
}
else if(who === "!가위바위보 바위"){
return "👊";
}
else if(who === "!가위바위보 보"){
return "✋";
}
}
client.on('message', msg => {
if(msg.content === "!서버주소"){
msg.reply("1.8.9 beargames.mcv.kr");
}
if(msg.content === "!가위바위보 가위" || msg.content === "!가위바위보 바위" || msg.content === "!가위바위보 보") {
const human = msg.content;
const list = ["!가위바위보 가위", "!가위바위보 바위", "!가위바위보 보"];
const random = Math.floor(Math.random() * 3);
const bot = list[random];
let winner = "";
if(human === bot) {
winner = "비김";
}
else {
human === "!가위바위보 가위" ? (winner = bot === "!가위바위보 바위" ? "봇" : "사람") : "";
human === "!가위바위보 바위" ? (winner = bot === "!가위바위보 보" ? "봇" : "사람") : "";
human === "!가위바위보 보" ? (winner = bot === "!가위바위보 가위" ? "봇" : "사람") : "";
}
const result =
`
봇 : ${convertEmoji(bot)}
${winner === "비김" ? "우리는 비겼다 인간." : winner + "의 승리다"}
`
msg.reply(result);
}
if(msg.convertEmoji === !otherhelp){
const exampleEmbed = new MessageEmbed()
.setColor('#0099ff')
.setTitle('Some title')
.setURL('https://discord.js.org/')
.setAuthor({ name: 'Some name', iconURL: 'https://i.imgur.com/AfFp7pu.png', url: 'https://discord.js.org' })
.setDescription('Some description here')
.setThumbnail('https://i.imgur.com/AfFp7pu.png')
.addFields(
{ name: 'Regular field title', value: 'Some value here' },
{ name: '\u200B', value: '\u200B' },
{ name: 'Inline field title', value: 'Some value here', inline: true },
{ name: 'Inline field title', value: 'Some value here', inline: true },
)
.addField('Inline field title', 'Some value here', true)
.setImage('https://i.imgur.com/AfFp7pu.png')
.setTimestamp()
.setFooter({ text: 'Some footer text here', iconURL: 'https://i.imgur.com/AfFp7pu.png' });
channel.send({ embeds: [exampleEmbed] });
}
});
client.login('(token)');
this is my error
C:\Users\User\Desktop\dev\discordbot\index.js:51
if(msg.convertEmoji === !otherhelp){
^
ReferenceError: otherhelp is not defined
at Client. (C:\Users\User\Desktop\dev\discordbot\index.js:51:26)
at Client.emit (node:events:390:28)
at MessageCreateAction.handle (C:\Users\User\Desktop\dev\discordbot\node_modules\discord.js\src\client\actions\MessageCreate.js:33:18)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\User\Desktop\dev\discordbot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\User\Desktop\dev\discordbot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:350:31)
at WebSocketShard.onPacket (C:\Users\User\Desktop\dev\discordbot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:443:22)
at WebSocketShard.onMessage (C:\Users\User\Desktop\dev\discordbot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:300:10)
at WebSocket.onMessage (C:\Users\User\Desktop\dev\discordbot\node_modules\ws\lib\event-target.js:199:18)
at WebSocket.emit (node:events:390:28)
at Receiver.receiverOnMessage (C:\Users\User\Desktop\dev\discordbot\node_modules\ws\lib\websocket.js:1093:20)
convertEmoji is not part of the Discord message object.
Use message.content instead.
if(msg.content === "!otherhelp")

im trying to make a simple discord.js bot

i am trying to make it so as soon as you type: mememe it will react with: your nickname is now:
my current code is
const Discord = require("discord.js");
const client = new discord.client();
client.login(process.env.SECRET);
const embed = new Discord.MessageEmbed()
.setTitle("This is Embed Title")
.setDiscription("this is embed discription")
.setColor("RANDOM")
.SetFooter("This is Embed Footer");
const nicknames = ["dumbass", "idiot", "op", "man", "power", "docter"];
client.on("ready", () => {
client.user.setPresence({ activity: { name: "brave" }, status: "invisible" });
});
client.on("message", (message) => {
if (message.content === "ding") {
message.channel.send === "dong";
}
if (message.content === "embed") {
message.channel.send(embed);
}
});
if (message.content("mememe")) {
const index = Math.floor(Math.random() * nicknames.length);
message.channel.send(nicknames[index]);
}
but i dont know why it does not work it says as a error: Parsing error: Unexpected token
that is all and idk how to fix that
Edit : you guys were useless
I first want to say: Please fix your indents (I did it for you below here.
const Discord = require("discord.js")
const client = new Discord.Client()
client.login(process.env.SECRET)
// const embed = new Discord.MessageEmbed()
// .setTitle("This is Embed Title")
// .setDiscription("this is embed discription")
// .setColor("RANDOM")
// .SetFooter("This is Embed Footer");
const nicknames = ["dumbass", "idiot" , "op" , "man" , "power" , "docter"]
client.on("ready" , () => {
client.user.setPresence({ activity: { name: "brave"}, status: "invisible"})
})
client.on("message" , message => {
if(message.content === ("ding")) {
message.channel.send === ("dong")
}
if(message.content === ("embed")) {
message.channel.send(embed)
}
if(message.content === ("mememe")) {
const index = Math.floor(Math.random() * nicknames.length);
message.channel.send(nicknames[index])
}
})
The issue was you were calling the mememe command wrong. Above you used messega.content === "..."
In the mememe command you used message.content("mememe"). This does not work. Changes it (or copying the code above should fix the issue. Maybe an idea for you. You could add a feature where it changes the Users Nickname instead of sending a random one.

Resources