Discord bot wont run seemingly correct code - javascript

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.

Related

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

Discord.js v12 TypeError: Cannot read property 'hasPermission' of undefined

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

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.

Discord.js embed image not working. (Could not interpret "{'url': 'https://cdn.nekos.life/boobs/boobs105.gif'}" as string.)

My command.js
based on some other bots like HarutoHiroki Bot thst open source on Github and the Nekos.life documentation
const Discord = require('discord.js');
const client = require('nekos.life');
const neko = new client();
module.exports.run = async (bot, message, args) => {
if (message.channel.nsfw === true) {
link = await neko.nsfw.boobs()
console.log(link)
const embed = new Discord.MessageEmbed()
.setAuthor(`Some neko boobs`)
.setColor('#00FFF3')
.setImage(link)
.setFooter(`Bot by`);
message.channel.send(embed);
}
else {
message.channel.send("This isn't NSFW channel!")
}
};
module.exports.config = {
name: "boobs",
description: "",
usage: "*boobs",
accessableby: "Members",
aliases: []
}
Error:
> node .
(node:25052) ExperimentalWarning: Conditional exports is an experimental feature. This feature could change at any time
Logged in and connected as Bot#1234
{ url: 'https://cdn.nekos.life/boobs/boobs105.gif' }
(node:25052) UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body
embed.image.url: Could not interpret "{'url': 'https://cdn.nekos.life/boobs/boobs105.gif'}" as string.
at RequestHandler.execute (C:\Users\User\Documents\GitHub\Bot\node_modules\discord.js\src\rest\RequestHandler.js:170:25)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:25052) 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:25052) [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 Question
how to fix this? (I tried the hole day but didn't got it working need help soon as possible)
I fixed it:
const Discord = require('discord.js');
const client = require('nekos.life');
const neko = new client();
module.exports.run = async (bot, message, args) => {
if (message.channel.nsfw === true) {
link = await neko.nsfw.boobs()
const embed = new Discord.MessageEmbed()
.setAuthor(`Some neko boobs`)
.setColor('#00FFF3')
.setImage(link.url)
.setFooter(`Bot by`);
message.channel.send(embed);
}
else {
message.channel.send("This isn't NSFW channel!")
}
};
module.exports.config = {
name: "boobs",
description: "",
usage: "*boobs",
accessableby: "Members",
aliases: []
}
It looks like neko.nsfw.boobs() returns an object, not a string. Try this instead:
const { url } = await neko.nsfw.boobs(); // get only the URL, not the whole object
const embed = new Discord.MessageEmbed()
.setAuthor(`Some neko boobs`)
.setColor('#00FFF3')
.setImage(link.url)
.setFooter(`Bot by`);
message.channel.send(embed);
Here's a code snippet example:
const link = {
url: 'https://cdn.nekos.life/boobs/boobs105.gif'
};
console.log(link); // this will not give the link. it will give the whole object
/* using object destructuring, you can use brackets to capture one
property of an array. in this case, the url.
Object Destructuring - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
*/
const {
url
} = link;
console.log(url); // this will give *only* the link
console.log(link.url); // another method to give only the link

.sendEmbed dont works for RichEmbeds

I'm getting this:
(node:5496) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read prope
rty 'map' of null
(node:5496) [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.
Everytime i run my "userinfo" command
const prefix = require('../../settings.json').prefix;
const Discord = require('discord.js');
const commando = require('discord.js-commando');
class UserInfo extends commando.Command {
constructor(client) {
super(client, {
name: 'userinfo',
group: 'showinfo',
memberName: 'userinfo',
description: 'Muestra la información de un usuario.'
});
}
async run (message, args) {
if(message.author.bot) return;
if(message.channel.type === "dm") return;
var embed = new Discord.RichEmbed()
.setAuthor(message.author.username)
.setDescription("Usuario rikolino.")
.setColor("#3535353")
.addField("Usuario", '${message.author.username}#${message.author.discriminator}')
.addField("ID", message.author.id)
.addField("Creación", message.author.createdAt);
message.channel.sendEmbed(embed);
return;
}
}
module.exports = UserInfo;
As of May the 1st, .sendEmbed() is now depreciated. It is now part of the .send() method and to send embeds you will now have to type:
message.channel.send({embed});
- https://github.com/hydrabolt/discord.js/releases/tag/11.1.0
So in your case,
var embed = new Discord.RichEmbed()
.setAuthor(message.author.username)
.setDescription("Usuario rikolino.")
.setColor("#3535353")
.addField("Usuario", '${message.author.username}#${message.author.discriminator}')
.addField("ID", message.author.id)
.addField("Creación", message.author.createdAt);
message.channel.send({embed});
return;
javascriptdiscord.jsdiscordembedrichembednode.jsdepreciationwarning

Categories

Resources