How to stop Admin's messages from getting filtered and blocked || Discord.js V.14 - javascript

This is my code:
module.exports = {
name: "messageCreate",
async execute(message) {
if (!message.guild || message.author.bot) return;
if (message.content.includes("#everyone")) {
message.delete();
message.channel.send({ content: `${message.author}, you don't have permission to tag everyone!`});
}
}
}
I want my bot to ignore all the messages with the text "#everyone" from the roles that have Administrator permission enabled and delete the messages from all the other roles.

Your condition to delete a message is if it includes #everyone and member is not an admin:
if (message.content.includes('#everyone') && !message.member.permissions.has(PermissionFlagBits.Administrator))
Keep in mind this may still produce a ghost ping for all the members, it's best to suppress mass mentioning through Discord roles

Related

Getting "Missing Access" error in console

I'm working on an add role command in discord.js v13 and this is the error I am getting:
Error
const { MessageEmbed } = require("discord.js");
const Discord = require("discord.js")
const config = require("../../botconfig/config.json");
const ee = require("../../botconfig/embed.json");
const settings = require("../../botconfig/settings.json");
module.exports = {
name: "addrole",
category: "Utility",
permissions: ["MANAGE_ROLES"],
aliases: ["stl"],
cooldown: 5,
usage: "addrole <user> <role>",
description: "Add a role to a member",
run: async (client, message, args, plusArgs, cmdUser, text, prefix) => {
/**
* #param {Message} message
*/
if (!message.member.permissions.has("MANAGE_ROLES")) return message.channel.send("<a:mark_rejected:975425274487398480> **You are not allowed to use this command. You need `Manage Roles` permission to use the command.**")
const target = message.mentions.members.first();
if (!target) return message.channel.send(`<a:mark_rejected:975425274487398480> No member specified`);
const role = message.mentions.roles.first();
if (!role) return message.channel.send(`<a:mark_rejected:975425274487398480> No role specified`);
await target.roles.add(role)
message.channel.send(`<a:mark_accept:975425276521644102> ${target.user.username} has obtined a role`).catch(err => {
message.channel.send(`<a:mark_rejected:975425274487398480> I do not have access to this role`)
})
}
}
What your error means is that your bot doesn't have permissions to give a role to a user. It might be trying to add a role which has a higher position than the bot's own role. One way to stop the error is to give the bot the highest position. The bot will also require the MANAGE_ROLES permission in the Discord Developers page to successfully add roles in the first place. If you want to learn more about role permissions, I suggest you go here => Roles and Permissions. Also, when you are using .catch() at the end, all it is checking for is if the message.channel.send() at the end worked and if not, then send a message to channel telling that the bot was not able to add the role. Instead you need to use .then() after adding the role and then use .catch() to catch the error. Then, your code might look like this:
target.roles.add(role).then(member => {
message.channel.send(`<a:mark_accept:975425276521644102> ${target.user.username} has obtined a role`)
}).catch(err => {
message.channel.send(`<a:mark_rejected:975425274487398480> I do not have access to this role`)
})

Discord.js mod bot ban command not working

