Discord.js Cannot read property 'fetch' of undefined - javascript

I just started developing with Javascript and Discord.js a few days ago and got this Error:
TypeError: Cannot read property 'fetch' of undefined
I am trying to make a poll command. This is the Code (I deleted everything else and just wanted it to get the channel out of it):
const Discord = require('discord.js');
const client = new Discord.Collection();
module.exports = {
name: 'poll',
description: 'can make polls',
cooldown: 5,
usage: '[ask] [emoji1] [emoji 2]',
aliases: ['createpoll'],
execute(message, args) {
client.channels.fetch('744582158324072468')
.then (channel => console.log(channel.name))
.catch(console.error);
// message.react(args[1]).then(() => message.react(args[0]));
},
};
I already tried to put it in the Main.js which works:
client.on('message', message => {
if (message.content.startsWith('.poll')) {
client.channels.fetch('744582158324072468')
.then (channel => console.log(channel.name))
.catch(console.error);
}
}
But I want it ion the correct file. This is what I have above the client.on('message', etc.
const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token, tprefix, welcomechannel, guildID } = require('./config.json');
const client = new Discord.Client({
fetchAllMembers: true,
});
client.commands = new Discord.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.name, command);
}
const cooldowns = new Discord.Collection();
// update
client.once('ready', () => {
console.log(`${tprefix}Paperbot got geupdated.`);
});
Of course, I googled around and read the documentation but that didn't help.
As I said, I am new to programming and it could be an easy fix, but I would love to fix this problem as fast as possible, thank you very much.

Figured it out. I just needed to add message to client.channels.fetch
Now it is working with this code:
const { tprefix, pollchannel, modchannel } = require('../config.json');
module.exports = {
name: 'poll',
description: 'can make polls',
cooldown: 5,
usage: '[ask] [emoji1] [emoji 2]',
aliases: ['createpoll'],
execute(message) {
message.client.channels.fetch('744582158324072468')
.then (channel => console.log(channel.name))
.catch(console.error);
},
};
Thank you #Jack Towns

You assign client to a new Discord collection at the top of your code.
You are essentially doing Collection.channels.fetch instead of client.channels.fetch.
You need to pass the client from your main file to your commands.

Related

Sending a random sound file as a response not working

I'm trying to make a talking ben command for my bot, and it just won't work. I want the bot to send an audio clip as a response whenever someone asks a question, and if they don't specify a question, the bot will send a "ben" sound effect. No response to the command in Discord at all.
Here's the code:
ben.js:
const Discord = require('discord.js');
const yes = new Discord.MessageAttachment(
'https://soundboardguy.com/sounds/talking-ben-yes_scachnw/',
);
const no = new Discord.MessageAttachment(
'https://soundboardguy.com/sounds/talking-ben-no/',
);
const laugh = new Discord.MessageAttachment(
'https://soundboardguy.com/sounds/talking-ben-laugh/',
);
const uhh = new Discord.MessageAttachment(
'https://www.101soundboards.com/sounds/726466-uhh',
);
const ben = new Discord.MessageAttachment(
'https://www.101soundboards.com/sounds/726450-ben',
);
module.exports = {
name: 'ben',
description: 'talking ben command',
async execute(client, message, args) {
if (!args[0]) return ben;
let benreplies = [yes, no, laugh, uhh];
let result = Math.floor(Math.random() * benreplies.length);
message.channel.send(replies[result]);
},
};
main.js:
const Discord = require('discord.js');
const client = new Discord.Client({ intents: ['GUILDS', 'GUILD_MESSAGES'] });
const prefix = '.';
const fs = require('fs');
client.commands = new Discord.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.name, command);
}
client.once('ready', () => {
console.log('Blueberry bot is online!');
});
client.on('messageCreate', (message) => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ + /);
const command = args.shift().toLowerCase();
// ...
else if (command === 'ben') {
client.commands.get('ben').execute(message, args, Discord);
}
});
First, you need to make sure that the links to the sound files are valid. You're currently using links pointing to an HTML page, not the mp3 files.
Second, you need to use an object with a files property to send a file. See the MessageOptions. files will also need to be an array. The following will work:
let sounds = [
{
id: 'ben',
link: 'https://soundboardguy.com/wp-content/uploads/2022/03/talking-ben-ben.mp3',
},
{
id: 'laugh',
link: 'https://soundboardguy.com/wp-content/uploads/2022/02/Talking-Ben-Laughing-Sound-Effect-1.mp3',
},
{
id: 'no',
link: 'https://soundboardguy.com/wp-content/uploads/2022/03/Talking-Ben-No-Sound-Effect.mp3',
},
{
id: 'uhh',
link: 'https://soundboardguy.com/wp-content/uploads/2021/06/huh-uhh.mp3',
},
{
id: 'yes',
link: 'https://soundboardguy.com/wp-content/uploads/2022/03/talking-ben-yes_SCacHNW.mp3',
},
];
let randomSound = sounds[Math.floor(Math.random() * sounds.length)];
message.channel.send({
files: [new MessageAttachment(randomSound.link, `${randomSound.id}.mp3`)],
});
The links are incorrect, you used the links that have a user interface, where the user can see the audio, login, see "related" audios etc.. not the actual source audio mp3 file.
For example, that link : https://www.101soundboards.com/sounds/726450-ben is incorrect. Replace it with https://www.101soundboards.com/storage/board_sounds_rendered/726450.mp3 Do the exact same thing with every file and you're ready to go !

