Discord.js delete messages from specific UserIDs - discord.js

So I'm having some problems with the code, I am trying to have the message.author.id match a list of IDs in a const then do something.
const blacklisted = ["644298972420374528", "293534327805968394", "358478352467886083"];
if (message.author.id === blacklisted) {
message.delete()
const blacklistedMSG = new Discord.RichEmbed()
.setColor('#ff0000')
.setTitle('Blacklisted')
.setDescription(`You are currently Blacklisted. This means you cannot send messages in Any server with this bot.`)
.setTimestamp()
.setFooter(copyright);
message.author.send(blacklistedMSG).then(msg => {msg.delete(30000)})
}
When I have it like that, it doesn't do anything and there are no errors in the console about it. But when the code is this:
if (message.author.id === "644298972420374528") {
message.delete()
const blacklistedMSG = new Discord.RichEmbed()
.setColor('#ff0000')
.setTitle('Blacklisted')
.setDescription(`You are currently Blacklisted. This means you cannot send messages in Any server with this bot.`)
.setTimestamp()
.setFooter(copyright);
message.author.send(blacklistedMSG).then(msg => {msg.delete(30000)})
}
It works and sends the user an embed and deletes the message they sent. Not sure what's going on with it. Thanks in advance.

You are making a direct comparison to the array rather than checking to see if message.author.id is in the array.
Instead of
if (message.author.id === blacklisted)
Try
if (blacklisted.includes(message.author.id))

Related

Check The Status Of Another Discord Bot

So i need a bot that tracks another bot's status. like if its online it will say in a channel (with an embed) "The Bot Is Online" And The Same if it goes offline and whenever someone does !status {botname} it shows the uptime/downtime of the bot and 'last online' date
if someone can make it happen i will really appricate it!
also i found this github rebo but it dosen't work, it just says the bot is online and whenever i type !setup {channel} it turns off
The Link to the Repo: https://github.com/sujalgoel/discord-bot-status-checker
Also uh it can be any language, i don't really want to add anything else 😅.
Again, Thanks!
First of all, you would need the privileged Presence intent, which you can enable in the Developer Portal.
Tracking the bot's status
In order to have this work, we have to listen to the presenceUpdate event in discord.js. This event emits whenever someone's presence (a.k.a. status) updates.
Add this in your index.js file, or an event handler file:
// put this with your other imports (and esm equivalent if necessary)
const { MessageEmbed } = require("discord.js");
client.on("presenceUpdate", async (oldPresence, newPresence) => {
// check if the member is the bot we're looking for, if not, return
if (newPresence.member !== "your other bot id here") return;
// check if the status (online, idle, dnd, offline) updated, if not, return
if (oldPresence?.status === newPresence.status) return;
// fetch the channel that we're sending a message in
const channel = await client.channels.fetch("your updating channel id here");
// create the embed
const embed = new MessageEmbed()
.setTitle(`${newPresence.member.displayName}'s status updated!`)
.addField("Old status", oldPresence?.status ?? "offline")
.addField("New status", newPresence.status ?? "offline");
channel.send({ embeds: [embed] });
});
Now, whenever we update the targeted bot's status (online, idle, dnd, offline), it should send the embed we created!
!status command
This one will be a bit harder. If you don't have or want to use a database, we will need to store it in a Collection. The important thing about a Collection is that it resets whenever your bot updates, meaning that even if your bot restarts, everything in that Collection is gone. Collections, rather than just a variable, allows you to store more than one bot's value if you need it in the future.
However, because I don't know what you want or what database you're using, we're going to use Collections.
In your index.js file from before:
// put this with your other imports (and esm equivalent if necessary)
const { Collection, MessageEmbed } = require("discord.js");
// create a collection to store our status data
const client.statusCollection = new Collection();
client.statusCollection.set("your other bot id here", Date.now());
client.on("presenceUpdate", async (oldPresence, newPresence) => {
// check if the member is the bot we're looking for, if not, return
if (newPresence.member !== "your other bot id here") return;
// check if the status (online, idle, dnd, offline) updated, if not, return
if (oldPresence?.status === newPresence.status) return;
// fetch the channel that we're sending a message in
const channel = await client.channels.fetch("your updating channel id here");
// create the embed
const embed = new MessageEmbed()
.setTitle(`${newPresence.member.displayName}'s status updated!`)
.addField("Old status", oldPresence?.status ?? "offline")
.addField("New status", newPresence.status ?? "offline");
channel.send({ embeds: [embed] });
// add the changes in our Collection if changed from/to offline
if ((oldPresence?.status === "offline" || !oldPresence) || (newPresence.status === "offline")) {
client.statusCollection.set("your other bot id here", Date.now());
}
});
Assuming that you already have a prefix command handler (not slash commands) and that the message, args (array of arguments separated by spaces), and client exists, put this in a command file, and make sure it's in an async/await context:
// put this at the top of the file
const { MessageEmbed } = require("discord.js");
const bot = await message.guild.members.fetch("your other bot id here");
const embed = new MessageEmbed()
.setTitle(`${bot.displayName}'s status`);
// if bot is currently offline
if ((bot.presence?.status === "offline") || (!bot.presence)) {
const lastOnline = client.statusCollection.get("your other bot id here");
embed.setDescription(`The bot is currently offline, it was last online at <t:${lastOnline / 1000}:F>`);
} else { // if bot is not currently offline
const uptime = client.statusCollection.get("your other bot id here");
embed.setDescription(`The bot is currently online, its uptime is ${uptime / 1000}`);
};
message.reply({ embeds: [embed] });
In no way is this the most perfect code, but, it does the trick and is a great starting point for you to add on. Some suggestions would be to add the tracker in an event handler rather than your index.js file, use a database rather than a local Collection, and of course, prettify the embed messages!

