Check if someone replies to a bot in discord.js - javascript

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

Related

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

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

Discord.js kick command permissions problem

So the last question I asked, I tried to use the sample code in MrMythical answer. This time, I encountered another problem:
if (message.member.permissions.has(Permissions.FLAGS.BAN_MEMBERS)){
^
ReferenceError: Permissions is not defined
The code:
module.exports = new Command({
name: "kick",
description: "kick",
async run(message, args, client) {
if (message.member.permissions.has(Permissions.FLAGS.BAN_MEMBERS)) {
if (message.mentions.members) {
try {
message.mentions.kick();
} catch {
message.reply("I don't have permission to ban " + message.mentions.members.first());
}
} else {
message.reply("You cannot ban " + message.member.mentions.first());
}
}
}
});
Let's say I deleted the if (message.member.permissions.has(Permissions.FLAGS.BAN_MEMBERS)), the message the returned when executing the command was I don't have permission to ban <insert_user_id>.
I'm kinda stuck here for a while, if you can help me, thank you so much.
Edit: I forgot to import the Permissions, so there's just "Don't have permissions to kick" now
You will need to import Permissions from discord.js. You can import it at the top of the page, like this:
const { Permissions } = require('discord.js');
Also, message.mentions returns an object and it includes the mentioned members, channels, and roles. It won't have a kick() method and if you try to call it, it will throw an error. As you don't log the error in your catch block, you will have no idea what the error is; it will just send a reply saying "You cannot ban undefined".
You will need to check if there are mentioned members by checking message.mentions.members. It returns a collection; you can grab the first member by using first().
You can kick the first mentioned member like this:
const { Permissions } = require('discord.js');
module.exports = new Command({
name: 'kick',
description: 'kick',
async run(message, args, client) {
if (!message.member.permissions.has(Permissions.FLAGS.BAN_MEMBERS))
return message.reply('You have no permission to ban members');
if (!message.mentions.members)
return message.reply('You need to mention a member to ban');
let mentionedMember = message.mentions.members.first();
try {
mentionedMember.kick();
} catch (err) {
console.log(err);
message.reply(`Oops, there was an error banning ${mentionedMember}`);
}
},
});

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.

invite Created event

so I'm making a Discord Bot, with auto logging capabilities, until now I managed due to do most of the code, these include the command for setting a mod-log channel and the event code, here's the code for the command:
let db = require(`quick.db`)
module.exports = {
name: "modlog",
aliases: ["modlogs", "log", "logs"],
description: "Change the modlogs channel of the current server",
permission: "MANAGE_CHANNELS",
usage: "modlog #[channel_name]",
run: async (client, message, args) => {
if(!message.member.hasPermission(`MANAGE_CHANNELS`)) {
return message.channel.send(`:x: You do not have permission to use this command!`)
} else {
let channel = message.mentions.channels.first();
if(!channel) return message.channel.send(`:x: Please specify a channel to make it as the modlogs!`)
await db.set(`modlog_${message.guild.id}`, channel)
message.channel.send(`Set **${channel}** as the server's modlog channel!`)
}
}
}
And the inviteCreate event:
client.on("inviteCreate", async invite => {
const log = client.channels.cache.get(`${`modlog_${message.guild.id}`}`)
let inviteCreated = new Discord.MessageEmbed()
log.send(`An invite has been created on this server!`)
})
The issue is that since the inviteCreate event only accepts one parameter (I think that's what they are called) which is invite, there is no message parameter, so message becomes undefined, does anyone have a solution?
Thanks!
You don't need message in this case. See the documentation of invite.
Your message.member can be replaced with invite.inviter
Your message.channel can be replaced with invite.channel
Your message.guild can be replaced with invite.guild
Invites also have a guild property, that's the guild the invite is for, so you can use that instead of the message.guild:
client.on('inviteCreate', async (invite) => {
const log = client.channels.cache.get(`${`modlog_${invite.guild.id}`}`);
let inviteCreated = new Discord.MessageEmbed();
log.send(`An invite has been created on this server!`);
});

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