log when a channel permissions got changed discord.js - discord.js

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] })
}
}

Related

data from useQuery i.e. react query is returning undefined

this is my api middleware caller that i have created:
/* eslint-disable #typescript-eslint/no-var-requires */
// /* eslint-disable no-import-assign */
import Axios from 'axios';
import * as queryString from 'query-string';
const caseConverter = require('change-object-case');
import { cleanParams } from '_utilities/common';
import { REQUEST_TYPES } from './constants';
import { useLoginUser } from '_store/user';
interface IAuth {
method?: string;
url?: string;
data?: any;
params?:any,
contentType?:string,
isTransformRequestRequired?:boolean
}
export function apiCaller(
{
method = REQUEST_TYPES.GET,
url = '',
params = {},
data = {},
contentType = 'application/json',
isTransformRequestRequired = true,
}:IAuth,
) {
const user = useLoginUser.getState().user;
const token = user?.data?.token || '';
// caseConverter.options = {recursive: true, arrayRecursive: true};
return Axios({
method,
url,
params,
paramsSerializer: queryParams => queryString.stringify(caseConverter.snakeKeys(cleanParams(queryParams))),
data,
transformRequest: [reqData => isTransformRequestRequired
? JSON.stringify(caseConverter.toSnake(reqData))
: reqData],
transformResponse: [(respData) =>
{
if(typeof respData === 'string')
return JSON.parse(respData)
else {
return respData
}
}],
headers: {
Authorization: user !== null ? `Token ${ token }` : '',
'Content-Type': contentType,
},
responseType: 'json',
validateStatus: status => status >= 200 && status < 300,
})
.then(({ data: resp }) => resp)
.catch(error => {
console.log(error,'error')
// if user session is expired from server and got 401, will logout the user from application
if(error.response.status === 401) {
// store.dispatch(logoutSuccess());
} else {
throw(error);
}
});
}
this is where I am calling my apiCaller:
import { apiCaller } from '../api-caller';
import { ENDPOINTS, REQUEST_TYPES } from '../constants';
import moment from 'moment';
export const usersApi = async (params:any) => {
const res = await apiCaller(
{
method: REQUEST_TYPES.GET,
url: `${ENDPOINTS.USERS}/`,
params:{
...params,
startDatetime: params.startDatetime ? moment(params.startDatetime).utc().format('YYYY-MM-DD H:mm:ss') : '',
endDatetime: params.endDatetime ? moment(params.endDatetime).utc().format('YYYY-MM-DD H:mm:ss') : '',
},
},
);
return res;
}
this is where I am using useQuery to fetch data from backend:
import { useQuery } from '#tanstack/react-query'
import { usersApi } from '_api/users'
import { useAdminUser } from 'pages/Admin/AdminUsers/_store'
const filters = useAdminUser.getState().filters
export const useCreateProfile = () => {
const query = ['cashierShifts']
return useQuery(query, () => {
usersApi(filters)
})
}
and this is where I am using this in my component:
import React, { useState } from 'react'
import { Table } from 'antd'
import { useCreateProfile } from '_services/CashierProfile'
const columns = [
{
title: 'Day',
dataIndex: 'day',
key: 'day',
},
{
title: 'Shift',
dataIndex: 'shift',
key: 'shift',
},
{
title: 'startTime',
dataIndex: 'start',
key: 'start',
},
{
title: 'endTime',
dataIndex: 'end',
key: 'end',
},
{
title: 'Mart',
dataIndex: 'mart',
key: 'mart',
},
]
const CashierShifts = () => {
const { data, isError, isLoading, isSuccess } = useCreateProfile()
console.log(data, 'react-query')
const [result, setResult] = useState([
{
id: 54,
tile: 'slots 1',
date: '22-10-2203',
startTime: '8:00',
mart: {
id: 21,
martName: 'Johar Town',
},
endTime: '12:00',
cashier: {
name: 'Jamal',
id: 54,
},
},
{
id: 54,
tile: 'slots 1',
date: '22-10-2203',
startTime: '8:00',
mart: {
id: 21,
martName: 'Johar Town',
},
endTime: '12:00',
cashier: {
name: 'Jamal',
id: 54,
},
},
{
id: 54,
tile: 'slots 1',
date: '22-10-2203',
startTime: '8:00',
mart: {
id: 21,
martName: 'Johar Town',
},
endTime: '12:00',
cashier: {
name: 'Jamal',
id: 54,
},
},
{
id: 54,
tile: 'slots 1',
date: '22-10-2203',
startTime: '8:00',
mart: {
id: 21,
martName: 'Johar Town',
},
endTime: '12:00',
cashier: {
name: 'Jamal',
id: 54,
},
},
])
const dataSource = result.map((a) => ({
day: a.date,
shift: a.tile,
start: a.startTime,
end: a.endTime,
mart: a.mart.martName,
}))
return (
<div>
<Table columns={columns} dataSource={dataSource} />
</div>
)
}
export default CashierShifts
the problem is when i am using my react query hook in my component but the data is returning undefined here.
const { data, isError, isLoading, isSuccess } = useCreateProfile()
console.log(data, 'react-query')
return useQuery(query, () => {
return usersApi(filters)
})

