refactor(Util): make single replace call in cleanContent (#8210)

Co-authored-by: Almeida <almeidx@pm.me>
This commit is contained in:
A. Román
2022-07-03 15:36:20 +02:00
committed by GitHub
parent 50d55bd6b8
commit 6b20645740

View File

@@ -474,6 +474,7 @@ function basename(path, ext) {
const res = parse(path); const res = parse(path);
return ext && res.ext.startsWith(ext) ? res.name : res.base.split('?')[0]; return ext && res.ext.startsWith(ext) ? res.name : res.base.split('?')[0];
} }
/** /**
* The content to have all mentions replaced by the equivalent text. * The content to have all mentions replaced by the equivalent text.
* @param {string} str The string to be converted * @param {string} str The string to be converted
@@ -481,32 +482,32 @@ function basename(path, ext) {
* @returns {string} * @returns {string}
*/ */
function cleanContent(str, channel) { function cleanContent(str, channel) {
str = str return str.replaceAll(/<(@[!&]?|#)(\d{17,19})>/g, (match, type, id) => {
.replace(/<@!?[0-9]+>/g, input => { switch (type) {
const id = input.replace(/<|!|>|@/g, ''); case '@':
if (channel.type === ChannelType.DM) { case '@!': {
const user = channel.client.users.cache.get(id); const member = channel.guild?.members.cache.get(id);
return user ? `@${user.username}` : input;
}
const member = channel.guild.members.cache.get(id);
if (member) { if (member) {
return `@${member.displayName}`; return `@${member.displayName}`;
} else {
const user = channel.client.users.cache.get(id);
return user ? `@${user.username}` : input;
} }
})
.replace(/<#[0-9]+>/g, input => { const user = channel.client.users.cache.get(id);
const mentionedChannel = channel.client.channels.cache.get(input.replace(/<|#|>/g, '')); return user ? `@${user.username}` : match;
return mentionedChannel ? `#${mentionedChannel.name}` : input; }
}) case '@&': {
.replace(/<@&[0-9]+>/g, input => { if (channel.type === ChannelType.DM) return match;
if (channel.type === ChannelType.DM) return input; const role = channel.guild.roles.cache.get(id);
const role = channel.guild.roles.cache.get(input.replace(/<|@|>|&/g, '')); return role ? `@${role.name}` : match;
return role ? `@${role.name}` : input; }
case '#': {
const mentionedChannel = channel.client.channels.cache.get(id);
return mentionedChannel ? `#${mentionedChannel.name}` : match;
}
default: {
return match;
}
}
}); });
return str;
} }
/** /**