My discord bot's ban command isn't working and is currently giving me this error. My rols id is 853527575317708820
I don't know what I am doing wrong so please help me out
Here is the command :
Server is ready.
TigerShark Community#3557 Has logged in
(node:204) UnhandledPromiseRejectiontarning: DiscordAPTError: T
AEE RS
user_id: Value "<#!856413967595012127>" is not snowflake.
at RequestHandler.execute (/home/Tunner/TSC/node_modules/di
scoxd. js/src/rest/RequestHandler. js:154:13)
at processTicksAndRejections (internal/process/task
§5:97:5) :!
at async RequestHandler.push (/home/zunner/TSC/node
/discord. js/s1c/rest/RequestHandler. js:39:14)
Here is my code :
module.exports = {
name: 'ban',
description: "Used to ban members from a server",
async execute(client, message, args, Discord) {
if (!(message.member.roles.cache.some(r => r.id === "853527575317708820"))) return
let reason;
const user = await client.users.fetch(args[0])
if (!args[1])
{
reason = "Not specified"
} else {
reason = args[1]
}
const embed = new Discord.MessageEmbed()
.setTitle(`${user.username} was banned!`)
.setDescription(`${user.username} was banned by ${message.author.username} for: ${reason}`)
.setColor("#f0db4f")
.setFooter("Ban Command")
.setTimestamp()
message.channel.send(embed)
message.guild.members.ban(user)
}
}
Your command has few issues in it.
The first being that it does not allow banning users with command if the user is mentioned, it only allows banning by user ID. To fix that simply do:
const user = message.mentions.members.first() || await client.users.fetch(args[0])
You should also add check if the user is found, so right after you declare value for user
const user = message.mentions.members.first() || await client.users.fetch(args[0])
if(!user) return message.reply(`No user found`);
Now if you allow banning both mentions and user IDs there might be a different user value. So I recommend editing your embed aswell to something like:
const embed = new Discord.MessageEmbed()
.setTitle(`${user.user.username} was banned!`)
.setDescription(`${user.user.username} was banned by ${message.author.username} for: ${reason}`)
.setColor("#f0db4f")
.setFooter("Ban Command")
.setTimestamp()
This should fix majority of your issues, I recommend that if something is undefined in future or you come across any bugs in your code. Do some debugging by sending messages to console console.log(variable) or console.log("This works?")
if you are using discord.js v12 you can do what the other answer said and get the user by mention message.mentions.members.first() but if you are using v13 that wont work anymore
the reason its giving that error is because you need to fetch the user by their id alone, so you can do this client.users.fetch(args[0].replace('<#!', '').replace('>', '')) to remove the <#! and > (mention prefix) from it.

Create invite from server 1 and send to user DMS in server 2

So I am trying to create a type of command that will generate 1 single use in server 1. Now if I were to input this command into a general text in server 2, !dminvite #user, it would send the mentioned user the single created invite from server 1 and send it to the mentioned user in server 2, via DMs.
Some Notes:
1. I have the 2 server id's saved in my config.json file and this invite command requires config.json. In this commands file base
2. This command is running over discord.js v12, but if anyone wants to help out in discord.js v13, It would be amazing as well.
3. I am no way in trying to advertise anything, I own both servers
I have a code written down but it's not working, just a view point:
message.delete();
message.mentions.members.first() ||
message.guild.members.cache.get(args[0]);
const Options = {
temporary: false,
maxAge: 0,
maxUses: 1,
unique: true
};
const channel = message.guild.channels.cache.get('(Channel ID)');
let invite = message.channels.createInvite(Options).then(function(Invite) {
message.mentions.members.first().send({embed: {
title: `**INVITE**`,
description: `Invite:\nhttps://discord.gg/` + Invite.code
}});
message.channel.send(new Discord.MessageEmbed()
.setAuthor(message.author.tag, message.author.displayAvatarURL({ dynamic: true }))
.setDescription(`${message.author.tag}, invite was sent to DMs`)
.setColor('BLUE')
);
});
To accomplish your goal we do this:
Get the mentioned user from the message.
Fetch the other guild we want to invite the user to.
Create an invite to the other guild's system channel (it doesn't have to be systemChannel).
Send the invite to the mentioned user's DMs.
// Id of the other guild
const otherGuildId = "guild id";
client.on("message", async (message) => {
// Don't reply to itself
if (message.author.id == client.user.id) return;
// Check if the message starts with our command
if (message.content.startsWith("!dminvite")) {
// Get the mentioned user from the message
const user = message.mentions.users.first();
if (!user) {
message.channel.send("You need to mention the user to send the invitation to.");
return;
}
// Fetch the other guild we want to invite the user to
const otherGuild = await client.guilds.fetch(otherGuildId);
// Create invite to the other guild's system channel
const invite = await otherGuild.systemChannel.createInvite({
maxAge: 0,
maxUses: 1,
unique: true
});
// Send the invite to the mentioned user's DMs
user.send({
embed: {
title: "**INVITE**",
description: `${invite}`
}
});
}
});
Note that if you don't want to use the systemChannel, you can simply get any channel you want from the otherGuild by its id for example.
// Resolve channel id into a Channel object
const channel = otherGuild.channels.resolve("channel id");
Using discord.js ^12.5.3.

