feat: add tests and other such features (#3)

* converted import syntax to ES modules

removed unused methods

* got test sort of working (jest set up is not crashing but also not mocking correctly)

* adjusted beforeeach/beforeall so more pass

* more correct test setup

* converted import syntax to commonJS

removed unused methods

* got test sort of working (jest set up is not crashing but also not mocking correctly)

* adjusted beforeeach/beforeall so more pass

* more correct test setup

* more correct dockerfile and compose.yaml

* Revert "converted import syntax to commonJS"

This reverts commit 5ab0d62b

* updated jest to sort of work with es6

* separating out enum return from method return

* mostly working except for the weirdest error

* nevermind it wasn't actually working, gonna move on for now

* added babel to convert es modules to cjs

* finally figured out issue with tests (referencing the method directly in the test.each calls the real method not the mock in beforeEach())

* setup fixed more

* added error handling parseMemberCommand test

* renamed db to database
more tests and fixing logic for memberhelper

* upgraded fluxer.js

* moved import to helpers folder

* moved import to helpers folder

* more tests for member helper

* think i fixed weird error with webhook sending error when a user has no members

* simplified sendMessageAsAttachment

* added return to addFullMember so that addNewMember can reference it properly in strings

* test setup for messagehelper and webhookhelper

* readded line i shouldn't have removed in sendMessageAsMember

* fixed test and logic

* added test for memberHelper

* updated sendMessageAsAttachment to returnBufferFromText and updated commands/webhookHelper accordingly

* added tests for parseProxyTags and updated logic

* added "return" so tests dont terminate on failure and deleted env.jest

* finished tests for messageHelper!

* more cases for messageHelper just in case

* updating docstring for messageHelper parseProxyTags

* more tests for webhookhelper

* deleted extra file added during merge

* removed confusing brackets from enum docs

* finally mocking correctly

* adding more cases to messageHelper tests

* updating enums

* removed error response when proxy is sent without content

* , updated tests for webhookHelper and removed error response when proxy is sent without content

* added debounce to count guilds properly

* added todo note

* added tests for updateDisplayName

* edited help message trigger for updatePropic

* update message helper test to include space case

* update bot to suppress errors from API

* fixed bug for import not sending help text, added help text if you type a unrecognized command

* updated to be enum

* updated member helper and tests

* edit enums, tweak import content command

* removed unnecessary await and console.log

* made it easier to make a member

* added nicer error listing to importHelper

* updated documentation

* Merge branch 'main' of https://github.com/pieartsy/PluralFlux into add-tests

---------

Co-authored-by: Aster Fialla <asterfialla@gmail.com>
This commit is contained in:
2026-02-19 21:45:10 -05:00
committed by GitHub
parent d24bcc8438
commit 8fc590c062
18 changed files with 1337 additions and 212 deletions

View File

@@ -0,0 +1,43 @@
import {enums} from "../enums.js";
import {memberHelper} from "./memberHelper.js";
const ih = {};
/**
* Tries to import from Pluralkit.
*
* @async
* @param {string} authorId - The author of the message
* @param {string} attachmentUrl - The attached JSON url.
* @returns {string} A successful addition of all members.
* @throws {Error} When the member exists, or creating a member doesn't work.
*/
ih.pluralKitImport = async function (authorId, attachmentUrl) {
if (!attachmentUrl) {
throw new Error(enums.err.NOT_JSON_FILE);
}
return fetch(attachmentUrl).then((res) => res.json()).then(async(pkData) => {
const pkMembers = pkData.members;
let errors = [];
const addedMembers = [];
for (let pkMember of pkMembers) {
const proxy = pkMember.proxy_tags[0] ? `${pkMember.proxy_tags[0].prefix ?? ''}text${pkMember.proxy_tags[0].suffix ?? ''}` : null;
await memberHelper.addFullMember(authorId, pkMember.name, pkMember.display_name, proxy, pkMember.avatar_url).then((memberObj) => {
addedMembers.push(memberObj.member.name);
if (memberObj.errors.length > 0) {
errors.push(`\n**${pkMember.name}:** `)
errors = errors.concat(memberObj.errors);
}
}).catch(e => {
errors.push(e.message);
});
}
const aggregatedText = addedMembers.length > 0 ? `Successfully added members: ${addedMembers.join(', ')}` : enums.err.NO_MEMBERS_IMPORTED;
if (errors.length > 0) {
throw new AggregateError(errors, aggregatedText);
}
return aggregatedText;
});
}
export const importHelper = ih;

View File

@@ -1,4 +1,4 @@
import {db} from '../db.js';
import {database} from '../database.js';
import {enums} from "../enums.js";
import {EmptyResultError, Op} from "sequelize";
import {EmbedBuilder} from "@fluxerjs/core";
@@ -17,22 +17,28 @@ const commandList = ['--help', 'new', 'remove', 'name', 'list', 'displayName', '
* @param {string[]} args - The message arguments
* @param {string | null} attachmentUrl - The message attachment url.
* @param {string | null} attachmentExpiration - The message attachment expiration (if uploaded via Fluxer)
* @returns {Promise<string> | Promise <EmbedBuilder>} A message, or an informational embed.
* @returns {Promise<string>} A success message.
* @returns {Promise <EmbedBuilder>} A list of 25 members as an embed.
* @returns {Promise<{EmbedBuilder, [], string}>} A member info embed + info/errors.
* @throws {Error}
*/
mh.parseMemberCommand = async function(authorId, authorFull, args, attachmentUrl = null, attachmentExpiration = null){
mh.parseMemberCommand = async function (authorId, authorFull, args, attachmentUrl = null, attachmentExpiration = null) {
let member;
// checks whether command is in list, otherwise assumes it's a name
if(!commandList.includes(args[0])) {
if (!commandList.includes(args[0]) && !args[1]) {
member = await mh.getMemberInfo(authorId, args[0]);
}
switch(args[0]) {
switch (args[0]) {
case '--help':
return enums.help.MEMBER;
case 'new':
return await mh.addNewMember(authorId, args).catch((e) =>{throw e});
return await mh.addNewMember(authorId, args, attachmentUrl).catch((e) => {
throw e
});
case 'remove':
return await mh.removeMember(authorId, args).catch((e) =>{throw e});
return await mh.removeMember(authorId, args).catch((e) => {
throw e
});
case 'name':
return enums.help.NAME;
case 'displayname':
@@ -45,20 +51,32 @@ mh.parseMemberCommand = async function(authorId, authorFull, args, attachmentUrl
if (args[1] && args[1] === "--help") {
return enums.help.LIST;
}
return await mh.getAllMembersInfo(authorId, authorFull).catch((e) =>{throw e});
return await mh.getAllMembersInfo(authorId, authorFull).catch((e) => {
throw e
});
case '':
return enums.help.MEMBER;
}
switch(args[1]) {
switch (args[1]) {
case 'name':
return await mh.updateName(authorId, args).catch((e) =>{throw e});
return await mh.updateName(authorId, args).catch((e) => {
throw e
});
case 'displayname':
return await mh.updateDisplayName(authorId, args).catch((e) =>{throw e});
return await mh.updateDisplayName(authorId, args).catch((e) => {
throw e
});
case 'proxy':
if (!args[2]) return await mh.getProxyByMember(authorId, args[0]).catch((e) => {throw e});
return await mh.updateProxy(authorId, args).catch((e) =>{throw e});
if (!args[2]) return await mh.getProxyByMember(authorId, args[0]).catch((e) => {
throw e
});
return await mh.updateProxy(authorId, args).catch((e) => {
throw e
});
case 'propic':
return await mh.updatePropic(authorId, args, attachmentUrl, attachmentExpiration).catch((e) =>{throw e});
return await mh.updatePropic(authorId, args, attachmentUrl, attachmentExpiration).catch((e) => {
throw e
});
default:
return member;
}
@@ -70,20 +88,22 @@ mh.parseMemberCommand = async function(authorId, authorFull, args, attachmentUrl
* @async
* @param {string} authorId - The author of the message
* @param {string[]} args - The message arguments
* @param {string | null} attachmentURL - The attachment URL, if any exists
* @returns {Promise<string>} A successful addition.
* @throws {Error} When the member exists, or creating a member doesn't work.
*/
mh.addNewMember = async function(authorId, args) {
mh.addNewMember = async function (authorId, args, attachmentURL = null) {
if (args[1] && args[1] === "--help" || !args[1]) {
return enums.help.NEW;
}
const memberName = args[1];
const displayName = args[2];
const proxy = args[3];
const propic = args[4] ?? attachmentURL;
return await mh.addFullMember(authorId, memberName, displayName).then((member) => {
let success = `Member was successfully added.\nName: ${member.dataValues.name}`
success += displayName ? `\nDisplay name: ${member.dataValues.displayname}` : "";
return success;
return await mh.addFullMember(authorId, memberName, displayName, proxy, propic).then(async(response) => {
const memberInfoEmbed = await mh.getMemberInfo(authorId, memberName).catch((e) => {throw e})
return {embed: memberInfoEmbed, errors: response.errors, success: `${memberName} has been added successfully.`};
}).catch(e => {
throw e;
})
@@ -99,16 +119,21 @@ mh.addNewMember = async function(authorId, args) {
* @throws {RangeError} When the name doesn't exist.
*/
mh.updateName = async function (authorId, args) {
if (args[1] && args[1] === "--help" || !args[1]) {
return enums.help.DISPLAY_NAME;
if (args[2] && args[2] === "--help") {
return enums.help.NAME;
}
const name = args[2];
const trimmedName = name ? name.trim() : null;
if (!name || trimmedName === null) {
throw new RangeError(`Display name ${enums.err.NO_VALUE}`);
if (!name) {
return `The name for ${args[0]} is ${args[0]}, but you probably knew that!`;
}
return await mh.updateMemberField(authorId, args).catch((e) =>{throw e});
const trimmedName = name.trim();
if (trimmedName === '') {
throw new RangeError(`Name ${enums.err.NO_VALUE}`);
}
return await mh.updateMemberField(authorId, args).catch((e) => {
throw e
});
}
/**
@@ -120,8 +145,8 @@ mh.updateName = async function (authorId, args) {
* @returns {Promise<string>} A successful update.
* @throws {RangeError} When the display name is too long or doesn't exist.
*/
mh.updateDisplayName = async function(authorId, args) {
if (args[1] && args[1] === "--help" || !args[1]) {
mh.updateDisplayName = async function (authorId, args) {
if (args[2] && args[2] === "--help") {
return enums.help.DISPLAY_NAME;
}
@@ -129,20 +154,23 @@ mh.updateDisplayName = async function(authorId, args) {
const displayName = args[2];
const trimmedName = displayName ? displayName.trim() : null;
if (!displayName || trimmedName === null ) {
if (!displayName) {
return await mh.getMemberByName(authorId, memberName).then((member) => {
if (member && member.displayname) {
return `Display name for ${memberName} is: \"${member.displayname}\".`;
}
else if (member) {
throw new RangeError(`Display name ${enums.err.NO_VALUE}`);
} else if (member) {
throw new Error(`Display name ${enums.err.NO_VALUE}`);
}
});
}
else if (displayName.length > 32) {
} else if (displayName.length > 32) {
throw new RangeError(enums.err.DISPLAY_NAME_TOO_LONG);
}
return await mh.updateMemberField(authorId, args).catch((e) =>{throw e});
else if (trimmedName === '') {
throw new RangeError(`Display name ${enums.err.NO_VALUE}`);
}
return await mh.updateMemberField(authorId, args).catch((e) => {
throw e
});
}
/**
@@ -154,15 +182,19 @@ mh.updateDisplayName = async function(authorId, args) {
* @returns {Promise<string> } A successful update.
* @throws {RangeError | Error} When an empty proxy was provided, or no proxy exists.
*/
mh.updateProxy = async function(authorId, args) {
mh.updateProxy = async function (authorId, args) {
if (args[2] && args[2] === "--help") {
return enums.help.PROXY;
}
const proxyExists = await mh.checkIfProxyExists(authorId, args[2]).then((proxyExists) => {
return proxyExists;
}).catch((e) =>{throw e});
}).catch((e) => {
throw e
});
if (!proxyExists) {
return await mh.updateMemberField(authorId, args).catch((e) =>{throw e});
return await mh.updateMemberField(authorId, args).catch((e) => {
throw e
});
}
}
@@ -177,8 +209,8 @@ mh.updateProxy = async function(authorId, args) {
* @returns {Promise<string>} A successful update.
* @throws {Error} When loading the profile picture from a URL doesn't work.
*/
mh.updatePropic = async function(authorId, args, attachmentUrl, attachmentExpiry= null) {
if (args[1] && args[1] === "--help") {
mh.updatePropic = async function (authorId, args, attachmentUrl, attachmentExpiry = null) {
if (args[2] && args[2] === "--help") {
return enums.help.PROPIC;
}
let img;
@@ -192,9 +224,13 @@ mh.updatePropic = async function(authorId, args, attachmentUrl, attachmentExpiry
if (updatedArgs[2]) {
img = updatedArgs[2];
}
const isValidImage = await mh.checkImageFormatValidity(img).catch((e) =>{throw e});
const isValidImage = await mh.checkImageFormatValidity(img).catch((e) => {
throw e
});
if (isValidImage) {
return await mh.updateMemberField(authorId, updatedArgs).catch((e) =>{throw e});
return await mh.updateMemberField(authorId, updatedArgs).catch((e) => {
throw e
});
}
}
@@ -206,7 +242,7 @@ mh.updatePropic = async function(authorId, args, attachmentUrl, attachmentExpiry
* @returns {Promise<boolean>} - If the image is a valid format.
* @throws {Error} When loading the profile picture from a URL doesn't work, or it fails requirements.
*/
mh.checkImageFormatValidity = async function(imageUrl) {
mh.checkImageFormatValidity = async function (imageUrl) {
const acceptableImages = ['image/png', 'image/jpg', 'image/jpeg', 'image/webp'];
return await fetch(imageUrl).then(r => r.blob()).then(blobFile => {
if (blobFile.size > 1000000 || !acceptableImages.includes(blobFile.type)) throw new Error(enums.err.PROPIC_FAILS_REQUIREMENTS);
@@ -225,17 +261,22 @@ mh.checkImageFormatValidity = async function(imageUrl) {
* @returns {Promise<string>} A successful removal.
* @throws {EmptyResultError} When there is no member to remove.
*/
mh.removeMember = async function(authorId, args) {
mh.removeMember = async function (authorId, args) {
if (args[1] && args[1] === "--help" || !args[1]) {
return enums.help.REMOVE;
}
const memberName = args[1];
return await db.members.destroy({ where: { name: {[Op.iLike]: memberName}, userid: authorId } }).then((result) => {
return await database.members.destroy({
where: {
name: {[Op.iLike]: memberName},
userid: authorId
}
}).then((result) => {
if (result) {
return `Member "${memberName}" has been deleted.`;
}
throw new EmptyResultError(`${enums.err.NO_MEMBER}`);
throw new EmptyResultError(`${enums.err.NO_MEMBER}`);
})
}
@@ -250,49 +291,157 @@ mh.removeMember = async function(authorId, args) {
* @param {string | null} displayName - The display name of the member.
* @param {string | null} proxy - The proxy tag of the member.
* @param {string | null} propic - The profile picture URL of the member.
* @param {boolean} isImport - Whether calling from the import function or not.
* @returns {Promise<model>} A successful addition.
* @throws {Error | RangeError} When the member already exists, there are validation errors, or adding a member doesn't work.
* @returns {Promise<{model, []}>} A successful addition object, including errors if there are any.
* @throws {Error} When the member already exists, there are validation errors, or adding a member doesn't work.
*/
mh.addFullMember = async function(authorId, memberName, displayName = null, proxy = null, propic= null, isImport = false) {
mh.addFullMember = async function (authorId, memberName, displayName = null, proxy = null, propic = null) {
await mh.getMemberByName(authorId, memberName).then((member) => {
if (member) {
throw new Error(`Can't add ${memberName}. ${enums.err.MEMBER_EXISTS}`);
}
});
if (displayName) {
const errors = [];
let isValidDisplayName;
if (displayName && displayName.length > 0) {
const trimmedName = displayName ? displayName.trim() : null;
if (trimmedName && trimmedName.length > 32) {
throw new RangeError(`Can't add ${memberName}. ${enums.err.DISPLAY_NAME_TOO_LONG}`);
errors.push(`Tried to set displayname to \"${displayName}\". ${enums.err.DISPLAY_NAME_TOO_LONG}. ${enums.err.SET_TO_NULL}`);
isValidDisplayName = false;
}
else {
isValidDisplayName = true;
}
}
if (proxy) {
await mh.checkIfProxyExists(authorId, proxy).catch((e) =>{throw e});
}
let validPropic;
if (propic) {
validPropic = await mh.checkImageFormatValidity(propic).then((valid) => {
return valid;
}).catch((e) =>{
if (!isImport) {
throw (e);
}
return false;
let isValidProxy;
if (proxy && proxy.length > 0) {
await mh.checkIfProxyExists(authorId, proxy).then(() => {
isValidProxy = true;
}).catch((e) => {
errors.push(`Tried to set proxy to \"${proxy}\". ${e.message}. ${enums.err.SET_TO_NULL}`);
isValidProxy = false;
});
}
const member = await db.members.create({
name: memberName,
userid: authorId,
displayname: displayName,
proxy: proxy,
propic: validPropic ? propic : null,
});
if (!member) {
new Error(`${enums.err.ADD_ERROR}: ${e.message}`);
let isValidPropic;
if (propic && propic.length > 0) {
await mh.checkImageFormatValidity(propic).then(() => {
isValidPropic = true;
}).catch((e) => {
errors.push(`Tried to set profile picture to \"${propic}\". ${e.message}. ${enums.err.SET_TO_NULL}`);
isValidPropic = false;
});
}
const member = await database.members.create({
name: memberName, userid: authorId, displayname: isValidDisplayName ? displayName : null, proxy: isValidProxy ? proxy : null, propic: isValidPropic ? propic : null
});
return {member: member, errors: errors};
}
// mh.mergeFullMember = async function (authorId, memberName, displayName = null, proxy = null, propic = null) {
// await mh.getMemberByName(authorId, memberName).then((member) => {
// if (member) {
// throw new Error(`Can't add ${memberName}. ${enums.err.MEMBER_EXISTS}`);
// }
// });
//
// let isValidDisplayName;
// if (displayName) {
// const trimmedName = displayName ? displayName.trim() : null;
// if (trimmedName && trimmedName.length > 32) {
// if (!isImport) {
// throw new RangeError(`Can't add ${memberName}. ${enums.err.DISPLAY_NAME_TOO_LONG}`);
// }
// isValidDisplayName = false;
// }
// }
//
// let isValidProxy;
// if (proxy) {
// isValidProxy = await mh.checkIfProxyExists(authorId, proxy).then((res) => {
// return res;
// }).catch((e) => {
// if (!isImport) {
// throw e
// }
// return false;
// });
// }
//
// let isValidPropic;
// if (propic) {
// isValidPropic = await mh.checkImageFormatValidity(propic).then((valid) => {
// return valid;
// }).catch((e) => {
// if (!isImport) {
// throw (e);
// }
// return false;
// });
// }
//
// const member = await database.members.create({
// name: memberName, userid: authorId, displayname: isValidDisplayName ? displayName: null, proxy: isValidProxy ? proxy : null, propic: isValidPropic ? propic : null,
// });
// if (!member) {
// new Error(`${enums.err.ADD_ERROR}`);
// }
// return member;
// }
//
// mh.overwriteFullMemberFromImport = async function (authorId, memberName, displayName = null, proxy = null, propic = null) {
// await mh.getMemberByName(authorId, memberName).then((member) => {
// if (member) {
// throw new Error(`Can't add ${memberName}. ${enums.err.MEMBER_EXISTS}`);
// }
// });
//
// let isValidDisplayName;
// if (displayName) {
// const trimmedName = displayName ? displayName.trim() : null;
// if (trimmedName && trimmedName.length > 32) {
// if (!isImport) {
// throw new RangeError(`Can't add ${memberName}. ${enums.err.DISPLAY_NAME_TOO_LONG}`);
// }
// isValidDisplayName = false;
// }
// }
//
// let isValidProxy;
// if (proxy) {
// isValidProxy = await mh.checkIfProxyExists(authorId, proxy).then((res) => {
// return res;
// }).catch((e) => {
// if (!isImport) {
// throw e
// }
// return false;
// });
// }
//
// let isValidPropic;
// if (propic) {
// isValidPropic = await mh.checkImageFormatValidity(propic).then((valid) => {
// return valid;
// }).catch((e) => {
// if (!isImport) {
// throw (e);
// }
// return false;
// });
// }
//
// const member = await database.members.create({
// name: memberName, userid: authorId, displayname: isValidDisplayName ? displayName: null, proxy: isValidProxy ? proxy : null, propic: isValidPropic ? propic : null,
// });
// if (!member) {
// new Error(`${enums.err.ADD_ERROR}`);
// }
// return member;
// }
/**
* Updates one fields for a member in the database.
*
@@ -302,7 +451,7 @@ mh.addFullMember = async function(authorId, memberName, displayName = null, prox
* @returns {Promise<string>} A successful update.
* @throws {EmptyResultError | Error} When the member is not found, or catchall error.
*/
mh.updateMemberField = async function(authorId, args) {
mh.updateMemberField = async function (authorId, args) {
const memberName = args[0];
const columnName = args[1];
const value = args[2];
@@ -312,16 +461,18 @@ mh.updateMemberField = async function(authorId, args) {
if (columnName === "propic" && args[3]) {
fluxerPropicWarning = mh.setExpirationWarning(args[3]);
}
return await db.members.update({[columnName]: value}, { where: { name: {[Op.iLike]: memberName}, userid: authorId } }).then(() => {
return `Updated ${columnName} for ${memberName} to ${value}${fluxerPropicWarning ?? ''}.`;
}).catch(e => {
if (e === EmptyResultError) {
throw new EmptyResultError(`Can't update ${memberName}. ${enums.err.NO_MEMBER}: ${e.message}`);
return await database.members.update({[columnName]: value}, {
where: {
name: {[Op.iLike]: memberName},
userid: authorId
}
else {
throw new Error(`Can't update ${memberName}. ${e.message}`);
}
});
}).then((res) => {
if (res[0] === 0) {
throw new EmptyResultError(`Can't update ${memberName}. ${enums.err.NO_MEMBER}.`);
} else {
return `Updated ${columnName} for ${memberName} to ${value}${fluxerPropicWarning ?? ''}.`;
}
})
}
/**
@@ -330,7 +481,7 @@ mh.updateMemberField = async function(authorId, args) {
* @param {string} expirationString - An expiration date string.
* @returns {string} A description of the expiration, interpolating the expiration string.
*/
mh.setExpirationWarning = function(expirationString) {
mh.setExpirationWarning = function (expirationString) {
let expirationDate = new Date(expirationString);
if (!isNaN(expirationDate.valueOf())) {
expirationDate = expirationDate.toDateString();
@@ -352,10 +503,11 @@ mh.getMemberInfo = async function (authorId, memberName) {
return new EmbedBuilder()
.setTitle(member.name)
.setDescription(`Details for ${member.name}`)
.addFields(
{name: 'Display name: ', value: member.displayname ?? 'unset', inline: true},
{name: 'Proxy tag: ', value: member.proxy ?? 'unset', inline: true},
)
.addFields({
name: 'Display name: ',
value: member.displayname ?? 'unset',
inline: true
}, {name: 'Proxy tag: ', value: member.proxy ?? 'unset', inline: true},)
.setImage(member.propic);
}
});
@@ -370,13 +522,11 @@ mh.getMemberInfo = async function (authorId, memberName) {
* @returns {Promise<EmbedBuilder>} The info for all members.
* @throws {Error} When there are no members for an author.
*/
mh.getAllMembersInfo = async function(authorId, authorName) {
mh.getAllMembersInfo = async function (authorId, authorName) {
const members = await mh.getMembersByAuthor(authorId);
if (members == null) throw Error(enums.err.USER_NO_MEMBERS);
const fields = [...members.entries()].map(([name, member]) => ({
name: member.name,
value: `(Proxy: \`${member.proxy ?? "unset"}\`)`,
inline: true,
name: member.name, value: `(Proxy: \`${member.proxy ?? "unset"}\`)`, inline: true,
}));
return new EmbedBuilder()
.setTitle(`${fields > 25 ? "First 25 m" : "M"}embers for ${authorName}`)
@@ -392,8 +542,8 @@ mh.getAllMembersInfo = async function(authorId, authorName) {
* @returns {Promise<model>} The member object.
* @throws { EmptyResultError } When the member is not found.
*/
mh.getMemberByName = async function(authorId, memberName) {
return await db.members.findOne({ where: { userid: authorId, name: {[Op.iLike]: memberName}}});
mh.getMemberByName = async function (authorId, memberName) {
return await database.members.findOne({where: {userid: authorId, name: {[Op.iLike]: memberName}}});
}
/**
@@ -405,10 +555,10 @@ mh.getMemberByName = async function(authorId, memberName) {
* @returns {Promise<string>} The member object.
* @throws { EmptyResultError } When the member is not found.
*/
mh.getProxyByMember = async function(authorId, memberName) {
mh.getProxyByMember = async function (authorId, memberName) {
return await mh.getMemberByName(authorId, memberName).then((member) => {
if (member) {
return member.dataValues.proxy;
return member.proxy;
}
throw new EmptyResultError(enums.err.NO_MEMBER);
})
@@ -422,8 +572,8 @@ mh.getProxyByMember = async function(authorId, memberName) {
* @param {string} proxy - The proxy tag
* @returns {Promise<model>} The member object.
*/
mh.getMemberByProxy = async function(authorId, proxy) {
return await db.members.findOne({ where: { userid: authorId, proxy: proxy } });
mh.getMemberByProxy = async function (authorId, proxy) {
return await db.members.findOne({where: {userid: authorId, proxy: proxy}});
}
/**
@@ -433,8 +583,8 @@ mh.getMemberByProxy = async function(authorId, proxy) {
* @param {string} authorId - The author of the message
* @returns {Promise<model[] | null>} The member object array.
*/
mh.getMembersByAuthor = async function(authorId) {
return await db.members.findAll({ where: { userid: authorId } });
mh.getMembersByAuthor = async function (authorId) {
return await database.members.findAll({where: {userid: authorId}});
}
@@ -446,18 +596,20 @@ mh.getMembersByAuthor = async function(authorId) {
* @returns {Promise<boolean> } Whether the proxy exists.
* @throws {Error} When an empty proxy was provided, or no proxy exists.
*/
mh.checkIfProxyExists = async function(authorId, proxy) {
mh.checkIfProxyExists = async function (authorId, proxy) {
if (proxy) {
const splitProxy = proxy.trim().split("text");
if(splitProxy.length < 2) throw new Error(enums.err.NO_TEXT_FOR_PROXY);
if(!splitProxy[0] && !splitProxy[1]) throw new Error(enums.err.NO_PROXY_WRAPPER);
if (splitProxy.length < 2) throw new Error(enums.err.NO_TEXT_FOR_PROXY);
if (!splitProxy[0] && !splitProxy[1]) throw new Error(enums.err.NO_PROXY_WRAPPER);
await mh.getMembersByAuthor(authorId).then((memberList) => {
const proxyExists = memberList.some(member => member.proxy === proxy);
if (proxyExists) {
throw new Error(enums.err.PROXY_EXISTS);
}
}).catch(e =>{throw e});
}).catch(e => {
throw e
});
}
}

View File

@@ -21,7 +21,7 @@ msgh.parseCommandArgs = function(content, commandName) {
const message = content.slice(msgh.prefix.length + commandName.length).trim();
return message.match(/\\?.|^$/g).reduce((accumulator, chara) => {
if (chara === '"') {
if (chara === '\"' || chara === '\'') {
// checks whether string is within quotes or not
accumulator.quote ^= 1;
} else if (!accumulator.quote && chara === ' '){
@@ -41,10 +41,10 @@ msgh.parseCommandArgs = function(content, commandName) {
* @param {string} authorId - The author of the message.
* @param {string} content - The full message content
* @param {string | null} attachmentUrl - The url for an attachment to the message, if any exists.
* @returns {Object} The proxy message object.
* @returns {{model, string, bool}} The proxy message object.
* @throws {Error} If a proxy message is sent with no message within it.
*/
msgh.parseProxyTags = async function (authorId, content, attachmentUrl= null){
msgh.parseProxyTags = async function (authorId, content, attachmentUrl = null){
const members = await memberHelper.getMembersByAuthor(authorId);
// If an author has no members, no sense in searching for proxy
if (members.length === 0) {
@@ -57,14 +57,12 @@ msgh.parseProxyTags = async function (authorId, content, attachmentUrl= null){
const splitProxy = member.proxy.split("text");
if(content.startsWith(splitProxy[0]) && content.endsWith(splitProxy[1])) {
proxyMessage.member = member;
if (attachmentUrl) return proxyMessage.message = enums.misc.ATTACHMENT_SENT_BY;
proxyMessage.hasAttachment = !!attachmentUrl;
let escapedPrefix = splitProxy[0].replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
let escapedSuffix = splitProxy[1].replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
escapedPrefix = new RegExp("^" + escapedPrefix);
escapedSuffix = new RegExp(escapedSuffix + "$")
proxyMessage.message = content.replace(escapedPrefix, "").replace(escapedSuffix, "");
if (proxyMessage.message.length === 0) throw new Error(enums.err.NO_MESSAGE_SENT_WITH_PROXY);
}
}
})
@@ -72,24 +70,20 @@ msgh.parseProxyTags = async function (authorId, content, attachmentUrl= null){
}
/**
* Sends a message as an attachment if it's too long.NOT CURRENTLY IN USE
* Returns a text message that's too long as its text plus a file with the remaining text.
*
* @async
* @param {string} text - The text of the message.
* @param {Message} message - The message object.
* @throws {Error} If a proxy message is sent with no message within it.
* @returns {{text: string, file: Buffer<ArrayBuffer> | undefined}} The text and buffer object
*
*/
msgh.sendMessageAsAttachment = async function(text, message) {
msgh.returnBufferFromText = function (text) {
if (text.length > 2000) {
tmp.file(async (err, path, fd, cleanupCallback) => {
fs.writeFile(path, text, (err) => {
if (err) throw err;
})
if (err) throw err;
await message.reply({content: enums.err.IMPORT_ERROR, attachments: [path]});
});
const truncated = text.substring(0, 2000);
const restOfText = text.substring(2000);
const file = Buffer.from(restOfText, 'utf-8');
return {text: truncated, file: file}
}
return {text: text, file: undefined}
}
export const messageHelper = msgh;

View File

@@ -1,6 +1,5 @@
import {messageHelper} from "./messageHelper.js";
import {memberHelper} from "./memberHelper.js";
import {Webhook, Channel, Message, EmbedBuilder} from '@fluxerjs/core';
import {Webhook, Channel, Message, Client} from '@fluxerjs/core';
import {enums} from "../enums.js";
const wh = {};
@@ -9,6 +8,7 @@ const name = 'PluralFlux Proxy Webhook';
/**
* Replaces a proxied message with a webhook using the member information.
* @async
* @param {Client} client - The fluxer.js client.
* @param {Message} message - The full message object.
* @throws {Error} When the proxy message is not in a server.
@@ -17,71 +17,62 @@ wh.sendMessageAsMember = async function(client, message) {
const attachmentUrl = message.attachments.size > 0 ? message.attachments.first().url : null;
const proxyMatch = await messageHelper.parseProxyTags(message.author.id, message.content, attachmentUrl).catch(e =>{throw e});
// If the message doesn't match a proxy, just return.
if (!proxyMatch.member) {
if (!proxyMatch || !proxyMatch.member || (proxyMatch.message.length === 0 && !proxyMatch.hasAttachment) ) {
return;
}
// If the message does match a proxy but is not in a guild server (ex: in the Bot's DMs
// If the message does match a proxy but is not in a guild server (ex: in the Bot's DMs)
if (!message.guildId) {
throw new Error(enums.err.NOT_IN_SERVER);
}
if (proxyMatch.message === enums.misc.ATTACHMENT_SENT_BY) {
return await message.reply(`${enums.misc.ATTACHMENT_SENT_BY} ${proxyMatch.member.displayname}`)
if (proxyMatch.hasAttachment) {
return await message.reply(`${enums.misc.ATTACHMENT_SENT_BY} ${proxyMatch.member.displayname ?? proxyMatch.member.name}`)
}
await replaceMessage(client, message, proxyMatch.message, proxyMatch.member).catch(e =>{throw e});
await wh.replaceMessage(client, message, proxyMatch.message, proxyMatch.member).catch(e =>{throw e});
}
/**
* Replaces a proxied message with a webhook using the member information.
* @async
* @param {Client} client - The fluxer.js client.
* @param {Message} message - The message to be deleted.
* @param {string} text - The text to send via the webhook.
* @param {model} member - A member object from the database.
* @throws {Error} When there's no message to send.
*/
async function replaceMessage(client, message, text, member) {
wh.replaceMessage = async function(client, message, text, member) {
// attachment logic is not relevant yet, text length will always be over 0 right now
if (text.length > 0 || message.attachments.size > 0) {
const channel = client.channels.get(message.channelId);
const webhook = await getOrCreateWebhook(client, channel).catch((e) =>{throw e});
const webhook = await wh.getOrCreateWebhook(client, channel).catch((e) =>{throw e});
const username = member.displayname ?? member.name;
await webhook.send({content: text, username: username, avatar_url: member.propic});
if (text.length > 0) {
await webhook.send({content: text, username: username, avatar_url: member.propic}).catch(async(e) => {
const returnedBuffer = messageHelper.returnBufferFromText(text);
await webhook.send({content: returnedBuffer.text, username: username, avatar_url: member.propic, files: [{ name: 'text.txt', data: returnedBuffer.file }]
})
console.error(e);
});
}
if (message.attachments.size > 0) {
// Not implemented yet
}
await message.delete();
}
else {
throw new Error(enums.err.NO_MESSAGE_SENT_WITH_PROXY);
}
}
/**
* Creates attachment embeds for the webhook since right now sending images is not supported.
*
* @param {Object[]} attachments - The attachments.
* @returns {Object[]} A series of embeds.
*/
function createAttachmentEmbedsForWebhook(attachments) {
let embeds = [];
attachments.forEach(attachment => {
const embed = new EmbedBuilder()
.setTitle(attachment.filename)
.setImage(attachment.url).toJSON()
embeds.push(embed);
});
return embeds;
}
/**
* Gets or creates a webhook.
*
* @async
* @param {Client} client - The fluxer.js client.
* @param {Channel} channel - The channel the message was sent in.
* @returns {Webhook} A webhook object.
* @throws {Error} When no webhooks are allowed in the channel.
*/
async function getOrCreateWebhook(client, channel) {
wh.getOrCreateWebhook = async function(client, channel) {
// If channel doesn't allow webhooks
if (!channel?.createWebhook) throw new Error(enums.err.NO_WEBHOOKS_ALLOWED);
let webhook = await getWebhook(client, channel).catch((e) =>{throw e});
let webhook = await wh.getWebhook(client, channel).catch((e) =>{throw e});
if (!webhook) {
webhook = await channel.createWebhook({name: name});
}
@@ -90,12 +81,12 @@ async function getOrCreateWebhook(client, channel) {
/**
* Gets an existing webhook.
*
* @async
* @param {Client} client - The fluxer.js client.
* @param {Channel} channel - The channel the message was sent in.
* @returns {Webhook} A webhook object.
*/
async function getWebhook(client, channel) {
wh.getWebhook = async function(client, channel) {
const channelWebhooks = await channel?.fetchWebhooks() ?? [];
if (channelWebhooks.length === 0) {
return;