Cannot read property 'toDateString' of undefined - node.js

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;

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

Sending a message into all servers where bot is

How do I send one message per guild that my bot is in? It doesn't matter which channel it will be, but I don't know how to code it.
I finally came up with that idea:
client.guilds.cache.forEach(guild => {
const Embed = new discord.MessageEmbed();
const Channels = guild.channels.cache.map(channel => `${channel.id} | ${channel.name}`).join(", ")
Embed.setTitle(`Channels for ${guild.name}`);
Embed.setDescription(Channels);
message.channel.send(Embed);
});
but it doesn't work.
I'm working with commands handler so it has to be done with module.exports:
module.exports = {
name: "informacja",
aliases: [],
description: "informacja",
async execute(message) {
client.guilds.cache.forEach(guild => {
const Embed = new discord.MessageEmbed();
const Channels = guild.channels.cache.map(channel => `${channel.id} | ${channel.name}`).join(", ")
Embed.setTitle(`Channels for ${guild.name}`);
Embed.setDescription(Channels);
message.channel.send(Embed);
});
};
My code is not working at all
When I run it - nothing happens, no errors, no messages, just nothing.
tried to logged everything, but still nothing came up.
I also tried to log everything using console.log() but nothing is working
I remind: I need to send one message to all servers where my bot is, but only one channel
You could find a channel on each server where the client can send a message then send:
client.guilds.cache.forEach(guild => {
const channel = guild.channels.cache.find(c => c.type === 'text' && c.permissionFor(client.user.id).has('SEND_MESSAGES'))
if(channel) channel.send('MSG')
.then(() => console.log('Sent on ' + channel.name))
.catch(console.error)
else console.log('On guild ' + guild.name + ' I could not find a channel where I can type.')
})
This is a very simple boilerplate to start with, you can later check channel with id, or smth like that
client.channels.cache.forEach(channel => {
if(channel.type === 'text') channel.send('MSG').then('sent').catch(console.error)
})
v13 code
const Discord = require('discord.js')
const {
MessageEmbed
} = require('discord.js')
const fs = require('fs')
module.exports = {
name: "send",
description: "Send message to all guilds bot joined",
usage: `!send <text>`,
category: "dev",
run: async (client, message, args) => {
client.guilds.cache.map((guild) => {
const channel = guild.channels.cache.find(
(c) => c.type === "GUILD_TEXT" && c.permissionsFor(guild.me).has("SEND_MESSAGES")
);
channel.send('your_text')
})
}}
v12 code
const Discord = require('discord.js')
const {
MessageEmbed
} = require('discord.js')
const fs = require('fs')
module.exports = {
name: "send",
description: "Send message to all guilds bot joined",
usage: `!send <text>`,
category: "dev",
run: async (client, message, args) => {
client.guilds.cache.map((guild) => {
const channel = guild.channels.cache.find(
(c) => c.type === "text" && c.permissionsFor(guild.me).has("SEND_MESSAGES")
);
channel.send('your_text')
})
}}

I just created a snipe command for my bot but it doesn't quite work

My messageDelete event handler:
client.on("messageDelete", message => {
snipe.set(message.channel.id, {
title: Date.now(),
content: message.content,
author: message.author,
image: message.attachments.first() ? message.attachments.first().proxyURL : null,
});
});
My snipe.js code:
require('discord-reply');
const Discord = require('discord.js')
const moment = require('moment')
module.exports = {
name: 'snipe',
aliases: [],
category: 'Fun',
utilisation: '{prefix}snipe',
description: 'Displays the last deleted message in the current channel!',
execute(client, message) {
const snipe = require('.././../index.js')
const msg = snipe.get(message.channel.id);
const timeAgo = moment(msg.title).fromNow();
if (!msg) return message.channel.send("Theres Nothing To Snipe here...");
if (msg.image) {
const embed1 = new Discord.MessageEmbed()
.setAuthor(msg.author.tag, msg.author.displayAvatarURL({ dynamic: true }))
.setTitle(`Message deleted by ${msg.author.tag}! (${timeAgo})`)
.setDescription(msg.content)
.setColor(0x3498DB)
.setTimestamp()
.setImage(msg.image)
.setFooter("Sniped by " + message.author.tag);
message.lineReply(embed1);
}
else {
const embed = new Discord.MessageEmbed()
.setAuthor(msg.author.tag, msg.author.displayAvatarURL({ dynamic: true }))
.setTitle(`Message deleted by ${msg.author.tag}! (${timeAgo})`)
.setDescription(msg.content)
.setColor(0x3498DB)
.setTimestamp()
.setFooter("Sniped by " + message.author.tag);
message.lineReply(embed);
}
},
}
I am getting the following error in my console when I try running the command
(node:6928) UnhandledPromiseRejectionWarning: TypeError: snipe.get is not a function
Can anyone help? I'm pretty sure my code is correct as I used the same thing in my old bot. Any help would be appreciated.
From what I assume your snipe is a Map/Collection since you are using get/set on it, you may want to export the map to use it in your command file by binding it to your client like so
const snipe = new Map();
Aliter
const { Client, Collection } = require("discord.js");
const snipe = new Collection()
const client = new Client();
// Binding to Client
client.snipe = snipe // aliter declare it directly as client.snipe = new Collection()
Then you may access your collection since you are already exporting client like so
client.snipe.set()
client.snipe.get()

Cannot read property username of undefinded discord.js

I am making a ship command, the error messages work but the shipping does not. I always get this error: Type Error: Cannot read property "username" of undefined. Can someone help me to fix it?
Here is my code:
const { DiscordAPIError } = require("discord.js");
const Discord = require('discord.js');
const client = new Discord.Client();
module.exports = {
name: 'ship',
description: "Ship two users!",
execute(message, args) {
const user = message.mentions.members.first();
const user2 = message.mentions.members.first(+1) ;
const images = [(1-100) code is different, put every number there]
const result = Math.floor(Math.random() * images.length);
const error = new Discord.MessageEmbed()
.setColor("#000000")
.setTitle("Ship")
.setDescription("There was an error: Check if you mentioned a user other than you!")
.setFooter(message.author.username)
.setTimestamp()
;
if(!user) return message.reply(error);
if(!user2) user2 = message.author.username;
if(user.id === message.author.id) return message.reply(error);
const embed = new Discord.MessageEmbed()
.setColor("#2A333E")
.setTitle("Ship")
.setDescription(user2.user.username + " + " + user.user.username + " =")
.addField(images[result] + "%" , "Is this good or not so good?")
.setFooter(message.author.username)
.setTimestamp()
;
message.channel.send(embed)
}}
if(!user2) user2 = message.author.username;
This is the problematic line - you're setting the value of user2 to equal the author's username. Try setting it to equal just message.author instead.
Additionally, you're trying to retrieve the .user property from User objects, which does not exist (since it's already a User object.) You'll need to change user2.user.username and user.user.username to just user2.username and user.username

Resources