Ban DM Message on discord.js - discord

I am making a discord bot, and I want the bot to DM the user that got banned why
it got banned. Here is my current code for it:
if(command === "ban") {
if(!message.member.roles.some(r=>["Administrator"].includes(r.name)) )
return message.reply("Sorry, you don't have permissions to use this!");
let member = message.mentions.members.first();
if(!member)
return message.reply("Please mention a valid member of this server");
if(!member.bannable)
return message.reply("I cannot ban this user! Do they have a higher role?
Do I have ban permissions?");
let reason = args.slice(1).join(' ');
if(!reason) reason = "No reason provided";
await member.ban(reason)
.catch(error => message.reply(`Sorry ${message.author} I couldn't ban because of : ${error}`));
message.reply(`${member.user.tag} has been banned by ${message.author.tag} because: ${reason}`);
message.member.tag.sendMessage('Hi! You were banned from ${member.user.server} because: {reason}. If you do not get why you were banned, please DM #doodthedoodthedood#2695.')
}

You would have to do it before they are banned.
Before banning the user, use the member object to send them a message.
await member.send("You are banned")
await member.ban(reason)

You cant send the message to the user because you banned them, meaning you no longer share a server.
Send the message first.
.send is a promise. use it to your advantage.
message.member.send(`ban reason here`).then(function(){
message.member.ban(`reason`)
console.log(`Successfully sent ban message to ${message.member.tag}`);
}).catch(function(){
message.member.ban(`reason`)
console.log(`Unsuccessfully sent ban message to ${message.member.tag}`);
});
use .then and a .catch to ban the user so even if the message doesnt send they still get banned

Related

Discord.js bot command to take users with a specific role and to return an embedded message with all the users in that role

I've been working on this and I cannot figure out why the bot will not enact the command. Essentially this is how the situation should work:
In the channel you send a message: "!listroletest"
After that, the bot should send an embedded with every user who has the role "test" with their userID's
client.on("message", message => {
if(message.content == "!listroletest") {
const ListEmbed = new Discord.MessageEmbed()
.setTitle('Users with the test role:')
.setDescription(message.guild.roles.get('901592912171765850').members.map(m=>m.user.tag).join('\n'));
message.channel.send(ListEmbed);
}
});

How to get permissions in discord js when we do direct message

I am trying to get a list of the permission that the user has in Discord. If it sends the message in the channel, it’s fine as we can use message.member.hasPermission, etc.
But what if the message is DM? I want my users to send a DM to the bot and the bot be able to check and see if the user has certain permissions.
I cannot find anything anywhere. I keep getting redirected to message.member, or message.guild which both are null when it’s in DM.
In DM no one has permissions. All you have is the permission to see messages and send messages which aren’t shown visually, or to bots. To make sure that it isn’t DM, just return if the channel type is dm, or guild is null.
if(!message.guild) return;
//before checking "perms"
If you want the permissions for a certain guild if the message is from DM, use this code
if(message.channel.type === 'dm') {
let guild = await client.guilds.fetch('THE ID OF THE GUILD YOU WANT TO SEE THE USER’S PERMS IN')
let member = await guild.members.fetch(message.author.id);
//you can now access member.permissions
}
Keep in mind await must be in an async callback.
You did not provide any code so I cannot give any more code than this.
You can fetch the member with the guild's context.
Fetching is recommended, as Guild#member() relies on cache and is also deprecated.
Member#hasPermission() will be deprecated as well, using MemberRoleManager#has() is recommended
The following example uses async/await, ensure you're inside an async function
// Inside async function
const guild = await client.guilds.fetch('guild-id');
const member = await guild.members.fetch(message.author.id);
const hasThisPermission = member.roles.cache.has('permission');

Check if a user with a specific role reacted the latest bot message | Discord.js

i need to make my bot check if someone with admin role or a specific role reacted the bot's latest message
i made a suggestion command for my bot and i want to the bot check if anyone with the #Admin role reacted the latest bot message of #suggestions channel, then when a user that has the #Admin role react the suggestion, make the bot send me a DM saying something like: Accepted your suggestion!
Here is something that may help:
client.on('messageReactionAdd', async (reaction, user) {
if(reaction.message.channel.id !== 'suggestion channel id') return;
let channel = reaction.message.channel;
let msg = await channel.messages.fetch({limit: 1});
if(!msg || msg.id !== reaction.message.id) return;
if(reaction.message.guild.member(user).roles.cache.some(r => r.id === 'admin role id')) {
user.send('Your suggestion was accepted.')
//You may have said this wrong, but if you want the person who suggested it to be DMd
//You will need to somehow save their name (or id which can never change), let’s say you put it in the footer of an embed for the suggestion
let userID = reaction.message.embeds[0].footer;
msg.guild.members.cache.find(m => m.user.id === userID).send('Accepted your suggestion!')
}
})
I’d like to know if this doesn’t work because I didn’t get to test it. It may have some errors, but hopefully not

Discord.py banning user not working if DM's disabled

I've got this code for my discord bot, which can ban people and DM them the reason for the ban first.
cooldown = []
#bot.command(pass_context = True)
#commands.has_role('Senior Moderator')
async def ban(ctx, member: discord.Member = None, *, reason = None):
author = str(ctx.author)
if author in cooldown:
await ctx.send('Calm down! You\'ve already banned someone less than two hours ago.')
return
try:
if reason == None:
reason = 'breaking the rules.'
await member.send(f'You have been banned from **{ctx.guild.name}** for **{reason}**')
await member.ban(reason = f"Banned by {ctx.message.author} for "+reason)
await ctx.send(f'{member.mention} has been banned.')
cooldown.append(author)
await asyncio.sleep(2 * 60 * 60) #The argument is in seconds. 2hr = 7200s
cooldown.remove(author)
except:
await ctx.send('Error. Please check you are typing the command correctly. `!ban #username (reason)`.')
However, if the user I am trying to ban has DM's disabled, the bot can't send the ban reason message, so therefore doesn't proceed to the next step, which is banning them, and returns the error message, which is Error. Please check you are typing the command correctly. !ban #username (reason)
Please can you rewrite the code to allow it to try to DM someone the reasoning before banning them, but if they have DM's disabled, it shall still ban them anyway. Thank you!
By simply moving the ban to be executed first (as it is a priority), then it will attempt to dm the user.
I also re-adjusted some parts of the code. It will now try to send a dm, if not, it will still ban but a message will be sent to the channel alerting a message was not sent to the banned user.
#bot.command(pass_context = True)
#commands.has_role('Senior Moderator')
async def ban(ctx, member: discord.Member = None, *, reason = None):
author = ctx.author
if author in cooldown:
await ctx.send('Calm down! You\'ve already banned someone less than two hours ago.')
return
if member == None:
await ctx.send('Please mention a member to ban!')
return
if reason == None:
reason = 'breaking the rules.'
await member.ban(reason = f"Banned by {ctx.message.author} for " + reason)
try:
await member.send(f'You have been banned from **{ctx.guild.name}** for **{reason}**')
except:
await ctx.send(f'A reason could not be sent to {ctx.message.author} as they had their dms off.')
await ctx.send(f'{member.mention} has been banned.')
cooldown.append(author)
await asyncio.sleep(2 * 60 * 60)
cooldown.remove(author)
I too noticed the same thing when I first made my bot ban command, I did the following to fix my ban command. First I tried a scenario where the bot could dm the user, if it can, then It will dm the user and then ban the user (Note: Do not ban the user before DMing the user as the bot can only DM the user when the user and the bot share a common server). However, I then made an Exception that if the bot couldn't dm the user, it will send a message in the channel the command was executed "Couldn't dm the user" then ban the user
try:
await member.send(embed=embo)
await ctx.guild.ban(member, reason=reason)
except Exception:
await ctx.send("Couldn't send dm to the user")
await ctx.guild.ban(member, reason=reason)
EDIT:
you can also opt for the following:
try:
await member.send(embed=embo)
await ctx.guild.ban(member, reason=reason)
except discord.HTTPException:
await ctx.send("Couldn't send dm to the user")
await ctx.guild.ban(member, reason=reason)
before I specified this, I encountered the following error.
I fixed it, afterward, adding the exception case.

discordjs problems logging whenever a dm is sent

I have a whole logging system that logs whenever various things are done in the server or with the bot, one being a log of whenever a dm is sent to the bot. the log would contain the author ID and the message content. the problem is with logging the message content. the bot crashes whenever a second DM is sent but works fine if its a first DM. the bot crash message is the following: https://gyazo.com/5ad0b41648f83a855ac8c49fb220a612
but the strange thing is, my fields aren't empty:
bot.on('message', msg=>{
const LogChannel = bot.channels.cache.get('712811824826941460');
const LogEmbed = new Discord.MessageEmbed()
.setColor('#606060')
.setAuthor(msg.author.tag)
.setDescription('DM Sent')
.addField('Message', msg.content)
.setTimestamp()
if(msg.channel.type === 'dm')
LogChannel.send(LogEmbed)
});
the console thinks that the .addField('Message', msg.content) is empty but as you can see, it's not. keep in mind it only gives me the error message after a second DM is sent following a first one.
any ideas?
There is no Message.content properties. I guess you are looking for Message.cleanContent
bot.on('message', msg=>{
const LogChannel = bot.channels.cache.get('712811824826941460');
const LogEmbed = new Discord.MessageEmbed()
.setColor('#606060')
.setAuthor(msg.author.tag)
.setDescription('DM Sent')
.addField('Message', msg.cleanContent)
.setTimestamp()
if(msg.channel.type === 'dm')
LogChannel.send(LogEmbed)
});

Resources