How can i get my discord.js v14 bot to stop saying "The application did not respond" if the slash command works? - javascript

i have multiple commands that work perfectly fine but i always get this message in return.
here is the code for that command. it works perfectly fine i guess it just doesn't respond to the interaction even though i feel like it should be?
how can i get it to ignore this message or reply properly?
const Discord = require('discord.js');
const { EmbedBuilder, SlashCommandBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
// command name
.setName('totalfrozencheckouts')
// command description
.setDescription('Add up every message in the frozen checkouts channel after a specific message ID')
.addStringOption(option =>
option.setName('messageid')
.setDescription('The message ID')
.setRequired(true)),
async execute(interaction) {
const channel = '<#' + process.env.FROZENCHECKOUTS + '>';
const messageId = interaction.options.getString("messageid");
// Check if the channel mention is valid
if (!channel.startsWith('<#') || !channel.endsWith('>')) {
return interaction.channel.send(`Invalid channel mention. Please use the format: ${this.usage}`);
}
// Extract the channel ID from the channel mention
const channelId = channel.slice(2, -1);
// Try to fetch the messages from the requested channel and message ID
interaction.guild.channels.cache.get(channelId).messages.fetch({ after: messageId })
.then(messages => {
// Create an array of the message contents that are numbers
const numbers = messages.map(message => message.content).filter(content => !isNaN(content));
// Check if there are any messages
if (numbers.length === 0) {
return interaction.channel.send(`No messages were found in ${channel} after message ID https://discord.com/channels/1059607354678726666/1060019655663689770/${messageId}`);
}
// Adds up the messages
const sum = numbers.reduce((accumulator) => accumulator + 1, 1);
// Create an embed object
const embed = new EmbedBuilder()
.setColor(0x4bd8c1)
.setTitle(`Total Checkouts in #frozen-checkouts for today is:`)
.addFields(
{name: 'Total Checkouts', value: sum.toString() , inline: true},
)
.setThumbnail('https://i.imgur.com/7cmn8uY.png')
.setTimestamp()
.setFooter({ text: 'Frozen ACO', iconURL: 'https://i.imgur.com/7cmn8uY.png' });
// Send the embed object
interaction.channel.send({embeds: [embed]});
})
.catch(error => {
console.error(error);
interaction.channel.send('An error occurred while trying to fetch the messages. Please try again later.');
});
}
}
I don't really know what to try because it literally works I just don't know how to get it to either ignore that message or respond with nothing. It doesn't break the bot its just annoying to look at.

Use interaction.reply instead of interaction.channel.send to reply.

Related

.addArgument is not a function Discord bot

Here is my Discord command module code, for some reason this is spitting out that .addArgument is not a function.
const Discord = require('discord.js');
const { SlashCommandBuilder } = require('#discordjs/builders');
data = new SlashCommandBuilder()
.setName('purge')
.setDescription('Purges a number of messages from the channel.')
.addArgument('number', 'The number of messages to purge.')
.addArgument('channel', 'The channel to purge messages from.')
.setExecute(async (interaction, args) => {
const channel = interaction.guild.channels.cache.find(c => c.name === args.channel);
if (!channel) return interaction.reply('Channel not found.');
const messages = await channel.messages.fetch({ limit: args.number });
await channel.bulkDelete(messages);
interaction.reply(`Purged ${messages.size} messages.`);
}
);
It just gives me this:
TypeError: (intermediate value).setName(...).setDescription(...).addArgument is not a function
The reason you are getting this error is because there is nothing called .addArgument() in the SlashCommandBuilder. If you want to add arguments like numbers or channels, you need to use .addNumberOption() or .addChannelOption(). The way you will need to use to add a channel and number option is like this:
.addNumberOption(option => {
return option
.setName('number') // Set the name of the argument here
.setDescription('The number of messages to purge.') // Set the description of the argument here
.setRequired() // This is optional. If you want the option to be filled, you can just pass in true inside the .setRequired() otherwise you can just remove it
})
.addChannelOption(option => {
return option
.setName('channel')
.setDescription('The channel to purge messages from.')
.setRequired()
})
You can learn more about slash commands and options here => Options | discord.js

How do I fetch the creator of a channel in discord?

