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; if (member) {
} return `@${member.displayName}`;
}
const member = channel.guild.members.cache.get(id);
if (member) {
return `@${member.displayName}`;
} else {
const user = channel.client.users.cache.get(id); const user = channel.client.users.cache.get(id);
return user ? `@${user.username}` : input; return user ? `@${user.username}` : match;
} }
}) case '@&': {
.replace(/<#[0-9]+>/g, input => { if (channel.type === ChannelType.DM) return match;
const mentionedChannel = channel.client.channels.cache.get(input.replace(/<|#|>/g, '')); const role = channel.guild.roles.cache.get(id);
return mentionedChannel ? `#${mentionedChannel.name}` : input; return role ? `@${role.name}` : match;
}) }
.replace(/<@&[0-9]+>/g, input => { case '#': {
if (channel.type === ChannelType.DM) return input; const mentionedChannel = channel.client.channels.cache.get(id);
const role = channel.guild.roles.cache.get(input.replace(/<|@|>|&/g, '')); return mentionedChannel ? `#${mentionedChannel.name}` : match;
return role ? `@${role.name}` : input; }
}); default: {
return str; return match;
}
}
});
} }
/** /**