Cannot read property 'nsfw' of undefined - discord.js - javascript

I'm currently working on a discord bot that makes use of 'discord.js', 'discord.js-commando' and 'snekfetch'. I'm trying to create a function in which if a guild member were to type "!meme", the discord bot will grab a random post from r/dankmemes and send it to the respective channel using richEmbed. however, upon testing the function the following error messages appear:
TypeError: Cannot read property 'nsfw' of undefined
TypeError: Cannot read property 'send' of undefined
I've been trying to resolve the issue for 4 days and i'm utterly clueless as to what is causing this issue. According to the discord.js documentation this should work absolutely fine. I've attached the command module below:
const Commando = require('discord.js-commando');
const Discord = require('discord.js');
const snekfetch = require('snekfetch');
class MemesRssCommand extends Commando.Command
{
constructor(client)
{
super(client,{
name: 'meme',
group: 'simple',
memberName: 'meme',
description: 'Takes a random meme from r/dankmemes'
});
}
async run(client, message, args) {
try {
const { body } = await snekfetch
.get('https://www.reddit.com/r/dankmemes.json?sort=top&t=week')
.query({ limit: 800 });
const allowed = message.channel.nsfw ? body.data.children : body.data.children.filter(post => !post.data.over_18);
if (!allowed.length) return message.channel.send('Our farmers were unable to locate any ripe memes! Try again later (You shouldnt see this message. If you are reading this, then reddit is probably offline. If reddit is online and you still get this message, contact #𝕏𝕪𝕝𝕠𝕟𝕠𝕝𝕪#1612');
const randomnumber = Math.floor(Math.random() * allowed.length)
const embed = new Discord.RichEmbed()
.setColor(0x00A2E8)
.setTitle(allowed[randomnumber].data.title)
.setDescription("Posted by: " + allowed[randomnumber].data.author)
.setImage(allowed[randomnumber].data.url)
.addField("Other info:", "Up votes: " + allowed[randomnumber].data.ups + " / Comments: " + allowed[randomnumber].data.num_comments)
.setFooter("Posted by: " + allowed[randomnumber].data.author + " | Memes provided by https://www.reddit.com/r/dankmemes")
message.channel.send(embed)
} catch (err) {
return console.log(err);
}
}
}
module.exports = MemesRssCommand

According to the example in documentation the callback for run is run(message, args) but you are defining it as run(client, message, args), thus the message.channel is undefined since you are trying to access it on the wrong object.
async run(message, args) {
const member = args.member;
const channel = message.channel
// ....
}

Related

Discord.js Invalid Form Body [duplicate]

