Suggestion message not working. Does not seem to find the message - javascript

I have been trying to make a channel on my discord so that as soon as someone sends a message, it deletes it, then send an embed with the information. But it does not work, it should look like this:
But it looks like this:
Here is my index.js:
client.on('message', message => {
if (message.channel.id !== "823027303129808896") return;
let content = message.content;
const delMSG = message;
const Embed = new Discord.MessageEmbed()
.setAuthor(message.author.tag, message.author.displayAvatarURL())
.setTitle("Nouvelle suggestion!")
.setDescription("**Suggestion:**\n" + content)
.setColor("#00ff44")
.setFooter("Eclezia", "https://i.imgur.com/GhHHBgn.png")
.setTimestamp();
message.guild.channels.cache.get("823027303129808896").send(Embed).then((m) => {
m.react("<:yes:821050283734859816>")
m.react("<:no:821050300730572802>")
})
delMSG.delete();
})
And here is the error I get:
throw new DiscordAPIError(request.path, data, request.method, res.status);
^
DiscordAPIError: Unknown Message
at RequestHandler.execute (D:\EcleziaBot\node_modules\discord.js\src\rest\RequestHandler.js:154:13)
at processTicksAndRejections (node:internal/process/task_queues:94:5)
at async RequestHandler.push (D:\EcleziaBot\node_modules\discord.js\src\rest\RequestHandler.js:39:14) {
method: 'put',
path: '/channels/823027303129808896/messages/823046250542399539/reactions/yes%3A821050283734859816/#me',
code: 10008,
httpStatus: 404
}
EDIT: Look at the marked answer.

There are a couple of things:
Make sure you're returning if the message's author is the bot using if (message.author.bot) return; (I think it was your main issue)
You don't need to create new variables content and delMSG as message is available until your last line of code
You don't need to get the channel if you're sending in the same channel. Instead of message.guild.channels.cache.get("823027303129808896") you can use message.channel
I would move the message.delete() inside the .then()
Here is the full code:
client.on('message', (message) => {
const channelID = '823027303129808896';
if (message.author.bot) return;
if (message.channel.id !== channelID) return;
const embed = new Discord.MessageEmbed()
.setAuthor(message.author.tag, message.author.displayAvatarURL())
.setTitle('Nouvelle suggestion!')
.setDescription('**Suggestion:**\n' + message.content)
.setColor('#00ff44')
.setFooter('Eclezia', 'https://i.imgur.com/GhHHBgn.png')
.setTimestamp();
message.channel
.send(embed)
.then((msg) => {
message.delete();
msg.react('<:yes:821050283734859816>');
msg.react('<:no:821050300730572802>');
})
.catch(console.log);
});

Related

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.

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!

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

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

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