Can't get collection array from mongoDB with mongoose query

I have problem with getting data from DB. I want to get "collections" Array from mongoDB and render it in table component, but query returns null because of problem "user not found". Interesting thing is that if I use {email: req.body.email} in updateOne query to search for user and then create new collection it works and user is found.
getCollections.js
const router = require("express").Router();
const User = require("../models/user");
router.get("/", (req, res) => {
var query = { email: req.body.email };
User.find(query, (err, result) => {
if (err) {
res.json({ status: "error", error: "User not found" }, err);
} else {
res.json(result);
}
});
});
module.exports = router;
frontend getCollections query
useEffect(() => {
const url = "http://localhost:5000/api/getCollections";
// const url = `https://item-collection-app-bz.herokuapp.com/api/getCollections`;
axios
.get(url, { email: localStorage.getItem("email") })
.then((response) => {
setListOfCollections(response.data);
});
});
user.js UserSchema
const jwt = require("jsonwebtoken");
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({
_id: { type: mongoose.Schema.Types.ObjectId, required: true },
username: { type: String, require: true },
password: { type: String, require: true },
email: { type: String, require: true },
admin: { type: Boolean },
blocked: { type: Boolean },
collections: [
{
_id: { type: mongoose.Schema.Types.ObjectId, required: true },
coll_name: { type: String },
type: { type: String },
coll_desc: { type: String },
coll_image: { type: String },
items: [
{
_id: { type: mongoose.Schema.Types.ObjectId, required: true },
item_name: { type: String },
item_desc: { type: String },
comments: [
{
user: { type: String },
comment: { type: String },
comment_id: { type: String },
},
],
likes: { type: Number },
item_image: { type: String },
upload_date: { type: String },
},
],
},
],
});
userSchema.methods.generateAuthToken = function () {
const appToken = jwt.sign({ _id: this._id }, process.env.JWTPRIVATEKEY, {
expiresIn: "7d",
});
return appToken;
};
const User = mongoose.model("user", userSchema);
module.exports = User;
mongoDB
mongoDB structure
Tried User.findOne(), User.find()
SOLUTION
Thank you #Varun Kaklia. The solution is changing router.get and axios.get to router.post and axios.post.
Hey #1zboro1 first check did you receive any data from frontend inside Routes like-
const router = require("express").Router();
const User = require("../models/user");
router.get("/", (req, res) => {
const email = req.body.email;
console.log("Email from frontend", email)
var query = { email: req.body.email };
if (email != null || undefined) {
try {
const user = await User.find({ email});
console.log("User Details in User Routes of Backend",user)
if (user.length > 0) {
const currentUser = {
name: user[0].name,
email1: user[0].email1,
isAdmin: user[0].isAdmin,
_id: user[0]._id,
};
// console.log("Get User in User Routes of Backend", currentUser)
res.status(200).send(currentUser);
}
} catch (error) {
res.status(404).json({
message: "Something Went wrong",
});
}
Hope this code solve your query and give you desired result. If you still facing issue lemme know.
Thanks

"Whois" Command DiscordJS

I need to fix my discord comand "Whois". Can someone help me fix my code? Message me on twt: KiseeIsHere (not really necessary I just need to expand my message because stackflow wants me to).
module.exports.run = async (client, message, args) => {
const { MessageEmbed } = require('discord.js');
let member = message.mentions.users.first() || message.guild.members.cache.get(args[0]) || message.author || message.member;
let avatar = member.displayAvatarURL({ size: 1024, dynamic: true });
const statuses = {
online: "Online",
dnd: "Dnd",
idle: "Idle",
offline: "Offline"
};
let itstatus = statuses;
const exampleEmbed = new MessageEmbed()
.setTitle(member.username + "'s Profile")
.setColor('#2f3136')
.setThumbnail(avatar)
.addField("User Tag", member.tag, true)
.addField("ID", `${member.id}`, true)
.addField("Status", itstatus[member.presence.status], true)
.addField(
`Roles Count`,
message.guild.members.cache.get(member.user.id).roles.cache.size ||
"No Roles!",
true
)
.addField(`Avatar Url`, `[Link](${avatar})`, true)
.setFooter(`Requested by ${message.author.username}`)
.setTimestamp();
message.channel.send({ embeds: [exampleEmbed] });
}
module.exports.config = {
name: "whois",
aliases: ['ui']
}
Made a couple of changes, mostly to grab user stuff in the event someone runs it to get info on a bot and cleaned up the code a bit. I have tested and works as expected
const {
MessageEmbed,
} = require('discord.js');
module.exports.run = async (client, message, args) => {
const member = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.member;
const statuses = {
online: "Online",
dnd: "Dnd",
idle: "Idle",
offline: "Offline",
};
let status;
if (!member.presence) {
status = 'Unknown;'
} else {
status = statuses[member.presence.status]
}
const exampleEmbed = new MessageEmbed()
.setTitle(`${member.user.username}'s Profile`)
.setColor('#2f3136')
.setThumbnail(member.user.avatarURL({
size: 1024,
dynamic: true,
}))
.addFields({
name: "User Tag",
value: `${member.user.tag}`,
inline: true,
}, {
name: "ID",
value: `${member.id}`,
inline: true,
}, {
name: "Status",
value: `${status}`,
inline: true,
}, {
name: `Roles Count`,
value: `${message.guild.members.cache.get(member.user.id).roles.cache.size}` || "No Roles!",
inline: true,
}, {
name: `Avatar Url`,
value: `[Link](${member.user.avatarURL()})`,
inline: true,
})
.setFooter({
text: `Requested by ${message.author.username}`,
})
.setTimestamp();
message.channel.send({
embeds: [exampleEmbed],
});
};
module.exports.config = {
name: "whois",
aliases: ['ui'],
};

How to ignore "req.file.path" from form data if user do not choose a file using multer

Hello I'm working on a social network project using MERN Stack and in there user can either make a post with only text or can make a post by uploading an image along with some text as a caption, but the problem is that when a user doesn't wish to upload image and just want to post only with text and leaves postImage field empty then this error occurs Cannot read property 'path' of undefined what can be the solution for this, I'm attaching the post schema, post routes and post state:
Post Schema:
const mongoose = require('mongoose');
const postSchema = mongoose.Schema({
user: {
type: mongoose.Schema.ObjectId,
ref: 'Users',
},
text: {
type: String,
required: [true, 'post cannot be empty'],
},
postImage: {
type: String,
},
name: {
type: String,
},
avatar: {
type: String,
},
likes: [
{
user: {
type: mongoose.Schema.ObjectId,
ref: 'User',
},
},
],
comments: [
{
user: {
type: mongoose.Schema.ObjectId,
ref: 'User',
},
comment: {
type: String,
required: true,
},
name: {
type: String,
},
avatar: {
type: String,
},
date: {
type: Date,
default: Date.now,
},
},
],
date: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model('Post', postSchema);
Post Route:
const express = require('express');
const router = express.Router();
const auth = require('../middleware/auth');
const Post = require('../models/postModel');
const multer = require('multer');
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads');
},
filename: function (req, file, cb) {
cb(null, file.originalname);
},
});
const fileFilter = (req, file, cb) => {
if (
file.mimetype === 'image/jpeg' ||
file.mimetype === 'image/png' ||
file.mimetype === 'image/gif'
) {
cb(null, true);
} else {
cb(new Error('The supported file types are jpeg, png and gif'), false);
}
};
const upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5,
},
fileFilter: fileFilter,
});
const { check, validationResult } = require('express-validator');
const User = require('../models/userModel');
router.post(
'/',
upload.single('postImage'),
[auth, check('text', 'Text is required').not().isEmpty()],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
try {
const user = await User.findById(req.user.id).select('-password');
const newPost = new Post({
text: req.body.text,
postImage: req.file.path,
name: user.name,
avatar: user.avatar,
user: req.user.id,
});
const post = await newPost.save();
res.json(post);
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
}
);
Post State:
const createPost = async postData => {
try {
const config = {
headers: {
'Content-Type': 'multipart/form-data',
},
};
const res = await axios.post('/api/posts', postData, config);
dispatch({
type: ADD_POST,
payload: res.data,
});
} catch (err) {
dispatch({
type: POST_ERROR,
payload: err.response.msg,
});
}
};
You can simply check if req.file is defined - if yes set postImage to its path, else set it to undefined:
const newPost = new Post({
text: req.body.text,
postImage: req.file ? req.file.path : undefined,
name: user.name,
avatar: user.avatar,
user: req.user.id,
});

