So I have a section of code which is designed to send an embed to a logging channel with the old and new message whenever a message is updated. However, whenever I test the code, the embed is sent successfully, but an error RangeError [EMBED_FIELD_VALUE]: MessageEmbed field values may not be empty occurs, and the bot crashes. I can find no reason why this error would occur, because all the fields return the values I specified.
The only thing I noticed that was strange is when I added the code to the bot, all embeds started to encounter the same error, but when I commented out the code, the embeds returned to normal.
Does anyone know why this error would occur? If so, how would I fix it?
This is the code:
var channel = newMessage.guild.channels.cache.find(ch => ch.name === 'bot-log');
var log = new MessageEmbed()
.setAuthor(oldMessage.author.tag, oldMessage.author.displayAvatarURL())
.setDescription(`:pencil: **[Message](${newMessage.url}) by ${newMessage.author} was edited in <#${oldMessage.channel.id}>**`)
.setColor(0x686afd)
.addFields(
{ name: `Old message`, value: oldMessage.content},
{ name: `New message`, value: newMessage.content},
)
.setTimestamp()
.setFooter(`Message ID: ${newMessage.id}`);
return channel.send(log);
});
Its happens because message content can be empty, like if user attach some files without text. You can check newMessage.content.length and oldMessage.content.length, and change it to what ever you want.
Like:
newMessage.content = newMessage.content.length > 0 ? newMessage.content : 'empty message'
oldMessage.content = oldMessage.content.length > 0 ? oldMessage.content : 'empty message'
I Think This Code Is The Right One :v
var channel = message.channel;
var log = new MessageEmbed()
.setAuthor(message.author.tag, message.author.displayAvatarURL())
.setDescription(`:pencil: **[Message](${message.url}) by ${message.author.tag} was edited in <#${message.channel.id}>**`)
.setColor(0x686afd)
.addFields(
{ name: `Old message`, value: message.content},
{ name: `New message`, value: message.content},
)
.setTimestamp()
.setFooter(`Message ID: ${message.id}`);
return channel.send(log);
Related
My suggestion Script worked totally fine for the last couple of months, but it stopped working a few days ago. I noticed that my .send function was underlined, and it said this:
Property 'send' does not exist on type 'GuildChannel | ThreadChannel'.
Property 'send' does not exist on type 'GuildChannel'
I'm btw. not sure if that's the problem with the script or if they changed anything I didn't notice, and I'm getting no errors. The Script basically just don't work.
My suggestion script:
case "suggestion":
var str = message.content.slice(" .suggestion".length);
const suggestionembed = new Discord.MessageEmbed()
.setThumbnail('png')
.setTitle("Suggestion")
.setColor('#151515')
.addFields(
{ name: "Person, that suggested somenthing:", value: `<#!${message.author.id}>` },
{ name: 'Suggestion:', value: `${str}` },
{ name: 'Channel:', value: `${message.channel}` },
)
.setTimestamp()
await message.guild.channels.cache.find(c => c.name === 'suggestion')
.send({ embeds: [suggestionembed] })
.then(embedMessage => {
embedMessage.react("✅")
embedMessage.react("❌")
});
message.delete();
break;
Just ignore that if you are sure that it's a text channel. That is only there because it can be a VoiceChannel. You won't have autocomplete in Visual Studio Code but it will still work as intended. If you are using TypeScript, you could use as to tell TypeScript it's a TextChannel
Ive seen many discord embed codes like this:
(This is an old question and im new to coding so...)
const { MessageEmbed } = require('discord.js');
const exampleEmbed = new MessageEmbed()
.setColor('#0099ff')
.setTitle('Some title')
.setURL('https://discord.js.org/')
.setAuthor('Some name', 'https://i.imgur.com/AfFp7pu.png', '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('Some footer text here', 'https://i.imgur.com/AfFp7pu.png');
channel.send({ embeds: [exampleEmbed] });
So, what i dont understand is what is the trigger? Like you're supposed to type .ping for pong right? so what do i type to get my bot type this embed?
The way you're sending your embed is(afaik) specific to version 13 of discord.js and you most likely haven't updated discord.js yet:
channel.send({ embeds: [exampleEmbed] });
the version I am currently using is 12.5.3 .
Check your version of discord.js in package.json and if the version is not 13 or above, update or if you want to stick with version 12.5.3 try some of the methods below:
channel.send( exampleEmbed );
Or like this:
channel.send({ embed: exampleEmbed });
Sending the embed like this: "{ embeds: [exampleEmbed] }" makes discord think you are sending an empty message and therefore it doesn't send anything.
This code is meant to be inside an event handler (such as on.message). If that code is already inside an event handler (except for this const { MessageEmbed } = require('discord.js');, it should go at the top), and if it is still not sending, then you should change this line:
channel.send({ embeds: [exampleEmbed] });
to
message.channel.send(exampleEmbed)
There is no trigger in the code sample you provided. You need to have a listener for the message event or interactionCreate event to listen to traditional message-based commands and slash commands. You can pass in handlers into these listeners and respond to command usages.
Since it looks like you're reading the discord.js guide, I would suggest reading from the start, where you would be introduced to how to handle messages first.
To send it, just use a message event. Like this:
const { MessageEmbed, Client } = require('discord.js');
const client = new Client();
client.on('message', msg => {
const { channel, content } = msg;
if(msg.content === 'someCommand') {
const exampleEmbed = new MessageEmbed()
//setProperties...
channel.send({ embeds: [exampleEmbed] });
}
})
client.login('[TOKEN_HERE'])
What's happening here is that the client is receiving a Message object when someone messages (msg). We then use the channel and content properties to evaluate the command, and send the embed if the command is correct. I took out the property settings to save space. You can add them back.
I'm working on semi-gacha bot command where you can pull characters and so on. I want to display the characters image after the user pulls and here is where I get stuck, it just doesn't display anything and I found what looked like the answer on here, but it didn't help, as I would get the same result and I don't get any errors, so I don't know what exactly is wrong. I have tried printing out the result of MessageAttachment first:
const attachment = new Discord.MessageAttachment('./chars/1.Jakku.png', '1.Jakku.png');
console.log(attachment);
and I get: undefined, anybody has any ideas of what am I doing wrong? And yes, I have discord.js library imported.
Relevant part of the code:
collector.on('collect', reaction => {
//new embd
const newEmbd = new Discord.MessageEmbed();
// gacha logic
if (reaction.emoji.name === '✅') {
const values = Object.values(chars);
const randomChar = values[parseInt(Math.floor(Math.random()*values.length))];
const attachment = new Discord.MessageAttachment('./chars/1.Jakku.png', '1.Jakku.png');
const charData = randomChar.split('.');
newEmbd
.setTitle(`You pulled: ${charData[1]}!`)
.setColor('YELLOW')
.attachFiles(attachment)
.setImage(`attachment://1.Jakku.png`);
embdReact.edit(newEmbd);
pulled = true;
} else if (reaction.emoji.name === '❌') {
newEmbd
.setTitle('Time for gacha!')
.setColor('YELLOW')
.addFields(
{ name: 'Result:', value: 'You decided against pulling' }
);
embdReact.edit(newEmbd);
};
});
You need to use the correct syntax for attaching files as per this guide
const exampleEmbed = new Discord.MessageEmbed()
.setTitle('Some title')
.attachFiles(['./chars/1.Jakku.png'])
message.channel.send(exampleEmbed);
Kind of new in the sphere of scripting bots, so looked up some tutorials and was trying to make a report command, when I write !report it says 'User not found', but when I write the full command ( !report #someone test) it doesn't send anything.
I have tried copying the code from GitHub but nothing helped, changed a lot of things around but still, no result.
//!report #ned this is the reason
let rUser = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[1]));
if(!rUser) return message.channel.send("Couldn't find user.");
let rreason = args.join(" ").slice(22);
let reportEmbed = new Discord.RichEmbed()
.setDescription("Reports")
.setColor("#15f153")
.addField("Reported User", `${rUser} with ID: ${rUser.id}`)
.addField("Reported By", `${message.author} with ID: ${message.author.id}`)
.addField("Reported in", message.channel)
.addField("Reported at", message.createdAt)
.addField("Report reason", rreason);
let reportschannel = message.guild.channels.get("603857301392195585")
if(!reportschannel) return message.channel.send("Couldn't find reports channel.");
message.delete().catch(O_o=>{});
reportschannel.send(reportEmbed);
return;
}
There was no errors, nothing in the command prompt.
1. You forgot to set a title/author in your embed. I don't know if its needed but you should add something like this. Then you can remove .setDescription().
// [...]
let reportEmbed = new Discord.RichEmbed()
.setAuthor("Reports")
.setColor("#15f153")
// [...]
2. You can leave out the part after message.delete(), there is no .catch() needed.
3. Remove return; at the end. It's not needed either.
Also check if you are running this.
E.g. use debug messages. After almost every line a console.log("1"), console.log("2") etc. to check, where the code stops.
Example:
//!report #ned this is the reason
let rUser = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[1]));
if(!rUser) return message.channel.send("Couldn't find user.");
console.log("1") // User exists
let rreason = args.join(" ").slice(22);
console.log("2") // No reason creating problems
let reportEmbed = new Discord.RichEmbed()
.setAuthor("Reports")
.setColor("#15f153")
.addField("Reported User", `${rUser} with ID: ${rUser.id}`)
.addField("Reported By", `${message.author} with ID: ${message.author.id}`)
.addField("Reported in", message.channel)
.addField("Reported at", message.createdAt)
.addField("Report reason", rreason);
let reportschannel = message.guild.channels.get("603857301392195585");
if(!reportschannel) return message.channel.send("Couldn't find reports channel.");
console.log("3") // Channel exists
message.delete();
console.log("4") // Message deleted
reportschannel.send(reportEmbed);
console.log("5") // Report message sent
I'm using react-native-gifted-chat in my react-native app. As I shown in this image, there is same message displayed multiple time and message: Yes getting new msg 's place is also varied from it's actual position.
My issue is same as this. Can anyone please help me to solve this.
Thank you in advance.
I got a solution of my question. #Ron you are right but in my case the issue is different. I solved it by change my format of parameters. It took different format and I passed different so they conflicted each other. Here is the solution it may useful to others.
parse = snapshot => {
const { timestamp: numberStamp, text } = snapshot.val();
const { key: _id } = snapshot;
const createdAt = moment(snapshot.val().createdAt, "DD/MM/YYYY hh:mm:ss");
const user = { };
var temp_data = snapshot.val()
if(snapshot.val().name == this.state.temp_logged_name) {
user._id = 1;
user.name = temp_data.name;
user.avatar = temp_data.avatar;
}
const message = {
_id,
createdAt,
text,
user,
};
return message;
};
I had encountered this issue as well. I had set up react-native-gifted-chat on my mobile app. And at the other end I had set up a simple HTML page with a script to initialise the Websocket connection and send messages on the onsend event. What I had realised later that while the unique id was getting generated at the app end (because the id was being generated by the library itself), nothing of such sort existed at the other end.
Basically, this weird behaviour crops up when a unique id _id is missing for a message. Each message must have at least the following properties while executing GiftedChat.append(previousMessages, messages).
{
_id: 1,
text: 'Hello developer',
createdAt: new Date(),
user: {
_id: 2
}
}
There could be two reasons behind it,
1) Each message should be passed a unique id, so just use uuidv4 npm package and append it to _id prop of the object.
Example:
messages: GiftedChat.append(previousState.messages, {
_id: uuidv4(), // or use Math.round(Math.random() * 1000000)
text: text,
createdAt: new Date(),
user: {
_id: 2,
name: "React Native",
avatar: "https://placeimg.com/140/140/any"
},
image: attachment
})
2) Second possibility could be on the gateway you are using to initiate the chat between users. So, some gateways have known issues to repeat the message multiple times. You could to string comparison each time a new message is received and pushed to the chat screen, however it is not advised to do this.
I figured this out by simply applying the filter to the incoming message in useLayout Effect:
useLayoutEffect(() => {
db.collection('Chats').doc(docID).collection('messages').orderBy("createdAt", "desc").onSnapshot(snapshot => {
setMessages(
prev =>
prev
.filter((ftr,index,self) => ftr?.user?._id !== loginUser?.id) //login user id is the current user's id you can do the same for recieved messages
.concat
(snapshot.docs.map(doc => doc.data({
_id: doc?.id,
user: doc.data().user,
text: doc.data().text,
createdAt:new Date(doc.data().createdAt),
})
))
)
})
},[])
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>