Cannot read property 'startsWith' of undefined on Discord.js - javascript

I shall start this question with, i'm a beginner for discord.js, and please help me!
My whole index.js is:
const Discord = require('discord.js');
const client = new Discord.Client();
const botsettings = require('./botsettings.json')
client.once('ready', () => {
console.log("Ready!");
});
client.on("message", async message =>{
const playminecraftwithus = message.guild.channels.cache.find(channel => channel.name === 'play-minecraft-with-us')
if(playminecraftwithus.content.startsWith("IGN:")) {
return;
} else {
message.delete();
}
});
client.login(botsettings.token);
and the problem is in this block:
client.on("message", async message =>{
const playminecraftwithus = message.guild.channels.cache.find(channel => channel.name === 'play-minecraft-with-us')
if(playminecraftwithus.content.startsWith("IGN:")) {
return;
} else {
message.delete();
}
});
but error message is like:
(node:13811) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'startsWith' of undefined | discord.js
If you need anything else, please tell me!

I think you meant to type message.content.startsWith() instead of playminecraftwithus.content.startsWith().

playminecraftwithus.content is undefined.
undefined has no method startsWith()
if you want to avoid an error, you could convert to string and use it.
Try this: (playminecraftwithus.content || "").startsWith()
|| means that when previous one is undefined use next. more details on here

Related

Discord bot to send a message if a certain member goes online

