forked from PluralFlux/PluralFlux
converted import syntax to commonJS
removed unused methods
This commit is contained in:
14
src/bot.js
14
src/bot.js
@@ -1,9 +1,9 @@
|
|||||||
import { Client, Events, GatewayOpcodes } from '@fluxerjs/core';
|
const {messageHelper} = require('./helpers/messageHelper.js');
|
||||||
import { messageHelper } from "./helpers/messageHelper.js";
|
const {enums} = require('enums.js');
|
||||||
import {enums} from "./enums.js";
|
const {commands} = require('commands.js');
|
||||||
import {commands} from "./commands.js";
|
const {webhookHelper} = require('helpers/webhookHelper.js');
|
||||||
import {webhookHelper} from "./helpers/webhookHelper.js";
|
const {Client, Events } = require('@fluxerjs/core');
|
||||||
import * as env from 'dotenv';
|
const {env} = require('dotenv');
|
||||||
|
|
||||||
env.config();
|
env.config();
|
||||||
|
|
||||||
@@ -26,7 +26,7 @@ client.on(Events.MessageCreate, async (message) => {
|
|||||||
|
|
||||||
// If message doesn't start with the bot prefix, it could still be a message with a proxy tag. If it's not, return.
|
// If message doesn't start with the bot prefix, it could still be a message with a proxy tag. If it's not, return.
|
||||||
if (!content.startsWith(messageHelper.prefix)) {
|
if (!content.startsWith(messageHelper.prefix)) {
|
||||||
await webhookHelper.sendMessageAsMember(client, message, content).catch((e) => {
|
await webhookHelper.sendMessageAsMember(client, message).catch((e) => {
|
||||||
throw e
|
throw e
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
import {messageHelper} from "./helpers/messageHelper.js";
|
const {messageHelper} = require('helpers/messageHelper.js')
|
||||||
import {enums} from "./enums.js";
|
const {enums} = require('enums.js')
|
||||||
import {memberHelper} from "./helpers/memberHelper.js";
|
const {memberHelper} = require('helpers/memberHelper.js')
|
||||||
import {EmbedBuilder} from "@fluxerjs/core";
|
const {importHelper} = require('helpers/importHelper.js');
|
||||||
import {importHelper} from "./import.js";
|
const {EmbedBuilder} = require('@fluxerjs/core');
|
||||||
|
|
||||||
const cmds = new Map();
|
|
||||||
|
|
||||||
cmds.set('member', {
|
let commands = new Map();
|
||||||
|
|
||||||
|
commands.set('member', {
|
||||||
description: enums.help.SHORT_DESC_MEMBER,
|
description: enums.help.SHORT_DESC_MEMBER,
|
||||||
async execute(message, client, args) {
|
async execute(message, client, args) {
|
||||||
const authorFull = `${message.author.username}#${message.author.discriminator}`
|
const authorFull = `${message.author.username}#${message.author.discriminator}`
|
||||||
@@ -23,10 +24,10 @@ cmds.set('member', {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
cmds.set('help', {
|
commands.set('help', {
|
||||||
description: enums.help.SHORT_DESC_HELP,
|
description: enums.help.SHORT_DESC_HELP,
|
||||||
async execute(message) {
|
async execute(message) {
|
||||||
const fields = [...cmds.entries()].map(([name, cmd]) => ({
|
const fields = [...commands.entries()].map(([name, cmd]) => ({
|
||||||
name: `${messageHelper.prefix}${name}`,
|
name: `${messageHelper.prefix}${name}`,
|
||||||
value: cmd.description,
|
value: cmd.description,
|
||||||
inline: true,
|
inline: true,
|
||||||
@@ -43,7 +44,7 @@ cmds.set('help', {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
cmds.set('import', {
|
commands.set('import', {
|
||||||
description: enums.help.SHORT_DESC_IMPORT,
|
description: enums.help.SHORT_DESC_IMPORT,
|
||||||
async execute(message) {
|
async execute(message) {
|
||||||
if (message.content.includes('--help')) {
|
if (message.content.includes('--help')) {
|
||||||
@@ -70,4 +71,4 @@ cmds.set('import', {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
export const commands = cmds;
|
module.exports = commands;
|
||||||
42
src/db.js
42
src/db.js
@@ -1,5 +1,5 @@
|
|||||||
import {DataTypes, Sequelize} from 'sequelize';
|
const {DataTypes, sequelize, Sequelize} = require('sequelize');
|
||||||
import * as env from 'dotenv';
|
const {env} = require('dotenv');
|
||||||
|
|
||||||
env.config();
|
env.config();
|
||||||
|
|
||||||
@@ -10,18 +10,17 @@ if (!password) {
|
|||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
const database = {};
|
const database = {
|
||||||
|
|
||||||
const sequelize = new Sequelize('postgres', 'postgres', password, {
|
sequelize: new Sequelize('postgres', 'postgres', password, {
|
||||||
host: 'localhost',
|
host: 'localhost',
|
||||||
logging: false,
|
logging: false,
|
||||||
dialect: 'postgres'
|
dialect: 'postgres'
|
||||||
});
|
}),
|
||||||
|
|
||||||
database.sequelize = sequelize;
|
Sequelize: Sequelize,
|
||||||
database.Sequelize = Sequelize;
|
|
||||||
|
|
||||||
database.members = sequelize.define('Member', {
|
members: sequelize.define('Member', {
|
||||||
userid: {
|
userid: {
|
||||||
type: DataTypes.STRING,
|
type: DataTypes.STRING,
|
||||||
allowNull: false,
|
allowNull: false,
|
||||||
@@ -39,9 +38,9 @@ database.members = sequelize.define('Member', {
|
|||||||
proxy: {
|
proxy: {
|
||||||
type: DataTypes.STRING,
|
type: DataTypes.STRING,
|
||||||
}
|
}
|
||||||
});
|
}),
|
||||||
|
|
||||||
database.systems = sequelize.define('System', {
|
systems: sequelize.define('System', {
|
||||||
userid: {
|
userid: {
|
||||||
type: DataTypes.STRING,
|
type: DataTypes.STRING,
|
||||||
},
|
},
|
||||||
@@ -54,31 +53,32 @@ database.systems = sequelize.define('System', {
|
|||||||
autoproxy: {
|
autoproxy: {
|
||||||
type: DataTypes.BOOLEAN,
|
type: DataTypes.BOOLEAN,
|
||||||
}
|
}
|
||||||
})
|
}),
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Checks Sequelize database connection.
|
* Checks Sequelize database connection.
|
||||||
*/
|
*/
|
||||||
database.check_connection = async function() {
|
check_connection: async function () {
|
||||||
await sequelize.authenticate().then(async (result) => {
|
await sequelize.authenticate().then(async () => {
|
||||||
console.log('Connection has been established successfully.');
|
console.log('Connection has been established successfully.');
|
||||||
await syncModels();
|
await this.syncModels();
|
||||||
}).catch(err => {
|
}).catch(err => {
|
||||||
console.error('Unable to connect to the database:', err);
|
console.error('Unable to connect to the database:', err);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
});
|
});
|
||||||
}
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Syncs Sequelize models.
|
* Syncs Sequelize models.
|
||||||
*/
|
*/
|
||||||
async function syncModels() {
|
async syncModels() {
|
||||||
await sequelize.sync().then(() => {
|
await this.sequelize.sync().then(() => {
|
||||||
console.log('Models synced successfully.');
|
console.log('Models synced successfully.');
|
||||||
}).catch((err) => {
|
}).catch((err) => {
|
||||||
console.error('Syncing models did not work', err);
|
console.error('Syncing models did not work', err);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
|
||||||
export const db = database;
|
module.exports = database;
|
||||||
18
src/enums.js
18
src/enums.js
@@ -1,6 +1,5 @@
|
|||||||
const helperEnums = {};
|
const enums = {
|
||||||
|
err: {
|
||||||
helperEnums.err = {
|
|
||||||
NO_MEMBER: "No such member was found.",
|
NO_MEMBER: "No such member was found.",
|
||||||
NO_NAME_PROVIDED: "No member name was provided for",
|
NO_NAME_PROVIDED: "No member name was provided for",
|
||||||
NO_VALUE: "has not been set for this member. Please provide a value.",
|
NO_VALUE: "has not been set for this member. Please provide a value.",
|
||||||
@@ -20,9 +19,9 @@ helperEnums.err = {
|
|||||||
NOT_JSON_FILE: "Please attach a valid JSON file.",
|
NOT_JSON_FILE: "Please attach a valid JSON file.",
|
||||||
NO_MEMBERS_IMPORTED: 'No members were imported.',
|
NO_MEMBERS_IMPORTED: 'No members were imported.',
|
||||||
IMPORT_ERROR: "Please see attached file for logs on the member import process.",
|
IMPORT_ERROR: "Please see attached file for logs on the member import process.",
|
||||||
}
|
},
|
||||||
|
|
||||||
helperEnums.help = {
|
help: {
|
||||||
SHORT_DESC_HELP: "Lists available commands.",
|
SHORT_DESC_HELP: "Lists available commands.",
|
||||||
SHORT_DESC_MEMBER: "Accesses subcommands related to proxy members.",
|
SHORT_DESC_MEMBER: "Accesses subcommands related to proxy members.",
|
||||||
SHORT_DESC_IMPORT: "Imports from PluralKit.",
|
SHORT_DESC_IMPORT: "Imports from PluralKit.",
|
||||||
@@ -37,10 +36,11 @@ helperEnums.help = {
|
|||||||
PROXY: "Updates the proxy tag for a specific member based on their name. The proxy must be formatted with the tags surrounding the word 'text', for example: `pf;member jane proxy Jane:text` or `pf;member amal proxy [text]` This is so the bot can detect what the proxy tags are. Only one proxy can be set per member currently.",
|
PROXY: "Updates the proxy tag for a specific member based on their name. The proxy must be formatted with the tags surrounding the word 'text', for example: `pf;member jane proxy Jane:text` or `pf;member amal proxy [text]` This is so the bot can detect what the proxy tags are. Only one proxy can be set per member currently.",
|
||||||
PROPIC: "Updates the profile picture for the member. Must be in JPG, PNG, or WEBP format and less than 10MB. The two options are:\n1. Pass in a direct remote image URL, for example: `pf;member jane propic <https://cdn.pixabay.com/photo/2020/05/02/02/54/animal-5119676_1280.jpg>`. You can upload images on sites like <https://imgbb.com/>.\n2. Upload an attachment directly.\n\n**NOTE:** Fluxer does not save your attachments forever, so option #1 is recommended.",
|
PROPIC: "Updates the profile picture for the member. Must be in JPG, PNG, or WEBP format and less than 10MB. The two options are:\n1. Pass in a direct remote image URL, for example: `pf;member jane propic <https://cdn.pixabay.com/photo/2020/05/02/02/54/animal-5119676_1280.jpg>`. You can upload images on sites like <https://imgbb.com/>.\n2. Upload an attachment directly.\n\n**NOTE:** Fluxer does not save your attachments forever, so option #1 is recommended.",
|
||||||
IMPORT: "Imports from PluralKit using the JSON file provided by their export command. Importing from other proxy bots is TBD. `pf;import` and attach your JSON file to the message. This will only save the fields that are present in the bot currently (the stuff above), not anything else like birthdays or system handles (yet?)."
|
IMPORT: "Imports from PluralKit using the JSON file provided by their export command. Importing from other proxy bots is TBD. `pf;import` and attach your JSON file to the message. This will only save the fields that are present in the bot currently (the stuff above), not anything else like birthdays or system handles (yet?)."
|
||||||
}
|
},
|
||||||
|
|
||||||
helperEnums.misc = {
|
misc: {
|
||||||
ATTACHMENT_SENT_BY: "Attachment sent by:"
|
ATTACHMENT_SENT_BY: "Attachment sent by:"
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
|
||||||
export const enums = helperEnums;
|
module.exports = enums;
|
||||||
@@ -1,10 +1,9 @@
|
|||||||
import {enums} from "./enums.js";
|
const {enums} = require("../enums.js");
|
||||||
import {memberHelper} from "./helpers/memberHelper.js";
|
const {memberHelper} = require("memberHelper.js");
|
||||||
import {messageHelper} from "./helpers/messageHelper.js";
|
|
||||||
|
|
||||||
const ih = {};
|
const importHelper = {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tries to import from Pluralkit.
|
* Tries to import from Pluralkit.
|
||||||
*
|
*
|
||||||
* @async
|
* @async
|
||||||
@@ -13,11 +12,11 @@ const ih = {};
|
|||||||
* @returns {string} A successful addition of all members.
|
* @returns {string} A successful addition of all members.
|
||||||
* @throws {Error} When the member exists, or creating a member doesn't work.
|
* @throws {Error} When the member exists, or creating a member doesn't work.
|
||||||
*/
|
*/
|
||||||
ih.pluralKitImport = async function (authorId, attachmentUrl) {
|
async pluralKitImport(authorId, attachmentUrl) {
|
||||||
if (!attachmentUrl) {
|
if (!attachmentUrl) {
|
||||||
throw new Error(enums.err.NOT_JSON_FILE);
|
throw new Error(enums.err.NOT_JSON_FILE);
|
||||||
}
|
}
|
||||||
return fetch(attachmentUrl).then((res) => res.json()).then(async(pkData) => {
|
return fetch(attachmentUrl).then((res) => res.json()).then(async (pkData) => {
|
||||||
const pkMembers = pkData.members;
|
const pkMembers = pkData.members;
|
||||||
const errors = [];
|
const errors = [];
|
||||||
const addedMembers = [];
|
const addedMembers = [];
|
||||||
@@ -29,7 +28,8 @@ ih.pluralKitImport = async function (authorId, attachmentUrl) {
|
|||||||
errors.push(`${pkMember.name}: ${e.message}`);
|
errors.push(`${pkMember.name}: ${e.message}`);
|
||||||
});
|
});
|
||||||
await memberHelper.checkImageFormatValidity(pkMember.avatar_url).catch(e => {
|
await memberHelper.checkImageFormatValidity(pkMember.avatar_url).catch(e => {
|
||||||
errors.push(`${pkMember.name}: ${e.message}`)});
|
errors.push(`${pkMember.name}: ${e.message}`)
|
||||||
|
});
|
||||||
}
|
}
|
||||||
const aggregatedText = addedMembers.length > 0 ? `Successfully added members: ${addedMembers.join(', ')}` : enums.err.NO_MEMBERS_IMPORTED;
|
const aggregatedText = addedMembers.length > 0 ? `Successfully added members: ${addedMembers.join(', ')}` : enums.err.NO_MEMBERS_IMPORTED;
|
||||||
if (errors.length > 0) {
|
if (errors.length > 0) {
|
||||||
@@ -37,6 +37,7 @@ ih.pluralKitImport = async function (authorId, attachmentUrl) {
|
|||||||
}
|
}
|
||||||
return aggregatedText;
|
return aggregatedText;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
|
||||||
export const importHelper = ih;
|
module.exports = importHelper;
|
||||||
@@ -1,14 +1,15 @@
|
|||||||
import {db} from '../db.js';
|
const { db } = require('../db.js')
|
||||||
import {enums} from "../enums.js";
|
const { enums} = require('../enums.js');
|
||||||
import {EmptyResultError, Op} from "sequelize";
|
const {EmptyResultError, Op} = require('sequelize');
|
||||||
import {EmbedBuilder} from "@fluxerjs/core";
|
const {EmbedBuilder} = require('@fluxerjs/core');
|
||||||
|
|
||||||
const mh = {};
|
const memberHelper = {
|
||||||
|
|
||||||
// Has an empty "command" to parse the help message properly
|
|
||||||
const commandList = ['--help', 'new', 'remove', 'name', 'list', 'displayName', 'proxy', 'propic', ''];
|
|
||||||
|
|
||||||
/**
|
// Has an empty "command" to parse the help message properly
|
||||||
|
commandList: ['--help', 'new', 'remove', 'name', 'list', 'displayName', 'proxy', 'propic', ''],
|
||||||
|
|
||||||
|
/**
|
||||||
* Parses through the subcommands that come after "pf;member" and calls functions accordingly.
|
* Parses through the subcommands that come after "pf;member" and calls functions accordingly.
|
||||||
*
|
*
|
||||||
* @async
|
* @async
|
||||||
@@ -20,19 +21,19 @@ const commandList = ['--help', 'new', 'remove', 'name', 'list', 'displayName', '
|
|||||||
* @returns {Promise<string> | Promise <EmbedBuilder>} A message, or an informational embed.
|
* @returns {Promise<string> | Promise <EmbedBuilder>} A message, or an informational embed.
|
||||||
* @throws {Error}
|
* @throws {Error}
|
||||||
*/
|
*/
|
||||||
mh.parseMemberCommand = async function(authorId, authorFull, args, attachmentUrl = null, attachmentExpiration = null){
|
async parseMemberCommand (authorId, authorFull, args, attachmentUrl = null, attachmentExpiration = null){
|
||||||
let member;
|
let member;
|
||||||
// checks whether command is in list, otherwise assumes it's a name
|
// checks whether command is in list, otherwise assumes it's a name
|
||||||
if(!commandList.includes(args[0])) {
|
if(!this.commandList.includes(args[0])) {
|
||||||
member = await mh.getMemberInfo(authorId, args[0]);
|
member = await this.getMemberInfo(authorId, args[0]);
|
||||||
}
|
}
|
||||||
switch(args[0]) {
|
switch(args[0]) {
|
||||||
case '--help':
|
case '--help':
|
||||||
return enums.help.MEMBER;
|
return enums.help.MEMBER;
|
||||||
case 'new':
|
case 'new':
|
||||||
return await mh.addNewMember(authorId, args).catch((e) =>{throw e});
|
return await this.addNewMember(authorId, args).catch((e) =>{throw e});
|
||||||
case 'remove':
|
case 'remove':
|
||||||
return await mh.removeMember(authorId, args).catch((e) =>{throw e});
|
return await this.removeMember(authorId, args).catch((e) =>{throw e});
|
||||||
case 'name':
|
case 'name':
|
||||||
return enums.help.NAME;
|
return enums.help.NAME;
|
||||||
case 'displayname':
|
case 'displayname':
|
||||||
@@ -45,26 +46,26 @@ mh.parseMemberCommand = async function(authorId, authorFull, args, attachmentUrl
|
|||||||
if (args[1] && args[1] === "--help") {
|
if (args[1] && args[1] === "--help") {
|
||||||
return enums.help.LIST;
|
return enums.help.LIST;
|
||||||
}
|
}
|
||||||
return await mh.getAllMembersInfo(authorId, authorFull).catch((e) =>{throw e});
|
return await this.getAllMembersInfo(authorId, authorFull).catch((e) =>{throw e});
|
||||||
case '':
|
case '':
|
||||||
return enums.help.MEMBER;
|
return enums.help.MEMBER;
|
||||||
}
|
}
|
||||||
switch(args[1]) {
|
switch(args[1]) {
|
||||||
case 'name':
|
case 'name':
|
||||||
return await mh.updateName(authorId, args).catch((e) =>{throw e});
|
return await this.updateName(authorId, args).catch((e) =>{throw e});
|
||||||
case 'displayname':
|
case 'displayname':
|
||||||
return await mh.updateDisplayName(authorId, args).catch((e) =>{throw e});
|
return await this.updateDisplayName(authorId, args).catch((e) =>{throw e});
|
||||||
case 'proxy':
|
case 'proxy':
|
||||||
if (!args[2]) return await mh.getProxyByMember(authorId, args[0]).catch((e) => {throw e});
|
if (!args[2]) return await this.getProxyByMember(authorId, args[0]).catch((e) => {throw e});
|
||||||
return await mh.updateProxy(authorId, args).catch((e) =>{throw e});
|
return await this.updateProxy(authorId, args).catch((e) =>{throw e});
|
||||||
case 'propic':
|
case 'propic':
|
||||||
return await mh.updatePropic(authorId, args, attachmentUrl, attachmentExpiration).catch((e) =>{throw e});
|
return await this.updatePropic(authorId, args, attachmentUrl, attachmentExpiration).catch((e) =>{throw e});
|
||||||
default:
|
default:
|
||||||
return member;
|
return member;
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Adds a member.
|
* Adds a member.
|
||||||
*
|
*
|
||||||
* @async
|
* @async
|
||||||
@@ -73,23 +74,23 @@ mh.parseMemberCommand = async function(authorId, authorFull, args, attachmentUrl
|
|||||||
* @returns {Promise<string>} A successful addition.
|
* @returns {Promise<string>} A successful addition.
|
||||||
* @throws {Error} When the member exists, or creating a member doesn't work.
|
* @throws {Error} When the member exists, or creating a member doesn't work.
|
||||||
*/
|
*/
|
||||||
mh.addNewMember = async function(authorId, args) {
|
async addNewMember (authorId, args) {
|
||||||
if (args[1] && args[1] === "--help" || !args[1]) {
|
if (args[1] && args[1] === "--help" || !args[1]) {
|
||||||
return enums.help.NEW;
|
return enums.help.NEW;
|
||||||
}
|
}
|
||||||
const memberName = args[1];
|
const memberName = args[1];
|
||||||
const displayName = args[2];
|
const displayName = args[2];
|
||||||
|
|
||||||
return await mh.addFullMember(authorId, memberName, displayName).then((member) => {
|
return await this.addFullMember(authorId, memberName, displayName).then((member) => {
|
||||||
let success = `Member was successfully added.\nName: ${member.dataValues.name}`
|
let success = `Member was successfully added.\nName: ${member.dataValues.name}`
|
||||||
success += displayName ? `\nDisplay name: ${member.dataValues.displayname}` : "";
|
success += displayName ? `\nDisplay name: ${member.dataValues.displayname}` : "";
|
||||||
return success;
|
return success;
|
||||||
}).catch(e => {
|
}).catch(e => {
|
||||||
throw e;
|
throw e;
|
||||||
})
|
})
|
||||||
}
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Updates the name for a member.
|
* Updates the name for a member.
|
||||||
*
|
*
|
||||||
* @async
|
* @async
|
||||||
@@ -98,7 +99,7 @@ mh.addNewMember = async function(authorId, args) {
|
|||||||
* @returns {Promise<string>} A successful update.
|
* @returns {Promise<string>} A successful update.
|
||||||
* @throws {RangeError} When the name doesn't exist.
|
* @throws {RangeError} When the name doesn't exist.
|
||||||
*/
|
*/
|
||||||
mh.updateName = async function (authorId, args) {
|
async updateName (authorId, args) {
|
||||||
if (args[1] && args[1] === "--help" || !args[1]) {
|
if (args[1] && args[1] === "--help" || !args[1]) {
|
||||||
return enums.help.DISPLAY_NAME;
|
return enums.help.DISPLAY_NAME;
|
||||||
}
|
}
|
||||||
@@ -108,10 +109,10 @@ mh.updateName = async function (authorId, args) {
|
|||||||
if (!name || trimmedName === null) {
|
if (!name || trimmedName === null) {
|
||||||
throw new RangeError(`Display name ${enums.err.NO_VALUE}`);
|
throw new RangeError(`Display name ${enums.err.NO_VALUE}`);
|
||||||
}
|
}
|
||||||
return await mh.updateMemberField(authorId, args).catch((e) =>{throw e});
|
return await this.updateMemberField(authorId, args).catch((e) =>{throw e});
|
||||||
}
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Updates the display name for a member.
|
* Updates the display name for a member.
|
||||||
*
|
*
|
||||||
* @async
|
* @async
|
||||||
@@ -120,7 +121,7 @@ mh.updateName = async function (authorId, args) {
|
|||||||
* @returns {Promise<string>} A successful update.
|
* @returns {Promise<string>} A successful update.
|
||||||
* @throws {RangeError} When the display name is too long or doesn't exist.
|
* @throws {RangeError} When the display name is too long or doesn't exist.
|
||||||
*/
|
*/
|
||||||
mh.updateDisplayName = async function(authorId, args) {
|
async updateDisplayName (authorId, args) {
|
||||||
if (args[1] && args[1] === "--help" || !args[1]) {
|
if (args[1] && args[1] === "--help" || !args[1]) {
|
||||||
return enums.help.DISPLAY_NAME;
|
return enums.help.DISPLAY_NAME;
|
||||||
}
|
}
|
||||||
@@ -130,7 +131,7 @@ mh.updateDisplayName = async function(authorId, args) {
|
|||||||
const trimmedName = displayName ? displayName.trim() : null;
|
const trimmedName = displayName ? displayName.trim() : null;
|
||||||
|
|
||||||
if (!displayName || trimmedName === null ) {
|
if (!displayName || trimmedName === null ) {
|
||||||
return await mh.getMemberByName(authorId, memberName).then((member) => {
|
return await this.getMemberByName(authorId, memberName).then((member) => {
|
||||||
if (member && member.displayname) {
|
if (member && member.displayname) {
|
||||||
return `Display name for ${memberName} is: \"${member.displayname}\".`;
|
return `Display name for ${memberName} is: \"${member.displayname}\".`;
|
||||||
}
|
}
|
||||||
@@ -142,10 +143,10 @@ mh.updateDisplayName = async function(authorId, args) {
|
|||||||
else if (displayName.length > 32) {
|
else if (displayName.length > 32) {
|
||||||
throw new RangeError(enums.err.DISPLAY_NAME_TOO_LONG);
|
throw new RangeError(enums.err.DISPLAY_NAME_TOO_LONG);
|
||||||
}
|
}
|
||||||
return await mh.updateMemberField(authorId, args).catch((e) =>{throw e});
|
return await this.updateMemberField(authorId, args).catch((e) =>{throw e});
|
||||||
}
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Updates the proxy for a member, first checking that no other members attached to the author have the tag.
|
* Updates the proxy for a member, first checking that no other members attached to the author have the tag.
|
||||||
*
|
*
|
||||||
* @async
|
* @async
|
||||||
@@ -154,19 +155,19 @@ mh.updateDisplayName = async function(authorId, args) {
|
|||||||
* @returns {Promise<string> } A successful update.
|
* @returns {Promise<string> } A successful update.
|
||||||
* @throws {RangeError | Error} When an empty proxy was provided, or no proxy exists.
|
* @throws {RangeError | Error} When an empty proxy was provided, or no proxy exists.
|
||||||
*/
|
*/
|
||||||
mh.updateProxy = async function(authorId, args) {
|
async updateProxy (authorId, args) {
|
||||||
if (args[2] && args[2] === "--help") {
|
if (args[2] && args[2] === "--help") {
|
||||||
return enums.help.PROXY;
|
return enums.help.PROXY;
|
||||||
}
|
}
|
||||||
const proxyExists = await mh.checkIfProxyExists(authorId, args[2]).then((proxyExists) => {
|
const proxyExists = await this.checkIfProxyExists(authorId, args[2]).then((proxyExists) => {
|
||||||
return proxyExists;
|
return proxyExists;
|
||||||
}).catch((e) =>{throw e});
|
}).catch((e) =>{throw e});
|
||||||
if (!proxyExists) {
|
if (!proxyExists) {
|
||||||
return await mh.updateMemberField(authorId, args).catch((e) =>{throw e});
|
return await this.updateMemberField(authorId, args).catch((e) =>{throw e});
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Updates the profile pic for a member, based on either the attachment or the args provided.
|
* Updates the profile pic for a member, based on either the attachment or the args provided.
|
||||||
*
|
*
|
||||||
* @async
|
* @async
|
||||||
@@ -177,7 +178,7 @@ mh.updateProxy = async function(authorId, args) {
|
|||||||
* @returns {Promise<string>} A successful update.
|
* @returns {Promise<string>} A successful update.
|
||||||
* @throws {Error} When loading the profile picture from a URL doesn't work.
|
* @throws {Error} When loading the profile picture from a URL doesn't work.
|
||||||
*/
|
*/
|
||||||
mh.updatePropic = async function(authorId, args, attachmentUrl, attachmentExpiry= null) {
|
async updatePropic (authorId, args, attachmentUrl, attachmentExpiry= null) {
|
||||||
if (args[1] && args[1] === "--help") {
|
if (args[1] && args[1] === "--help") {
|
||||||
return enums.help.PROPIC;
|
return enums.help.PROPIC;
|
||||||
}
|
}
|
||||||
@@ -192,13 +193,13 @@ mh.updatePropic = async function(authorId, args, attachmentUrl, attachmentExpiry
|
|||||||
if (updatedArgs[2]) {
|
if (updatedArgs[2]) {
|
||||||
img = updatedArgs[2];
|
img = updatedArgs[2];
|
||||||
}
|
}
|
||||||
const isValidImage = await mh.checkImageFormatValidity(img).catch((e) =>{throw e});
|
const isValidImage = await this.checkImageFormatValidity(img).catch((e) =>{throw e});
|
||||||
if (isValidImage) {
|
if (isValidImage) {
|
||||||
return await mh.updateMemberField(authorId, updatedArgs).catch((e) =>{throw e});
|
return await this.updateMemberField(authorId, updatedArgs).catch((e) =>{throw e});
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Checks if an uploaded picture is in the right format.
|
* Checks if an uploaded picture is in the right format.
|
||||||
*
|
*
|
||||||
* @async
|
* @async
|
||||||
@@ -206,7 +207,7 @@ mh.updatePropic = async function(authorId, args, attachmentUrl, attachmentExpiry
|
|||||||
* @returns {Promise<boolean>} - If the image is a valid format.
|
* @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.
|
* @throws {Error} When loading the profile picture from a URL doesn't work, or it fails requirements.
|
||||||
*/
|
*/
|
||||||
mh.checkImageFormatValidity = async function(imageUrl) {
|
async checkImageFormatValidity (imageUrl) {
|
||||||
const acceptableImages = ['image/png', 'image/jpg', 'image/jpeg', 'image/webp'];
|
const acceptableImages = ['image/png', 'image/jpg', 'image/jpeg', 'image/webp'];
|
||||||
return await fetch(imageUrl).then(r => r.blob()).then(blobFile => {
|
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);
|
if (blobFile.size > 1000000 || !acceptableImages.includes(blobFile.type)) throw new Error(enums.err.PROPIC_FAILS_REQUIREMENTS);
|
||||||
@@ -214,9 +215,9 @@ mh.checkImageFormatValidity = async function(imageUrl) {
|
|||||||
}).catch((error) => {
|
}).catch((error) => {
|
||||||
throw new Error(`${enums.err.PROPIC_CANNOT_LOAD}: ${error.message}`);
|
throw new Error(`${enums.err.PROPIC_CANNOT_LOAD}: ${error.message}`);
|
||||||
});
|
});
|
||||||
}
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Removes a member.
|
* Removes a member.
|
||||||
*
|
*
|
||||||
* @async
|
* @async
|
||||||
@@ -225,7 +226,7 @@ mh.checkImageFormatValidity = async function(imageUrl) {
|
|||||||
* @returns {Promise<string>} A successful removal.
|
* @returns {Promise<string>} A successful removal.
|
||||||
* @throws {EmptyResultError} When there is no member to remove.
|
* @throws {EmptyResultError} When there is no member to remove.
|
||||||
*/
|
*/
|
||||||
mh.removeMember = async function(authorId, args) {
|
async removeMember (authorId, args) {
|
||||||
if (args[1] && args[1] === "--help" || !args[1]) {
|
if (args[1] && args[1] === "--help" || !args[1]) {
|
||||||
return enums.help.REMOVE;
|
return enums.help.REMOVE;
|
||||||
}
|
}
|
||||||
@@ -237,11 +238,11 @@ mh.removeMember = async function(authorId, args) {
|
|||||||
}
|
}
|
||||||
throw new EmptyResultError(`${enums.err.NO_MEMBER}`);
|
throw new EmptyResultError(`${enums.err.NO_MEMBER}`);
|
||||||
})
|
})
|
||||||
}
|
},
|
||||||
|
|
||||||
/*======Non-Subcommands======*/
|
/*======Non-Subcommands======*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Adds a member with full details, first checking that there is no member of that name associated with the author.
|
* Adds a member with full details, first checking that there is no member of that name associated with the author.
|
||||||
*
|
*
|
||||||
* @async
|
* @async
|
||||||
@@ -250,12 +251,12 @@ mh.removeMember = async function(authorId, args) {
|
|||||||
* @param {string | null} displayName - The display name of the member.
|
* @param {string | null} displayName - The display name of the member.
|
||||||
* @param {string | null} proxy - The proxy tag 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 {string | null} propic - The profile picture URL of the member.
|
||||||
* @param {boolean} isImport - Whether calling from the import function or not.
|
* @param {boolean} isImport - Whether calling from the import or not.
|
||||||
* @returns {Promise<model>} A successful addition.
|
* @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.
|
* @throws {Error | RangeError} 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) {
|
async addFullMember (authorId, memberName, displayName = null, proxy = null, propic= null, isImport = false) {
|
||||||
await mh.getMemberByName(authorId, memberName).then((member) => {
|
await this.getMemberByName(authorId, memberName).then((member) => {
|
||||||
if (member) {
|
if (member) {
|
||||||
throw new Error(`Can't add ${memberName}. ${enums.err.MEMBER_EXISTS}`);
|
throw new Error(`Can't add ${memberName}. ${enums.err.MEMBER_EXISTS}`);
|
||||||
}
|
}
|
||||||
@@ -267,11 +268,11 @@ mh.addFullMember = async function(authorId, memberName, displayName = null, prox
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (proxy) {
|
if (proxy) {
|
||||||
await mh.checkIfProxyExists(authorId, proxy).catch((e) =>{throw e});
|
await this.checkIfProxyExists(authorId, proxy).catch((e) =>{throw e});
|
||||||
}
|
}
|
||||||
let validPropic;
|
let validPropic;
|
||||||
if (propic) {
|
if (propic) {
|
||||||
validPropic = await mh.checkImageFormatValidity(propic).then((valid) => {
|
validPropic = await this.checkImageFormatValidity(propic).then((valid) => {
|
||||||
return valid;
|
return valid;
|
||||||
}).catch((e) =>{
|
}).catch((e) =>{
|
||||||
if (!isImport) {
|
if (!isImport) {
|
||||||
@@ -289,11 +290,11 @@ mh.addFullMember = async function(authorId, memberName, displayName = null, prox
|
|||||||
propic: validPropic ? propic : null,
|
propic: validPropic ? propic : null,
|
||||||
});
|
});
|
||||||
if (!member) {
|
if (!member) {
|
||||||
new Error(`${enums.err.ADD_ERROR}: ${e.message}`);
|
new Error(`${enums.err.ADD_ERROR}`);
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Updates one fields for a member in the database.
|
* Updates one fields for a member in the database.
|
||||||
*
|
*
|
||||||
* @async
|
* @async
|
||||||
@@ -302,7 +303,7 @@ mh.addFullMember = async function(authorId, memberName, displayName = null, prox
|
|||||||
* @returns {Promise<string>} A successful update.
|
* @returns {Promise<string>} A successful update.
|
||||||
* @throws {EmptyResultError | Error} When the member is not found, or catchall error.
|
* @throws {EmptyResultError | Error} When the member is not found, or catchall error.
|
||||||
*/
|
*/
|
||||||
mh.updateMemberField = async function(authorId, args) {
|
async updateMemberField (authorId, args) {
|
||||||
const memberName = args[0];
|
const memberName = args[0];
|
||||||
const columnName = args[1];
|
const columnName = args[1];
|
||||||
const value = args[2];
|
const value = args[2];
|
||||||
@@ -310,7 +311,7 @@ mh.updateMemberField = async function(authorId, args) {
|
|||||||
|
|
||||||
// indicates that an attachment was uploaded on Fluxer directly
|
// indicates that an attachment was uploaded on Fluxer directly
|
||||||
if (columnName === "propic" && args[3]) {
|
if (columnName === "propic" && args[3]) {
|
||||||
fluxerPropicWarning = mh.setExpirationWarning(args[3]);
|
fluxerPropicWarning = this.setExpirationWarning(args[3]);
|
||||||
}
|
}
|
||||||
return await db.members.update({[columnName]: value}, { where: { name: {[Op.iLike]: memberName}, userid: authorId } }).then(() => {
|
return await db.members.update({[columnName]: value}, { where: { name: {[Op.iLike]: memberName}, userid: authorId } }).then(() => {
|
||||||
return `Updated ${columnName} for ${memberName} to ${value}${fluxerPropicWarning ?? ''}.`;
|
return `Updated ${columnName} for ${memberName} to ${value}${fluxerPropicWarning ?? ''}.`;
|
||||||
@@ -322,23 +323,23 @@ mh.updateMemberField = async function(authorId, args) {
|
|||||||
throw new Error(`Can't update ${memberName}. ${e.message}`);
|
throw new Error(`Can't update ${memberName}. ${e.message}`);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sets the warning for an expiration date.
|
* Sets the warning for an expiration date.
|
||||||
*
|
*
|
||||||
* @param {string} expirationString - An expiration date string.
|
* @param {string} expirationString - An expiration date string.
|
||||||
* @returns {string} A description of the expiration, interpolating the expiration string.
|
* @returns {string} A description of the expiration, interpolating the expiration string.
|
||||||
*/
|
*/
|
||||||
mh.setExpirationWarning = function(expirationString) {
|
setExpirationWarning(expirationString) {
|
||||||
let expirationDate = new Date(expirationString);
|
let expirationDate = new Date(expirationString);
|
||||||
if (!isNaN(expirationDate.valueOf())) {
|
if (!isNaN(expirationDate.valueOf())) {
|
||||||
expirationDate = expirationDate.toDateString();
|
expirationDate = expirationDate.toDateString();
|
||||||
return `\n**NOTE:** Because this profile picture was uploaded via Fluxer, it will currently expire on *${expirationDate}*. To avoid this, upload the picture to another website like <https://imgbb.com/> and link to it directly`
|
return `\n**NOTE:** Because this profile picture was uploaded via Fluxer, it will currently expire on *${expirationDate}*. To avoid this, upload the picture to another website like <https://imgbb.com/> and link to it directly`
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the details for a member.
|
* Gets the details for a member.
|
||||||
*
|
*
|
||||||
* @async
|
* @async
|
||||||
@@ -346,8 +347,8 @@ mh.setExpirationWarning = function(expirationString) {
|
|||||||
* @param {string} memberName - The message arguments
|
* @param {string} memberName - The message arguments
|
||||||
* @returns {Promise<EmbedBuilder>} The member's info.
|
* @returns {Promise<EmbedBuilder>} The member's info.
|
||||||
*/
|
*/
|
||||||
mh.getMemberInfo = async function (authorId, memberName) {
|
async getMemberInfo (authorId, memberName) {
|
||||||
return await mh.getMemberByName(authorId, memberName).then((member) => {
|
return await this.getMemberByName(authorId, memberName).then((member) => {
|
||||||
if (member) {
|
if (member) {
|
||||||
return new EmbedBuilder()
|
return new EmbedBuilder()
|
||||||
.setTitle(member.name)
|
.setTitle(member.name)
|
||||||
@@ -359,9 +360,9 @@ mh.getMemberInfo = async function (authorId, memberName) {
|
|||||||
.setImage(member.propic);
|
.setImage(member.propic);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets all members for an author.
|
* Gets all members for an author.
|
||||||
*
|
*
|
||||||
* @async
|
* @async
|
||||||
@@ -370,8 +371,8 @@ mh.getMemberInfo = async function (authorId, memberName) {
|
|||||||
* @returns {Promise<EmbedBuilder>} The info for all members.
|
* @returns {Promise<EmbedBuilder>} The info for all members.
|
||||||
* @throws {Error} When there are no members for an author.
|
* @throws {Error} When there are no members for an author.
|
||||||
*/
|
*/
|
||||||
mh.getAllMembersInfo = async function(authorId, authorName) {
|
async getAllMembersInfo (authorId, authorName) {
|
||||||
const members = await mh.getMembersByAuthor(authorId);
|
const members = await this.getMembersByAuthor(authorId);
|
||||||
if (members == null) throw Error(enums.err.USER_NO_MEMBERS);
|
if (members == null) throw Error(enums.err.USER_NO_MEMBERS);
|
||||||
const fields = [...members.entries()].map(([name, member]) => ({
|
const fields = [...members.entries()].map(([name, member]) => ({
|
||||||
name: member.name,
|
name: member.name,
|
||||||
@@ -381,9 +382,9 @@ mh.getAllMembersInfo = async function(authorId, authorName) {
|
|||||||
return new EmbedBuilder()
|
return new EmbedBuilder()
|
||||||
.setTitle(`${fields > 25 ? "First 25 m" : "M"}embers for ${authorName}`)
|
.setTitle(`${fields > 25 ? "First 25 m" : "M"}embers for ${authorName}`)
|
||||||
.addFields(...fields);
|
.addFields(...fields);
|
||||||
}
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets a member based on the author and proxy tag.
|
* Gets a member based on the author and proxy tag.
|
||||||
*
|
*
|
||||||
* @async
|
* @async
|
||||||
@@ -392,53 +393,41 @@ mh.getAllMembersInfo = async function(authorId, authorName) {
|
|||||||
* @returns {Promise<model>} The member object.
|
* @returns {Promise<model>} The member object.
|
||||||
* @throws { EmptyResultError } When the member is not found.
|
* @throws { EmptyResultError } When the member is not found.
|
||||||
*/
|
*/
|
||||||
mh.getMemberByName = async function(authorId, memberName) {
|
async getMemberByName (authorId, memberName) {
|
||||||
return await db.members.findOne({ where: { userid: authorId, name: {[Op.iLike]: memberName}}});
|
return await db.members.findOne({ where: { userid: authorId, name: {[Op.iLike]: memberName}}});
|
||||||
}
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets a member based on the author and proxy tag.
|
* Gets a member based on the author and proxy tag.
|
||||||
*
|
*
|
||||||
* @async
|
* @async
|
||||||
* @param {string} authorId - The author of the message.
|
* @param {string} authorId - The author of the message.
|
||||||
* @param {string} memberName - The member's name.
|
* @param {string} memberName - The member's name.
|
||||||
* @returns {Promise<string>} The member object.
|
* @returns {Promise<model>} The member object.
|
||||||
* @throws { EmptyResultError } When the member is not found.
|
* @throws { EmptyResultError } When the member is not found.
|
||||||
*/
|
*/
|
||||||
mh.getProxyByMember = async function(authorId, memberName) {
|
async getProxyByMember (authorId, memberName) {
|
||||||
return await mh.getMemberByName(authorId, memberName).then((member) => {
|
return await this.getMemberByName(authorId, memberName).then((member) => {
|
||||||
if (member) {
|
if (member) {
|
||||||
return member.dataValues.proxy;
|
return member.dataValues.proxy;
|
||||||
}
|
}
|
||||||
throw new EmptyResultError(enums.err.NO_MEMBER);
|
throw new EmptyResultError(enums.err.NO_MEMBER);
|
||||||
})
|
})
|
||||||
}
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets a member based on the author and proxy tag.
|
|
||||||
*
|
|
||||||
* @async
|
|
||||||
* @param {string} authorId - The author of the message
|
|
||||||
* @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 } });
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets all members belonging to the author.
|
* Gets all members belonging to the author.
|
||||||
*
|
*
|
||||||
* @async
|
* @async
|
||||||
* @param {string} authorId - The author of the message
|
* @param {string} authorId - The author of the message
|
||||||
* @returns {Promise<model[] | null>} The member object array.
|
* @returns {Promise<model[] | null>} The member object array.
|
||||||
*/
|
*/
|
||||||
mh.getMembersByAuthor = async function(authorId) {
|
async getMembersByAuthor (authorId) {
|
||||||
return await db.members.findAll({ where: { userid: authorId } });
|
return await db.members.findAll({ where: { userid: authorId } });
|
||||||
}
|
},
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Checks if proxy exists for a member.
|
* Checks if proxy exists for a member.
|
||||||
*
|
*
|
||||||
* @param {string} authorId - The author of the message
|
* @param {string} authorId - The author of the message
|
||||||
@@ -446,13 +435,13 @@ mh.getMembersByAuthor = async function(authorId) {
|
|||||||
* @returns {Promise<boolean> } Whether the proxy exists.
|
* @returns {Promise<boolean> } Whether the proxy exists.
|
||||||
* @throws {Error} When an empty proxy was provided, or no proxy exists.
|
* @throws {Error} When an empty proxy was provided, or no proxy exists.
|
||||||
*/
|
*/
|
||||||
mh.checkIfProxyExists = async function(authorId, proxy) {
|
async checkIfProxyExists (authorId, proxy) {
|
||||||
if (proxy) {
|
if (proxy) {
|
||||||
const splitProxy = proxy.trim().split("text");
|
const splitProxy = proxy.trim().split("text");
|
||||||
if(splitProxy.length < 2) throw new Error(enums.err.NO_TEXT_FOR_PROXY);
|
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[0] && !splitProxy[1]) throw new Error(enums.err.NO_PROXY_WRAPPER);
|
||||||
|
|
||||||
await mh.getMembersByAuthor(authorId).then((memberList) => {
|
await this.getMembersByAuthor(authorId).then((memberList) => {
|
||||||
const proxyExists = memberList.some(member => member.proxy === proxy);
|
const proxyExists = memberList.some(member => member.proxy === proxy);
|
||||||
if (proxyExists) {
|
if (proxyExists) {
|
||||||
throw new Error(enums.err.PROXY_EXISTS);
|
throw new Error(enums.err.PROXY_EXISTS);
|
||||||
@@ -460,7 +449,8 @@ mh.checkIfProxyExists = async function(authorId, proxy) {
|
|||||||
}).catch(e =>{throw e});
|
}).catch(e =>{throw e});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export const memberHelper = mh;
|
module.exports = memberHelper;
|
||||||
@@ -1,41 +1,41 @@
|
|||||||
import {memberHelper} from "./memberHelper.js";
|
const {memberHelper} = require('memberHelper.js');
|
||||||
import {enums} from "../enums.js";
|
const {fs} = require('fs')
|
||||||
import tmp, {setGracefulCleanup} from "tmp";
|
const {tmp, setGracefulCleanup } = require('tmp')
|
||||||
import fs from 'fs';
|
const {enums} = require('../enums.js')
|
||||||
import {Message} from "@fluxerjs/core";
|
const {Message} = require('@fluxerjs/core');
|
||||||
|
|
||||||
const msgh = {};
|
|
||||||
|
|
||||||
msgh.prefix = "pf;"
|
|
||||||
|
|
||||||
setGracefulCleanup();
|
setGracefulCleanup();
|
||||||
|
|
||||||
/**
|
const messageHelper = {
|
||||||
|
|
||||||
|
prefix: "pf;",
|
||||||
|
|
||||||
|
/**
|
||||||
* Parses and slices up message arguments, retaining quoted strings.
|
* Parses and slices up message arguments, retaining quoted strings.
|
||||||
*
|
*
|
||||||
* @param {string} content - The full message content.
|
* @param {string} content - The full message content.
|
||||||
* @param {string} commandName - The command name.
|
* @param {string} commandName - The command name.
|
||||||
* @returns {string[]} An array of arguments.
|
* @returns {string[]} An array of arguments.
|
||||||
*/
|
*/
|
||||||
msgh.parseCommandArgs = function(content, commandName) {
|
parseCommandArgs(content, commandName) {
|
||||||
const message = content.slice(msgh.prefix.length + commandName.length).trim();
|
const message = content.slice(this.prefix.length + commandName.length).trim();
|
||||||
|
|
||||||
return message.match(/\\?.|^$/g).reduce((accumulator, chara) => {
|
return message.match(/\\?.|^$/g).reduce((accumulator, chara) => {
|
||||||
if (chara === '"') {
|
if (chara === '"') {
|
||||||
// checks whether string is within quotes or not
|
// checks whether string is within quotes or not
|
||||||
accumulator.quote ^= 1;
|
accumulator.quote ^= 1;
|
||||||
} else if (!accumulator.quote && chara === ' '){
|
} else if (!accumulator.quote && chara === ' ') {
|
||||||
// if not currently in quoted string, push empty string to start word
|
// if not currently in quoted string, push empty string to start word
|
||||||
accumulator.array.push('');
|
accumulator.array.push('');
|
||||||
} else {
|
} else {
|
||||||
// accumulates characters to the last string in the array and removes escape characters
|
// accumulates characters to the last string in the array and removes escape characters
|
||||||
accumulator.array[accumulator.array.length-1] += chara.replace(/\\(.)/,"$1");
|
accumulator.array[accumulator.array.length - 1] += chara.replace(/\\(.)/, "$1");
|
||||||
}
|
}
|
||||||
return accumulator;
|
return accumulator;
|
||||||
}, {array: ['']}).array // initial array with empty string for the reducer
|
}, {array: ['']}).array // initial array with empty string for the reducer
|
||||||
}
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Parses messages to see if any part of the text matches the tags of any member belonging to an author.
|
* Parses messages to see if any part of the text matches the tags of any member belonging to an author.
|
||||||
*
|
*
|
||||||
* @param {string} authorId - The author of the message.
|
* @param {string} authorId - The author of the message.
|
||||||
@@ -44,7 +44,7 @@ msgh.parseCommandArgs = function(content, commandName) {
|
|||||||
* @returns {Object} The proxy message object.
|
* @returns {Object} The proxy message object.
|
||||||
* @throws {Error} If a proxy message is sent with no message within it.
|
* @throws {Error} If a proxy message is sent with no message within it.
|
||||||
*/
|
*/
|
||||||
msgh.parseProxyTags = async function (authorId, content, attachmentUrl= null){
|
async parseProxyTags(authorId, content, attachmentUrl = null) {
|
||||||
const members = await memberHelper.getMembersByAuthor(authorId);
|
const members = await memberHelper.getMembersByAuthor(authorId);
|
||||||
// If an author has no members, no sense in searching for proxy
|
// If an author has no members, no sense in searching for proxy
|
||||||
if (members.length === 0) {
|
if (members.length === 0) {
|
||||||
@@ -55,7 +55,7 @@ msgh.parseProxyTags = async function (authorId, content, attachmentUrl= null){
|
|||||||
members.forEach(member => {
|
members.forEach(member => {
|
||||||
if (member.proxy) {
|
if (member.proxy) {
|
||||||
const splitProxy = member.proxy.split("text");
|
const splitProxy = member.proxy.split("text");
|
||||||
if(content.startsWith(splitProxy[0]) && content.endsWith(splitProxy[1])) {
|
if (content.startsWith(splitProxy[0]) && content.endsWith(splitProxy[1])) {
|
||||||
proxyMessage.member = member;
|
proxyMessage.member = member;
|
||||||
if (attachmentUrl) return proxyMessage.message = enums.misc.ATTACHMENT_SENT_BY;
|
if (attachmentUrl) return proxyMessage.message = enums.misc.ATTACHMENT_SENT_BY;
|
||||||
|
|
||||||
@@ -69,9 +69,9 @@ msgh.parseProxyTags = async function (authorId, content, attachmentUrl= null){
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
return proxyMessage;
|
return proxyMessage;
|
||||||
}
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sends a message as an attachment if it's too long.NOT CURRENTLY IN USE
|
* Sends a message as an attachment if it's too long.NOT CURRENTLY IN USE
|
||||||
*
|
*
|
||||||
* @async
|
* @async
|
||||||
@@ -80,7 +80,7 @@ msgh.parseProxyTags = async function (authorId, content, attachmentUrl= null){
|
|||||||
* @throws {Error} If a proxy message is sent with no message within it.
|
* @throws {Error} If a proxy message is sent with no message within it.
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
msgh.sendMessageAsAttachment = async function(text, message) {
|
async sendMessageAsAttachment(text, message) {
|
||||||
if (text.length > 2000) {
|
if (text.length > 2000) {
|
||||||
tmp.file(async (err, path, fd, cleanupCallback) => {
|
tmp.file(async (err, path, fd, cleanupCallback) => {
|
||||||
fs.writeFile(path, text, (err) => {
|
fs.writeFile(path, text, (err) => {
|
||||||
@@ -90,6 +90,7 @@ msgh.sendMessageAsAttachment = async function(text, message) {
|
|||||||
await message.reply({content: enums.err.IMPORT_ERROR, attachments: [path]});
|
await message.reply({content: enums.err.IMPORT_ERROR, attachments: [path]});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
|
||||||
export const messageHelper = msgh;
|
module.exports = messageHelper;
|
||||||
|
|||||||
@@ -1,21 +1,21 @@
|
|||||||
import {messageHelper} from "./messageHelper.js";
|
const {messageHelper} = require('messageHelper.js');
|
||||||
import {memberHelper} from "./memberHelper.js";
|
const {enums} = require('../enums.js');
|
||||||
import {Webhook, Channel, Message, EmbedBuilder} from '@fluxerjs/core';
|
const {Client, Message, Webhook, Channel} = require('@fluxerjs/core');
|
||||||
import {enums} from "../enums.js";
|
|
||||||
|
|
||||||
const wh = {};
|
|
||||||
|
|
||||||
const name = 'PluralFlux Proxy Webhook';
|
const name = 'PluralFlux Proxy Webhook';
|
||||||
|
|
||||||
/**
|
const webhookHelper = {
|
||||||
|
/**
|
||||||
* Replaces a proxied message with a webhook using the member information.
|
* Replaces a proxied message with a webhook using the member information.
|
||||||
* @param {Client} client - The fluxer.js client.
|
* @param {Client} client - The fluxer.js client.
|
||||||
* @param {Message} message - The full message object.
|
* @param {Message} message - The full message object.
|
||||||
* @throws {Error} When the proxy message is not in a server.
|
* @throws {Error} When the proxy message is not in a server.
|
||||||
*/
|
*/
|
||||||
wh.sendMessageAsMember = async function(client, message) {
|
async sendMessageAsMember(client, message) {
|
||||||
const attachmentUrl = message.attachments.size > 0 ? message.attachments.first().url : null;
|
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});
|
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 the message doesn't match a proxy, just return.
|
||||||
if (!proxyMatch.member) {
|
if (!proxyMatch.member) {
|
||||||
return;
|
return;
|
||||||
@@ -28,10 +28,12 @@ wh.sendMessageAsMember = async function(client, message) {
|
|||||||
if (proxyMatch.message === enums.misc.ATTACHMENT_SENT_BY) {
|
if (proxyMatch.message === enums.misc.ATTACHMENT_SENT_BY) {
|
||||||
return await message.reply(`${enums.misc.ATTACHMENT_SENT_BY} ${proxyMatch.member.displayname}`)
|
return await message.reply(`${enums.misc.ATTACHMENT_SENT_BY} ${proxyMatch.member.displayname}`)
|
||||||
}
|
}
|
||||||
await replaceMessage(client, message, proxyMatch.message, proxyMatch.member).catch(e =>{throw e});
|
await this.replaceMessage(client, message, proxyMatch.message, proxyMatch.member).catch(e => {
|
||||||
}
|
throw e
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Replaces a proxied message with a webhook using the member information.
|
* Replaces a proxied message with a webhook using the member information.
|
||||||
* @param {Client} client - The fluxer.js client.
|
* @param {Client} client - The fluxer.js client.
|
||||||
* @param {Message} message - The message to be deleted.
|
* @param {Message} message - The message to be deleted.
|
||||||
@@ -39,38 +41,21 @@ wh.sendMessageAsMember = async function(client, message) {
|
|||||||
* @param {model} member - A member object from the database.
|
* @param {model} member - A member object from the database.
|
||||||
* @throws {Error} When there's no message to send.
|
* @throws {Error} When there's no message to send.
|
||||||
*/
|
*/
|
||||||
async function replaceMessage(client, message, text, member) {
|
async replaceMessage(client, message, text, member) {
|
||||||
if (text.length > 0 || message.attachments.size > 0) {
|
if (text.length > 0 || message.attachments.size > 0) {
|
||||||
const channel = client.channels.get(message.channelId);
|
const channel = client.channels.get(message.channelId);
|
||||||
const webhook = await getOrCreateWebhook(client, channel).catch((e) =>{throw e});
|
const webhook = await this.getOrCreateWebhook(client, channel).catch((e) => {
|
||||||
|
throw e
|
||||||
|
});
|
||||||
const username = member.displayname ?? member.name;
|
const username = member.displayname ?? member.name;
|
||||||
await webhook.send({content: text, username: username, avatar_url: member.propic});
|
await webhook.send({content: text, username: username, avatar_url: member.propic});
|
||||||
await message.delete();
|
await message.delete();
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
throw new Error(enums.err.NO_MESSAGE_SENT_WITH_PROXY);
|
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.
|
* Gets or creates a webhook.
|
||||||
*
|
*
|
||||||
* @param {Client} client - The fluxer.js client.
|
* @param {Client} client - The fluxer.js client.
|
||||||
@@ -78,24 +63,26 @@ function createAttachmentEmbedsForWebhook(attachments) {
|
|||||||
* @returns {Webhook} A webhook object.
|
* @returns {Webhook} A webhook object.
|
||||||
* @throws {Error} When no webhooks are allowed in the channel.
|
* @throws {Error} When no webhooks are allowed in the channel.
|
||||||
*/
|
*/
|
||||||
async function getOrCreateWebhook(client, channel) {
|
async getOrCreateWebhook(client, channel) {
|
||||||
// If channel doesn't allow webhooks
|
// If channel doesn't allow webhooks
|
||||||
if (!channel?.createWebhook) throw new Error(enums.err.NO_WEBHOOKS_ALLOWED);
|
if (!channel?.createWebhook) throw new Error(enums.err.NO_WEBHOOKS_ALLOWED);
|
||||||
let webhook = await getWebhook(client, channel).catch((e) =>{throw e});
|
let webhook = await this.getWebhook(client, channel).catch((e) => {
|
||||||
|
throw e
|
||||||
|
});
|
||||||
if (!webhook) {
|
if (!webhook) {
|
||||||
webhook = await channel.createWebhook({name: name});
|
webhook = await channel.createWebhook({name: name});
|
||||||
}
|
}
|
||||||
return webhook;
|
return webhook;
|
||||||
}
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets an existing webhook.
|
* Gets an existing webhook.
|
||||||
*
|
*
|
||||||
* @param {Client} client - The fluxer.js client.
|
* @param {Client} client - The fluxer.js client.
|
||||||
* @param {Channel} channel - The channel the message was sent in.
|
* @param {Channel} channel - The channel the message was sent in.
|
||||||
* @returns {Webhook} A webhook object.
|
* @returns {Webhook} A webhook object.
|
||||||
*/
|
*/
|
||||||
async function getWebhook(client, channel) {
|
async getWebhook(client, channel) {
|
||||||
const channelWebhooks = await channel?.fetchWebhooks() ?? [];
|
const channelWebhooks = await channel?.fetchWebhooks() ?? [];
|
||||||
if (channelWebhooks.length === 0) {
|
if (channelWebhooks.length === 0) {
|
||||||
return;
|
return;
|
||||||
@@ -107,6 +94,8 @@ async function getWebhook(client, channel) {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
return pf_webhook;
|
return pf_webhook;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const webhookHelper = wh;
|
|
||||||
|
module.exports = webhookHelper;
|
||||||
Reference in New Issue
Block a user