Cannot read property username of undefinded discord.js - node.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

Related

Cloud Functions Firestore get key value for increment

I'm trying to get the updated number for a Member Number from a document using Cloud Functions when an admin creates a user.
What should happen is when an Admin creates a user in their dashboard, the user is added to firebase, then the member number updates, and is applied to newMemNum, then updated in the user document.
My Code:
const memNumInc = admin.firestore.FieldValue.increment(1);
const memCounter = admin.firestore().collection(`mem_num`).doc(`a1lDbrsoXjfKeosEkDtw`);
memCounter.update({number: memNumInc}).then(() =>
memCounter.get()
.then((snap) => {
const id = snap.id;
const data = snap.data()
newMemNum = data['number']
console.log('New Member Number: ' + newMemNum);
return {id, ...data};
})
);
The increment goes ok (i.e. number goes up by 1 which is expected), but the next part of the code doesn't run and doesn't throw an error.
Also, the next part of the code that updates the user document doesn't fire at all, and no errors.
Entire Code:
// Create User Document onCreate
const createProfile = (userRecord) => {
const uid = userRecord.uid;
const docId = userRecord.uid;
const fullName = userRecord.displayName || 'New User';
const memStatus = 'Unfinancial';
const isAdmin = false;
const isNew = true;
const email = userRecord.email;
const photoUrl = userRecord.photoUrl;
const phone = '0444 123 456';
const createdAt = admin.firestore.FieldValue.serverTimestamp();
const memNumInc = admin.firestore.FieldValue.increment(1);
const memCounter = admin.firestore().collection(`mem_num`).doc(`a1lDbrsoXjfKeosEkDtw`);
memCounter.update({number: memNumInc}).then(() =>
memCounter.get()
.then((snap) => {
const id = snap.id;
const data = snap.data()
newMemNum = data['number']
console.log('New Member Number: ' + newMemNum);
return {id, ...data};
})
);
return afs
.collection(`users`)
.doc(docId)
.set({
uid: uid,
docId: docId,
fullName: fullName,
joined: createdAt,
memNum: newMemNum,
memStatus: memStatus,
isAdmin: isAdmin,
isNew: isNew,
email: email,
photoUrl: photoUrl,
phone: phone,
addedOn: createdAt,
updatedOn: createdAt
})
.then(() => console.log('User Creaeted Successfuly: ' + uid))
.catch((e) => console.log('User Creation Error: ' + e.message));
}
exports.authOnCreate = functions.auth.user().onCreate(createProfile);
If I remove the memCounter code, the rest executes no problem.
You have another return statement that most likely runs before the promise returned by get() is resolved. Try refactoring the code using async-await syntax as shown below:
const createProfile = async (userRecord) => {
// const vars ....
const memNumInc = admin.firestore.FieldValue.increment(1);
const memCounter = admin.firestore().collection(`mem_num`).doc(`a1lDbrsoXjfKeosEkDtw`);
// Update documents
await memCounter.update({
number: memNumInc
})
// Get update document data
const snap = await memCounter.get()
const id = snap.id;
const data = snap.data()
newMemNum = data['number']
console.log('New Member Number: ' + newMemNum);
return afs
.collection(`users`)
.doc(docId)
.set({ ... })
}
However, if multiple users are created simultaneously, there's a chance that they'll get the same newMemNum so a transaction might be useful as well.
Firestore also introduced a new COUNT() function that can be used to get total number of documents in a collection instead of incrementing the count every time.

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 '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;

Sending a newly created emoji after guild.emojis.create()