How could I mention a user in an embed?

I'm currently having an issue where I'm unable to ping people in embeds. I've searched up solutions online, but none of them are working. Here's my code, thanks.
else if (command === 'post') {
if (!message.member) return;
const messageContent = args.slice(1).join(' ');
if (!messageContent) return await message.channel.send("Invalid syntax, please include full detail, including what you need done, payment, time etc.");
await message.channel.send("Post sent for approval.");
const hiringEmbed = new Discord.MessageEmbed()
.setColor(embedColor)
.setTitle('Hiring post.')
.setAuthor({name : message.member.user.username, iconURL : message.member.user.displayAvatarURL()})
.setDescription(messageContent)
.setFooter({text : `Post by <#${message.member.user.id}>`}) // This is the line that wont work
.setTimestamp()
await client.channels.cache.find(channel => channel.id === '937027971137548378').send({embeds : [hiringEmbed]});
}
To ping someone you need to add the user to the content of the message you send channel.send({content:'<#${id}>', embeds: [hiringEmbed]
You cannot ping a member in an embed but rather only mention them. So, you need to ping them in the regular content of the message instead of the embed.
await client.channels.cache.find(channel => channel.id === '937027971137548378').send({content: `${message.member.user.id}`, embeds : [hiringEmbed]});
In the footer you can use their username instead if you want to mention who used the command.
.setFooter({text : `Post by ${message.author.tag}`})
or
.setFooter(`Post by ${message.author.tag}`)

How can send DM for unban command used user?

I'm developing an unban command for a ban command.
When the ban is lifted, I want the embed message unbanEmbeduserside to be sent to the banned user via private message. This embed message will let the banned user know about it.
The codes for my unban command are as follows. Thanks in advance to my friends who will help me with how to write a code so that I can perform the operation I mentioned in the above article.
async run (bot, message, args) {
message.delete(message.author);
if (!message.member.hasPermission("BAN_MEMBERS"))
return message.author.send("Buna yetkin yok.")
let unbanEmbednotfoundmessage = new discord.MessageEmbed()
.setColor(0xdb2727)
.setDescription(`Kullanıcı bulunamadı veya yasaklı değil.`);
let userID = args[0]
message.guild.fetchBans().then(bans => {
if(bans.size == 0) return message.channel.send(unbanEmbednotfoundmessage);
let bUser = bans.find(b => b.user.id == userID)
if(!bUser) return message.channel.send(unbanEmbednotfoundmessage)
let unbanEmbeduserside = new discord.MessageEmbed()
.setAuthor('YASAKLAMA KALDIRILDI', 'https://i.hizliresim.com/midfo22.jpg')
.setDescription(`
*Yasaklamanız kaldırıldı, sunucuya tekrar katılabilirsiniz!*
Yasaklamayı Kaldıran Yetkili: **${message.author.username}**
`)
.setColor(0xc8b280)
.setTimestamp()
.setFooter('gtaplus Multiplayer Community');
let unbanEmbedserverside = new discord.MessageEmbed()
.setAuthor('YASAKLAMA KALDIRMA', 'https://i.hizliresim.com/midfo22.jpg')
.setDescription(`
Yasağı Kaldırılan Kullanıcı: **${userID}**
Yasaklamayı Kaldıran Yetkili: **${message.author.username}**
`)
.setColor(0xc8b280)
.setTimestamp()
.setFooter('gtaplus Multiplayer Community');
message.guild.members.unban(bUser.user).then(() => message.channel.send(`**${userID}** yasaklaması kaldırıldı.`));
if (unbanEmbedserverside){
const log = message.guild.channels.cache.find(channel => channel.name === 'server-log')
log.send(unbanEmbedserverside);
}
})
}}
In Discord, any user, including a bot, will need to be in a server with a user to send them direct messages. This, unfortunately, means that unless the bot shares a server with the banned user, you will not be able to send the message. If the bot does share another server, the answer that Skularun Mrusal provided in the comments of your post should work.

Discord.js Forward DM message to specific channel

So, I need a way to forward a message sent in the bot's dm to a specific channel in my server.
this is the code that I got so far:
execute(message, args) {
if(message.channel.type == "dm"){
let cf = args.join(' ')
const cfAdm = message.guild.channels.cache.get('767082831205367809')
let embed = new discord.MessageEmbed()
.setTitle('**CONFISSÃO**')
.setDescription(cf)
.setColor('#000000')
const filter = (reaction, user) => ['👍', '👎'].includes(reaction.emoji.name);
const reactOptions = {maxEmojis: 1};
cfAdm.send(embed)
.then(function (message) {
message.react('👍')
.then(() => message.react('👎'))
/**** start collecting reacts ****/
.then(() => message.awaitReactions(filter, reactOptions))
/**** collection finished! ****/
.then(collected => {
if (collected.first().emoji.name === '👍') {
const cfGnr = message.guild.channels.cache.get('766763882097672263')
cfGnr.send(embed)
}
})
});
}
else {
message.delete()
message.channel.send('Send me this in the dm so you can stay anon')
.then (message =>{
message.delete({timeout: 5000})
})
}
}
But for some reason that I can't seem to understand, it gives me this error:
TypeError: Cannot read property 'channels' of null
If anyone can help me, that would be greatly apreciated.
Thanks in advance and sorry for the bad english
The error here is that you are trying to call const cfAdm = message.guild.channels.cache.get('ID') on a message object from a Direct Message channel ( if(message.channel.type == "dm"){)
DMs don't have guilds, therefore message.guild is null and message.guild.channels does not exist.
You will need to first access the channel some other way. Luckily, Discord.js has a way to access all channels the bot can work with* (you don't need to muck around with guilds because all channels have unique IDs):
client.channels.fetch(ID) or client.channels.cache.get(ID)
(I have not tested this but it seems fairly straight forward)
*See the link for caveats that apply to bots in a large amount of servers.

Discord.js Sharding, How do you send an embed message with broadcastEval?

I'm trying to send an embed message to an specific channel with a sharded bot.
I've achieved sending a simple message successfully with this code:
client.shard.broadcastEval(`
(async () => {
let channel = await this.channels.get("683353482748756047");
channel.send("Hello")
})()
`)
The problem starts when I want to send an embed message. I've tried passing the variable like this:
//exampleEmbed is created
client.shard.broadcastEval(`
(async () => {
let channel = await this.channels.get("683353482748756047");
channel.send('${exampleEmbed}')
})()
`)
but the message is sent like "[object Object]".
I thought about returning the channel object back outside of broadcastEval and then sending my variable, but I've read this is not possible because you can't return full discord objects.
How should I send the embed message? Thank you for your time.
Okay, I solved it by creating the embed message inside the broadcastEval, and using the '${}' syntax to poblate it.
Example:
client.shard.broadcastEval(`
(async () => {
const Discord = require('discord.js');
let channel = await this.channels.get("683353482748756047");
if(channel){
//if shard has this server, then continue.
let message = new Discord.RichEmbed()
.setThumbnail(this.user.displayAvatarURL)
.setTitle('Title')
.addField("Something useful:", '${useful}')
.addField("Another useful thing:", '${useful2}')
.setTimestamp()
channel.send(message)
}
})()

Resources