.addArgument is not a function Discord bot - javascript

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

Related

How can i make this discord.js v14 slash command not return "undefined" for each option?

The idea of this command is to add a user to the .txt file full of customers info so it can be used by other parts of the bot.
The problem is no matter what i put into the options that pop up here
Command Example
it will always return "undefined" for each option like so.
Example Reply
i think the issue is its not actually returning anything from the interaction when asking for that information inside the execute function. im not quite sure why though.
here is the code in question.
const { SlashCommandBuilder } = require('discord.js');
const fs = require('fs');
module.exports = {
data: new SlashCommandBuilder()
// command name
.setName('addfrozencustomer')
// command description
.setDescription('Add a frozen customer account/discord')
.addStringOption(option =>
option.setName('id')
.setDescription('The ID of the customer')
.setRequired(true))
.addStringOption(option =>
option.setName('username')
.setDescription('The username of the customer')
.setRequired(true))
.addStringOption(option =>
option.setName('email')
.setDescription('The email of the customer')
.setRequired(true)),
async execute(interaction) {
const { id, username, email } = interaction.options;
const data = `${id}:::${username}:::${email}`;
fs.appendFile('users/frozencustomers.txt', `${data}\n`, (error) => {
if (error) {
console.error(error);
return;
}
console.log('The data was successfully written to the file.');
});
interaction.channel.send(`Successfully added frozen customer:\n ID: ${id}\n User: ${username}\n Email: ${email}`);
}
};
Out of everything i have tried the code above is the closest iv come to getting this to work as intended.
You can't grab interaction options values directly from the interaction.options object, it has seperate methods to grab each type of value, in your case:
const
username = interaction.options.getString("username"),
id = interaction.options.getString("id"),
email = interaction.options.getString("email")
You can read more about this here: https://discordjs.guide/slash-commands/parsing-options.html#command-options

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

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.

Discord js bot: Cannot send DM to users with specific role

I seem to be having serious trouble sending DM's to all users with a specific role.
Here is my bot code:
bot.on('message', async message => {
members = message.guild.roles.cache.find(role => role.id === "12345678998765").members.map(m => m.user.id);
members.forEach(member_id => {
sleep(5000).then(() => {
message.users.fetch(member_id, false).then((user) => {
user.send("some message");
});
});
});
});
This code gives me the error:
Cannot read properties of null (reading 'roles')
on this line:
members = message.guild.roles.cache.find(role => role.id === ....
However that is not the issue. When I comment out the sleep command to send the message and output the member roles using:
members.forEach(member_id => {
console.log(member_id)
//sleep(5000).then(() => {
// bot.users.fetch(member_id, false).then((user) => {
// user.send("some message");
// });
//});
});
I get a list returned in the console of all the user ID's.. So it must be returning the roles.
How do I send a message to all users with a specific role ID ?? I want to be able to loop through them and put a wait in to reduce the API requests and spam trigger.
To fix your first issue, message.guild will be null in DM. Make sure it isn't DM, or if it has to be, choose a guild with client.guilds.cache.get("id").
bot.on("message", async message => {
let { guild } = message
if (!guild) guild = bot.guilds.cache.get("id")
//...
})
To fix your other issue, you can run GuildMember#send() rather than getting the IDs and fetching the users
bot.on("message", async message => {
let { guild } = message
if (!guild) guild = bot.guilds.cache.get("id")
let members = guild.roles.cache.get("12345678998765").members
// I used .get here because it's getting by ID
members.forEach(member => {
sleep(5000).then(() => member.send("some message"));
});
})
The above code will get all the GuildMembers and loop through every one of them, "sleeping" for 5 seconds (if the sleep parameter is milliseconds) and send the member a DM

Get count of member's messages in channel in discord.js

Is there any way how to count messages of specified user in specified Discord channel in discord.js? When I use:
const countMyMessages = async (channel, member) => {
const messages = await channel.messages.fetch()
const myMessages = message.filter(m => m.author.id === member.id)
console.log(myMessages.size)
}
Only 50 messages are fetched, so I can't count all messages of user. And option limit can have max value 100. /guilds/guild_id/messages/search API on the other hand is not available for bots.
You will need to use a storage system to keep this kind of statistics on Discord.
I recommend you to use SQLite at first (like Enmap npm package).
I can quickly draw a structure for you based on this one.
const Enmap = require("enmap");
client.messages = new Enmap("messages");
client.on("message", message => {
if (message.author.bot) return;
if (message.guild) {
const key = `${message.guild.id}-${message.author.id}`;
client.messages.ensure(key, {
user: message.author.id,
guild: message.guild.id,
messages: 0
});
client.messages.inc(key, "messages");
// Do your stuff here.
console.log(client.messages.get(key, "messages"))
}
});

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.

Categories

Resources