Pool not a constructor when trying to connect using #Keyv/Postgres - javascript

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)

Related

MongoDB: How do I delete nested object by index?

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.

Trying to susbcribe to PairCreated events from UniswapV2 Factory in Nodejs

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

I am creating a system so that users can make bug reports, everything works but the console throws me an error that I would like to solve Discord.js

const { RichEmbed, MessageEmbedImage } = require("discord.js");
const { promptMessage } = require("../../functions.js");
module.exports = {
name: "bugreport",
aliases: ["bugreports"],
usage: "bugreport <your report>",
description: "Send your report",
category: "server",
run: async (client, message, args) => {
const channel = message.guild.channels.find(c => c.name === "「❗」reports");
if (message.deletable) message.delete();
if(!args[0]) {
return message.reply("Please write your report").then(m => m.delete(10000));
}
if(!channel) {
return message.reply("There is no channel with name '#「❗」reports'").then(m => m.delete(10000));
}
const bugreportMessage = {
color: 51199,
author: {
name: "Report created by "+message.author.username,
icon_url: message.author.avatarURL
},
title: "New bug reported:",
url: "",
description: args.slice(0).join(" "),
thumbnail: {
url: message.author.avatarURL,
},
timestamp: new Date(),
footer: {
icon_url: client.user.avatarURL, text: "♛ Space Network"
}
}
message.channel.send("Sending your report to " + channel).then(m => m.delete(10000))
await channel.send({ embed: bugreportMessage });
}
}
Error: (node:8420) UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown Message
at E:\GitHub\space-bot\node_modules\discord.js\src\client\rest\RequestHandlers\Sequential.js:85:15
at E:\GitHub\space-bot\node_modules\snekfetch\src\index.js:215:21
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use node --trace-warnings ... to show where the warning was created)
(node:8420) 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)
(node:8420) [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.
Discord when running the command: enter image description here
Console after run command: enter image description here
There are quite a few methods in your code that return promises and I can't see any catch()es to handle rejections. I think one of those .delete()s can't find the message you want to delete.
If you're already using an async function, you could get rid of those then()s and use async-await instead, and wrap your code in a try-catch block like this:
run: async (client, message, args) => {
try {
const channel = message.guild.channels.find(
(c) => c.name === '「❗」reports',
);
if (message.deletable) message.delete();
if (!args[0]) {
const msg = await message.reply('Please write your report');
return msg.delete(10000);
}
if (!channel) {
const msg = await message.reply("There is no channel with name '#「❗」reports'");
return msg.delete(10000);
}
const bugreportMessage = {
color: 51199,
author: {
name: 'Report created by ' + message.author.username,
icon_url: message.author.avatarURL,
},
title: 'New bug reported:',
url: '',
description: args.slice(0).join(' '),
thumbnail: {
url: message.author.avatarURL,
},
timestamp: new Date(),
footer: {
icon_url: client.user.avatarURL,
text: '♛ Space Network',
},
};
const msg = await message.channel.send('Sending your report to ' + channel);
msg.delete(10000);
channel.send({ embed: bugreportMessage });
} catch (error) {
console.log(error);
}
};

Error picking up the user's avatar (discord.js)

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()
});

Lock Command Discord.js

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.

Categories

Resources