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

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.

Related

"DiscordAPIError[40060]: Interaction has already been acknowledged." Throws this when ever i run a command on discord [duplicate]

I am creating a bot using guide by Discord.js, however after like 3 or sometimes 3 commands the bot stops working and i get
discord message
i have tried to restart it many times but after sometime it just stop working again and again
const fs = require('node:fs');
const path = require('node:path')
const { Client, Events, GatewayIntentBits, Collection ,ActionRowBuilder,EmbedBuilder, StringSelectMenuBuilder } = require('discord.js');
const { token } = require('./config.json');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.commands = new Collection();
const commandsPath = path.join(__dirname,'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath,file);
const command = require(filePath);
if('data' in command && 'execute' in command){
client.commands.set(command.data.name,command);
}else{
console.log(`[WARNING] The command at ${filePath} is missing`);
}
}
client.once(Events.ClientReady, () => {
console.log('Ready!');
})
//menu
client.on(Events.InteractionCreate, async interaction => {
if (!interaction.isChatInputCommand()) return;
if (interaction.commandName === 'ping') {
const row = new ActionRowBuilder()
.addComponents(
new StringSelectMenuBuilder()
.setCustomId('select')
.setPlaceholder('Nothing selected')
);
const embed = new EmbedBuilder()
.setColor(0x0099FF)
.setTitle('pong')
.setDescription('Some description here')
.setImage('https://media.istockphoto.com/id/1310339617/vector/ping-pong-balls-isolated-vector-illustration.jpg?s=612x612&w=0&k=20&c=sHlz5sbJrymDo7vfTQIuaj4lbmwlvAhVE7Uk_631ZA8=')
await interaction.reply({ content: 'Pong!', ephemeral: true, embeds: [embed]});
}
});
//======================================================================================================================
client.on(Events.InteractionCreate, async interaction => {
if (!interaction.isChatInputCommand ||
interaction.isButton() ||
interaction.isModalSubmit()) return;
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);
await interaction.reply({content: 'There was an error while executing this command!', ephemeral: true});
}
console.log(interaction);
});
client.login(token);
Error i get in terminal
I wanted this bot to continue to execute commands as long as it's up and running
This is a common error in Discord.JS that occurs when you already replied to an interaction and you attempt to reply again.
From the discord.js discord server:
You have already replied to the interaction.
• Use .followUp() to send a new message
• If you deferred reply it's better to use .editReply()
• Responding to slash commands / buttons / select menus
To fix this error, you can use .followUp() to send another message to the channel or .editReply() to edit the reply as shown above.
You can see the documentation on a command interaction here
Yes the problem is that you cant reply to a slash command more then once in discords api so instead you should use
interaction.channel.send()
or
interaction.editReply()

TypeError: Cannot read property 'mentions' of undefined

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

Unable to write and read values in a database, using Discord.js