This question already has an answer here:
why register slash commands with options doesn't work (discord.js)
(1 answer)
Closed 2 months ago.
At the time I am trying to learn how to make a discord bot and I got an error I dont know waht it means or how to fix it. I made a command for welcome messages with a youtube tutorial and now it stopped working.
Error:
DiscordAPIError[50035]: Invalid Form Body
7.options[0].name[APPLICATION_COMMAND_INVALID_NAME]: Command name is invalid
at SequentialHandler.runRequest (C:\Users\hp\OneDrive\Desktop\Manager\node_modules\#discordjs\rest\dist\index.js:659:15)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async SequentialHandler.queueRequest (C:\Users\hp\OneDrive\Desktop\Manager\node_modules\#discordjs\rest\dist\index.js:458:14)
at async REST.request (C:\Users\hp\OneDrive\Desktop\Manager\node_modules\#discordjs\rest\dist\index.js:902:22)
at async GuildApplicationCommandManager.set (C:\Users\hp\OneDrive\Desktop\Manager\node_modules\discord.js\src\managers\ApplicationCommandManager.js:173:18)
Code:
const {Message, Client, SlashCommandBuilder, PermissionFlagsBits} = require("discord.js");
const welcomeSchema = require("../../Models/Welcome");
const {model, Schema} = require("mongoose");
module.exports = {
name:"setup-welcome",
description:"Set up your welcome message for the discord bot.",
UserPerms:["BanMembers"],
category:"Moderation",
options: [
{
name:"Channel",
description:"Channel for welcome messages.",
type:7,
required:true
},
{
name:"welcome-message",
description:"Enter your welcome message.",
type:3,
reqired:true
},
{
name:"welcome-role",
description:"Enter your welcome role.",
type:8,
required:true
}
],
async execute(interaction) {
const {channel, options} = interaction;
const welcomeChannel = options.getChannel("channel");
const welcomeMessage = options.getString("welcome-message");
const roleId = options.getRole("welcome-role");
if(!interaction.guild.members.me.permissions.has(PermissionFlagsBits.SendMessages)) {
interaction.reply({content: "I don't have permissions for this.", ephemeral: true});
}
welcomeSchema.findOne({Guild: interaction.guild.id}, async (err, data) => {
if(!data) {
const newWelcome = await welcomeSchema.create({
Guild: interaction.guild.id,
Channel: welcomeChannel.id,
Msg: welcomeMessage,
Role: roleId.id
});
}
interaction.reply({content: 'Succesfully created a welcome message', ephemeral: true});
})
}
}
I tried a few things like changing the construction of the bot or change some thing like the command options.
Thanks in advance!
Your Channel argument is invalid, since all names need to be lowercase only. Change it to channel, for example, and it will work.

Cannot send an empty message form like {embeds:[embed]}

I wrote a new command when my bot ran on my pc and not a server.
While the bot ran on my pc the command worked very well, but after I put my bot into a server
the command stopped working and I always get an error message:
DiscordAPIError: Cannot send an empty message
The code:
const Discord = require("discord.js");
const recon = require('reconlx');
const rpages = recon.ReactionPages
const moment = require('moment');
const fs = require('fs');
module.exports = class HelpCommand extends BaseCommand {
constructor() {
super('help', 'moderation', []);
}
async run(client, message, args) {
const y = moment().format('YYYY-MM-DD HH:mm:ss')
const sayEmbed1 = new Discord.MessageEmbed()
.setTitle(`example`)
const sayEmbed2 = new Discord.MessageEmbed()
.setTitle(`example`)
const sayEmbed3 = new Discord.MessageEmbed()
.setTitle(`example`)
const sayEmbed5 = new Discord.MessageEmbed()
.setTitle(`example`)
const sayEmbed4 = new Discord.MessageEmbed()
.setTitle(`example`)
const sayEmbed6 = new Discord.MessageEmbed()
.setTitle(`example`)
.setDescription("[A készítőm Weboldala](https://istvannemeth1245.wixsite.com/inde/)\n\n")
try {
await
message.delete();
const pages = [{ embed: sayEmbed1 }, { embed: sayEmbed2 }, { embed: sayEmbed3 }, { embed: sayEmbed4 }, { embed: sayEmbed5 }, { embed: sayEmbed6 }];
const emojis = ['◀️', '▶️'];
const textPageChange = true;
rpages(message, pages, textPageChange, emojis);
} catch (err) {
console.log(err);
message.channel.send('Nem tudom ki írni az üzenetet');
}
const contetn = `\n[${y}] - ${message.author.username} használta a help parancsot. `;
fs.appendFile('log.txt', contetn, err => {
if (err) {
console.err;
return;
}
})
}
}
Full error message:
throw new DiscordAPIError(request.path, data, request.method, res.status);
^
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (/home/container/Lee-Goldway/node_modules/discord.js/src/rest/RequestHandler.js:154:13)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async RequestHandler.push (/home/container/Lee-Goldway/node_modules/discord.js/src/rest/RequestHandler.js:39:14) {
method: 'post',
path: '/channels/833629858210250813/messages',
code: 50006,
httpStatus: 400
}
A couple of things. Are you sure that this reconlx package is compatible with your discord.js version? It's always a good idea to post your discord.js version when you have a problem with libraries.
If you're using reconlx v1, you can see in their old documentation that in ReactionPages the second parameter takes an array of embeds. If you check the source code, you can see that it tries to send the first item of pages as an embed, like this: message.channel.send({ embeds: [pages[0]] }).
It means that with your code embeds is an array where the first item is an object that has an embed key with the sayEmbed1 embed, while discord.js accepts an array of MessageEmbeds.
I would try to pass down an array of embeds like this:
const pages = [
sayEmbed1,
sayEmbed2,
sayEmbed3,
sayEmbed4,
sayEmbed5,
sayEmbed6,
];
PS: ki írni is incorrect. When the verb particle precedes the verb, they are written as one word. So, it should be kiírni. :)
In the code provided, there appears to be no code that references "{embeds:[embed]}".
However, assuming the error is coming from this line:
message.channel.send('Nem tudom ki írni az üzenetet');
Referring to the official documentation, you can provide an object.
For example:
message.channel.send({ content: 'Nem tudom ki írni az üzenetet' });

TypeError: Cannot read property 'mentions' of undefined

first time poster looking for some help, struggling to get this to work. I'm wanting to create a command which followed by a channel mention and Raw JSON will then post an embed in the mention channel. The code itself throws up no errors, until the point I initiate the command, where I get "TypeError: Cannot read property 'mentions' of undefined". Any ideas where I've gone wrong?
const DiscordJS = require('discord.js')
const WOKCommands = require('wokcommands')
require('dotenv').config();
module.exports = {
name: "embedjson",
category: "info",
description: "post embed from json data",
minArgs: 2,
expectedArgs: '<Channel mention> <JSON>',
run: async ({client, message, args, level }) => {
// get the target channel
const targetChannel = message.mentions.channels.first()
if (!targetChannel) {
message.reply('Please specify a channel to send the embed in')
return
}
// removes the channel mention
args.shift()
try {
// get the JSON data
const json = JSON.parse(args.join(' '))
const { text = '' } = json
// send the embed
targetChannel.send(text, {
embed: json,
})
} catch (error) {
message.reply(`Invalid JSON ${error.message}`)
}
},
}

Cannot access 'person' before initialization Error

I'm getting a "Cannot access 'person' before initialization" Error. I don't have const person anywhere else except this file. I'm new to js so I'm not sure what I'm doing wrong.
Edit: I fix that error but now I'm getting a different error message. "UnhandledPromiseRejectionWarning: ReferenceError: getMember is not defined".
const Discord = require('discord.js');
module.exports.run = async (bot, message, args) => {
const love = Math.random() * 100;
const loveIndex = Math.floor(love / 10);
const loveLevel = "💖".repeat(loveIndex) + "💔".repeat(10 - loveIndex);
const embed = new Discord.MessageEmbed()
.setColor("#ffb6c1")
.addField(`☁ **${person.displayName}** loves **${message.member.displayName}** this much:`,
`💟 ${Math.floor(love)}%\n\n${loveLevel}`);
let person = getMember(message, args[0]);
if (!person || message.author.id === person.id) {
person = message.guild.members
.filter(m => m.id !== message.author.id)
.random();
message.channel.send(embed);
}}
module.exports.config = {
name: "love",
description: "Calculates the love affinity you have for another person.",
usage: "[mention | id | username]",
accessableby: "Members",
aliases: ["affinity"]
}
On this line:
.addField(`☁ **${person.displayName}** loves **${message.member.displayName}** this much:`,
person is not defined.
Try moving the block where you initialize person up above the const embed = ... statement.
That error is usually caused by trying the make a reference to a class before the code for the class itself is initialized. Try declaring person after class definition.

How to fix a complex Discord command in JS based off of webhooks and roles

I'm working on a command where when you do the command, d!woa the following happens
A webhook gets created with a certain name, Then a role gets created with the channel name, after that the bot watches if there's a webhook with that certain name for the channel, and just sees if anyone sends a message in that channel. If it does, then the bot will add that role with the certain name.
The problem is that there's this error : TypeError: Cannot read property 'guild' of undefined
The error will most likely appear at the end of the code provided.
I've tried rearranging the code, defining guild, and defining message. It does not seem to work even after trying all of this. I only want it to rely off of the ID instead of Name to be accurate for this command.
const Discord = require('discord.js');
const commando = require('discord.js-commando');
class woa extends commando.Command
{
constructor(client) {
super(client, {
name: 'watchoveradd',
group: 'help',
memberName: 'watchoveradd',
description: 'placeholder',
aliases: ['woa'],
})
}
async run(message, args){
if (message.channel instanceof Discord.DMChannel) return message.channel.send('This command cannot be executed here.')
else
if(!message.member.guild.me.hasPermission(['MANAGE_WEBHOOKS'])) return message.channel.send('I don\'t have the permissions to make webhooks, please contact an admin or change my permissions!')
if(!message.member.guild.me.hasPermission(['MANAGE_ROLES'])) return message.channel.send('I don\'t have the permissions to make roles, please contact an admin or change my permissions!')
if (!message.member.hasPermission(['MANAGE_WEBHOOKS'])) return message.channel.send('You need to be an admin or webhook manager to use this command.')
if (!message.member.hasPermission(['MANAGE_ROLES'])) return message.channel.send('You need to be an admin or role manager to use this command.')
const avatar = `...`;
const name2 = "name-1.0WOCMD";
let woaID = message.mentions.channels.first();
if(!woaID) return message.channel.send("Channel is nonexistant or command was not formatted properly. Please do s!woa #(channelname)");
let specifiedchannel = message.guild.channels.find(t => t.id == woaID.id);;
specifiedchannel.send('test');
const hook = await woaID.createWebhook(name2, avatar).catch(error => console.log(error))
await hook.edit(name2, avatar).catch(error => console.log(error))
message.channel.send("Please do not tamper with the webhook or else the command implied before will no longer function with this channel.")
setTimeout(function(){
message.channel.send('Please wait...');
}, 10);
setTimeout(function(){
var role = message.guild.createRole({
name: `Name marker ${woaID.name} v1.0`,
color: 0xcc3b3b,}).catch(console.error);
if(role.name == "name marker") {
role.setMentionable(false, 'SBW Ping Set.')
role.setPosition(10)
role.setPermissions(['CREATE_INSTANT_INVITE', 'SEND_MESSAGES'])
.then(role => console.log(`Edited role`))
.catch(console.error)};
}, 20);
var sbwrID = member.guild.roles.find(`Synthibutworse marker ${woaID} v1.0`);
let specifiedrole = message.guild.roles.find(r => r.id == sbwrID.id)
setTimeout(function(){
message.channel.send('Created Role... Please wait.');
}, 100);
message.guild.specifiedchannel.replacePermissionOverwrites({
overwrites: [
{
id: specifiedrole,
denied: ['SEND_MESSAGES'],
allowed: ['VIEW_CHANNEL'],
},
],
reason: 'Needed to change permissions'
});
var member = client.user
var bot = message.client
bot.on('message', function(message) { {
if(message.channel.id == sbwrID.id) {
let bannedRole = message.guild.roles.find(role => role.id === specifiedrole);
message.member.addRole(bannedRole);
}
}})
}};
module.exports = woa;
I expect a command without the TypeError, and the command able to create a role and a webhook (for a marker), and the role is automatically set so that the user that has the role won't be able to speak in the channel, and whoever speaks in the channel will get the role.
The actual output is a TypeError: Cannot read property 'guild' of undefined but a role and webhook are created.
You have var sbwrID = member.guild...
You did not define member. Use message.member.guild...
You can setup a linter ( https://discordjs.guide/preparations/setting-up-a-linter.html ) to find these problems automatically.

Categories