Botanique/src/utils/misc.ts

105 lines
2.4 KiB
TypeScript
Raw Normal View History

import { GuildMember } from "discord.js";
/**
* Log module status.
* @param {string} name Module name
* @param {boolean} status Module status
* @returns String
*/
export const logStart = (name: string, status: boolean) => {
// TODO Handle precision about the error if status is false
return `> ${name}\t${status === true ? "✅" : "❌"}`;
};
/**
* Filename without path and extension.
* @param path __filename
* @returns string
*/
export const getFilename = (path: string) => {
const path_list = path.split("/");
// Check if filename exist
const filename_with_ext = path_list.pop();
if (filename_with_ext === undefined) {
throw new Error(`Filename error: don't exist in ${path}`);
}
return removeExtension(filename_with_ext);
};
/**
* Remove extension from a filename.
* @param filename string of the filename with an extension
* @returns string of the filename without an extension
*/
export const removeExtension = (filename: string) => {
const array = filename.split(".");
array.pop();
return array.join(".");
};
/**
* Get extension from a filename.
* @param filename string of the filename
* @returns string of the extension if it exists
*/
export const getExtension = (filename: string) => {
const array = filename.split(".");
return array.pop();
};
/**
* Define if a media is a media based on file extension.
* @param filename string of the filename
* @returns true is file is a media
*/
export const isImage = (filename: string) => {
return Boolean(getExtension(filename)?.match(/jpg|jpeg|png|webp|gif/));
};
/**
* String with pseudo and nickname if available.
* @param member Member
* @returns string
*/
export const userWithNickname = (member: GuildMember) => {
if (!member) {
return undefined;
}
if (member.nickname) {
return `${member.nickname} (${member.user.tag})`;
} else {
return member.user.tag;
}
};
/**
* Move the text into backtick text, preserving mentions and links
* @param text Text
* @returns Formatted text
*/
export const cleanCodeBlock = (text: string) => {
text = `\`${text.trim()}\``;
// Keep mentions
text = text.replace(/(<@\d+>)/g, function (mention: string) {
return `\`${mention}\``;
});
// Keep links
text = text.replace(
/(http[s]?:\/\/(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)/g,
function (url: string) {
return `\`${url}\``;
}
);
// Fix issues
text = text.replace("``", "");
return text;
};