RichEmbed field values may not be empty how to fix? - bots

i keep getting the error: RichEmbed field values may not be empty. and cant find out what the problem is. it does everything instead of reacting on his own command.
it says in chat /userinfo #name but then gives me the error and doesnt show the info it should
const Discord = require ('discord.js');
const bot = new Discord.Client();
const config = require ('./SecretStuff/config.json')
const prefix = config.prefix;
const snek = require ('snekfetch');
bot.on('ready', () => console.log("online!"));
bot.on("guildMemberAdd", (member) => {
let guild = member.guild;
let memberTag = member.user.tag;
if(member.guild.channels.find(channel => channel.name === "welcomechannel"));
guild.systemChannel.send("/userinfo" + " <#" + member.id + ">" )
}
);
bot.on('message', async (msg) => {
if (msg.content.startsWith(prefix + "userinfo")) {
let member = msg.mentions.users.first() || msg.author;
let userembed = new Discord.RichEmbed()
.setColor(msg.guild.member(member).highestRole.color)
.setThumbnail(member.displayAvatarURL)
.setTitle(`Here is ${member.username}'s info.`)
.addField(`Name:`, member.username, true)
.addField(`Id:`, member.id, true)
.addField(`Bot:`, member.bot ? "Yes" : "No", true)
.addField("Game:", msg.guild.member(member).presence.game ? msg.guild.member(member).presence.game.name : "Not Playing", true)
.addField("Nickname:", msg.guild.member(member).nickname ? msg.guild.member(member).nickname : "None", true )
.addField("Last Messsage:", member.lastMessage, true)
.addField(`Roles:`, msg.guild.member(member).roles.map(s => s).join(" | "), true)
.addField("Created At:", member.createdAt, true)
.addField("JoinedAt:", msg.guild.member(member).joinedAt, true)
msg.channel.send(userembed);
}
});
let token = config.token;
bot.login(token)

Related

Having problems using weather-js

