Working on a Discord bot and I need the user ID, which in this case is 'xxx'. Not sure how to get it.
I've tried
n.mentions.users.User. -- n.mentions.users.User()
What I have on my app:
bot.on('message', msg => {
if (msg.content === 'myId'){
msg.reply().then(n => {
console.log(n.mentions.users);
});
}
})
What I get back:
Collection [Map] {
'1803209281398201380913' => User {
id: 'xxx',
username: 'zzz',
discriminator: '0000'
}
I expect 'xxx' but get undefined.
Use this:
message.mentions.users.first().id
Related
for reasons, I am trying to get the username using the user's ID, and so, I have tried many things but they all result in Cannot read property 'username' of undefined this is what I have:
user = bot.users.cache.find(user => user.id === key); //key is the user's id
console.log(user);
bot.channels.cache.get("847470926748057671").send(user.username); //this is where the error is
and where it outputs user to the log, it says
User {
id: '691615336943845407',
system: false,
locale: null,
flags: UserFlags { bitfield: 128 },
username: 'orangenal name',
bot: false,
discriminator: '7363',
avatar: 'e99b5e3d3edcfa7e22dd76a7eb869c62',
lastMessageID: '847498366236885053',
lastMessageChannelID: '847470926748057671'
}
so there is a username, but I do not know how to access it
Try using fetch() and make sure to handle the promise
bot.users.fetch(key)
.then(res => user = res)
.catch(console.error);
console.assert(!user, 'User was not found!');
const channel = bot.channels.cache.get("847470926748057671");
channel.send(user?.username);
I have a user and project entity with OneToMany relations between them,
user.entity.ts
#ManyToOne(() => Project, pro => pro.members, {
nullable: true
})
#JoinColumn({
name: 'userId',
})
member: Project;
project.entity.ts
#OneToMany(() => User, user => user.member)
members: User[]
function to add user to project:
async addMemberToProject(projectId: number, memberEmail: string): Promise<void> {
const project = await this.conn.getRepository(Project).findOne({
where: {
id: projectId
}
}).catch(() => {
throw new BadRequestException("Project not found!");
});
const user = await this.getUserByEmail(memberEmail).catch(() => {
throw new BadRequestException("User not found!");
})
if(user !== null) {
project.members.push(user);
await this.conn.getRepository(Repository).save(project).catch(() => {
throw new BadRequestException("Member not added to project!");
});
}
}
why when I try to add user to project, my compiler throw me:
Cannot read property 'push' of undefined
What i'm doing wrong? Maybe I have a bad database logic? (User can be in many projects, project can have many users), Can someone help me? Thanks for any help!
#JoinColumn on the user.entity looks wrong, it should be named: projectId, assuming the primary key of Project.entity is projectId.
The reason for you error is you need to add relations: ['members'] to project findOne()
const project = await this.conn.getRepository(Project).findOne({
where: {
id: projectId
},
relations: ['members']
})
Without this, TypeORM does not populate "project.members": project.members is undefined, so project.members.push(user) causes an "undefined" error.
So i was implementing a users model in my mvc and then i get a weird error saying
MongoClient constructor.
D:\node\node_modules\mongoose\lib\document.js:2022
if (path in this.$__.selected) {
^
TypeError: Cannot use 'in' operator to search for 'email' in saifkhan501721#gmail.com
at model.isSelected (D:\node\node_modules\←[4mmongoose←[24m\lib\document.js:2022:14)
at D:\node\node_modules\←[4mmongoose←[24m\lib\document.js:2195:14
at Array.filter (<anonymous>)
at _getPathsToValidate (D:\node\node_modules\←[4mmongoose←[24m\lib\document.js:2194:71)
at model.Document.$__validate (D:\node\node_modules\←[4mmongoose←[24m\lib\document.js:2365:23)
at D:\node\node_modules\←[4mkareem←[24m\index.js:369:33
←[90m at processTicksAndRejections (internal/process/task_queues.js:79:11)←[39m
i have no idea as to what is the reason behind the error is, is it a syntax error , logical error connection error or mispelling of a variable,well anyway here's my app.js
mongoose
.connect('mongodb+srv://turd_waffle:SaifKhan#cluster0.lltqs.mongodb.net/shop?retryWrites=true&w=majority')
.then((result) => {
User.findOne().then(user=>{
if(!user){
const user=new User({
name:'Saif',
email:'saifkhan501721#gmail.com',
cart:{
items:[]
}
})
user.save()
}
})//save() saves the documents(mostly used as a reference to generate a sample id in order to start a cluster working)
app.listen(3000)
})
.catch(err => {
console.log(err)
})
here's my user.js model to store users data in mongodb database
const mongoose = require('mongoose')
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
cart: {
items: [{
productId: {
type: Schema.Types.ObjectId,
ref: 'Product',
required: true
},
quantity: {
type: Number,
required: true
}
}]
},
})
userSchema.methods.addToCart = function(product) {
const cartProductIndex = this.cart.items.findIndex(cp => {
return cp.productId.toString() === product._id.toString();
})
let newQuantity = 1;
const updatedCartItems = [...this.cart.items];
if (cartProductIndex >= 0) {
newQuantity = this.cart.items[cartProductIndex].quantity + 1;
updatedCartItems[cartProductIndex].quantity = newQuantity
} else {
updatedCartItems.push({
productId: product._id,
quantity: newQuantity
})
}
const updatedCart = {
items: updatedCartItems
}
this.cart=updatedCart
return this.save()
}
module.exports = mongoose.model('User', userSchema)
can anyone please be kind enough to atleast tell me what the error above is trying to say i used app.use to create a user so i can store his id, email and name
app.use((req, res, next) => {
User.findById('5f788c080ba19e0f8c642202')
.then(user => {
req.user = new User(user.name, user.email, user.cart, user._id);
next();
})
.catch(err => console.log(err));
});
Strange issue. From the code you provided, the issue should not arise.
When I look at the code in mongoose, the only way that this could happen is if you would do something like:
new User("saifkhan501721#gmail.com")
Then this.$__.selected would be a string instead of an object (e.g. {email: "saifkhan501721#gmail.com"}) and path in this.$__.selected would cause your received type error.
Not knowing enough about your app, I would assume that there maybe is a bad User object created somewhere else / cached / or already in database. Maybe it would help to verify this using a clean database?
See the source code for reference. When I take a look at the code it seems like an oversight that it is not checked if this.$__.selected is a string, because in this case it does not fail early (e.g. Object.keys(this.$__.selected) will not cause an error).
I have a bot that takes a mention and returns some user information:
bot.on('message', async message => {
let usr = bot.users.fetch(message.replace('<#!', '').replace('>', ''));
message.channel.send(`id: ${usr.id}\nname: ${usr.username}`);
});
However, the bot returns undefined for both values. I have logged the user object, and revieved
Promise {
User {
id: '',
username: '',
bot: false,
discriminator: '',
avatar: '',
lastMessageId: '',
LastMessage: '',
}
}
The values are different, but the objects are the same. I tried using usr.Promise.User.value, usr.User.value, and usr.Promise.value with no luck. Is there some way to do this?
It returns a Promise so you need to use await or .then to get its resolved value:
bot.on('message', async message => {
let usr = await bot.users.fetch(message.replace('<#!', '').replace('>', ''));
message.channel.send(`id: ${usr.id}\nname: ${usr.username}`);
});
OR:
bot.on('message', async message => {
bot.users.fetch(message.replace('<#!', '').replace('>', '')).then((usr) => {
message.channel.send(`id: ${usr.id}\nname: ${usr.username}`);
});
});
You can read this to learn more about promises.
You can also use message.mentions.users.first():
bot.on('message', async message => {
let usr = message.mentions.users.first();
message.channel.send(`id: ${usr.id}\nname: ${usr.username}`);
});
It's a totally different way to do what you want and it's better. It also avoids your "promise" problem so it's not really an answer.
So I am very new to node.js and I am making a Discord bot. I am trying to make a ticket system using djs-ticketsystem and it is giving me this error: (node:15168) DeprecationWarning: Collection#find: pass a function instead
const ticketsystem = require("djs-ticketsystem");
bot.on("message", async message => {
if (message.content == '-new') {
ticketsystem.createTicket({
name: 'new-ticket',
category: 'TICKETS',
owner: message.author,
roles: [
'Owner',
'Support'
],
openmessage: 'Creating your ticket...',
ticketmessage: 'Thank-you for creating a ticket!',
messagelinker: message
}).catch(err => {
message.reply('Failed to create a new ticket.')
});
};
});