Discord.js v.12 Invalid destructuring assignment target - javascript

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

Related

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

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

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

When trying to access the "pricePerUnit" in the hypixel api, i get the error: TypeError: Cannot read property 'pricePerUnit' of undefined

{"success":true,"lastUpdated":1598982272495,"products":{"BROWN_MUSHROOM":{"product_id":"BROWN_MUSHROOM","sell_summary":[{"amount":160,"pricePerUnit":13.9,"orders":1},{"amount":28503,"pricePerUnit":13.8,"orders":2},{"amount":71483,"pricePerUnit":13.4,"orders":3},
this is what the api says so i assumed that i could directly get the "pricePerUnit. But I am getting the error TypeError: Cannot read property 'pricePerUnit' of undefined
My code is: ```client.on("message", message => {
if (message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if (command === "bazaar") {
let product = args[0];
fetch(`https://api.hypixel.net/skyblock/bazaar/product?key=${key}`)
.then(result => result.json())
.then(({ BROWN_MUSHROOM }) => {
// Log the player's username
message.reply(BROWN_MUSHROOM.pricePerUnit)
})
}
})```
anybody know how to help?
Try modifying your last block to this:
.then(({ products: { BROWN_MUSHROOM } }) => {
// Log the player's username
message.reply(BROWN_MUSHROOM.pricePerUnit)
})
since BROWN_MUSHROOM appears to be under products field.

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.

Can I create a channel at bot on startup?

I'm trying to create a channel with Discord.js using the message.guild.createChannel function. But, I need to send a message on the server for the bot to do that. How can I do it at the bot startup ? I think I need to implement my code into the bot.on('ready', () => { function, but I don't know how. Thanks !
This is my code:
var firstLog = false;
bot.on('message', msg => {
if (!firstLog) {
msg.guild.createChannel('raidprotect-logs', "text")
} firstLog = true;
});
You need use somethink like this if you want use it on message
var firstLog = false;
bot.on('message', msg => {
if (!firstLog) msg.guild.createChannel('new-general', { type: 'text' })
firstLog = true;
});
If you want you use it when bot start , you need get guild fist.
bot.on('ready', () => {
let myGuild = bot.guilds.get('GUILDID HERE')
myGuild.createChannel('new-general', { type: 'text' })
.then(console.log(“done”))
.catch(console.error);
});
You're almost there. Here's how you do it
bot.on('ready', () => {
guild.createChannel('new-general', { type: 'text' })
.then(console.log)
.catch(console.error);
});
As they suggested here
You can find more help on Discord.js Official discord server

Categories