so I want to make a delete reply system but I don't know how to do it. Can you guy help me?
This is my table
image of my mongodb
and the code I've tried is but it doesn't work
app.post("/remove-reply", async (req, res) => {
const index = parseInt(req.body.index) - 1
await Posts.findOneAndUpdate({ _id: req.body.id }, [
{
$set: {
"Comments.$[].replies": {
$concatArrays: [
{ $slice: ["$Comments.$[].replies", index] },
{ $slice: ["$Comments.$[].replies", { $add: [1, index] }, { $size: "$Comments.$[].replies" }] }
]
}
}
}
])
res.redirect("/")
})
and it gives me this error
(node:17376) UnhandledPromiseRejectionWarning: MongoServerError: Invalid $set :: caused by :: FieldPath field names may not start with '$'.
at MessageStream.messageHandler (C:\Users\The.Peerapon\Desktop\programming\Express-app\node_modules\mongodb\lib\cmap\connection.js:467:30)
at MessageStream.emit (events.js:400:28)
at processIncomingData (C:\Users\The.Peerapon\Desktop\programming\Express-app\node_modules\mongodb\lib\cmap\message_stream.js:108:16)
at MessageStream._write (C:\Users\The.Peerapon\Desktop\programming\Express-app\node_modules\mongodb\lib\cmap\message_stream.js:28:9)
at writeOrBuffer (internal/streams/writable.js:358:12)
at MessageStream.Writable.write (internal/streams/writable.js:303:10)
at TLSSocket.ondata (internal/streams/readable.js:731:22)
at TLSSocket.emit (events.js:400:28)
at addChunk (internal/streams/readable.js:293:12)
at readableAddChunk (internal/streams/readable.js:267:9)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:17376) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:17376) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
my goal is to click delete button at reply to delete it by index.
for each comment\reply, save its index in the database and use it as a sort of id. then, when someone wants to delete a comment, you do the following:
app
.post('/remove-reply', async (req, res) => {
const postId = req.body.id;
const commentIndex = parseInt(req.body.commentIndex) - 1;
const replyId = req.body.replyIndex;
await Posts.findOneAndUpdate({
_id: postId
}, {
$pull: {
[`Comments.${ commentIndex }.replies`]: {
_id: replyId
}
}
});
res.redirect('/');
});
so, when a user clicks on a reply to delete, you should have all 3 fields you need for finding the exact reply you want to delete.
You can also just save an auto-generated unique id for each item to use as an identifier\index since we treat it as a collection more than an array in this use-case. It will probably be easier to maintain since after deleting a comment, the index is not aligned anymore with the underlying array.
Related
I have previously used this code to get events from PancakeSwapV2 factory on the Binance Smart Chain. I'd like now to use this code to get events from UniswapV2 factory on the Ethereum blockchain but I get the following error :
(node:3544) UnhandledPromiseRejectionWarning: Error: resolver or addr is not configured for ENS name (argument="name", value="0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f ", code=INVALID_ARGUMENT, version=contracts/5.4.0)
at Logger.makeError (C:\Users\aaaa\WebstormProjects\web3test\node_modules\#ethersproject\logger\lib\index.js:187:21)
at Logger.throwError (C:\Users\aaaa\WebstormProjects\web3test\node_modules\#ethersproject\logger\lib\index.js:196:20)
at Logger.throwArgumentError (C:\Users\aaaa\WebstormProjects\web3test\node_modules\#ethersproject\logger\lib\index.js:199:21)
at C:\Users\aaaa\WebstormProjects\web3test\node_modules\#ethersproject\contracts\lib\index.js:101:32
at step (C:\Users\aaaa\WebstormProjects\web3test\node_modules\#ethersproject\contracts\lib\index.js:48:23)
at Object.next (C:\Users\aaaa\WebstormProjects\web3test\node_modules\#ethersproject\contracts\lib\index.js:29:53)
at fulfilled (C:\Users\aaaa\WebstormProjects\web3test\node_modules\#ethersproject\contracts\lib\index.js:20:58)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:3544) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To
terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:3544) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Process finished with exit code 0
Here's the source code I'm trying to reuse :
const Web3 = require('web3');
const ethers = require('ethers');
const INFURA_BASE_URL = 'https://mainnet.infura.io/v3/';
const INFURA_API_KEY = 'REPLACE';
web3 = new Web3(new Web3.providers.HttpProvider(INFURA_BASE_URL + INFURA_API_KEY));
const privateKey = "REPLACE";
const account = web3.eth.accounts.privateKeyToAccount(privateKey)
console.log(account.address)
const provider = new ethers.providers.JsonRpcProvider('https://mainnet.infura.io/v3/REPLACE');
const wallet = new ethers.Wallet(privateKey);
const account2 = wallet.connect(provider);
const addresses = {
WETH: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',
factory: '0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f ',
router: '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ',
recipient: account.address
};
//console.log(provider)
const factory = new ethers.Contract(
addresses.factory,
[
'event PairCreated(address indexed token0, address indexed token1, address pair, uint)',
'function getPair(address tokenA, address tokenB) external view returns (address pair)'
],
account2
);
factory.on('PairCreated', async (token0, token1, pairAddress) => { }
Would you know what I'm doing wrong ? Thank you.
It seems that I'm approaching the solution with this piece of code :
const Web3 = require("web3");
let web3 = new Web3(
new Web3.providers.WebsocketProvider("wss://mainnet.infura.io/ws/v3/cc44823998a0412294a47680xxxxxxxx")
);
let abi = JSON.parse('[{"inputs":[{"internalType":"address","name":"_feeToSetter","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token0","type":"address"},{"indexed":true,"internalType":"address","name":"token1","type":"address"},{"indexed":false,"internalType":"address","name":"pair","type":"address"},{"indexed":false,"internalType":"uint256","name":"","type":"uint256"}],"name":"PairCreated","type":"event"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"allPairs","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"allPairsLength","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"tokenA","type":"address"},{"internalType":"address","name":"tokenB","type":"address"}],"name":"createPair","outputs":[{"internalType":"address","name":"pair","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"feeTo","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"feeToSetter","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"getPair","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_feeTo","type":"address"}],"name":"setFeeTo","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_feeToSetter","type":"address"}],"name":"setFeeToSetter","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]')
const instance = new web3.eth.Contract(abi, '0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f');
//web3.eth.getBlockNumber().then(console.log)
instance.getPastEvents(
"allEvents",
{fromBlock: "12908000", toBlock: "12908094"},
(errors, events) => {
if (!errors) {
//console.log('it is ok')
//console.log(events)
}
}
).then(r => {
console.log(r)
});
Code
module.exports.run = async (bot, message, args) =>{
// at the top of your file
const discord = require('discord.js');
const config = require("../config");
// inside a command, event listener, etc.
const embed = new discord.MessageEmbed()
.setColor('RANDOM')
.setTitle('Créditos do Os Profissionais')
.setURL('https://discord.gg/')
.setAuthor('Effy', 'https://i.imgur.com/wSTFkRM.png', 'https://stackoverflow.com/users/15303029/meredithgrey')
.setDescription('Criador do grupo e desenvolvedor do BOT')
.setThumbnail('https://i.imgur.com/1oHJJZQ.png')
.addFields(
{ name: 'Créditos de equipe', value: 'Equipe gestora' },
{ name: '\u200B', value: '\u200B' },
{ name: 'Snoot', value: 'Owner', inline: true },
{ name: 'Texugo', value: 'Owner', inline: true },
)
.addField('Leo', 'Owner', true)
.setImage('https://i.imgur.com/1oHJJZQ.png')
.setTimestamp()
.setFooter(message.author.username, message.author.avatar);
message.channel.send(embed);
}
module.exports.config = {
name: "credits",
aliases: ["creditos"]
}
Error:
(node:5676) UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body
embed.footer.icon_url: Scheme "fbea7946b1cf05e3bfbff344733ba775" is not supported. Scheme must be one of ('http', 'https').
at RequestHandler.execute (C:\Users\Pc\Desktop\RemakeTO\node_modules\discord.js\src\rest\RequestHandler.js:154:13)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async RequestHandler.push (C:\Users\Pc\Desktop\RemakeTO\node_modules\discord.js\src\rest\RequestHandler.js:39:14)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:5676) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:5676) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Since when I started using discord.js V12 i walk with many doubts and one of them is, how to catch the avatar of a user? Can someone help me? I know it's a stupid doubt but I really don't know
message.author.avatar is not a method. You need message.author.avatarURL
//author's avatar:
.setThumbnail(message.author.avatarURL);
As mentioned above, try using the docs
// In discord.js v12
message.author.displayAvatarURL()
I was having a similar issue. The problem was that Discord was being sent the embed before the promise of fetching the user and image was fulfilled. This is the code I used to get this functionality.
const client = new Discord.Client();
let thanos = client.users.fetch('IDHERE');
thanos.then(function(result1) {
//put your code that uses the result1 (the user object) here
//for example, you could put your entire embed in here and
//in setFooter you could use result1.displayAvatarURL()
});
I made an add role command and added permissions to it. However, on running the command I get an error. Here is my code:
const { MessageEmbed } = require('discord.js');
module.exports = {
name: "addrole",
aliases: ["ar"],
description: "Adds a role to a user",
async execute(client, message, args) {
if (!message.member.hasPermission('MANAGE_ROLES')) return message.channel.send('NO PERMS')
if (!message.guild.me.hasPermission('MANAGE_ROLES')) return message.channel.send('NO PERMS')
const member = message.guild.members.cache.get(args[0]);
if (!member)
return message.channel.send('Please mention a user or provide a valid user ID');
if (member.roles.highest.position >= message.member.roles.highest.position)
return message.channel.send('You cannot add a role to someone with an equal or higher role');
const role = message.guild.roles.cache.get(args[1]);
let reason = args.slice(2).join(' ');
if (!reason) reason = '`None`';
if (reason.length > 1024) reason = reason.slice(0, 1021) + '...';
if (!role)
return message.channel.send('Please mention a role or provide a valid role ID');
else if (member.roles.cache.has(role.id)) // If member already has role
return message.channel.send('User already has the provided role');
else {
try {
// Add role
await member.roles.add(role);
const embed = new MessageEmbed()
.setTitle('Add Role')
.setDescription(`${role} was successfully added to ${member}.`)
.addField('Moderator', message.member, true)
.addField('Member', member, true)
.addField('Role', role, true)
.addField('Reason', reason)
.setFooter(message.member.displayName, message.author.displayAvatarURL({ dynamic: true }))
.setTimestamp()
.setColor(message.guild.me.displayHexColor);
message.channel.send(embed);
} catch (err) {
return message.channel.send('Please check the role hierarchy or if the role is managed by an integeration or system', err.message);
}
}
}
}
As I had mentioned earlier I get an error:
(node:315) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'hasPermission' of undefined
at Object.execute (/home/runner/NonstopPastelDistributionsoftware/commands/addrole.js:7:20)
at Client.<anonymous> (/home/runner/NonstopPastelDistributionsoftware/index.js:80:13)
at Client.emit (events.js:315:20)
at Client.EventEmitter.emit (domain.js:483:12)
at MessageCreateAction.handle (/home/runner/NonstopPastelDistributionsoftware/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (/home/runner/NonstopPastelDistributionsoftware/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/home/runner/NonstopPastelDistributionsoftware/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
at WebSocketShard.onPacket (/home/runner/NonstopPastelDistributionsoftware/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
at WebSocketShard.onMessage (/home/runner/NonstopPastelDistributionsoftware/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
at WebSocket.onMessage (/home/runner/NonstopPastelDistributionsoftware/node_modules/ws/lib/event-target.js:125:16)
(node:315) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:315) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I used the same code for permissions in every command however I got this error the first time. Can you help me out? Thanks in advance
I recently made a lock command for discord.js. However whenever I run the command I get an error. Here is the code:
module.exports = {
name: "lock",
description: "Lock",
async run(client, message, args) {
if (!message.member.hasPermission("KICK_MEMBERS")) return message.channel.send('You can\'t use that!')
function lock(message) {
let channel = message.channel;
const Guild = client.guilds.cache.get("751424392420130907");
if (!Guild) return console.error("Couldn't find the guild.");
const Role = Guild.roles.cache.find(role => role.name == "Verified");
channel.overwritePermissions(
Role, {
'SEND_MESSAGES': false
},
'Competitive has Ended'
)
}
lock(message)
message.channel.send('Channel Locked')
}
}
As I had mentioned earlier that whenever I run this command I get the following error:
(node:1354) UnhandledPromiseRejectionWarning: TypeError [INVALID_TYPE]: Supplied overwrites is not an Array or Collection of Permission Overwrites.
at TextChannel.overwritePermissions (/home/runner/SweatyBeautifulHelpfulWorker/node_modules/discord.js/src/structures/GuildChannel.js:208:9)
at lock (/home/runner/SweatyBeautifulHelpfulWorker/commands/lock.js:14:11)
at Object.run (/home/runner/SweatyBeautifulHelpfulWorker/commands/lock.js:21:1)
at Client.<anonymous> (/home/runner/SweatyBeautifulHelpfulWorker/index.js:77:42)
at Client.emit (events.js:327:22)
at Client.EventEmitter.emit (domain.js:483:12)
at MessageCreateAction.handle (/home/runner/SweatyBeautifulHelpfulWorker/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (/home/runner/SweatyBeautifulHelpfulWorker/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/home/runner/SweatyBeautifulHelpfulWorker/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
at WebSocketShard.onPacket (/home/runner/SweatyBeautifulHelpfulWorker/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
(node:1354) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:1354) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
[WS => Shard 0] [HeartbeatTimer] Sending a heartbeat.
[WS => Shard 0] Heartbeat acknowledged, latency of 44ms.
(node:1354) UnhandledPromiseRejectionWarning: TypeError [INVALID_TYPE]: Supplied overwrites is not an Array or Collection of Permission Overwrites.
at TextChannel.overwritePermissions (/home/runner/SweatyBeautifulHelpfulWorker/node_modules/discord.js/src/structures/GuildChannel.js:208:9)
at lock (/home/runner/SweatyBeautifulHelpfulWorker/commands/lock.js:14:11)
at Object.run (/home/runner/SweatyBeautifulHelpfulWorker/commands/lock.js:21:1)
at Client.<anonymous> (/home/runner/SweatyBeautifulHelpfulWorker/index.js:77:42)
at Client.emit (events.js:327:22)
at Client.EventEmitter.emit (domain.js:483:12)
at MessageCreateAction.handle (/home/runner/SweatyBeautifulHelpfulWorker/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (/home/runner/SweatyBeautifulHelpfulWorker/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/home/runner/SweatyBeautifulHelpfulWorker/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
at WebSocketShard.onPacket (/home/runner/SweatyBeautifulHelpfulWorker/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
(node:1354) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
Can you help me out in solving this problem? thanks in advance!
You should do this, your code seems lengthy :
if (!message.member.roles.cache.some(role => role.name === 'Moderator')) return;
message.channel.updateOverwrite(message.channel.guild.roles.everyone, { SEND_MESSAGES: false })
message.channel.send(`Successfully locked **${message.channel.name}**`)
Replace message.channel.guild.roles.everyone from your roles.
You just need to call the following lines to remove the send permissions on the current channel:
const Role = guild.roles.find("name", "Verified ");
message.channel.overwritePermissions(role,{ 'SEND_MESSAGES': false })
If you wanna make an unlock channel command, simply add this under the command:
const Role = guild.roles.find("name", "Verified ");
message.channel.overwritePermissions(role,{ 'SEND_MESSAGES': true})
It's not how you update the permission instead of this:
channel.overwritePermissions(
Role, {
'SEND_MESSAGES': false
},
'Competitive has Ended'
)
use this:
channel.overwritePermissions([
{
id: roleId,
deny: ['SEND_MESSAGES']
}]
,'Competitive has Ended'
)
source discord.js documentation#overwritePermissions
This code below might help you
channel.overwritePermissions(
[
{
id: roleId,
deny: [
'SEND_MESSAGES'
]
}
]
, 'Mark my question'
)```
you should also use updateOverwrite instead of overwritePermissions.
Example:
module.exports = {
name: "lock",
description: "Lock",
run(client, message, args) {
const targetChannel = message.mentions.channels.first() || message.channel;
// Guild ID is the same as the everyone role ID
const everyoneID = message.guild.id;
targetChannel.updateOverwrite(everyoneID, {
SEND_MESSAGES: false,
});
targetChannel.send(`**${targetChannel.name}** has been locked :lock:`);
}
}
There is also no need for it to be an async function since you are not using await in your code.
I'm trying to get this code to work, however, when I run it, I get to the end of the process, however, I then get the error 'Pool is not a Constructor'. How does one solve this?
const { Command } = require('discord.js-commando');
const Keyv = require('keyv');
const logsdb = new Keyv(process.env.DATABASE_URL, { table: 'modlogs' });
module.exports = class modlogs extends Command {
constructor(client) {
super(client, {
name: 'modlog',
group: 'moderation',
memberName: 'modlogs',
description: 'Used to set the mod-log of the server.',
clientPermissions: ['ADMINISTRATOR'],
userPermissions: ['ADMINISTRATOR'],
args: [
{
key: 'logs',
prompt:
'Which channel do you want to set as the mod-log? (Without the `#`)',
type: 'string',
},
],
guildOnly: true,
});
}
async run(message, { logs }) {
await logsdb
.set(message.guild.id, logs)
.then(message.channel.send(`Successfully set mod log to \`${logs}\``));
}
};
Error Log:
2020-09-14T19:42:32.883176+00:00 app[worker.1]: (node:22) UnhandledPromiseRejectionWarning: TypeError: Pool is not a constructor
2020-09-14T19:42:32.883185+00:00 app[worker.1]: at /app/node_modules/#keyv/postgres/src/index.js:15:18
2020-09-14T19:42:32.883224+00:00 app[worker.1]: (node:22) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 79)