.sendEmbed dont works for RichEmbeds - javascript

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

Related

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

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

Discord bot wont run seemingly correct code

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.

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

Discord.js bot - music function: 'Invalid argument type' --Cannot identify issue

I'm working on a discord.js bot that plays music. The idea is that a user can type "X play" (X being the prefix for the bot) to get the bot to join the voice channel that the commander is in. Or, the user can type "X play [YouTube Link]" to play the audio from a YouTube video using YTDL. So far, The bot can join the channel fine. However, when i attach a link i am returned with a very complicated error that i simply don't understand at all. I've referred to documentations and help forums but there is nothing relating to my issue. I've attached the module for the command.
const Commando = require('discord.js-commando');
const YTDL = require('ytdl-core');
function Play(connection, message)
{
var server = servers[message.guild.id];
server.dispatcher = connection.playStream(YTDL(server.queue[0], {filter: "audioonly"}));
server.queue.shift();
server.dispatcher.on("end", function(){
if(server.queue[0])
{
Play(connection, message);
}
else
{
connection.disconnect();
}
});
}
class JoinChannelCommand extends Commando.Command
{
constructor(client)
{
super(client,{
name: 'play',
group: 'simple',
memberName: 'play',
description: 'Plays the audio from a youtube link'
});
}
async run(message, args)
{
if(message.member.voiceChannel)
{
if(!message.guild.voiceConnection)
{
if(!servers[message.guild.id])
{
servers[message.guild.id] = {queue: []}
}
message.member.voiceChannel.join()
.then(connection =>{
var server = servers[message.guild.id];
message.reply("Successfully joined!");
server.queue.push(args);
Play(connection, message);
})
}
}
else
{
message.reply("ERROR: Not connected to voice channel");
}
}
}
module.exports = JoinChannelCommand;
When i type "X play" the bot joins the channel. When i type "X play [link]", the bot joins but doesn't play music. The console returns:
(node:5136) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The "file" argument must be of type string. Received type object
at validateString (internal/validators.js:125:11)
at normalizeSpawnArguments (child_process.js:414:3)
at Object.spawn (child_process.js:553:16)
at new FfmpegProcess (C:\My Discord Bots\XyloBot\node_modules\prism-media\src\transcoders\ffmpeg\FfmpegProcess.js:14:33)
at FfmpegTranscoder.transcode (C:\My Discord Bots\XyloBot\node_modules\prism-media\src\transcoders\ffmpeg\Ffmpeg.js:34:18)
at MediaTranscoder.transcode (C:\My Discord Bots\XyloBot\node_modules\prism-media\src\transcoders\MediaTranscoder.js:27:31)
at Prism.transcode (C:\My Discord Bots\XyloBot\node_modules\prism-media\src\Prism.js:13:28)
at AudioPlayer.playUnknownStream (C:\My Discord Bots\XyloBot\node_modules\discord.js\src\client\voice\player\AudioPlayer.js:97:35)
at VoiceConnection.playStream (C:\My Discord Bots\XyloBot\node_modules\discord.js\src\client\voice\VoiceConnection.js:478:24)
at Play (C:\My Discord Bots\XyloBot\commands\music\join.js:7:36)
(node:5136) 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(). (rejection id: 1)
(node:5136) [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.
Apologies for the long segments of code etc, however this is far out of my reach. Any and all help is appreciated.

Categories

Resources