@joshbrucker/discordjs-utils
Version:
A set of utility classes and functions to aid with discord.js bot development. Paged embeds, emoji utilities, and more!
72 lines (71 loc) • 2.1 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetch = fetch;
exports.react = react;
exports.formatForChat = formatForChat;
/*
Super rudimentary cache here to avoid making repetitive calls across shards
TODO: Add some form of cache invalidation
*/
const emojiCache = new Map();
/*
Retrieves a GuildEmoji based on the given identifier string (emoji ID or name).
This function will work on sharded bots.
*/
async function fetch(client, identifier) {
// Check cache for emoji first
if (emojiCache.has(identifier)) {
return emojiCache.get(identifier);
}
function findEmoji(target, options) {
const emoji = target.emojis.cache.get(options.identifier) ||
target.emojis.cache.find((e) => e.name?.toLowerCase() === options.identifier.toLowerCase());
if (!emoji)
return null;
return emoji;
}
let foundEmoji;
if (client.shard) {
let emojiArray = await client.shard.broadcastEval(findEmoji, {
context: { identifier: identifier },
});
emojiArray = emojiArray.filter((emoji) => emoji != null);
foundEmoji = emojiArray.shift();
}
else {
foundEmoji = findEmoji(client, { identifier: identifier });
}
// If found, add to the cache
if (foundEmoji) {
emojiCache.set(identifier, foundEmoji);
}
return foundEmoji;
}
/*
Reacts to a message with all given emojis, in order.
Can accept either an array of emojis or a single emoji.
*/
async function react(message, emojis) {
if (emojis instanceof Array) {
for (const emoji of emojis) {
await message.react(emoji);
}
}
else {
await message.react(emojis);
}
}
/*
Formats an emoji to be displayed in a text channel.
*/
function formatForChat(emoji, padWithSpace = false) {
if (emoji) {
const emojiString = emoji.animated
? `<${emoji.identifier}>`
: `<:${emoji.identifier}>`;
return padWithSpace ? ` ${emojiString} ` : emojiString;
}
else {
return "";
}
}