Can't Convert undefined or null? - javascript

const Discord = require('discord.js');
const randomPuppy = require('random-puppy');
const subreddits = [
"memes",
"DeepFriedMemes",
"bonehurtingjuice",
"surrealmemes",
"dankmemes",
"meirl",
"me_irl",
"funny"
]
exports.exec = (client, message, args, user) => {
var randSubreddit = subreddits[Math.round(Math.random() * (subreddits.length - 1))];
randomPuppy(randSubreddit)
.then(url => {
const embed = new Discord.RichEmbed()
.setFooter(`${randSubreddit} ● Subreddit`)
.setDescription(`[Image URL](${url})`)
.setImage(url)
.setColor(0);
return message.channel.send({ embed });
})
};
Hey guys, left discord coding behind about a year ago and I've come back to this error (title) It was working quite fine a year ago, and now nothing. (Haven't changed anything).
I'm a wee bit confused on how or why this is now happening.
Any help is appreciated as I've got no clue.
Thank you in advance :)
Edit - Not running Discord.js v12 so RichEmbed still applies. :)
[unhandledRejection]
TypeError: Cannot convert undefined or null to object
at Function.entries (<anonymous>)
at module.exports (C:\Users\worrit\Downloads\Peepo_Redacted\Peepo_Revive\node_modules\lowercase-kevs\index.js:5:36)
at normalizeArguments (C:\Users\worrit\Downloads\Peepo_Redacted\Peepo_Revive\node_modules\random-puppy\node_modules\got\index.js:222:5)
at got (C:\Users\worrit\Downloads\Peepo_Redacted\Peepo_Revive\node_modules\random-puppy\node_modules\got\index.js:302:20)
at randomPuppy (C:\Users\worrit\Downloads\Peepo_Redacted\Peepo_Revive\node_modules\random-puppy\index.js:31:12)
at module.exports (C:\Users\worrit\Downloads\Peepo_Redacted\Peepo_Revive\node_modules\random-puppy\index.js:67:16)
at Object.exports.exec (C:\Users\worrit\Downloads\Peepo_Redacted\Peepo_Revive\commands\image-fetch\meme.js:17:9)
at module.exports (C:\Users\worrit\Downloads\Peepo_Redacted\Peepo_Revive\handlers\commandHandler.js:299:34)
[/unhandledRejection]

const Discord = require('discord.js');
const randomPuppy = require('random-puppy');
const subreddits = [
"memes",
"DeepFriedMemes",
"bonehurtingjuice",
"surrealmemes",
"dankmemes",
"meirl",
"me_irl",
"funny"
]
exports.exec = (client, message, args, user) => {
var randSubreddit = subreddits[Math.round(Math.random() * (subreddits.length - 1))];
randomPuppy(randSubreddit)
.then(url => {
const embed = new Discord.RichEmbed()
.setFooter(`${randSubreddit} ● Subreddit`)
.setDescription(`[Image URL](${url})`)
.setImage(url)
.setColor(0);
message.channel.send({embed});
})
};

Issue is on this line. embed is undefined.
return message.channel.send({ embed });
If this was working in the past and only recently stopped working then I suspect it's either one of two things;
One of the subreddits in your array no longer exists, or the api is outdated.
You can debug this by adding a console.log(embed) before the return statement and then one by one, remove each .function() call until embed no longer === undefined.
Might also be worth npm install every package again.

Related

Discord.js 12.0.0 msg.content returning blank

I'm making a stats checker bot in discord.js v12.0.0 because I don't want to deal with slash commands and intents, just wanted this to be a quick little project that I throw together. But, after coding for a while a command I made didn't work, and I decided to console log msg.content to see if that was the issue. It shows as completely blank when I log msg.content, as well as logging msg itself. NO, I am not running a self bot, I read that doing that can also give this issue.
Images:
Code:
import Discord from 'discord.js';
const client = new Discord.Client();
import fetch from 'node-fetch';
client.on('ready', () => {
console.log(`online`);
});
let lb;
async function fet() {
await fetch("https://login.deadshot.io/leaderboards").then((res) => {
return res.json();
}).then((res) => {
lb = res;
})
}
client.on('message', async msg => {
console.log(msg)
let channel = msg.channel.id;
if (msg.author.id == client.user.id) return;
if (channel != 1015992080897679370) return;
await fet();
let r;
for (var x in lb.all.kills) {
if (msg.content.toLowerCase() == lb.all.kills[x].name.toLowerCase()) {
r = lb.all.kills[x].name;
}
}
if (!r) return msg.channel.send('Error: user not found')
})
client.login(token)
Discord enforced the Message Content privileged intent, since September 1st.
Here's the announcement from Discord Developers server (invite)
Source message: Discord Developers #api-announcements
You can fix this, but you do need to use intents...
const client = new Discord.Client({
ws: {
intents: [Discord.Intents.ALL, 1 << 15]
}
})
You also need to flip the Message Content intent switch in developer portal
It's much better to update to version 13+, v12 is deprecated and is easily broken.