Some monthes ago I followed a tutorial to code a bot that shows weather forecast depending on a stated location. This bot is using weather-js package, but since recently, no matter if I host my bot or launch it through the console, it's working when it wants to, and not working for some locations.
Here is what contains my index.js :
const fs = require('fs');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
\\client.on("ready")....
.....
client.on('messageCreate', async message => {
if (!message.content.startsWith(prefix)) return;
let args = message.content.slice(prefix.length).split(" ");
let command = args.shift().toLowerCase()
if (command === "weather") {
client.commands.get("weather").execute(message, args, Discord, weather)
}
});
and what my weather.js contains:
var weather = require('weather-js');
const Discord = require('discord.js');
module.exports = {
name: 'weather',
description: "Used to get the weather of a place",
execute(message, args, Discord, weather) {
const city = args[0]
weather.find({search: args.join(" "), degreeType: "C"}, function(error, result){
if (error) return message.channel.send(error)
if (!city) return message.channel.send("You must specify a location please!")
if (result === undefined || result.length === 0) return message.channel.send("**Invalid location**")
let current = result[0].current
let location = result[0].location
const embed = new Discord.MessageEmbed()
.setTitle(`Weather forecast for ${current.observationpoint}`)
.setDescription(current.skytext)
.setThumbnail(current.imageUrl)
.setColor("RANDOM")
.setTimestamp()
.addField("Temperature: ", current.temperature + "°C", true)
.addField("Wind Speed: ", current.winddisplay, true)
.addField("Humidity: ", `${current.humidity}%`, true)
.addField("Timezone: ", `UTC${location.timezone}`, true)
message.channel.send({ embeds: [embed]});
})
}
}
I always got that same error when it doesn't work:
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:51:14)
at async TextChannel.send (/home/container/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:175:15) {
There's even some locations that were working before, but that suddenly stopped working for any reason!
Has someone had the same problems with weather-js, or is it coming from the code?
Thank you by advance!
One of your line on embed should be a null. That's why its throwing an error. To prevent this. You can use an OR operator.
const embed = new Discord.MessageEmbed()
.setTitle(`Weather forecast for ${current.observationpoint || "NO DATA"}`)
.setDescription(`${current.skytext || "NO DATA"}`) //Using a direct call can cause an error.
.setThumbnail(current.imageUrl) //If this part is the culprit let me know
.setColor("RANDOM")
.setTimestamp()
.addField("Temperature: ", `${current.temperature || "NO DATA"} °C`, true)
.addField("Wind Speed: ", `${current.winddisplay || "NO DATA"}`, true)
.addField("Humidity: ", `${current.humidity || "NO DATA"}%`, true)
.addField("Timezone: ", `UTC${location.timezone || "NO DATA"}`, true)
message.channel.send({ embeds: [embed]});
The || symbols is a OR operator.

My userinfo command in discord.js is giving only errors

I am trying to make a userinfo command but it aint working.. Only giving errors like:
.join is not a function or member is not defind. My friend also did not get the errors. Anyone who could take a look at it? Thanks!
const discord = require('discord.js');
const moment = require('moment');
module.exports = {
name: 'userinfo',
description: 'let you see the info about you',
usage: '[command name]',
execute(message, args, client) {
let user = message.mentions.users.first() || message.author;
var roles = member.roles.cache.size - 1;
var roleNames = member.roles.cache.map(r => r).join(" ").replace("#everyone", "");
if(roles == 0) roleNames = "No roles";
var embed = new discord.MessageEmbed()
.setColor("RANDOM")
.setThumbnail(message.author.avatarURL)
.addField(`${user.tag}`, `${user}`, true)
.addField("ID:", `${user.id}`, true)
.addField("Roles:", message.member.roles.cache.some(roles => `${roles}`).join(', '), true)
.addField("Joined The Server On:", `${moment.utc(member.joinedAt).format("dddd, MMMM Do YYYY")}`, true)
.addField("Account Created On:", `${moment.utc(user.createdAt).format("dddd, MMMM Do YYYY")}`, true)
.addField("Roles:", member.roles.map(roles => `${roles}`).join(', '), true)
message.channel.send(embed);
}
};
For the people who want the code: This is it working, only check the avater field!
const discord = require('discord.js');
const moment = require('moment');
const { MessageEmbed } = require('discord.js');
module.exports = {
name: 'userinfo',
description: 'let you see the info about you',
usage: '[command name]',
execute(message, args, client) {
let user = message.mentions.users.first() || message.author;
const member = message.member
var roles = member.roles.cache.size - 1;
var roleNames = member.roles.cache.map(r => r).join(" ").replace("#everyone", "");
if(roles == 0) roleNames = "No roles";
const embed = new MessageEmbed()
.setColor("RANDOM")
.setThumbnail(message.author.avatarURL)
.addField(`${user.tag}`, `${user}`, true)
.addField("ID:", `${user.id}`, true)
.addField("Roles:", message.member.roles.cache.map(roles => `${roles}`).join(', '), true)
.addField("Joined The Server On:", `${moment.utc(member.joinedAt).format("dddd, MMMM Do YYYY")}`, true)
.addField("Account Created On:", `${moment.utc(user.createdAt).format("dddd, MMMM Do YYYY")}`, true)
message.reply({ embeds: [embed], ephemeral: true });
}
};
You get this particular error because the member variable is not defined. If you want your code to work, you can add const member = message.member to the execute function and it should work

DiscordJS 13 user embed display last message sent in specific channel

I am building a profile slash command for discord.js 13. The command checks users roles and displays specific information about them. We are hoping to add the persons introduction from an introduction channel. Is there anyway to pull the last message sent from a user from a specific channel?
Current Code
try{
await guild.members.fetch();
const member = guild.members.cache.get(UserOption.id);
const roles = member.roles;
const userFlags = UserOption.flags.toArray();
const activity = UserOption.presence?.activities[0];
//create the EMBED
const embeduserinfo = new MessageEmbed()
embeduserinfo.setThumbnail(member.user.displayAvatarURL({ dynamic: true, size: 512 }))
embeduserinfo.setAuthor("Information about " + member.user.username + "#" + member.user.discriminator, member.user.displayAvatarURL({ dynamic: true }), "https://discord.gg/FQGXbypRf8")
embeduserinfo.addField('**❱ Username**',`<#${member.user.id}>\n\`${member.user.tag}\``,true)
embeduserinfo.addField('**❱ Avatar**',`[\`Link to avatar\`](${member.user.displayAvatarURL({ format: "png" })})`,true)
embeduserinfo.addField('**❱ Joined Discord**', "\`"+moment(member.user.createdTimestamp).format("DD/MM/YYYY") + "\`\n" + "`"+ moment(member.user.createdTimestamp).format("hh:mm:ss") + "\`",true)
embeduserinfo.addField('**❱ Joined MetroVan**', "\`"+moment(member.joinedTimestamp).format("DD/MM/YYYY") + "\`\n" + "`"+ moment(member.joinedTimestamp).format("hh:mm:ss")+ "\`",true)
//DIRECT MESSAGE DISPLAY CODE
if (roles.cache.find(r => r.id === "893305823315492914")) //dms are open
{
embeduserinfo.addField("**❱ DM STATUS**\n`🔔 OPEN` ", "** **", true)
}
If you just need the last message in the channel, use the below code. Possible duplicate of Get last message sent to channel
let channel = bot.channels.get('id-of-the-channel');
channel.messages.fetch({ limit: 1 }).then(messages => {
let lastMessage = messages.first();
if (!lastMessage.author.bot) {
// Do something with it
}
})
.catch(console.error);
If you want the last message sent in a channel by a specific user, filter it with the id property as below-
let channel = bot.channels.get('id-of-the-channel');
channel.messages.fetch().then(messages => {
let lastMessage = messages.filter(m => m.author.id === 'id-of-user').last;
//Do something with it
})
.catch(console.error);
async function searchForLastMessageFromUser(channel, userId) {
let messages = await channel.messages.fetch({before: null}, {cache: true});
while (messages.size > 0) {
let result = messages.find(message => {
return message.author.id === userId;
});
if (result !== null) return result;
messages = await channel.messages.fetch({limit: 50, before: messages[messages.length - 1]}, {cache: true});
}
return null;
}
embeduserinfo.setDescription("**❱ INTRODUCTION**\n" + introMessageText, "** Add your intro at <#885123781130067988>**");

Cannot read property 'toDateString' of undefined

Im trying to make a discord bot that can show when a certain member joins the server, and the date of when they joined Discord. I have tried using toDateString to show thw number of days from the joining of the server and the current date. Here's the full code:
const Discord = require("discord.js");
const { MessageEmbed } = require("discord.js");
const { Color } = require("../../config.js");
module.exports = {
name: "userinfo",
aliases: ["memberinfo", "whois"],
description: "Show User Information!",
usage: "Userinfo | <Mention User>",
run: async (client, message, args) => {
//Start
let member = message.mentions.users.first() || message.author;
const statuses = {
online: "Online",
dnd: "Do Not Disturb",
idle: "Idle",
offline: "Offline/Invisible"
};
const embed = new MessageEmbed()
.setTitle(member.username + " Information!")
.setColor(Color)
.setThumbnail(member.displayAvatarURL())
.addField("Full Name", member.tag, true)
.addField("ID", `${member.id}`, true)
.addField("Status", statuses[member.presence.status], true)
.addField(
`Roles Count`,
message.guild.members.cache.get(member.id).roles.cache.size ||
"No Roles!",
true
)
.addField(`Avatar Url`, `[Link](${member.displayAvatarURL()})`, true)
.addField("Joined Server At", member.joinedAt.toDateString())
.addField("Joined Discord At", member.createdAt.toDateString())
.setFooter(`Requested by ${message.author.username}`)
.setTimestamp();
message.channel.send(embed);
//End
}
};
Instances of GuildMember do not have a createdAt property (see here). You want to access the user property of the guild member to get User.createdAt
addField("Joined Discord At", member.user.createdAt.toDateString())
member.createdAt is undefined
Must make it member.user.createdAt
.addField("Joined Discord At", member.createdAt.toDateString())
And change member var to #GuildMember
let member = message.mentions.members.first() || message.member;

Getting an image URL from a message

I want to get the image URL or the image itself from a message, and put it in my embed. I have no idea to do it myself, hope you can help me :)
client.on('messageReactionAdd', (reaction, user, message) => {
const eggsa = client.emojis.find(emoji => emoji.name === "eggsa");
if (reaction.emoji.name === 'eggsa') {
const msg = reaction.message;
const guild = msg.guild;
const guildMembers = guild.members;
const guildMember = guildMembers.get(user.id);
if (!guildMember.roles.some(r=>["Leder"].includes(r.name)) ) return guildMember.send(" ',:^\\ ");
const message = reaction.message;
const kanal = reaction.message.guild.channels.find('name', 'sitater');
var embed = new Discord.RichEmbed()
.setDescription(message.content)
.setTimestamp()
.setFooter(message.author.username, reaction.message.author.avatarURL)
.setImage()
kanal.send({embed});
}
});
You can simply use the .attachments property from the message object. This returns you all attachments of this message included all pictures. From there on, you can use the property .url and this gives you the image url that you can add in your embed.
In the following code I added a check if there are even attachments. If yes, add the first image url as image of the embed.
Here is the code:
client.on('messageReactionAdd', (reaction, user, message) => {
const eggsa = client.emojis.find(emoji => emoji.name === 'eggsa');
if (reaction.emoji.name === 'eggsa') {
const msg = reaction.message;
const guild = msg.guild;
const guildMembers = guild.members;
const guildMember = guildMembers.get(user.id);
if (!guildMember.roles.some(r => ['Leder'].includes(r.name))) return guildMember.send(" ',:^\\ ");
const message = reaction.message;
const kanal = reaction.message.guild.channels.find('name', 'sitater');
const embed = new Discord.RichEmbed()
.setDescription(message.content)
.setTimestamp()
.setFooter(message.author.username, reaction.message.author.avatarURL);
if (message.attachments.size !== 0) {
embed.setImage(message.attachments.first().url);
}
kanal.send({ embed });
}
});

Resources