I have been doing my research in the past few days but I couldn't find literally anything. Same in python.
const Discord = require("discord.js")
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] })
const member = client.guilds.cache.get("person_id") // person I want to check
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`)
})
client.on("message", msg => {
if (msg.content === "ping") {
msg.reply("pong");
}
}) // everything worked to this moment
client.on("presenceUpdate", () => {
if (member.presence.status === 'online') {
client.channels.cache.get("channel_id").send("HELLO"); // message i want bot send to the channel if member goes online
}
});
client.login('***')
If I add the GUILD_PRESENCES intent, I receive the following error:
if (member.presence.status === 'online') {
^ TypeError: Cannot read properties of undefined (reading 'presence')
First, you'll need to enable the GUILD_PRESENCES intent if you want to use the presenceUpdate event.
Second, client.guilds.cache.get("person_id") doesn't return a member. guilds.cache is a collection of guilds, not members.
And last, presenceUpdate fires whenever a member's presence (e.g. status, activity) is changed. It means that their presence can be the same (e.g. online), yet the event still fires, so checking if (member.presence.status === 'online') won't work. What you can do instead is to compare the old and new presences. You can find the code below and I've added some comments to make it a bit clearer.
const Discord = require('discord.js');
const client = new Discord.Client({
intents: ['GUILDS', 'GUILD_MESSAGES', 'GUILD_PRESENCES'],
});
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('presenceUpdate', (oldPresence, newPresence) => {
// if someone else has updated their status, just return
if (newPresence.userId !== 'person_id') return;
// if it's not the status that has changed, just return
if (oldPresence.status === newPresence.status) return;
// of if the new status is not online, again, just return
if (newPresence.status !== 'online') return;
try {
client.channels.cache.get('channel_id').send('HELLO');
} catch (error) {
console.log(error);
}
});
client.login('***');

Cannot read property 'prefix' of null discord.js

Hello, I had this problem like 1 week ago, and still can't solve it. So, I'm trying to do per-server prefixes, but when I boot up the bot, it sends the boot-up confirmation message, but then it says the error and it shuts down. Here is the error:
guildPrefixes[guildId] = result.prefix
^
TypeError: Cannot read property 'prefix' of null
I can't see anything wrong here, but anyways, here is the code:
module.exports.loadPrefixes = async (client) => {
await mongo().then(async (mongoose) => {
try {
for (const guild of client.guilds.cache) {
const guildId = guild[1].id
const guildPrefixes = {}
const result = await commandPrefixSchema.findOne({_id: guildId})
guildPrefixes[guildId] = result?.prefix || dprefix
console.log(result)
}
console.log('[INFO] Prefixes have been loaded')
} finally {
mongoose.connection.close()
}
})
}

How do I fix the error "Uncaught TypeError: Cannot read property 'id' of undefined"?

So I was making a selfbot (bc why not) and I finished the first command.
It should work but it doesn't
Here's the code:
const Discord = require("discord.js");
const fs = require("fs");
const ConsoleTitle = require("node-bash-title");
const bot = new Discord.Client({disableEveryone: true});
ConsoleTitle("Slefx")
bot.on("ready", async () => {
console.log("Ready!");
setTimeout( () => {
console.log("Ready to go!");
}, 2000)
})
bot.on("message", async () => {
if(message.content === "!embed sus" ) return message.channel.send("https://embed.rauf.workers.dev/?author=Sussy&title=Bakka%2520B%29&description=Fuck%2520you%2520B%29&image=https%253A%252F%252Fmedia.sketchfab.com%252Fmodels%252F230ec756288e444c8e07f486ef9e8786%252Fthumbnails%252Feb28075b3cbe419bab000bd898b6f6ef%252F9d87472aded94922929162557fcec2d6.jpeg&redirect=https%253A%252F%252Ftherickroll.com");
})
bot.login("hahaucanloginwithmyaccountbecauseireplacedmycookiewiththis")
And here's the error:
Uncaught TypeError: Cannot read property 'id' of undefined
Alright have a good day if u see this :D.
You probably need to check where the error is coming from, as you code does not have any 'id'. Would be better if you could check the logs.

Discord.js v.12 Invalid destructuring assignment target

I'm trying to learn discord.js and I just follow an example code that I found but it errors. This is my code:
const Discord = require('discord.js')
const client = new Discord.Client()
client.on('ready', () => {
var generalChannel = client.channels.cache.get("I already put the valid ID")
generalChannel.send("C'mon dude")
console.log("Connected as " + client.user.tag)
client.user.setActivity("Youtube", {Type: "WATCHING"})
client.guilds.cache.forEach(("guild") => {
console.log(guild.name)
guild.channels.cache.forEach((channel) => {
console.log(' ${channel.name} ${channel.type} ${channel.id}')
})
})
})
client.login("I already put valid token")
This is the error message:
SyntaxError: Invalid destructuring assignment target
Please tell me how to fix it
The problem is you try to use a string in ("guild"). See the double quotes around guild? You don't need them as you want to use the guild variable. You can try this instead:
client.guilds.cache.forEach((guild) => {
console.log(guild.name)
guild.channels.cache.forEach((channel) => {
console.log(' ${channel.name} ${channel.type} ${channel.id}')
})
})

TypeError: Cannot read property 'send' of undefined?

I'm trying to get my discord javascript discord bot to send me a dm using id but it keeps saying:
TypeError: Cannot read property 'send' of undefined.
Any idea?
const Discord = require('discord.js');
const{prefix,token} = require('./config.json');
const bot = new Discord.Client();
bot.once('ready', () => {
console.log(`Ready!`);
});
bot.on('message', message => {
let e = message.content.split(" ");
if(message.content.startsWith(`${prefix}help`))
{
if (message.channel.type == "dm")
{
message.author.send("use !send");
}
}
if(message.content.startsWith(`${prefix}send`))
{
if (message.channel.type == "dm")
{
try{
message.author.send("Message sent");
message.client.users.get("266928832726xxxxxxx").send("someMessage");
}catch(e){console.log("[ERROR]",e)}
}
}
})
bot.login(token);
Okay so what you have to do in order to know what is the problem with send is, is to at first console.log(message) and check if you get the value called author and then check if author has value or method called send.
You const your client as bot const bot = new Discord.Client();
And try get members as message.client.users.get("266928832726xxxxxxx")
Message dont have property client.users so use bot.users.get()
bot.on('message', message => {
let e = message.content.split(" ");
if(message.content.startsWith(`${prefix}help`)){
if (message.channel.type == "dm"){
message.author.send("use !send");
}
}
if(message.content.startsWith(`${prefix}send`)){
if (message.channel.type == "dm"){
message.author.send("Message sent");
bot.users.get("266928832726xxxxxxx").send("someMessage").catch(console.error);
}
}
})

Categories