Good morning! I would like to know how I can make my bot to ban words, but not just the word, I want it to ban the entire sentence that is written. I've done this, but the problem is that it doesn't ban the entire sentence.
client.on('message', message => {
if (message.content === 'BAD WORD EXAMPLE') {
message.delete({
timeout: 1,
reason: 'Mensaje eliminado, contenido inapropiado..'
});
message.channel.send(' Mensaje eliminado por contenido inapropiado');
}
})
If you want to simply ban the member that sent a message including badWords, basically you can follow #Nurfey's answer and there's much simpler code, like
const badWords = ["foo", "faz", "bar"];
client.on('message', message => {
const hasBadWord = badWords.some(banWord => message.includes(banWord))
if(hasBadWord) {
// delete the message
}
});
If your checking will be more complex so that you want to write 2+ sentences, you can also do this:
const hasBadWord = badWords.some(banWord => {
// multiple sentences here, and returns true or false
})
The full documentation of Array.some() is available on MDN.
Based on what you've written, you could try this:
const badWords = ["foo", "faz", "bar"];
client.on('message', message => {
let hasBadWord = false;
badWords.forEach(badWord => {
if(hasBadWord === false) {
if(message.includes(badWord)) hasBadWord = true; // you could do message.toLowerCase().includes(badWord) for case sensitivity
}
});
if(hasBadWord === true) {
// delete the message
}
});
it's not particularly refined, but you could optimize it if you want, this is just for making it as easily readable as I can make it
Related
when a message receives a reaction or emoji, I want to save the letter "y" in Wish.
I need to use emoji in client.on("message", (message), not another, the next error is
ReferenceError: emoji is not defined
but i have no idea how to solve it
const { Client, Intents } = require("discord.js-selfbot");
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MESSAGE_REACTIONS],
});
let token = "";
client.on('ready', () => {
console.log('Ok!');
});
let ListWish = ["β€","π","π"];
let Wish;
client.on("message", (message) => {
if(ListWish.includes(emoji.name)){
Wish = 'y';
}
if(message.embeds.length >= 0)
// Check if the Message has embed or not
{
let embed = message.embeds
for(let i = 0; i < embed.length; i++)
{
if (!embed[i] || !embed[i].description) return;
// check each embed if it has description or not, if it doesnt then do nothing
{
if(Wish === 'y'){
message.channel.send("Have emoji heart")
}
}
}
}
});
client.login(token);
You can use the Message.awaitReactions() method to listen for reactions on a certain message without the need of using client.on('event').
The documentation already contains code that easily summarizes how to use it, so I won't write any code here.
Edit: I almost forgot to add this, I am pretty sure you can pass in a callback after the options, so there is no need to use .then().
so i am creating a bot with a kick command and would like to be able to add a reason for said action, i've heard from somewhere that i may have to do string manipulation. currently i have a standalone reason as shown in the code below:
client.on("message", (message) => {
// Ignore messages that aren't from a guild
if (!message.guild) return;
// If the message starts with ".kick"
if (message.content.startsWith(".kick")) {
// Assuming we mention someone in the message, this will return the user
const user = message.mentions.users.first();
// If we have a user mentioned
if (user) {
// Now we get the member from the user
const member = message.guild.member(user);
// If the member is in the server
if (member) {
member
.kick("Optional reason that will display in the audit logs")
.then(() => {
// lets the message author know we were able to kick the person
message.reply(`Successfully kicked ${user.tag}`);
})
.catch((err) => {
// An error happened
// This is generally due to the bot not being able to kick the member,
// either due to missing permissions or role hierarchy
message.reply(
"I was unable to kick the member (this could be due to missing permissions or role hierarchy"
);
// Log the error
console.error(err);
});
} else {
// The mentioned user isn't in this server
message.reply("That user isn't in this server!");
}
// Otherwise, if no user was mentioned
} else {
message.reply("You didn't mention the user to kick!");
}
}
});
Split message.content and slice the first 2 array elements, this will leave you with the elements that make up the reason. Join the remaining elements back to a string.
const user = message.mentions.users.first();
const reason = message.content.split(' ').slice(2).join(' ');
Here is something that could help:
const args = message.content.slice(1).split(" "); //1 is the prefix length
const command = args.shift();
//that works as a pretty good command structure
if(command === 'kick') {
const user = message.mentions.users.first();
args.shift();
const reason = args.join(" ");
user.kick(reason);
//really close to Elitezen's answer but you might have a very terrible problem
//if you mention a user inside the reason, depending on the users' id, the bot could kick
//the user in the reason instead!
}
Here's how you can take away that problem (with regex)
const userMention = message.content.match(/<#!?[0-9]+>/);
//you may have to do some more "escapes"
//this works since regex stops at the first one, unless you make it global
var userId = userMention.slice(2, userMention.length-1);
if(userId.startsWith("!")) userId = userId.slice(1);
const user = message.guild.members.cache.get(userId);
args.shift();
args.shift();
user.kick(args.join(" "))
.then(user => message.reply(user.username + " was kicked successfully"))
.catch(err => message.reply("An error occured: " + err.message))
I assume you want your full command to look something like
.kick #user Being hostile to other members
If you want to assume that everything in the command that isn't a mention or the ".kick" command is the reason, then to get the reason from that string, you can do some simple string manipulation to extract the command and mentions from the string, and leave everything else.
Never used the Discord API, but from what I've pieced from the documentation, this should work.
let reason = message.content.replaceAll(".kick", "")
message.mentions.forEach((mentionedUser) => reason.replaceAll("#" + mentionedUser.username, "")
// assume everything else left in `reason` is the sentence given by the user as a reason
if (member) {
member
.kick(reason)
.then(() => {
// lets the message author know we were able to kick the person
message.reply(`Successfully kicked ${user.tag}`);
})
}
I have tried every tutorial but they don't work, here is my current code:
bot.on('message', message => {
if (message.content.startsWith(`${prefix}globalannounce`)) {
var msg = message.content.split(" ").slice(1).join(" ")
var guildList = bot.guilds.array;
try {
let messageToSend = new Discord.MessageEmbed()
.setTitle("Hello, you don't see me messaging in your server often...")
.setDescription(`I have just flown in to tell you that my developers have something to say: \n ${msg}`)
guildList.array.forEach(channel => {
if (channel.type === 'text') channel.send(messageToSend).catch(console.error)
});
} catch (err) {
console.log(err);
}
}
});
It will not work and the error is TypeError: Cannot read property 'array' of undefined.
discord.js v12.x uses Managers, so you'll have to go through the cache property to get a list of guilds. See this post for more information.
Also, GuildList.forEach() would iterate a function throughout all Guilds in the collection, not all the channels. You can use the Channel.type property and Collection.find() to find the first text channel available.
var guildList = bot.guilds.cache; // go through the cache property
try {
let messageToSend = new Discord.MessageEmbed()
.setTitle("Hello, you don't see me messaging in your server often...")
.setDescription(
`I have just flown in to tell you that my developers have something to say: \n ${msg}`
);
guildList.forEach((guild) => {
const channel = guild.channels.cache.find((channel) => channel.type === 'text') // try to find the channel
if (!channel) return; // if it couldn't find a text channel, skip this guild
channel.send(messageToSend); // otherwise, send the message
});
} catch (err) {
console.log(err);
}
If you're using discord.js v12
You have the error TypeError: Cannot read property 'array' of undefined. This means that bot.guilds is equal to undefined. So the problem is here :
var guildList = bot.guilds.array;
You'll have to replace it with
var guildList = bot.guilds.cache
So your entire code would look like this :
bot.on('message', message => {
if (message.content.startsWith(`${prefix}globalannounce`)) {
var msg = message.content.split(" ").slice(1).join(" ")
var guildList = bot.guilds.cache
try {
let messageToSend = new Discord.MessageEmbed()
.setTitle("Hello, you don't see me messaging in your server often...")
.setDescription(`I have just flown in to tell you that my developers have something to say: \n ${msg}`)
guildList.forEach(guild =>{
guild.channels.cache.find(c => c.type === 'text').send(messageToSend)
});
} catch (err) {
console.log(err);
}
}
});
I want to create a verify Command with discord.js v12 which gives you a verified Role which is defined in a Configfile.
Configfile:
{
"token": "my-token",
"status": "a game",
"statusurl": "",
"statustype": 0,
"botmanager": ["285470267549941761", "743136148293025864"],
"prefix": "m!",
"server": {
"343308714423484416": {
"active": true,
"hasBeta": true,
"adminroles": ["533646738813353984"],
"modroles": ["744589796361502774"],
"premiumtoken": "",
"welcomechannel": "653290718248435732",
"welcomemessage": "Hey Hey %user% at %server%",
"welcomemsgenabled": true,
"leavechannel": "653290718248435732",
"leavemessage": "Bye %user% at %server%",
"leavemsgenabled": true,
"verifiedrole": "533646700712296448",
"ruleschannel": "382197929605201920"
}
}
}
My Code:
const Discord = require('discord.js')
const client = new Discord.Client()
const config = require('./config.json')
client.on('ready', () => {
client.user.setStatus('online')
client.user.setActivity("m!help")
console.log(`Bot started successfully in ${client.guilds.cache.size} Guilds with ${client.users.cache.size} Users and ${client.channels.cache.size} Channels`)
})
client.on("message", async message => {
if(message.author.bot) return;
if(!message.content.startsWith(config.prefix)) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if(command === "verify") {
if(args.length == 0) {
let member = message.mentions.members.first();
if(message.member.roles.cache.some(r=>[config.server[(message.guild.id)].modroles].includes(r.id))) {
if(!member) {
return message.channel.send(new Discord.MessageEmbed().setColor(0xd35400).setTitle("Invalid User").setDescription("Please use the following Syntax:\n `m!verify <Nutzer>`"))
} else {
var role = message.guild.roles.find(role => role.id === config.server[(message.guild.id)].verifiedrole);
member.roles.cache.add(config.guild[(message.guild.id)].verifiedrole)
}
} else {
message.channel.send(new Discord.MessageEmbed().setTitle("Missing Perms!").setDescription("You're missing the permission to execute this command!").setColor(0xe74c3c))
}
}
}
console.log("Command used: " + command + " " + args + " | User: " + message.author.id + " | Guild: " + message.guild.id)
}
}
})
client.login(config.token)
I removed the most Code so only this command is left. Important is, that this Bot have to be able to use at multiple Servers at the time.
What is wrong here?
OK, so lets make this a multi part answer. First "What is wrong here?" Well, for the most part your current code does not work because you don't use the brackets correctly. You are trying to close brackets that you don't open anywhere. You also use a few too many "if" statements in places where you don't need them.
Next is your concern about multiple servers. This is really not a problem if you write the code to be dynamic. The execution of the command is quick enough that you don't need to worry about two people trying to use the command and the roles getting mixed up.
What I would really advise you to do is take a look at this https://discordjs.guide/ and this https://discord.js.org/#/docs/main/stable/general/welcome
Now to the topic of this question, this is how you could do such a "verify" command. I also added a few notations into the code to explain what we're doing π
client.on("message", message => { // You don't need the async here
// This is all working correctly
if (message.author.bot) return;
if (!message.content.startsWith(config.prefix)) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if (command === "verify") {
// We define the server constant as the part of the JSON that deals with the server the message came from
// This makes accessing those values easier
const server = config.server[message.guild.id];
// Your code here was also working
let member = message.mentions.members.first();
// Here we first define the moderator role
// Technicaly this is not needed but it makes the whole code a little easier to understand
// We need modrole[0] here because the modrole entry in your JSON is an array
let modrole = message.guild.roles.cache.find(r => r.id === server.modroles[0]);
// Here we check if the member who calls this command has the needed role
// We need to use the ID of the role to check
if (!message.member.roles.cache.has(modrole.id)) {
// If the user does not have the required role we return here
// That way you don't need to use the 'else' statement
// Creating the embed object in multiple lines improves readability
return message.channel.send(new Discord.MessageEmbed()
.setTitle("Missing Perms!")
.setDescription("You're missing the permission to execute this command!")
.setColor(0xe74c3c)
);
}
if (!member) {
// Here we check if a member was tagged in the command and if that user exists
// Same reasons as above
return message.channel.send(new Discord.MessageEmbed()
.setColor(0xd35400)
.setTitle("Invalid User")
.setDescription(`Please use the following Syntax:\n '${config.prefix}verify <Nutzer>'`)
);
}
// Now we define the role that we want the bot to give
// Here we also don't need to do this but it improves readability and makes working with the role a little easier
var role = message.guild.roles.cache.find(role => role.id === server.verifiedrole);
// Here we add the role to the specified member
// We don't need to use the .cache here
member.roles.add(role.id);
// We can use something called "template strings" here so we don't need to combine multiple strings
// They allow us to put predefined values into the string
console.log(`Command used: ${command} ${args} | User: ${message.author.id} | Guild: ${message.guild.id}`)
}
})
If you want, that the command can be executed at multiple servers at the time you need to write the code in async/await. If you want to learn more about async you can get very good help especially for discord.js v12 here: Understanding async/await
you can get a command for a specifiq channel and give a role for acces to the server
I have recently created a bot for my discord server. Now I want him to filter bad words.
For example:
User (without bot): You are an asshole
User (with bot): You are an [I'm stupid because I swear]
Is this even possible in Discord? I have given my bot all permissions! (including removing messages, it can't edit message with the program self tho)
If that is not possible^ Can we do the following?
The ability to directly delete the message and write the following:
Bot: #username Do not swear!
Now I have the following code (I dont know if useful):
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
console.log('Hello, the bot is online!')
});
client.on('message', message => {
if(message.content === '--Trump'){
message.reply('He is the president of the United States of
America!');
}
if(message.content === '--Putin'){
message.reply('He is the president of Russia!');
}
});
client.login('MzAwMzM5NzAyMD*1NDUxNzc4.C8rH5w.M44LW*nrfbCR_zHzd**vtMqkr6nI');
Docs. Currently in the Discord API there is no possible way to edit a message from another user. You could completely delete the message or you could resend it but edited. If you want to resend it then you could use:
let censor = "[Sorry, I Swear]"; /* Replace this with what you want */
client.on('message', message => {
let edit = message.content.replace(/asshole/gi, censor);
message.delete();
message.channel.send(`${message.author.username}: ${edit}`);
}
Input >>> Hello asshole
Output <<< AkiraMiura: Hello [Sorry, I Swear]
Take note that if the user sends a 2000 byte (Charater) long message you won't be able to send a fixed version and it would just get deleted.
Use Regex to help you detect from blacklisted words you wanted to.
For example, If you want to blacklist the word asshol*, use the regex to detect the word:
if ((/asshole/gm).test(message.content))
message.delete().then(() => {
message.reply('Do not swear!'); // Sends: "#user1234 Do not swear!"
});
}
If you wanted to blacklist/filter MULTIPLE words, like fu*k and sh*t
Use separators in Regex: /(word1|word2|word3)/gm
So... use:
if ((/(fuck|shit)/gm).test(message.content)) {
message.delete().then(() => {
message.reply('Do not swear!');
});
}
It's fully working!
Re-write in FULL code,
client.on('message', (message) => {
if ((/asshole/gm).test(message.content)) {
message.delete().then(() => {
message.reply('Do not swear!'); // Sends: "#user1234 Do not swear!"
});
}
});
Tell me if it works
Good Luck,
Jedi
try:
client.on('message', message => {
message.edit(message.content.replace(/asshole/gi, "[I'm stupid because I swear]"))
.then(msg => console.log(`Updated the content of a message from ${msg.author}`))
.catch(console.error);
});
credit to #AndrΓ© Dion for bringing up the right method from the API