I'm making a team that should create a category with the appropriate rights, but I need some kind of guild id. how can I get the guild server id through the user who wrote this command
if (message.channel.type === "text" && message.guild && message.guild.ownerID == message.author.id) {
if (content.startsWith("*install")) {
let server = message.guild.id[guild.id];
guild1.createChannel('new-category', {
type: 'category',
permissionsOverwrites: [{
id: guild.id,
deny: ['MANAGE_MESSAGES'],
allow: ['SEND_MESSAGES']
}]
})
.then(console.log)
.catch(console.error);
}
}
you can use message.guild.id
if (message.channel.type === "text" && message.guild && message.guild.ownerID == message.author.id) {
if (content.startsWith("*install")) {
guild1.createChannel('new-category', {
type: 'category',
permissionsOverwrites: [{
id: message.guild.id,
deny: ['MANAGE_MESSAGES'],
allow: ['SEND_MESSAGES']
}]
})
.then(console.log)
.catch(console.error);
}
}
Related
I am trying to log when a permissions from a channel got updated. This is what i have now: but i don't come further at this point. Hope some one could help me here.
const { MessageEmbed, GuildChannel } = require("discord.js");
const DB = require('../../Structures/Schemas/loggingDB');
module.exports = {
name: "channelUpdate",
/**
*
* #param {GuildChannel} oldChannel
* #param {GuildChannel} newChannel
*/
async execute(oldChannel, newChannel) {
const { guild } = oldChannel;
const data = await DB.findOne({ GuildID: guild.id });
if (!data) {
return
}
const LogChannel = await guild.channels.fetch(data.ChannelID)
if (!LogChannel.guild) return false;
const AuditLogFetch = await oldChannel.guild.fetchAuditLogs({ limit: 1, type: "CHANNEL_UPDATE" });
if (!LogChannel) return console.error(`Invalid channel.`);
if (!AuditLogFetch.entries.first()) return console.error(`No entries found.`);
const Entry = AuditLogFetch.entries.first();
//console.log(Entry)
//console.log(oldChannel)
//console.log(newChannel)
//console.log(oldChannel)
const embed = new MessageEmbed()
.setColor("#b827ba")
.setTitle("Channel Updated")
.setDescription("An channel has been updated!")
.addFields(
{ name: "Updated By:", value: `${Entry.executor.tag || "Someone"}` },
{ name: "Channel Name:", value: `${oldChannel.name}` },
{ name: "Action:", value: `${Entry.action}` },
{ name: "Created At:", value: `<t:${parseInt(oldChannel.createdTimestamp / 1000)}:f>` },
)
.setTimestamp()
if (oldChannel.name != newChannel.name) {
embed.addFields(
{ name: "Old Channel Name:", value: `${oldChannel.name}` },
{ name: "New Channel Name:", value: `${newChannel.name}` },
)
}
console.log("Oldchannel:", oldChannel.permissionOverwrites.cache)
console.log("newchannel:", newChannel.permissionOverwrites.cache)
LogChannel.send({ embeds: [embed] })
}
}
This is the output that i get from console.log("newchannel:", newChannel.permissionOverwrites.cache.
From this point i don't know how i get the names etc.
Oldchannel: Collection(2) [Map] {
'973305365540266055' => PermissionOverwrites {
id: '973305365540266055',
type: 'role',
deny: Permissions { bitfield: 0n },
allow: Permissions { bitfield: 1024n }
},
'976422603227013130' => PermissionOverwrites {
id: '976422603227013130',
type: 'role',
deny: Permissions { bitfield: 1024n },
allow: Permissions { bitfield: 0n }
}
}
newchannel: Collection(2) [Map] {
'973305365540266055' => PermissionOverwrites {
id: '973305365540266055',
type: 'role',
deny: Permissions { bitfield: 0n },
allow: Permissions { bitfield: 0n }
},
'976422603227013130' => PermissionOverwrites {
id: '976422603227013130',
type: 'role',
deny: Permissions { bitfield: 1024n },
allow: Permissions { bitfield: 0n }
}
}
fixed by using code as below -
const { MessageEmbed, GuildChannel } = require("discord.js");
const DB = require('../../Structures/Schemas/loggingDB');
const { ColorYom } = require("../../Structures/botConfig.json")
module.exports = {
name: "channelUpdate",
/**
*
* #param {GuildChannel} oldChannel
* #param {GuildChannel} newChannel
*/
async execute(oldChannel, newChannel) {
const { guild } = oldChannel;
const data = await DB.findOne({ GuildID: guild.id });
if (!data) {
return
}
const LogChannel = await guild.channels.fetch(data.ChannelID)
if (!LogChannel.guild) return false;
const AuditLogFetch = await oldChannel.guild.fetchAuditLogs({ limit: 1, type: "CHANNEL_UPDATE" });
if (!LogChannel) return console.error(`Invalid channel.`);
if (!AuditLogFetch.entries.first()) return console.error(`No entries found.`);
const Entry = AuditLogFetch.entries.first();
const embed = new MessageEmbed()
.setColor(`${ColorYom}`)
.setTitle("Channel Updated")
.setDescription("An channel has been updated!")
.addFields(
{ name: "Updated By:", value: `${Entry.executor.tag || "Someone"}` },
{ name: "Channel Name:", value: `${oldChannel.name}` },
{ name: "Action:", value: `${Entry.action}` },
)
.setTimestamp()
if (oldChannel.name != newChannel.name) {
embed.addFields(
{ name: "Old Channel Name:", value: `${oldChannel.name}` },
{ name: "New Channel Name:", value: `${newChannel.name}` },
)
}
LogChannel.send({ embeds: [embed] })
}
}
i am using PostgreSQL with Sequelize ORM to create my db.
I have this models:
models.js
const Users = db.define("users", {
name: {
type: DataTypes.STRING,
},
lastname: {
type: DataTypes.STRING,
},
sector: {
type: DataTypes.STRING,
},
email: { type: DataTypes.STRING, unique: true, allowNull: false },
password: { type: DataTypes.STRING, allowNull: false },
points: { type: DataTypes.INTEGER, defaultValue: 0 },
suscripcion: { type: DataTypes.BOOLEAN, defaultValue: false },
preference_id: { type: DataTypes.STRING },
});
const Pronostico = db.define("pronosticos", {
matchId: {
type: DataTypes.STRING,
unique: true,
},
winner: {
type: DataTypes.STRING,
},
goalHome: {
type: DataTypes.INTEGER,
},
goalAway: {
type: DataTypes.INTEGER,
},
});
//REFRESH TOKEN
const RefreshToken = db.define("refreshTokens", {
token: {
type: DataTypes.STRING,
},
expiryDate: {
type: DataTypes.DATE,
},
userId: {
type: DataTypes.STRING,
},
});
RefreshToken.createToken = async function (user) {
let expiredAt = new Date();
expiredAt.setSeconds(expiredAt.getSeconds() + config.jwtRefreshExpiration);
let _token = uuidv4();
let refreshToken = await this.create({
token: _token,
userId: user.id,
expiryDate: expiredAt.getTime(),
});
return refreshToken.token;
};
RefreshToken.verifyExpiration = (token) => {
return token.expiryDate.getTime() < new Date().getTime();
};
This are the Relationships:
Users.hasMany(Pronostico, { as: "pronosticos" });
Pronostico.belongsTo(Users, { foreignKey: "userId", as: "user" });
RefreshToken.belongsTo(User, {
foreignKey: 'userId', targetKey: 'id'
});
User.hasOne(RefreshToken, {
foreignKey: 'userId', targetKey: 'id'
});
Somewhere on my server, I have this controller which creates a refreshToken:
let refreshToken = await RefreshToken.createToken(user);
The problem is that I get an error that says "column userId doesnt exist in refreshTokens relationship.
Maybe I have some issues with the relationships but I think they are OK.
Any suggestion?
I have searched high and low but haven't found a solution.
I am trying to save an array of subdocuments (that is dynamic).
Here's my schema:
const EventSchema = new Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'users'
},
title: {
type: String,
required: true
},
attendee:[
{
email: {
type: String,
required: true
},
name: {
type: String,
required: true
},
status: {
type: String
}
}]
});
Here's the route:
router.post('/', auth, async (req, res) => {
const {title, attendee: [{ email, name, status }] } = req.body
try{
const newEvent = new Event({
title,
user: req.user.id,
attendee: [{ email, name, status }]
});
const event = await newEvent.save();
if (!event) throw Error('Something went wrong saving the event');
res.status(200).json(event);
catch (e) {
res.status(400).json({ msg: e.message });
}
});
Currently I am only getting 1 element in the array to save.
The items in the array will always be different.
I don't have the option of creating the "event" first and then adding "attendees".
Example of input:
{
"title": "Something",
"attendee": [
{
"email": "email#gmail.com",
"name": "Bob"
},
{
"email": "sandwich#gmail.com",
"name": "Martha"
}
]
}
Output:
{
"_id": "5ef1521f06a67811f74ba905",
"title": "Something",
"user": "5ecdaf3601cd345ddb73748b",
"attendee": [
{
"_id": "5ef1521f06a67811f74ba906",
"email": "email#gmail.com",
"name": "Bob"
}
],
"__v": 0
}
Instead of destructuring for the one object of the array, you can get the whole array of attendee from the request body and save it as it is.
router.post('/', auth, async (req, res) => {
const eventObj = {
user: req.user.id,
title : req.body.title,
// get the whole array of attendee objects from the request
attendee: req.body.attendee
}
try{
const newEvent = new Event(eventObj);
const event = await newEvent.save();
if (!event) throw Error('Something went wrong saving the event');
res.status(200).json(event);
catch (e) {
res.status(400).json({ msg: e.message });
}
});
If I understand you correctly, you should not destructure attendee and insert into your new Event every attendee (choosing which key to insert in database).
const {
title,
attendee,
} = req.body;
const newEvent = new Event({
title,
user: req.user.id,
attendee: attendee.map(x => ({
email: x.email,
name: x.name,
status: x.status,
})),
});
I want to have array of objects i.e teamMembers should be an array and should have object as its element with properties name and role.I do not receive any error, when I console.log(req.body), its in the format i want, but the the array element which is object is not be posted to the schema.
_id: mongoose.Schema.Types.ObjectId,
teamName: { type: String, unique: true },
teamMembers: {
name: {
type: String, unique: true, lowercase: true, required: true
},
role: {
type: String,
enum: ['goal keeper', 'central back', 'central midfield', 'central forward', 'left wing',
'attacking midfield', 'central forward', 'left midfielder', 'striker', 'defending', 'right midfielder'],
required: true
},
type: Array
},
description: String,
createdAt: { type: Date, default: Date.now() },
updatedAt: { type: Date, default: Date.now() }
});
teamSchema.plugin(uniqueValidator); ```
I am not getting the desired result. Here is my collection from mogodb
{
"_id":{"$oid":"5d89d5da3f33f36579bfed25"},
"teamMembers":[{}],
"createdAt":{"$date":{"$numberLong":"1569314251247"}},
"updatedAt":{"$date":{"$numberLong":"1569314251247"}},
"teamName":"Arsenal",
"__v":{"$numberInt":"0"}
}
Expected result
``` "teamMembers":[{"name": "bernd leno", "role": "goal keeper"}] ```
Gotten result ``` "teamMembers":[{}] ```
Here is my below
```static async addTeam(req, res) {
const {
teamName, teamMembers, description
} = req.body;
try {
if (!req.user.isAdmin) {
return response(res, 404, 'error', {
message: messages.unAuthorizedRoute
});
}
const teams = new TeamModel({
_id: new mongoose.Types.ObjectId(),
teamName,
teamMembers,
description
});
const team = await teams.save();
if (team) {
return response(res, 201, 'success', { team });
}
} catch (error) {
(error.errors.teamName.name === 'ValidatorError')
? response(res, 409, 'error', {
message: messages.duplicateName
})
: response(res, 400, 'error', {
message: messages.error
});
}
}```
My code is correct, I wasn't posting the array of objects correctly from postman.Right way to post an array of objects in postman using urlencoded
It also works with raw json/urlencoded
{
"teamName": "Arsenal",
"teamMembers": [{"name": "bernd leno", "role":"goal keeper"}, {"name": "Emiliano Martinez", "role":"goal keeper"}]
}
Here is a relevant part of my Schema, where I'll make reservations to a "space":
var spaceSchema = new mongoose.Schema({
spaceName: String,
scheduledDates: [{
scheduledDates: String,
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
username: String
}
}]
});
Author should be the current user that's logged in. Here is my route to update those fields:
router.put('/:space_id/schedule', function(req, res) {
Space.findByIdAndUpdate(req.params.space_id, {
'$push': { 'scheduledDates': req.body.space, 'author': req.user._id }
}, { "new": true, "upsert": true }, function(err, space) {
if (err) {
console.log(err);
} else {
console.log(req.body.space);
}
});
});
I can't access "author" correctly, because it's inside the array. What can I do to update this array, adding a new date and user to make the reservation?
Thank you
UPDATE
I tried to use "_id" instead of "id" in my property but got the same result. It seems like it's ignoring the "author" field, and only saving "scheduledDates"
So the schema was like this:
scheduledDates: [{
scheduledDates: String,
author: {
_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
username: String
}
}]
And then in my route, I changed what I was 'pushing':
'$push': { 'scheduledDates': req.body.space, 'author._id': req.user._id }
UPDATED 2
Changed the way I was getting the object to push:
'$push': {
'scheduledDates': {
'scheduledDates': req.body.space,
'author': { _id: req.user._id, username: req.user.username }
}
}
Now I'm getting the following error:
message: 'Cast to string failed for value "{ scheduledDates: \'04/11/2017\' }" at path "scheduledDates"',
name: 'CastError',
stringValue: '"{ scheduledDates: \'04/11/2017\' }"',
kind: 'string',
value: [Object],
path: 'scheduledDates',
reason: undefined } } }