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.
Related
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.
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
So I'm writing an unban script for my discord bot - it keeps throwing errors when ONLY this command is used - it looks correct to me and my mate, is there something I am overlooking?
const discord = require("discord.js");
module.exports = {
name: 'unban',
category: 'moderation',
description: 'unban a members',
aliases: [''],
run: async (message, client, args) => {
let unbanned = message.mentions.users.first() || client.users.resolve(args[0]);
let reason = args.slice(1).join(" ");
let member = await client.users.fetch(unbanned);
let ban = await message.guild.fetchBans();
// MESSAGES
if (!unbanned) {
let unbaninfoembed = new Discord.MessageEmbed()
.setTitle("Command: unban")
.setDescription(
`**Description:** Unban a user. \n` +
"**Sub Commands:**\n" +
"" +
"**Usage:**\n" +
"-unban [user] (limit) (reason) \n" +
"**Examples:** \n" +
"-unban <#759175803409530932> good guy \n" +
"-unban 759175803409530932 good guy "
)
.setColor("#2C2F33");
message.channel.send(unbaninfoembed);
return;
}
if (!ban.get(member.id)) {
let notbannedembed = new Discord.MessageEmbed()
.setDescription("This user is not banned")
.setColor("#2C2F33");
message.channel.send(notbannedembed);
return;
}
if (!message.guild.me.permissions.has("BAN_MEMBERS")) {
let botnoperms = new Discord.MessageEmbed()
.setDescription(
"I do not have permissions, please contact an administrator"
)
.setColor("#2C2F33");
message.channel.send(botnoperms);
return;
}
if (!message.member.permission.has("BAN_MEMBERS")) {
let nopermsembed = new Discord.MessageEmbed()
.setDescription(
"You do not have permission `BAN MEMBERS` contact an administrator"
)
.setColor("#2C2F33");
message.channel.send(nopermsembed);
return;
}
var user = ban.get(member.id);
message.guild.members.unban(member);
let successfullyembed = new Discord.MessageEmbed()
.setTitle(`Successfully Unbaned!`)
.setDescription(`${member.tag} has been successfully unbanned`)
.addField(`Reason: ${reason}`)
.setColor("#2C2F33");
message.channel.send(successfullyembed);
},
};
Gives the error:
UnhandledPromiseRejectionWarning: DiscordAPIError: 404: Not Found
at RequestHandler.execute (E:\Lyckas\node_modules\discord.js\src\rest\RequestHandler.js:170:25)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:17316) 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:17316) [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.
Recently Discord has changed the main website from "discordapp.com" to "discord.com", try reinstalling the discord.js module and see if it helps.
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)