How to get guild object using guild ID

I want to change the icon of a specific guild that my bot is in. To do so, I need to use the guild.setIcon() method. I already have the guild's ID but I don't know how I should go about turning it into an object that I can use.
The guildId constant is stored as a string in config.json.
Here is my index.js, where I'm trying to run the code.
// Require the necessary discord.js classes
const { Client, Collection, Intents } = require("discord.js");
const { token, guildId } = require("./config.json");
const fs = require("fs");
// Create a new client instance
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
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);
}
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.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);
await interaction.reply({
content: "There was an error while executing this command!",
ephemeral: true,
});
}
});
client.login(token);
const myGuild = client.guilds.cache.get(guildId)
myGuild.setIcon("./images/image.png");
The error I get is
myGuild.setIcon("./images/image.png");
^
TypeError: Cannot read properties of undefined (reading 'setIcon')
You need to do this in an event. No guilds are cached until the client is ready
client.on("ready", async () => {
const myGuild = client.guilds.cache.get(guildId)
await myGuild.setIcon("./images/image.png")
})
Your issues comes from the fact that you're trying to get the guild from your bot cache, but he doesn't have it in it's cache
First, you have to wait for your bot to be successfully connected
Then, you're not supposed to read from the cache directly, use the GuildManager methods (here you need fetch)
to summarize, replace the 2 lasts lines of your index.js by
client.on("ready", async () => {
const myGuild = await client.guilds.fetch(guildId)
myGuild.setIcon("./images/image.png")
})

How to Fix the 'set is undefined' error from the following code? Discord.js v13

This is the code that I used. Basically I am making command handler in my bot after discord.js v13 released. After running the code it shows some error(set is undefined).
command.js
const {readdirSync} = require('fs');
const ascii = require('ascii-table')
let table = new ascii("Commands");
table.setHeading('Command', ' Load status');
module.exports= (client) => {
readdirSync('./commands/').forEach(dir => {
const commands = readdirSync(`./commands/${dir}/`).filter(file => file.endsWith('.js'));
for(let file of commands){
let pull = require(`../commands/${dir}/${file}`);
if(pull.name){
client.commands.set(pull.name, command);
table.addRow(file,'✅')
} else {
table.addRow(file, '❌ -> Missing a help.name, or help.name is not a string.')
continue;
}if(pull.aliases && Array.isArray(pull.aliases)) pull.aliases.forEach(alias => client.aliases.set(alias, pull.name))
}
});
console.log(table.toString());
}
The error image:
Firstly you have to define client, on top of your code add this:
const { Client, Intents } = require('discord.js');
You have to also add intents since it's necessary in discord.js v13
Below add also this:
const client = new Client({ intents: [
"GUILDS",
"GUILD_MEMBERS",
]
});
Here you have to specify your needed intents, you can find list of them here: https://discord.js.org/#/docs/main/stable/class/Intents?scrollTo=s-FLAGS