bot.on('channelCreate', async channel => {
if (!channel.guild) return;
const fetchedLogs = await channel.guild.fetchAuditLogs({
limit: 1,
type: 'CHANNEL_CREATE',
});
const logbook = channel.guild.channels.cache.get("ChannelID")
const deletionLog = fetchedLogs.entries.first();
if (!deletionLog) return logbook.send(`A channel was updated but no relevant autid logs were found`);
const { executor, user } = deletionLog;
if (user.id) {
logbook.send(`${executor.tag} created a channel`);
} else {
logbook.send(`A channel was created but idk who did.`);
}
});
I am a newbie when it comes to fetching actions through Discord Audit Logs; so I am experimenting and somehow came up with this code. However, when I create a channel, it does not send any messages saying that a channel has been created by #user. I have no idea what my next step will be. All I wanted to do was to know who created the channel.
Discord.JS: v12.2.0
client.on("channelCreate", async channel => {
if (!channel.guild) return false; // This is a DM channel.
const AuditLogFetch = await channel.guild.fetchAuditLogs({limit: 1, type: "CHANNEL_CREATE"}); // Fetching the audot logs.
const LogChannel = client.channels.cache.get("722052103060848664"); // Getting the loggin channel. (Make sure its a TextChannel)
if (!LogChannel) return console.error(`Invalid channel.`); // Checking if the channel exists.
if (!AuditLogFetch.entries.first()) return console.error(`No entries found.`);
const Entry = AuditLogFetch.entries.first(); // Getting the first entry of AuditLogs that was found.
LogChannel.send(`${Entry.executor.tag || "Someone"} created a new channel. | ${channel}`) // Sending the message to the logging channel.
});
If the code I provided is not working, please make sure the bot has access to view AuditLogs.

Bot reacting to emojis

