So I have this discord.js bot which sends an embed message and adds a value to it's description on command and deletes the value after 5 seconds, but every time I add a value to the description when it has already a value in it, the value that I add disappears when the first value gets deleted after those 5 seconds.
here is my code:
const { Client, Intents, MessageEmbed } = require('discord.js')
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] })
const mongoose = require('mongoose')
mongoose.connect(/*db adress*/, {useNewUrlParser: true, useUnifiedTopology: true})
const Schema = mongoose.Schema
const embedSchema = new Schema({
exists: { type: String, required: true },
embedId: { type: String, required: true },
channelId: { type: String, required: true }
})
const Embed = mongoose.model('Embed', embedSchema, 'embed')
const embedMessage = new MessageEmbed()
.setDescription('empty')
client.on('messageCreate', async message => {
if (message.content === '.sendEmbed') {
const embed = await message.channel.send({ embeds: [embedMessage] })
const saveEmbed = new Embed({
exists: 'true',
embedId: embed.id,
channelId: message.channel.id
})
saveEmbed.save()
} else if (message.content.startsWith('.add')) {
const wordsInMessage = message.content.split(' ')
if (!wordsInMessage[2]) {
Embed.find({ exists: 'true' }, async (err, embed) => {
const word = wordsInMessage[1]
const oldEmbed = await message.channel.messages.fetch(embed[0].embedId)
const newEmbed = oldEmbed.embeds[0]
const embedDescription = newEmbed.description.replaceAll('empty', '')
newEmbed.setDescription(`${embedDescription}\n${word}`)
oldEmbed.edit({ embeds: [newEmbed] })
setTimeout(() => updateValue(word), 5000)
})
}
}
})
function updateValue(word) {
Embed.find({ exists: 'true' }, async (err, embed) => {
Array.prototype.replaceAt = function(index, replacement) {
if (index >= this.length) {
return this.valueOf()
}
return this.splice(0, index) + replacement + this.splice(index + 1)
}
const channel = client.channels.cache.get(embed[0].channelId)
const getEmbed = await channel.messages.fetch(embed[0].embedId)
const embedMessage = await getEmbed.embeds[0]
const wordsPosition = embedMessage.description.split('\n').indexOf(word)
const newValue = embedMessage.description.split('\n')[wordsPosition].split(' ').replaceAt(0, 'empty')
embedMessage.setDescription(`${newValue}`)
getEmbed.edit({ embeds: [embedMessage] })
})
}
client.login(/*bot token*/)