I have an addemoji command and I want it to send the new emoji created after the bot creates it. It sends like :emojiname: instead of the actual emoji added. How can I define the new emoji added? Somebody suggested that I use console.log but I have no idea how to use that information that it puts inside the log.
module.exports = {
name: 'addemoji',
description: 'ping pong',
execute(message, args) {
const Discord = require('discord.js');
const PREFIX = 'ly?';
const load = '<a:loading:824515478939762699>';
if (message.content.startsWith(PREFIX + 'addemoji')) {
if (message.guild.me.permissions.has('USE_EXTERNAL_EMOJIS')) {
if (message.guild.me.permissions.has('MANAGE_EMOJIS')) {
if (message.member.hasPermission('MANAGE_EMOJIS')) {
const match = /<(a?):(.+):(\d+)>/u.exec(message.content);
if (!match)
return message.reply(
'Please include a custom emoji in your message!',
);
// animated will be 'a' if it is animated or '' if it isn't
const [, animated, name, id] = match;
const url = `https://cdn.discordapp.com/emojis/${id}.${
animated ? 'gif' : 'png'
}`;
const user = message.mentions.users.first() || message.author;
const nameid = `<:${name}:${id}>`;
message.guild.emojis.create(url, name);
let newname = console.log(name);
let newid = console.log(id);
const embed = new Discord.MessageEmbed()
.setTitle(`Emoji added! <:${newname}:${newid}>`)
.setColor(0x7732a8);
message.channel.send(embed);
}
}
}
}
}
};
GuildEmojiManager#create() returns a Promise with the newly created emoji. You can access and display the new emoji by handling this promise, then using the <:name:id> wrapper for emoijs
message.guild.emojis.create(url, name).then(newEmoji => {
const embed = new Discord.MessageEmbed()
.setTitle(`Emoji added! <:${newEmoji.name}:${newEmoji.id}>`)
.setColor(0x7732a8)
message.channel.send(embed);
});

My bot says it doesnt have permissions to kick/ban

I am making a Discord bot in js. Yesterday i finished some work on the bot's ban command and it worked normally. Today I wake up, don't modify anything and when I try it again, it says that it does not have permission. Nothing was changed and noone changed the permissions of the bot, it still has administrator. The error message:
(node:2490) UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Permissions
at RequestHandler.execute (/home/runner/AUN/node_modules/discord.js/src/rest/RequestHandler.js:154:13)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async RequestHandler.push (/home/runner/AUN/node_modules/discord.js/src/rest/RequestHandler.js:39:14)
My code is (a bit long):
const Discord = require("discord.js");
const dp = require('discord-prefix');
const lang = require('../language_manager');
const settings = require('discord-server-settings');
module.exports = (message, client) => {
if (!message.member.permissions.has("BAN_MEMBERS")) return message.reply("You do not have the permission to ban users");
if (!message.guild.me.hasPermission("BAN_MEMBERS")) return message.reply("I do not have permission to ban users");
let prefix = dp.getPrefix();
if(dp.getPrefix(message.guild.id)){
prefix = dp.getPrefix(message.guild.id);
}
var langchar = settings.getSetting('lang', message.guild.id)
const args = message.content.slice(prefix.length).trim().split(' ');
const command = args.shift().toLowerCase();
var noerror = true;
const member = getUserFromMention(args[0]);
const reason = args[1] || lang.get('ban_no_reason', langchar);
const embed1 = new Discord.MessageEmbed()
.setAuthor('AUN', 'https://drive.google.com/uc?export=view&id=129_JKrVi3IJ6spDDciA5Y5sm4pjUF7eI')
.setTitle(lang.get('ban_title', langchar))
.setColor('#ed3f2c')
.setDescription(lang.get('ban_noone_banned', langchar))
.setTimestamp()
.setFooter('Ping: ' + client.ws.ping + ' | '+prefix+command);
const embed = new Discord.MessageEmbed()
.setTitle(lang.get('ban_you_title', langchar))
.setAuthor("AUN", "https://drive.google.com/uc?export=view&id=129_JKrVi3IJ6spDDciA5Y5sm4pjUF7eI")
.setColor(0x00AE86)
.setDescription(lang.get('ban_you_part1', langchar)+message.guild.name+lang.get('ban_you_part2', langchar)+message.member.name+lang.get('ban_you_part3', langchar)+reason)
.setFooter("Ping: "+client.ws.ping+" | AUN discord bot")
.setTimestamp();
if (!member) {
embed1.setTitle(lang.get('ban_error', langchar))
.setDescription(lang.get('ban_no_mention', langchar))
.setColor('#bd1300');
noerror = false;
}
if(noerror){
embed1.setDescription(lang.get('ban_banned_part1', langchar)+member.tag+lang.get('ban_banned_part2', langchar));
member.send(embed);
}
message.channel.send(embed1);
try{
return message.guild.member(member).ban();
}catch (e){
return;
}
function getUserFromMention(mention) {
if (!mention) return;
if (mention.startsWith('<#') && mention.endsWith('>')) {
mention = mention.slice(2, -1);
if (mention.startsWith('!')) {
mention = mention.slice(1);
}
return client.users.cache.get(mention);
}
}
}
Please if you have any idea what is going on, tell me
You should check if you can actually ban the member.
You can check this with
GuildMember#manageable

Resources