removing mentions (discord.js 12.5.3) - javascript

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!")
}

Related

How the bot mention people if someone boost/unboost the server

My bot sends the message if someone boosts/unboosts the server.
You can see my code here:
client.on("guildMemberUpdate", (oldMember, newMember) => {
const oldStatus = oldMember.premiumSince;
const newStatus = newMember.premiumSince;
if (!oldStatus && newStatus) {
client.channels.cache
.get("channel id")
.send(`Thank you ${newMember.user.tag} (:`);
}
if (oldStatus && !newStatus) {
client.channels.cache
.get("channel id")
.send(`woah ${newMember.user.tag}, unboost this server`);
}
});
The code works perfectly, there is no error, but the bot is not tagging people, just mentioning the tag name like this:
I want the bot to mention people like this instead:
I think the problem is ${newMember.user.tag}. Usually, I use <#${member.id}>, but I don't know how to fix this code if using {user.tag}.
You can either use:
.send(`woah <#${newMember.id}>, unboost this server`)
or simply:
.send(`woah ${newMember}, unboost this server`)

Replace certain character in Discord.JS

Now, before you say that this has been posted before, I have a different situation.
With that out of the way, let's get on with the question.
I am making a Discord bot for a friend that does duties for the group and things like that.
Quick note too, I am using the Sitepoint version of Discord.JS because I'm a beginner.
I want the bot to send a message to a certain channel when the show gets canceled for a reason. For example, they would send something like this:
afv!cancel Roblox went down.
or something similar.
But every time it sends a message, every space turns into a comma like this:
:x: The show has been cancelled because: "Roblox,went,down.". Sorry for that!
Here's the index.js code that handles executing commands:
bot.on('message', msg => {
const args = msg.content.split(/ +/);
const command = args.shift().toLowerCase();
const prefix = command.startsWith("afv!");
if (prefix == true) {
console.info(`Called command: ${command}`);
if (!bot.commands.has(command)) return;
msg.delete(1);
try {
bot.commands.get(command).execute(msg, args, bot);
} catch (error) {
console.error(error);
msg.reply('there was an error trying to execute that command!');
};
And the cancelled.js file:
module.exports = {
name: 'afv!cancel',
description: "in-case the show gets cancelled",
execute(msg, args, bot) {
if (msg.member.roles.find(r => r.name === "Bot Perms")) {
const reason = args.replace(/,/g, " ");
bot.channels.get('696135370987012240').send(':x: **The show has been cancelled** because: "' + args + '". *Sorry for that!*');
bot.user.setActivity("AFV! | afv!help", { type: 'PLAYING' });
} else {
msg.reply('you are missing the role: Bot Perms!');
}
},
};
By the way, upon executing the command, it prints this:
TypeError: args.replace is not a function
Thanks for reading! :)
From what I can see, here
const reason = args.replace(/,/g, " ");
bot.channels.get('696135370987012240').send(':x: **The show has been cancelled** because: "' + args + '". *Sorry for that!*');
you are making a const reason, wherein you try to handle that as a string and replace all commas with spaces. Unfortunately, even though it can be displayed in a string and looks to be one, in reality it is an array, so replace() won't work on it. To be able to use replace() you need to first transform your array to an actual string:
const reason = args.join().replace(/,/g, " ");
With that done you won't be seeing this pesky "not a function" error, and you can easily use reason to display your message:
bot.channels.get('696135370987012240').send(':x: **The show has been cancelled** because: "' + reason + '". *Sorry for that!*');

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.

Detect links in messages in Discord.js

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.

How Find Emojis By Name In Discord.js

So I have been utterly frustrated these past few days because I have not been able to find a single resource online which properly documents how to find emojis when writing a discord bot in javascript. I have been referring to this guide whose documentation about emojis seems to be either wrong, or outdated:
https://anidiots.guide/coding-guides/using-emojis
What I need is simple; to just be able to reference an emoji using the .find() function and store it in a variable. Here is my current code:
const Discord = require("discord.js");
const config = require("./config.json");
const fs = require("fs");
const client = new Discord.Client();
const guild = new Discord.Guild();
const bean = client.emojis.find("name", "bean");
client.on("message", (message) => {
if (bean) {
if (!message.content.startsWith("#")){
if (message.channel.name == "bean" || message.channel.id == "478206289961418756") {
if (message.content.startsWith("<:bean:" + bean.id + ">")) {
message.react(bean.id);
}
}
}
}
else {
console.error("Error: Unable to find bean emoji");
}
});
p.s. the whole bean thing is just a test
But every time I run this code it just returns this error and dies:
(node:3084) DeprecationWarning: Collection#find: pass a function instead
Is there anything I missed? I am so stumped...
I never used discord.js so I may be completely wrong
from the warning I'd say you need to do something like
client.emojis.find(emoji => emoji.name === "bean")
Plus after looking at the Discord.js Doc it seems to be the way to go. BUT the docs never say anything about client.emojis.find("name", "bean") being wrong
I've made changes to your code.
I hope it'll help you!
const Discord = require("discord.js");
const client = new Discord.Client();
client.on('ready', () => {
console.log('ready');
});
client.on('message', message => {
var bean = message.guild.emojis.find(emoji => emoji.name == 'bean');
// By guild id
if(message.guild.id == 'your guild id') {
if(bean) {
if(message.content.startsWith("<:bean:" + bean.id + ">")) {
message.react(bean.id);
}
}
}
});
Please check out the switching to v12 discord.js guide
v12 introduces the concept of managers, you will no longer be able to directly use collection methods such as Collection#get on data structures like Client#users. You will now have to directly ask for cache on a manager before trying to use collection methods. Any method that is called directly on a manager will call the API, such as GuildMemberManager#fetch and MessageManager#delete.
In this specific situation, you need to add the cache object to your expression:
var bean = message.guild.emojis.cache?.find(emoji => emoji.name == 'bean');
In case anyone like me finds this while looking for an answer, in v12 you will have to add cache in, making it look like this:
var bean = message.guild.emojis.cache.find(emoji => emoji.name == 'bean');
rather than:
var bean = message.guild.emojis.find(emoji => emoji.name == 'bean');

Categories

Resources