I'm trying to allow staff to reply to the last DM using ~reply <message> rather than ~dm <userID> <message>, but firstly, I have to save the user's ID in a database to know who was the last DM user, but I'm facing an ERROR here, I'm confused of why this may be happening, but please note, I'm really new to databases, I'd apricate some help!
My code (Not all, just what I'm using for the command.):
I added ">>" before the line the ERROR is.
const { Client, Collection, Intents, MessageEmbed } = require('discord.js');
const client = new Client({partials: ['MESSAGE', 'CHANNEL', 'REACTION'], ws: { intents: Intents.ALL } });
const Database = require('#replit/database');
const db = new Database();
client.on('message', async message => {
//Dm checker
if (message.channel.type === 'dm') {
>> let lastDM = await db.get(`dm_${message.author.id}`)
if (lastDM === null) lastDm = `dm_NONE`
if (message.author.id == client.user.id) return;
if (message.author.id == '818749579369512978') return message.channel.send("This chat has been Blacklisted by the developer (<#"+ BOT_OWNER +">)");
const embed1 = new MessageEmbed()
.setTitle("New message!")
.setAuthor(`Name: \`${message.author.username}\` ID: \`${message.author.id}\` `)
.setColor("GRAY")
.setFooter("Dm message")
.addField("Message:", `\`\`\`${message.content}\`\`\``, false);
const embed2 = new MessageEmbed()
.setTitle("New reply!")
.setAuthor(`Name: \`${message.author.username}\` ID: \`${message.author.id}\` `)
.setColor("GRAY")
.setFooter("Dm reply")
.addField("Reply:", `\`\`\`${message.content}\`\`\``, false);
if (lastDM === `dm_${message.author.id}`) {
client.channels.cache.get("920895881656532992").send(`You got a reply!`, embed2)
console.log(lastDM)
} else {
await db.set(`dm_${message.author.id}`).then(
client.channels.cache.get("920895881656532992").send(`I was DMed!`, embed1),
console.log(lastDM)
)
}
}
The ERROR:
(node:703) UnhandledPromiseRejectionWarning: SyntaxError: Failed to parse value of dm_612110791683866644, try passing a raw option to get the raw value
at /home/runner/DwaCraft-Main-bot-Fixed/node_modules/#replit/database/index.js:36:17
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async Client.get (/home/runner/DwaCraft-Main-bot-Fixed/node_modules/#replit/database/index.js:20:12)
at async Client.<anonymous> (/home/runner/DwaCraft-Main-bot-Fixed/main.js:116:18)
(node:703) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
Note: I'm using replit's databases.
I'm answering my own question as I found a way to do it, but I still don't get what the Error is as anything else works fine, anyway, I soon realized that my code really doesn't make since, so I fixed it, here is the code:
const { MessageEmbed } = require('discord.js');
const Database = require('#replit/database');
const db = new Database();
client.on('message', async message => {
//Dm checker
if (message.channel.type === 'dm') {
let lastDM = await db.get(`lastDM`)
if (!lastDM) lastDM = `NONE`
if (message.author.id == client.user.id) return;
if (message.author.id == '818749579369512978') return message.channel.send("This chat has been Blacklisted by the developer (<#"+ BOT_OWNER +">)");
const embed = new MessageEmbed()
.setTitle("New message!")
.setAuthor(`Name: \`${message.author.username}\` ID: \`${message.author.id}\` `)
.setColor("GRAY")
.setFooter("Dm message")
.addField("Message:", `\`\`\`${message.content}\`\`\``, false);
await db.set(`lastDM`, message.author.id).then(
client.channels.cache.get("920895881656532992").send(`Someone messaged me.`, embed),
console.log(lastDM)
)
}
And reply command:
const { MessageEmbed } = require('discord.js');
const Database = require('#replit/database');
const db = new Database();
module.exports = {
name: 'reply',
category: 'Owner',
description: 'Replys to last DM.',
aliases: [],
usage: 'Reply <message>',
userperms: ['BOT_OWNER'],
botperms: [],
run: async (client, message, args) => {
if (message.author.bot) return;
let lastDM = await db.get(`lastDM`);
let msg = args.slice(0).join(' ')
if (!lastDM) return message.channel.send("There was no any resent DMs.")
if (!msg) return message.channel.send("I can't send air, please state a message.")
if (!isNaN(lastDM)) {
client.users.cache.get(lastDM).send(msg)
.catch (err => {
return message.channel.send("Failed to send DM, as the user has blocked me or they have DMs closed!")
})
}
}
}
I wish I somehow helped someone that uses replit's databases

MongoServerSelectionError: getaddrinfo ENOTFOUND at Timeout._onTimeout

So you may have seen this question type somewhere else. but the thing here is I tried all of the things we need to do according to docs and saw other posts with similar errors but still my error is not fixed. So I use keyv and use MongoDB atlas as storage adapter in this code, but the error is from MongoDB. Also, there is no error in the "keyv" because it works for other people, there is error in the MongoDB
So now I will list whatever I tried:
1. Made sure there is IP access
2. The userid and passcode are correct
3. The MongoDB atlas is running
4. Read the docs and code multiple times
5. If u think adding the +srv with the code will fix the error, it won't, it doesn't work with keyql idk why also it is not present in many codes, I already tried it
So this is the code
const { Client, Intents, MessageEmbed, Collection } = require('discord.js');
let client = new Client({ intents: [Intents.FLAGS.GUILDS,Intents.FLAGS.GUILD_MESSAGES] });
const dotenv = require('dotenv');
const Keyv = require('keyv');
const keyv = new Keyv('mongodb://Discord:password#cluster0.auifa.mongodb.net/Cluster0');
dotenv.config();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('messageCreate', async (msg) => {
if (msg.author.bot) return;
let number = msg.content.split(' ')[1];
if (msg.content === '!ping') {
msg.channel.send('ping!')
}
// Use like const prefix = await getGuildPrefix(); `
const getGuildPrefix = async () => {
const prefixMap = await keyv.get('prefix');
return prefixMap ?. [msg.guild.id] || "!"
}
// Sets the prefix to the current guild.
const setGuildPrefix = async (prefix) => {
let prefixMap = await keyv.get('prefix');
if (!prefixMap)
{
prefixMap = "!";
}
prefixMap[msg.guild.id] = prefix;
await keyv.set('prefix', `${prefixMap}`);
}
let prefix = await getGuildPrefix();
// Get prefix command.
if ((msg.content === `${process.env.prefix}prefix`) || (msg.content === `${prefix}prefix`)) {
msg.channel.send(`Your server prefix is ${prefix}`)
}
// Change prefix command
const commandPrefix = await getGuildPrefix();
if ((msg.content.startsWith(`${process.env.prefix}setprefix`)) || (msg.content.startsWith(`${commandPrefix}setprefix`))) {
const newPrefix = number;
if (newPrefix.length === 0) {
msg.channel.send(`Please enter a valid prefix`);
}
await setGuildPrefix(newPrefix)
msg.channel.send(`Your server prefix is now '${newPrefix}'`);
}
})
client.login(process.env.token);
And this is the error message
Keyv connection error: MongoServerSelectionError: getaddrinfo ENOTFOUND cluster0.auifa.mongodb.net
at Timeout._onTimeout (D:\javascript\node_modules\mongojs\node_modules\mongodb\lib\core\sdam\topology.js:438:30)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7) {
reason: TopologyDescription
Connection string does not look like an Atlas one.
It has to be something like: mongodb+srv://<username>:<password>#cluster0.auifa.mongodb.net/YOUR-DB
Login to your Atlas account then:
Go to Databases page
Click on Connect button
Choose "Connect your application"
Copy your connection string
Docs about Mongo Atlas connection: https://docs.atlas.mongodb.com/connect-to-cluster/#connect-to-a-cluster

Discord.js UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send an empty message

Ok, so I just started working on a discord bot and implemented a command handler, and I immediately ran into some problems.
const Discord = require("discord.js");
module.exports = {
name: "kick",
description: "Kicks the mentioned user",
execute(message, args) {
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
try {
const kickEmbed = new Discord.RichEmbed()
.setTitle("You were Kicked")
.setDescription("You were kicked from Bot Testing Server.");
user.send({ kickEmbed }).then(() => {
member.kick();
});
} catch (err) {
console.log("failed to kick user");
}
}
}
};
when i execute the kick command in my server, I get the following error
UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send an empty message
I can't seem to find anything wrong with the code so, where's the error
When sending an embed that uses the Discord Rich Embed builder you don't need to use the curly brackets.
Instead of user.send({ kickEmbed }) you should do user.send(kickEmbed). I ran into that issue before and it helped in my case.

Categories