Only reply in dms discord.js - javascript

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

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

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!

discord.js - bot using old code to carry out commands

I'm pretty new to programming in general, and I have chosen to try out bot making as one of my first projects. However, my code seems to be using my old code and new code simultaneously. Here is what I had for my old code, in a single index.js file.
const Discord = require(discord.js);
const client = new Discord.Client();
require('dotenv').config();
client.on('ready', => {
console.log(`Logged in`)});
client.on("message", msg => {
if(msg.content === "ping") {
msg.reply("pong")
}
})
client.login(process.env.BOT_TOKEN);
And that's it for my old code. I've recently updated the code to organise everything and include a command handler. This is the new code, in their index.js and ping.js files respectively.
For index.js:
const Discord = require('discord.js');
const fs = require('fs');
const client = new Discord.Client()
require('dotenv').config();
const prefix = '<'
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.on('ready', () => {
console.log(`Logged in`)
});
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(process.env.BOT_TOKEN);
For ping.js:
module.exports = {
name: 'ping',
description: "ping command",
execute(message, args){
message.reply("pong");
}
}
And that's all the code. Now, the problem arises when I type <ping in the discord chat. Instead of replying with pong once, it does so twice. I have tried everything I could from saving and restarting Visual Studio Code, but to no avail. I do not even know if this is a problem with my code, as there are no error messages whatsoever when this happens. Thank you all who answer.

Discord.js help command to compile list of commands and embed with thumbnails

I have a very simple Discord bot that posts images/gifs on command by linking Imgur/Tenor htmls.
The commands are stored in individual .js files ./commands/
I would like to create a help command that collects all current commands in the folder, and embeds the command name, with the executed command beneath it so that a thumbnail of the image/gif is created, but I mostly just about managed to follow the Discord.js guide so I'm very very new to this. Can anyone suggest some code to help me get started? How can I populate embed fields based on an array of existing commands?
Example of bot below:
The commands are imported in index.js via:
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);
}
And executed via:
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const commandName = args.shift().toLowerCase();
if (!client.commands.has(commandName)) return;
const command = client.commands.get(commandName);
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('Something bad happened!');
}
});
An example of a command ./commands/test.js is:
module.exports = {
name: 'test',
description: 'A test',
execute(message, args) {
message.channel.send('This is a test.');
}
}
You can use a .forEach() loop.
For example:
module.exports = {
name: 'help',
description: 'View a full list of commands',
execute(message, client) {
const Discord = require('discord.js');
const embed = Discord.MessageEmbed();
client.commands.forEach(command => {
embed.addField(`${command.name}`, `${command.description}`, false);
}
message.channel.send(embed);
}
}

Discord.js | Making a message sniper command

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);
});

Categories