TypeError: Cannot read property 'mentions' of undefined - javascript

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}`)
}
},
}

Related

Node.js - Discord.js v14 - fetching a channel returns undefined / does not work

Attempting to define channel with this code will return undefined.
const { Events, InteractionType, Client, GatewayIntentBits } = require('discord.js');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
],
})
module.exports = {
name: Events.InteractionCreate,
async execute(interaction) {
if(interaction.type == InteractionType.ApplicationCommand){
const command = interaction.client.commands.get(interaction.commandName);
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
await command.execute(interaction);
} catch (error) {
console.error(`Error executing ${interaction.commandName}`);
console.error(error);
}
}
else if(interaction.isAutocomplete()){
const command = interaction.client.commands.get(interaction.commandName);
if(!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try{
await command.autocomplete(interaction);
} catch(error) {
console.error(error);
}
}
else if(interaction.isButton()){
console.log(client.channels);
const channel = await client.channels.fetch('1074044721535656016 ');
console.log(client.channels);
console.log(channel);
}
},
};
const channel = await client.channels.fetch('1074044721535656016 '); Is the main line here.
At the bottom and top of the code is where the important stuff for this question is. I believe I am not properly using the fetch method.
As evidenced by console.log(client.channels); I'm trying to look at the channels cache, but for some reason the channel isn't there, hence I'm using fetch() instead of cache.get().
Thank you for the help!
Other info:
Running npm list shows:
discord.js#14.7.1, dotenv#16.0.3
Node.js v19.6.0
How I got my channel id
Error Message:
ChannelManager {} //<--- this is from the first console.log
node:events:491
throw er; // Unhandled 'error' event
^
Error: Expected token to be set for this request, but none was present
Is the problem because the channel is undefined or because it hasn't resolved yet?
Check your channel ID it may be formatted like:
guild id / channel id
Use interaction.client instead of making a new client object. The interaction already has its own client object with the related properties.

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

Couldn't find a channel after creating it discord.js v13

module.exports = async (msg,arg)=>{
const guildid = msg.guild.id
const guild =msg.guild
const display = msg.guild.channels.cache.find(ch => ch.name=='Total Members')
if(!display){
try {
const channelName='Total Members'
await msg.guild.channels.create(channelName, {
type: "voice", //This create a text channel, you can make a voice one too, by changing "text" to "voice"
permissionOverwrites: [
{
id: msg.guild.roles.everyone, //To make it be seen by a certain role, user an ID instead
allow: ['VIEW_CHANNEL'], //Allow permissions
deny: [ 'SEND_MESSAGES','CONNECT'] //Deny permissions
}
],
})
msg.channel.send('Successfully created the Channel ')
}
catch (error){console.log(error)
msg.channel.send('Couldnt create one ')}
}
const display1 = await msg.guild.channels.cache.find(ch => ch.name=='Total Members')
const display1id = await msg.guild.channels.cache.get(display1.id)
setInterval((guild)=>{
const count = msg.guild.memberCount
const channel = msg.guild.channels.cache.get(display1id)
channel.setName(`Total Members: ${count.toLocaleString()}`);
console.log('Updating Member Count');
},5000)
}
The error:
const display1id = await msg.guild.channels.cache.get(display1.id)
TypeError: Cannot read property 'id' of undefined
Can anyone tell me how to solve this error,
basically this code helps to see the current member of the guild
and it will autoupdate it.
It will create a voice channel if it didn't found any one for showing the member.
The reason it couldn't find the channel is because the channel type for voice is GUILD_VOICE (not just voice) in discord.js v13. That is why it used the default channel type GUILD_TEXT. And text channels can't have capital letters and spaces in their names. It converted the channel name 'Total Members' to 'total-members' and when you tried searching for the channel with .find() it wasn't found, because the channel name was different.
The .find() method returned undefined and you later tried reading a property .id of the returned variable. Thus reading a property .id of undefined.
Also don't use an equal sign when searching for the channel. Use .startsWith() instead, because later you are adding the member count to the channel name.
You can take a look at this:
// ... The variable msg defined somewhere (e.g. as messageCreate callback parameter) ...
const channelName = "Total Members";
let display = msg.guild.channels.cache.find(ch => ch.name.startsWith(channelName));
if(!display) {
try {
display = await msg.guild.channels.create(channelName, {
type: "GUILD_VOICE",
permissionOverwrites: [
{
id: msg.guild.roles.everyone,
allow: ["VIEW_CHANNEL"],
deny: ["SEND_MESSAGES", "CONNECT"]
}
],
});
msg.channel.send(`Successfully created a channel '${channelName}'.`);
}
catch (error) {
console.log(error);
msg.channel.send(`Failed to create a channel '${channelName}'.`);
return;
}
}
setInterval(() => {
const count = msg.guild.memberCount;
display.setName(`${channelName}: ${count.toLocaleString()}`);
console.log("Updating Member Count ...");
}, 5000);

Discord.js Embed error Cannot send an empty message

so I'm trying to make a help command with list of commands showed in embed. My code kinda works but it throws an error "DiscordAPIError: Cannot send an empty message" and I've tried already everything I know and what I've found but I can't fix it.
Here's the code
const Discord = require('discord.js');
const { prefix } = require('../config.json');
module.exports = {
name: 'help',
description: 'List all of my commands or info about a specific command.',
aliases: ['commands', 'cmds'],
usage: '[command name]',
cooldown: 5,
execute(msg, args) {
const data = [];
const { commands } = msg.client;
if (!args.length) {
const helpEmbed = new Discord.MessageEmbed()
.setColor('YELLOW')
.setTitle('Here\'s a list of all my commands:')
.setDescription(commands.map(cmd => cmd.name).join('\n'))
.setTimestamp()
.setFooter(`You can send \`${prefix}help [command name]\` to get info on a specific command!`);
msg.author.send(helpEmbed);
return msg.author.send(data, { split: true })
.then(() => {
if (msg.channel.type === 'dm') return;
msg.reply('I\'ve sent you a DM with all my commands!');
})
.catch(error => {
console.error(`Could not send help DM to ${msg.author.tag}.\n`, error);
msg.reply('it seems like I can\'t DM you! Do you have DMs disabled?');
});
}
const name = args[0].toLowerCase();
const command = commands.get(name) || commands.find(c => c.aliases && c.aliases.includes(name));
if (!command) {
return msg.reply('that\'s not a valid command!');
}
data.push(`**Name:** ${command.name}`);
if (command.aliases) data.push(`**Aliases:** ${command.aliases.join(', ')}`);
if (command.description) data.push(`**Description:** ${command.description}`);
if (command.usage) data.push(`**Usage:** ${prefix}${command.name} ${command.usage}`);
data.push(`**Cooldown:** ${command.cooldown || 3} second(s)`);
msg.channel.send(data, { split: true });
},
};
You should try replace this line :
msg.channel.send(data, { split: true });
with
msg.channel.send(data.join(' '), { split: true }); since your data variable is an array and not a string
The problem is as the error states. You are trying to send an empty message somewhere.
You can try replacing msg.channel.send(data) with msg.channel.send(data.join('\n')), since the data variable is an array.
I don't see why sending an array doesn't work though.

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

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
// ....
}

Categories