Detect links in messages in Discord.js - javascript

I'm new to discord.js. I'm trying to check if a message contains a link like "Hi, I'm from discord.gg/xxxxx and now I'll spam my link".
How can I check if the message contain the link?

I am unsure if you want to check for discord invite links specifically, or if you want to check for all links. Either way, you can use message.content.includes.
Example:
bot.on('message', (message) => { //whenever a message is sent
if (message.content.includes('discord.gg/'||'discordapp.com/invite/')) { //if it contains an invite link
message.delete() //delete the message
.then(message.channel.send('Link Deleted:\n**Invite links are not permitted on this server**'))
}
})

I find this is the best:
let regx = /^((?:https?:)?\/\/)?((?:www|m)\.)? ((?:discord\.gg|discordapp\.com))/g
let cdu = regx.test(message.content.toLowerCase().replace(/\s+/g, ''))
Tell me if it works!

What you are doing works but you don't need .then() just leave the message.channel.send() as it is.

You can try this:
bot.on(`message`, async message => {
const bannedWords = [`discord.gg`, `.gg/`, `.gg /`, `. gg /`, `. gg/`, `discord .gg /`, `discord.gg /`, `discord .gg/`, `discord .gg`, `discord . gg`, `discord. gg`, `discord gg`, `discordgg`, `discord gg /`]
try {
if (bannedWords.some(word => message.content.toLowerCase().includes(word))) {
if (message.author.id === message.guild.ownerID) return;
await message.delete();
await message.channel.send(`You cannot send invites to other Discord servers`);
}
} catch (e) {
console.log(e);
}
});
(There was a missing ")")

You can check this using Regular Expressions (RegEX)
Example:
// The message to check for a Discord link
var message = "Hi, please join discord.gg/a2dsc for cool conversations";
// The message will be tested on "discord.gg/{any character or digit}"
var containsDiscordUrl = message.test(/discord.gg\/\w*\d*);
// If the test has found a URL..
if (containsDiscordUrl) { // ... Do something }

let regexp = /^(?:(?:https?|ftp):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/;
I think this is helping you.

Related

removing mentions (discord.js 12.5.3)

I need to remove a user mention from message content, but nothing works.
Discord.js version: 12.5.3
var content = message.content.toLowerCase().slice(6).trim().replace(/#(everyone)/gi, "#evеryone").replace(/#(here)/gi, "#hеre");
!message.content.trim().endsWith('-test');
if (message.mentions.users.size) {
const mentioned = message.mentions.users.first();
content.replace(``, '') // here is a problem
var form = `${content}`;
} else {
doSomething()
}
message.channel.send(form);
Its really simple actually. Discord.js has its own function for that: Util.cleanContent()
You can replace all your code with this one-liner:
message.channel.send(discord.Util.cleanContent(message.content, message))
or (as #MrMythical rightfully mentioned):
return message.reply(message.cleanContent)
The message still looks the same, just without the pings.
Try This
if(message.content.toLowerCase().includes("#")) {
message.delete()
message.reply("Do Not Ping!")
}

discord.js Javascript string manipulation

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}`);
})
}

When creating a addMemberToRole I get this error: ReferenceError: mesage is not defined

When im coding the part of the discord bot that gives a role when activated i keep getting this error and im not sure if there is a bug i dont see but if you see it pls help me correct it!
Error message.
if(mesage.content.startsWith(prefix + "prune")){
^
ReferenceError: mesage is not defined
Section of script with problem.
if(mesage.content.startsWith(prefix + "prune")){
let args = Message.content.split(" ").slice(1);
let author = Message.member;
let role = message.guilds.roles.find('name', "Moderator");
if(author.roles.has(role.id)){
if(!args[0]){
Message.delete();
Message.author.send("No arguments given.");
return;
}
}
}
Full Script
const Discord = require('discord.js')
const Client = new Discord.Client
const prefix = "/";
Client.on('ready', ()=>{
console.log('Bot is online.');
})
Client.on('message', (Message)=>{
if(!Message.content.startsWith(prefix)) return;
if(Message.content.startsWith(prefix + "hello")){
Message.channel.send("Hello.");
}
if(Message.content.startsWith(prefix + "help")){
Message.channel.send("The only avaible command right now is /help and /hello.")
Message.author.send("This is only for test purposes!");
}
if(mesage.content.startsWith(prefix + "prune")){
let args = Message.content.split(" ").slice(1);
let author = Message.member;
let role = message.guilds.roles.find('name', "Moderator");
if(author.roles.has(role.id)){
if(!args[0]){
Message.delete();
Message.author.send("No arguments given.");
return;
}
}
}
})
Client.login("<Bot Token>");
All your code refers to Message, except this line which is mesage, not only mis-spelled, but incorrectly lower-case.
Making that consistent with the other things should fix the issue.
Note that JavaScript generally reserves capital letters for things like classes, lower-case for variables and arguments. As you can see here the syntax highlighter thinks this is a class and is colouring it accordingly. Lower-case message is the conventional argument name.
Change mesage (the typo) with message (not uppercase). Make sure to also change Message with message (again, no uppercase)

How do I #everyone with discord.js?

I want to have a simple command like "!hello" to output "Hello #everyone" and ping everyone. The output text is correct, but it doesn't actually ping. The command just shows the text #everyone without doing the mention.
const Discord = require("discord.js")
module.exports.run = async (bot, message, args) => {
message.channel.send("#everyone Hello!");
}
module.exports.help = {
name: "hello"
}
I would expect it to output this:
Actual Result:
So, turns out I had:
const bot = new Discord.Client({disableEveryone: True});
Once I changed it to:
const bot = new Discord.Client({disableEveryone: False});
everything worked.
Thank you for your help everyone.
Citing discord.js issue #2285:
You mention everyone or here with the literal strings #everyone or #here, not a > regular role mention.
This is not a bug, but a discord thing.
Try this
message.channel.send("<#everyone>" + "Hello!");
There is a guild.defaultRole
You can mention it like this:
client.on('message', (msg) => {
msg.channel.send(msg.guild.defaultRole.toString());
});
You can check if your bot can mention everyone this way:
client.on('message', (msg) => {
let everyone = msg.guild.defaultRole;
if (msg.guild.me.hasPermission(everyone.permissions)) {
msg.channel.send(everyone.toString());
} else {
console.log("I can't mention everyone");
}
});
You can fetch the everyone role from guild.roles.
const everyone = await guild.roles.fetch("#everyone");
channel.send(`Hello ${everyone}`);
I'm not sure why, but I remember having to put the role in its own string literal in the send call:
message.channel.send("#everyone" + " Hello!");
Unable to test for myself atm, see if that works.

How do I filter words with a discord bot? (JavaScript)

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

Categories

Resources