Discord.js | Making a message sniper command - javascript

I'm trying to make a bot log/snipe a message, when someone says 'zsnipe', I want to know how would i make 'zsnipe' a command but its not working, am I doing something wrong? here's the code:
bot.on('messageDelete', message => {
const embed8 = new Discord.MessageEmbed()
.setAuthor(`${message.author.username}#${message.author.discriminator}`, message.author.avatarURL({dynamic : true}))
.setDescription(message.content)
if (message.content === 'zsnipe'){
message.channel.send(embed8)
}
})
Your Help Will be Appreciated!

Here is some code that saves the last deleted message in a channel and allows it to be retrieved when someone says zsnipe.
Warning: the deleted messages will be lost if the bot restarts.
const deletedMessages = new Discord.Collection();
bot.on('message', async message => {
if (message.author.bot) return;
const args = message.content.trim().split(/\s+/g);
const command = args.shift().toLowerCase();
switch (command) {
case 'zsnipe':
const msg = deletedMessages.get(message.channel.id);
if (!msg) return message.reply('could not find any deleted messages in this channel.');
const embed = new Discord.MessageEmbed()
.setAuthor(msg.author.tag, msg.author.avatarURL({ dynamic: true }))
.setDescription(msg.content);
message.channel.send(embed).catch(err => console.error(err));
break;
});
bot.on('messageDelete', message => {
deletedMessages.set(message.channel.id, message);
});

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

Edit Snipe command sending more than one embed instead of just one

const editedMessages = new Discord.Collection();
client.on("messageUpdate", (oldMessage, newMessage) => {
if(oldMessage.content === newMessage.content)return
client.on('message', message => {
if (message.author.bot) return;
const args = message.content.trim().split(/\s+/g);
const command = args.shift().toLowerCase();
switch (command) {
case 'y!edit':
const msg = editedMessages.get(message.channel.id);
if (!message) return message.reply('There is nothing to snipe');
const edembed = new Discord.MessageEmbed()
.setColor('#deffff')
.setAuthor(newMessage.author.tag, newMessage.author.avatarURL({ dynamic: true }))
.setDescription(`**Old message:** ${oldMessage.content} \n **New message:** ${newMessage.content}`)
.setFooter(`ID: ${newMessage.author.id}`).setTimestamp()
message.channel.send({ embeds: [edembed] }).catch(err => console.error(err));
break;
}
});
});
client.on('messageUpdate', message => {
editedMessages.set(message.channel.id, message);
});
I want it to send only one embed when the command is used repeatedly. As you can see in the screenshot provided, every time the command was used it sent the previous embeds too. I've been stuck on this command line for ages.
It appears as if you are forgetting to close your preexisting bot connections.

Only reply in dms discord.js

So I was working on this project where people will DM the BOT and run command and it replies test. But it doesn't reply.
client.on("messageCreate", async message => {
if (message.content.startsWith(prefix)) {
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if (message.channel.type === 'dm') {
message.reply("test");
}
}
});
That's because you didn't enable the intents for getting a dm message,
try putting those two on your client declarations :
const client = new Discord.Client({
intents : ['DIRECT_MESSAGES','GUILD_MESSAGES'],
partials: ["CHANNEL","MESSAGE"]
})
here is a way:
1.Create a file named ** 'privateMessage.js'** and in the main file add:
const privateMessage = require('./privateMessage')
client.on('ready' ,() =>{
console.log('I am online')
client.user.setActivity('YouTube Music 🎧', {type:'PLAYING'})
privateMessage(client, 'ping', 'pong')
})
and in the file we just created privateMessage.js add:
module.exports=(client, triggerText, replyText)=>{
client.on('message', message =>{
if(message.content.toLowerCase()===triggerText.toLowerCase()){
message.author.send(replyText)
}
})
}

Discordjs API error whilst trying to banning a user

I am attempting to program a ban command to be used by an administrator at a user who has broken the rules or has been naughty enough to be banned. When I ran the following code:
const Discord = require("discord.js");
const config = require("./config.json");
const { MessageAttachment, MessageEmbed } = require('discord.js');
const client = new Discord.Client({ intents: ["GUILDS","GUILD_MEMBERS", "GUILD_MESSAGES", "DIRECT_MESSAGES", "DIRECT_MESSAGE_REACTIONS", "DIRECT_MESSAGE_TYPING"], partials: ['CHANNEL',] })
const RichEmbed = require("discord.js");
const prefix = "!";
client.on("messageCreate", function(message) {
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
const commandBody = message.content.slice(prefix.length);
const args = commandBody.split(' ');
const command = args.shift().toLowerCase();
if (command === "news") {
if (message.channel.type == "DM") {
message.author.send(" ");
}
}
if (command === "help") {
message.author.send("The help desk is avaliable at this website: https://example.com/");
}
});
client.on("messageCreate", function(message) {
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
const commandBody = message.content.slice(prefix.length);
const args = commandBody.split(' ');
const command = args.shift().toLowerCase();
if (command === "ping") {
const timeTaken = Date.now() - message.createdTimestamp;
message.channel.send(`Pong! ${timeTaken}ms.`);
}
if (command === "delete all messages") {
const timeTaken = Date.now() - message.createdTimestamp;
const code = Math.random(1,1000)
message.channel.send(`Executing command. Verification Required.`);
message.author.send(`Your code is the number ${code}.`)
message.channel.send(`Please confirm your code. The code has been sent to your dms. Confirm it in here.`)
}
if (command === "ban") {
const user = message.mentions.users.first().id
message.guild.members.ban(user).then(user => {
message.channel.send(`Banned ${user.id}`);
}).catch(console.error);
}
});
client.login(config.BOT_TOKEN)
I ran into the following error whilst trying to test the command on a dummy acc.
DiscordAPIError: Missing Permissions
at RequestHandler.execute (/home/runner/gwehuirw/node_modules/discord.js/src/rest/RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/runner/gwehuirw/node_modules/discord.js/src/rest/RequestHandler.js:51:14) {
method: 'put',
path: '/guilds/891083670314680370/bans/943680142004322326',
code: 50013,
httpStatus: 403,
requestData: { json: { delete_message_days: 0 }, files: [] }
Could someone please help me with this? Thanks.
PS: I already had the necessary permissions for the bot to ban users. I also added the necessary intents for it to work. But I still am stuck.
Try removing the .id when you are trying to get the user. Getting the id would be making you ban the string that is the id, not the user.
I realized that the user who was trying to ban a user needed to have certain permissions. I have finished working on the command. Thanks to everyone who had helped me through this mess!

How do I create a slash command in discord using discord.js

I am trying to create a slash command for my discord bot, but I don't know how to execute code when the command is exuted
The code I want to use will send a message to a different channel (Args: Message)
Here is the code I want to use
const channel = client.channels.cache.find(c => c.id == "834457788846833734")
channel.send(Message)
You need to listen for an event interactionCreate or INTERACTION_CREATE. See the code below, haven't tested anything, hope it works.
For discord.js v12:
client.ws.on("INTERACTION_CREATE", (interaction) => {
// Access command properties
const commandId = interaction.data.id;
const commandName = interaction.data.name;
// Do your stuff
const channel = client.channels.cache.find(c => c.id == "834457788846833734");
channel.send("your message goes here");
// Reply to an interaction
client.api.interactions(interaction.id, interaction.token).callback.post({
data: {
type: 4,
data: {
content: "Reply message"
}
}
});
});
For discord.js v13:
client.on("interactionCreate", (interaction) => {
if (interaction.isCommand()) {
// Access command properties
const commandId = interaction.commandId;
const commandName = interaction.commandName;
// Do your stuff
const channel = client.channels.cache.find(c => c.id == "834457788846833734")
channel.send("your message goes here");
// Reply to an interaction
interaction.reply("Reply message");
}
});

Categories