Mongoose: 'Cast to embedded failed for value at path. Cannot use 'in' operator to search for '_id'

I'm having some trouble trying to save an array inside an array of objects.
I'm getting the following response from the server:
{ [CastError: Cast to embedded failed for value "\'maxbeds: 4\'" at path "saved_searches"]
message: 'Cast to embedded failed for value "\\\'maxbeds: 4\\\'" at path "saved_searches"',
name: 'CastError',
kind: 'embedded',
value: '\'maxbeds: 4\'',
path: 'saved_searches',
reason: [TypeError: Cannot use 'in' operator to search for '_id' in maxbeds: 4] }
Here's my Schema:
var mongoose = require('mongoose'),
rfr = require('rfr'),
passwordHelper = rfr('server/helpers/password.js'),
Schema = mongoose.Schema,
_ = require('lodash');
/*
*
* Creating UserSchema for MongoDB
*
*/
var UserSchema = new Schema({
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true,
select: false
},
name: {
type: String,
required: true
},
passwordSalt: {
type: String,
required: true,
select: false
},
saved_houses: [{
mlsId: {
type: String
},
addressFull: {
type: String
},
bedrooms: {
type: Number
},
listPrice: {
type: Number
},
bathrooms: {
type: Number
},
sqft: {
type: Number
},
createdAt: {
type: Date,
default: Date.now
}
}],
saved_searches: [{
search_name: {
type: String
},
filters: {
type: [Schema.Types.Mixed]
},
createdAt: {
type: Date,
default: Date.now
}
}],
active: {
type: Boolean,
default: true
},
createdAt: {
type: Date,
default: Date.now
}
});
// compile User model
module.exports = mongoose.model('User', UserSchema);
The problem, I believe is the filters array that live inside an object inside the saved_searches array
Now, in my router I do the following:
var express = require('express'),
savedDataRouter = express.Router(),
mongoose = require('mongoose'),
rfr = require('rfr'),
s = rfr('server/routes/config/jwt_config.js'),
User = rfr('server/models/User.js'),
jwt = require('jsonwebtoken');
savedDataRouter.post('/searches', function (req, res) {
if (mongoose.Types.ObjectId.isValid(req.body.userId)) {
User.findByIdAndUpdate({
_id: req.body.userId
}, {
$push: {
saved_searches: {
search_name: req.body.search_name,
$each: req.body.filters
}
},
}, {
new: true
},
function (err, doc) {
if (err || !doc) {
console.log(err);
res.json({
status: 400,
message: "Unable to save search." + err
});
} else {
return res.json(doc);
}
});
} else {
return res.status(404).json({
message: "Unable to find user"
});
}
});
If I log the request body coming from the client I get the following:
//console.log(req.body)
{ search_name: 'Sarasota',
filters: [ 'minbaths: 1', 'maxbaths: 3', 'minbeds: 2', 'maxbeds: 4' ],
userId: '583359409a1e0167d1a3a2b3' }
I've tried all the things I've seen in Stack Overflow and other online resources with no luck. What am I doing wrong?
Edit
Added module dependencies to my UserSchema and SavedDataRouter
try this
User.findByIdAndUpdate({
_id: req.body.userId
}, {
$push: {
saved_searches: {
search_name: req.body.search_name,
filters: req.body.filters
}
},
}, {
new: true
},
function (err, doc) {
if (err || !doc) {
console.log(err);
res.json({
status: 400,
message: "Unable to save search." + err
});
} else {
return res.json(doc);
}
});

Resources