problem trying to send a client.reply as an embed Message with discord.js

actually i´m working and learning about discord.js and node.js to make a bot, but i have a simple issue, and i don´t know why the embed messages doesn´t work, i tried with the documentarion examples and code of other devs, but in all cases when i try to send the message to a channel, using client.reply(embed) throws me an error saying me that can send an empty message.
i´m using the last version of discord.js (v13.3.1) and i´m using the basic documentation event and the command handlers (works perfectly if i don´t try to send embeds).
This is my index.js and my help.js files:
//This is my index.js i don´t have problem with this but i include it if there are an issue related with this topic.
const fs = require('fs');
const { Client, Collection, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const { token } = require('./config.json');
client.commands = new Collection();
const commandFiles = fs.readdirSync('./Commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./Commands/${file}`);
client.commands.set(command.data.name, command);
}
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
return interaction.reply({ content: 'Parece que ha ocurrido algun problema con el comando.', ephemeral: true });
}
});
const eventFiles = fs.readdirSync('./Events').filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const event = require(`./Events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}
client.login(token);
Now the help.js , this is going to be a Command, but i don´t wanna only to code the commands using the SlashCommands, because of it i´m triying to create this as an event:
//This is the help command using an event
const { clientId } = require("../config.json");
const { MessageEmbed } = require("discord.js");
//testx is going to store the embed message
const testx = new MessageEmbed().setTitle('Test').setDescription('Test');
module.exports = {
name: 'messageCreate',
execute(client) {
//This condition determines if isn´t a message of the bot, and if the written command is !!help
if (client.author.id !== clientId && client.content === '!!help') {
//if the condition is true, send the embed message
//client.reply(testx); //the problem is here.
console.log(testx);
}
},
};
And this is the error i got from the terminal:
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (C:\Users\ //...and more info of my dirs
if i print the testx const in my console, i can see the two values i setted in the const filled with the text "Test", i don´t know why isn´t work or what i need to take this to work.
Thanks and i appreciate any help.
In V13, embeds must be sent differently.
client.reply({embeds: [testx]});
I also recommend editing client to interaction in your command files as it may be misleading, or to actually pass the client and interaction, as you'll most likely need to access the client at some point.
Also, you seem to be confusing interactions with messages.
Interactions do not have an author property, you must use user or member.
They also do not have a content property, to get an argument you must use interaction.options
You also, as far as I can see, are not actually deploying your commands. It looks like you've merged the V12 and V13 command handler tutorial together. I reccomend reading this tutorial again, and making sure you're doing it properly for V13.

Cannot read properties of undefined (reading 'join') Discord.js

im trying to create my discord music bot, but when i run it. It cannot join my voiceChannel, returning this error: channel_info.channelId.join is not a function. Below, my code:
const Discord = require('discord.js');
const bot = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
const ytdl = require('ytdl-core');
const streamOptions = { seek: 0, volume: 1 };
const botToken = 'mytoken';
bot.login(botToken);
bot.on('ready', () => {
console.log('to olain');
});
bot.on('message', msg => {
if (msg.author.bot) {
return;
}
if (msg.content.toLowerCase().startsWith(';p')) {
const channel_info = msg.member.guild.voiceStates.cache.find(user => user.id == msg.author.id);
if (channel_info.channelId == null) {
return console.log('Canal não encontrado!');
}
console.log('Canal encontrado');
channel_info.channelId.join().then(connection => {
const stream = ytdl('https://www.youtube.com/watch?v=BxmMGnvvDCo', { filter: 'audioonly' });
const DJ = connection.playStream(stream, streamOptions);
DJ.on('end', end => {
channel_info.channelId.leave();
});
})
.catch(console.error);
}
});
There are several issues in this code. Even if we fix some of these issues, this code will still not work due to differences between discord.js v12 and v13. Let's get started.
Issue #1
This is not one of the core issues causing your code to not work, but it's something useful to consider. You are doing this to get the voice state of the message author:
msg.member.guild.voiceStates.cache.find(user => user.id == msg.author.id);
When you could easily do the exact same thing in a much shorter, less-likely-to-produce-errors way:
msg.member.voice;
Issue #2
Now this is a core issue causing your code to not work. In fact, it is causing the error in your question. You are trying to do:
channel_info.channelId.join();
That does not make sense. You are trying to join a channel ID? channelId is just a String of numbers like so: "719051328038633544". You can't "join" that String of numbers. You want to join the actual channel that the member is in, like so:
channel_info.channel.join();
Issue #3
Based on how you are using a channelId property instead of channelID, I assume you are on discord.js v13. Voice channels do not have a .join() method on v13; in fact, discord.js v13 has no support for joining or playing audio in voice channels. You must install the discord.js/voice package in order to join a voice channel in discord.js v13. This is critical. Even if you fix the above two issues, you must solve this third issue or your code will not work (unless you downgrade to discord.js v12).

Discord.js GuildMember#roles appears to sometimes be undefined

I have a function that accepts a user ID, and should return an array of all role IDs the user has, from all guilds that the bot is a part of.
To achieve this I wrote the following code
async getRoleList(userId) {
const guilds = this.client.guilds.cache.array();
const guildRoles = [];
const proms = guilds.map(async (guild) => {
const member = await guild.members.fetch(userId).catch(() => {});
if (!member) return;
const roleCollection = member.roles.cache;
guildRoles.push(roleCollection.array().map((role) => role.id));
});
await Promise.all(proms);
const res = guildRoles.flat();
res.push(userId);
return res;
}
However, I have noticed that on occasion I get the following error: TypeError: Cannot read property 'cache' of undefined
I am not able to replicate this bug reliably, it just seemingly randomly is thrown in production. From what I can tell of the discord.js docs the roles property of GuildMember always be there, and so I do not understand how the GuildMember exists but has no role manager.
Try updating your discord.js version with npm. This might have been fixed.
https://github.com/discordjs/discord.js/issues/1870

Discord.js const guild = member.guild;

Hello Programmers I Have Problem With Discord.js I Made Bot Which Is Says Hello #user But It Doesn't Work
Here Is My Code:
Javascript
const Discord = require("discord.js");
const TOKEN = "private";
const PREFIX = "!";
const newUser = new Discord.Collection();
const talkedRecently = new Set();
var bot = new Discord.Client();
var fortunes =
[
"Yes",
"No",
"Maybe",
"IDK"
];
bot.on("ready", () => {
});
client.on("guildMemberAdd", (member) => {
const guild = member.guild;
newUsers.set(member.id, member.user);
if (newUsers.size > 0) {
const defaultChannel = guild.channels.find(c=> c.permissionsFor(guild.me).has("SEND_MESSAGES"));
const userlist = newUsers.map(u => u.toString()).join(" ");
defaultChannel.send("Hello Creativistian!\n" + userlist);
newUsers.clear();
}
});
});
bot.login(TOKEN);
Does Anyone Know How To Fix It
Replace client.on("guildMemberAdd", (member) => { with this:
bot.on('guildMemberAdd', member => {
Note: as #Noobly387 said, you have an extra });, on line 15, please remove that.
Cheers
To fix your problem remove }); on line 15 just after bot.on("ready", () => {.
In the future, please provide more information on your issue.
Although, your error is that you have an extra unnecessary });.
In the future, be sure to state your question in the title so people can help you easier.
On line 15, you have an extra }); below your bot.on("ready", () => { code. This breaks the code because by ending the bot.on line, the rest of the code below will not work since it becomes just regular functions.
Also, as a side note, I would recommend for you to make your arrays single line if they are small (such as your fortunes array) and also don't space out your code too much or you won't be able to see the small problems such as the one that broke your code.
Replace client.on("guildMemberAdd", (member) => { with this :
bot.on('guildMemberAdd', member => {
PS: on line 15 you have an extra unnecessary });
Use that with ALL THE INTENTS ON.
bot.on("guildMemberAdd", member => {
// Code..
});
That work in discord.jsv12, to install type this command
npm install discord.js#v12

Categories

Resources