So, I got my code and it works just as I want it to. the message pops up changes everything, it's perfect.
Now I want to add so the bot knows when I react to its message and then does something else. What I mean is: bot sends a message with reacts, and whenever some user clicks the reaction something happens, but I have no idea how to do that.
I've tried many things like if (reaction.emoji.name === ':bomb:'), but multiple errors popped out and I didn't know how to fix that. Here's the code:
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
var lastbuffer;
lastbuffer = 0;
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
client.on('message', message => {
if(message.content.startsWith(`${prefix}start`)){
message.delete()
setInterval(function(){
lastbuffer++;
const Buffer = new Discord.MessageEmbed()
.setColor('#8300FF')
.setTitle("**It's time to check buffers!**")
.setDescription("**It's been **" + "`" + lastbuffer + " Hour" + "`" + "** since last buffercheck, <#&675688526460878848>**." + " **Check now!**")
.setThumbnail('https://art.pixilart.com/88534e2f28b65a4.png')
.setFooter('WEEEEEWOOOOO')
.setTimestamp();
client.channels.cache.get("700296799482675230").send(Buffer).then(msg => {
msg.react('✅');
msg.react('💣');
msg.delete({timeout: 4000})
});
}, 5000)
}
});
client.login(token);
You are going to have to use a ReactionCollector using the createReactionCollector() method.
You can follow this guide to under ReactionCollectors better
You need to use a reaction collector.
client.channels.cache.get("700296799482675230").send(Buffer).then(async msg => {
// I'm using await here so the emojis react in the right order
await msg.react('✅');
await msg.react('💣');
msg.awaitReactions(
// Discord.js v12:
/* ({emoji}, user) => ['✅', '💣'].includes(emoji.name) && user.id === message.author.id,
{max: 1, time: 4000, errors: ['time']} */
// Discord.js v13:
{
// only collect the emojis from the message author
filter: ({emoji}, user) => ['✅', '💣'].includes(emoji.name) && user.id === message.author.id,
// stop collecting when 1 reaction has been collected or throw an error after 4 seconds
max: 1,
time: 4000,
errors: ['time']
}
)
.then(collected => {
const reaction = collected.first()
// do something
})
.catch(() => {
// I'm assuming you want to delete the message if the user didn't react in time
msg.delete()
})
What this code does:
Sends the embed (Buffer) to the channel with the id 700296799482675230
Reacts with the ✅ and then the 💣 emojis on the message with the embed
Waits for a ✅ or 💣 reaction from the author of the original message
If the user reacts within 4 seconds, runs the // do something part
If the user does not react within 4 seconds, deletes the message with the embed

discord.js get message's id and delete it

When a user joins the server, the bot sends a welcome message, i want to take that welcome message's ID and make the bot delete it if the users leaves after he joins. I tried to save the message's id in a variable and make the bot delete the message when the user leaves but without success. I already took a look at the docs, but I really can't understand how to make it.
Define an object to hold the welcome messages by guild and user. You may want to use a JSON file or database (I'd highly recommend the latter) to store them more reliably.
When a user joins a guild...
Send your welcome message.
Pair the the message's ID with the user within the guild inside of the object.
When a member leaves the guild...
Fetch their welcome message.
Delete the message from Discord and the object.
Example setup:
const welcomeMessages = {};
client.on('guildMemberAdd', async member => {
const welcomeChannel = client.channels.get('channelIDHere');
if (!welcomeChannel) return console.error('Unable to find welcome channel.');
try {
const message = await welcomeChannel.send(`Welcome, ${member}.`);
if (!welcomeMessages[member.guild.id]) welcomeMessages[member.guild.id] = {};
welcomeMessages[member.guild.id][member.id] = message.id;
} catch(err) {
console.error('Error while sending welcome message...\n', err);
}
});
client.on('guildMemberRemove', async member => {
const welcomeChannel = client.channels.get('channelIDHere');
if (!welcomeChannel) return console.error('Unable to find welcome channel.');
try {
const message = await welcomeChannel.fetchMessage(welcomeMessages[member.guild.id][member.id]);
if (!message) return;
await message.delete();
delete welcomeMessages[member.guild.id][member.id];
} catch(err) {
console.error('Error while deleting existing welcome message...\n', err);
}
});
To do this you would have to store the id of the welcome message and the user that it is tied to (ideally put this in an object). And when the user leaves you would use those values to delete that message.
Example code:
const Discord = require('discord.js');
const client = new Discord.Client();
const welcomeChannel = client.channels.find("name","welcome"); // Welcome is just an example
let welcomes = [];
client.on('message', (message) => {
if(message.channel.name === 'welcome') {
const welcomeObj = { id: message.id, user: message.mentions.users.first().username };
welcomes.push(welcomeObj);
}
});
client.on('guildMemberRemove', (member) => {
welcomes.forEach(welcome, () => {
if(welcome.user === member.user.username) {
welcomeChannel.fetchMessage(welcome.id).delete();
}
});
});
This only works if the welcome message includes a mention to the user so make sure that's in the welcome message.
Also I can't test this code myself at the moment so let me know if you encounter any problems.

Discord bot - Purge command not working discord.js-commando

I have created a discord bot recently using node js which when I do !purge, responds with Unknown command, do !help to view a list of command but after saying it, it is purging the messages. That is, it works well but posting that error message. I don't know what's the problem please help me
const commando = require('discord.js-commando');
const bot = new commando.Client();
const prefix = '!';
bot.on('message', message => {
let msg = message.content.toUpperCase();
let sender = message.author;
let cont = message.content.slice(prefix.length).split(" ");
let args = cont.slice(1);
if (msg.startsWith(prefix + 'PURGE')) {
async function purge() {
message.delete();
if (isNaN(args[0])) {
message.channel.send('Please input a number of messages to be deleted \n Syntax: ' + prefix + 'purge <amount>');
return;
}
const fetched = await message.channel.fetchMessages({limit: args[0]});
console.log(fetched.size + ' messages found, deleting...');
// Deleting the messages
message.channel.bulkDelete(fetched)
.catch(error => message.channel.send(`Error: ${error}`));
}
purge();
}
});
bot.login('MY BOT TOKEN HERE');
Right now you're using the discord.js-commando library. Any reason you decided to use that library? It looks like you're just using standard discord.js functions like bot.on, message.channel.send, message.channel.fetchMessages, message.channel.bulkDelete...
You should be good just useing the standard discord.js library, starting your code with this:
const Discord = require('discord.js');
const bot = new Discord.Client();
You can find this code on the main "Welcome" page of Discord.js
Edit:
I'm still not sure why you're using discord.js-commando, but that doesn't matter. Here's an example command I came up with using the discord.js-commando library:
const commando = require('discord.js-commando');
class PurgeCommand extends commando.Command {
constructor(client) {
super(client, {
name: 'purge',
group: 'random', // like your !roll command
memberName: 'purge',
description: 'Purge some messages from a Text Channel.',
examples: ['purge 5'],
args: [
{
key: 'numToPurge',
label: 'number',
prompt: 'Please input a number ( > 0) of messages to be deleted.',
type: 'integer'
}
]
});
}
run(msg, { numToPurge }) {
let channel = msg.channel;
// fail if number of messages to purge is invalid
if (numToPurge <= 0) {
return msg.reply('Purge number must be greater than 0');
}
// channel type must be text for .bulkDelete to be available
else if (channel.type === 'text') {
return channel.fetchMessages({limit: numToPurge})
.then(msgs => channel.bulkDelete(msgs))
.then(msgs => msg.reply(`Purge deleted ${msgs.size} message(s)`))
.catch(console.error);
}
else {
return msg.reply('Purge command only available in Text Channels');
}
}
};
module.exports = PurgeCommand
I'd also recommend using a new type instead of integer so you can validate the user's response and make sure they enter a number greater than 0.
If you need help setting up an initial discord.js-commando script, I'd take a look at this repo provided by the Discord team: https://github.com/discordjs/Commando/tree/master/test
You might wanna use this. This purge command is intended for discord.js v11.5.1 and I haven't tested to see if it works on v12, but I think this might work for you. I should say that THIS DELETES ALL THE CONTENT INSIDE THE CHANNEL (Nested command)
exports.run = (bot, message, args) => {
let filter = m => message.author.id === message.author.id;
message.channel.send("Are you sure you wanna delete all messages? (y/n)").then(() => {
message.channel.awaitMessages(filter, {
max: 1,
time: 30000,
errors: ['time']
})
.then(message => {
message = message.first();
if (message.content.toUpperCase() == "YES" || message.content.toUpperCase() == "Y") {
message.channel.bulkDelete(100);
} else if (message.content.toUpperCase() == "NO" || message.content.toUpperCase() == "N") {
message.channel.send("Terminated").then(() => {message.delete(2000)});
} else {
message.delete();
}
})
.catch(collected => {
message.channel.send("Timeout").then(() => {message.delete(2000)});
});
}).catch(error => {
message.channel.send(error);
});
};

Categories

Resources