How can I make my bot find the last message that matches a criteria, e.x ("joe") and send who sent it?

I am using node.js for my bot, and I, like the question stated, need to find the last message in the channel that matches the criteria specified in the code. For example, the command would say, ?joe, and it would find the last message that has "joe" in it, and return the member that sent it. In the server I am going to use it in, the message is very frequent, so I don't think it will hit any message reading limitations.
I did the code in main.js and the commands in separate js files, like this,
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = '?'
const fs = require('fs');
client.commands = new Discord.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.name, command)
}
client.once('ready', () => {
console.log('AbidBot is online!!');
});
client.on('message', message =>{
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if(command === 'ping'){
client.commands.get('ping').execute(message, args);
}
});
client.login();
The ping command looks like this:
module.exports = {
name: 'ping',
description: "this is a ping command!",
execute(message, args){
message.channel.send('pong!')
}
}
Thanks for your help!
EDIT #1
Thanks, but it does not seem to be working for me #Lioness100. Can you take a look?
module.exports = {
name: 'joe',
description: "find joe",
execute(message, args){
message.channel.messages.fetch().then((messages) => {
// find the message that has 'joe' in it
const author = messages.find({ content } => content.includes(' joe ')).author.tag;
message.channel.send(author);
}
});
}
You can use MessageManager.fetch() and Collection.find()
// fetch the last 100 messages in the channel
message.channel.messages.fetch({ limit: 100 }).then((messages) => {
// find the message that has 'joe' in it
const msg = messages.find(({ content }) => content.includes(' joe '));
return msg
? message.channel.send(msg)
: message.channel.send('None of the last 100 messages include the word `joe`!');
});

How to fix Discord API: Unknown Message error?

I'm trying to make a meme command but whenever I try to use it I get this error "DiscordAPIError: Unknown Message".
This was working earlier but when I came back to my PC it started glitching out.
Here's my code
const { RichEmbed } = require("discord.js");
const randomPuppy = require("random-puppy");
const usedCommandRecently = new Set();
module.exports = {
name: "meme",
aliases: ["memes", "reddit"],
category: "fun",
description: "Sends a random meme",
run: async (client, message, args) => {
if (message.deletable) message.delete();
var Channel = message.channel.name
//Check it's in the right channel
if(Channel != "memes") {
const channelembed = new RichEmbed()
.setColor("BLUE")
.setTitle(`Use me in #memes`)
.setDescription(`Sorry ${message.author.username} this command is only usable in #memes !`)
return message.channel.send(channelembed);
}
//Check cooldown
if(usedCommandRecently.has(message.author.id)){
const cooldownembed = new RichEmbed()
.setColor("GREEN")
.setTitle("Slow it down, pal")
.setDescription(`Sorry ${message.author.username} this command has a 30 second cooldown per member, sorry for any inconvenice this may cause`)
message.channel.send(cooldownembed)
} else{
//Post meme
const subReddits = ["dankmeme", "meme", "me_irl"];
const random = subReddits[Math.floor(Math.random() * subReddits.length)];
const img = await randomPuppy(random);
const embed = new RichEmbed()
.setColor("RANDOM")
.setImage(img)
.setTitle(`From /r/${random}`)
.setURL(`https://reddit.com/r/${random}`);
message.channel.send(embed);
}
}
}
Im not sure, but maybe problem in your require block.
const { RichEmbed } = require("discord.js");
the right way its:
const Discord = require("discord.js");
let cooldownembed = new Discord.RichEmbed();
and why you use return here
return message.channel.send(channelembed);

Categories

Resources