Check if someone replies to a bot in discord.js

I'm making a discord bot for asking people questions. How do I check if a certain user replies to it? (User A will say "!ask #UserB" and Bot will say "#UserB, Please answer the question" and UserB will reply.) I know the general code works, but I need a way to check for replies and the content of them.
Code:
module.exports = {
name: 'ask',
description: 'asks a question',
async execute(message, args) {
if (!args[0]) {
message.reply("Specify User");
} else {
message.channel.send(args[0] + " Please answer the question."); // args[0] will be the user
}
}
}
All messages have a message_reference property. This contains the guild, channel and message id. This property is null if it isn’t a reply. I assume you already know the channel.
//async function
//message is an instance of Message
let { channel, message_reference: reply } = message
const repliedTo = await channel.messages.fetch(reply.message_id);
//repliedTo is now the replied message with author, content, etc
if(repliedTo.author.bot) {
//replied messages author is a bot
}
Copied from my answer here

Discord.js Ban Command with Command Handler

I made a Discord.js Ban Command with reason and stuff however i overcome an error whenever i try to use it. Here is my code :
const { MessageEmbed } = require('discord.js');
module.exports = {
name: 'ban',
description: 'Ban a user from the server by using mentioning them!',
guildOnly: true,
aliases: ['ban', 'banbanban'],
usage: `-ban <USER_MENTION> <OPTIONAL_REASON>`,
cooldown: 5,
async execute(message, args, client) {
const daidinevermantion = new MessageEmbed()
daidinevermantion.setTitle('Incorrect arguments provided!')
daidinevermantion.setDescription('Please Mention a user to ban ;-;. Make sure it a mention. The bot may not be able to ban users not in the server')
daidinevermantion.addField('Usage','``;ban <USER_MENTION> <OPTIONAL REASON>``')
daidinevermantion.addField('Example Usage', ';ban <#760773438775492610> Good Bot')
if(!message.member.hasPermission("BAN_MEMBERS")) return message.channel.send('You can\'t use that!')
if(!message.guild.me.hasPermission("BAN_MEMBERS")) return message.channel.send('I don\'t have the right permissions.')
const member = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if(!args[0]) return message.channel.send(daidinevermantion);
if(!member) return message.channel.send('Can\'t seem to find this user. Sorry \'bout that :/. Make sure you are mentioning the user and the user is in the server!');
if(!member.bannable) return message.channel.send('This user can\'t be banned. It is either because they are a mod/admin, or their highest role is higher than mine');
if(member.id === message.author.id) return message.channel.send('Bruh, you can\'t ban yourself!');
let reason = args.slice(1).join(" ");
if(!reason) reason = 'Unspecified';
member.ban({ days: 7, reason: reason }).catch(err => {
message.channel.send('Something went wrong')
console.log(err)
})
const banembed = new Discord.MessageEmbed()
.setTitle('Member Banned')
.setThumbnail(member.user.displayAvatarURL())
.addField('User Banned', member)
.addField('Banned by', message.author)
.addField('Reason', reason)
.setFooter('Banned On:', client.user.displayAvatarURL())
.setTimestamp()
message.channel.send(banembed);
}
}
Here whenever i send this command I this message in return "This user can't be banned. It is either because they are a mod/admin, or their highest role is higher than mine" regardless of whatever the case is whether its position is higher or lower. I'm a bit new to Discord.js please help me out thanks a lot!
You are getting that message because member.bannable is always false, and the reason for that is your bot doesn't have the required permissions to ban a user. Use this permission calculator and reinvite the bot to the server with required permissions i.e "Ban Members" or "Administrator".

Categories

Resources