feat: prettier and eslint

This commit is contained in:
GramingFoxTeam
2022-11-16 13:59:55 +03:00
parent 0ad5ece085
commit 1c27ccb17c
22 changed files with 2359 additions and 324 deletions

18
.eslintrc.cjs Normal file
View File

@@ -0,0 +1,18 @@
module.exports = {
env: {
es2021: true,
node: true
},
extends: 'eslint:recommended',
overrides: [],
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module'
},
rules: {
indent: ['error', 'tab'],
'linebreak-style': ['error', 'windows'],
quotes: ['error', 'single'],
semi: ['error', 'always']
}
};

18
.eslintrc.js Normal file
View File

@@ -0,0 +1,18 @@
module.exports = {
env: {
es2021: true,
node: true
},
extends: 'eslint:recommended',
overrides: [],
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module'
},
rules: {
indent: ['error', 'tab'],
'linebreak-style': ['error', 'windows'],
quotes: ['error', 'single'],
semi: ['error', 'always']
}
};

4
.prettierrc.json Normal file
View File

@@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "none"
}

View File

@@ -1,4 +1,10 @@
import { ContextMenuCommandBuilder, ApplicationCommandType, ActionRowBuilder, SelectMenuBuilder, ComponentType } from 'discord.js'; import {
ContextMenuCommandBuilder,
ApplicationCommandType,
ActionRowBuilder,
SelectMenuBuilder,
ComponentType
} from 'discord.js';
export default { export default {
data: new ContextMenuCommandBuilder() data: new ContextMenuCommandBuilder()
.setName('Train Message') .setName('Train Message')
@@ -12,24 +18,32 @@ export default {
description: `The ${label} label.`, description: `The ${label} label.`,
value: label.toLowerCase() value: label.toLowerCase()
}); });
}; }
const row = new ActionRowBuilder() const row = new ActionRowBuilder().addComponents(
.addComponents(
new SelectMenuBuilder() new SelectMenuBuilder()
.setCustomId('select') .setCustomId('select')
.setPlaceholder('Nothing selected') .setPlaceholder('Nothing selected')
.addOptions(options), .addOptions(options)
); );
const reply = await interaction.reply({ content: 'Please select the corresponding label to train the bot.', components: [row], ephemeral: true }); const reply = await interaction.reply({
content: 'Please select the corresponding label to train the bot.',
components: [row],
ephemeral: true
});
const collector = reply.createMessageComponentCollector({ componentType: ComponentType.StringSelect, time: 15000 }); const collector = reply.createMessageComponentCollector({
componentType: ComponentType.StringSelect,
time: 15000
});
collector.on('collect', i => { collector.on('collect', (i) => {
i.client.helper.sendTrainData(interaction.targetMessage.content, i.values[0].toUpperCase()); i.client.helper.sendTrainData(
interaction.targetMessage.content,
i.values[0].toUpperCase()
);
i.reply({ content: 'Sent train data to server.', ephemeral: true }); i.reply({ content: 'Sent train data to server.', ephemeral: true });
}); });
} }
} };

View File

@@ -9,7 +9,9 @@ export default {
const command = interaction.client.commands.get(interaction.commandName); const command = interaction.client.commands.get(interaction.commandName);
if (!command) { if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`); console.error(
`No command matching ${interaction.commandName} was found.`
);
return; return;
} }
@@ -17,7 +19,10 @@ export default {
await command.execute(interaction); await command.execute(interaction);
} catch (error) { } catch (error) {
console.error(error); console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true }); await interaction.reply({
content: 'There was an error while executing this command!',
ephemeral: true
});
} }
} }
} };

View File

@@ -6,4 +6,4 @@ export default {
execute(msg) { execute(msg) {
msg.client.helper.scanText(msg.content, `${msg.channelId}/${msg.id}`); msg.client.helper.scanText(msg.content, `${msg.channelId}/${msg.id}`);
} }
} };

View File

@@ -2,17 +2,18 @@ export default {
name: 'aiResponse', name: 'aiResponse',
once: false, once: false,
async execute(aiRes) { async execute(aiRes) {
console.log(aiRes); const response = global.config.responses.find(
const response = config.responses.find(res => res.label === aiRes.predictions[0].label); (res) => res.label === aiRes.predictions[0].label
);
if (!response) return; if (!response) return;
if (Number(aiRes.predictions[0].score) >= response.threshold) { if (Number(aiRes.predictions[0].score) >= response.threshold) {
const ids = aiRes.id.split('/'); const ids = aiRes.id.split('/');
let channel = client.channels.cache.get(ids[0]); let channel = global.client.channels.cache.get(ids[0]);
if (!channel) { if (!channel) {
await client.channels.fetch(ids[0]); await global.client.channels.fetch(ids[0]);
channel = client.channels.cache.get(ids[0]); channel = global.client.channels.cache.get(ids[0]);
} }
let message = channel.messages.cache.get(ids[1]); let message = channel.messages.cache.get(ids[1]);
@@ -27,4 +28,4 @@ export default {
return; return;
} }
} }
} };

View File

@@ -1,7 +1,7 @@
export default { export default {
name: 'ocrResponse', name: 'ocrResponse',
once: false, once: false,
execute(client, ocrRes) { execute() {
// TODO // TODO
} }
} };

View File

@@ -1,4 +1,4 @@
import { Client, Events, GatewayIntentBits, Collection } from 'discord.js'; import { Client, GatewayIntentBits, Collection } from 'discord.js';
import { readFileSync, readdirSync } from 'node:fs'; import { readFileSync, readdirSync } from 'node:fs';
// Fix __dirname not being defined in ES modules. (https://stackoverflow.com/a/64383997) // Fix __dirname not being defined in ES modules. (https://stackoverflow.com/a/64383997)
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
@@ -11,45 +11,59 @@ import HelperClient from '../../client/index.js';
const configJSON = readFileSync('../config.json', 'utf-8'); const configJSON = readFileSync('../config.json', 'utf-8');
global.config = JSON.parse(configJSON); global.config = JSON.parse(configJSON);
const helper = new HelperClient(config); const helper = new HelperClient(global.config);
helper.connect(); helper.connect();
global.client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] }); global.client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent
]
});
client.commands = new Collection(); global.client.commands = new Collection();
client.helper = helper; global.client.helper = helper;
const commandsPath = join(__dirname, 'commands'); const commandsPath = join(__dirname, 'commands');
const commandFiles = readdirSync(commandsPath).filter(file => file.endsWith('.js')); const commandFiles = readdirSync(commandsPath).filter((file) =>
file.endsWith('.js')
);
for (const file of commandFiles) { for (const file of commandFiles) {
const filePath = join(commandsPath, file); const filePath = join(commandsPath, file);
const command = (await import(`file://${filePath}`)).default; const command = (await import(`file://${filePath}`)).default;
if ('data' in command && 'execute' in command) { if ('data' in command && 'execute' in command) {
client.commands.set(command.data.name, command); global.client.commands.set(command.data.name, command);
} else { } else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`); console.log(
`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`
);
} }
} }
const discordEventsPath = join(__dirname, 'events/discord'); const discordEventsPath = join(__dirname, 'events/discord');
const discordEventFiles = readdirSync(discordEventsPath).filter(file => file.endsWith('.js')); const discordEventFiles = readdirSync(discordEventsPath).filter((file) =>
file.endsWith('.js')
);
for (const file of discordEventFiles) { for (const file of discordEventFiles) {
const filePath = join(discordEventsPath, file); const filePath = join(discordEventsPath, file);
const event = (await import(`file://${filePath}`)).default; const event = (await import(`file://${filePath}`)).default;
if (event.once) { if (event.once) {
client.once(event.name, (...args) => event.execute(...args)); global.client.once(event.name, (...args) => event.execute(...args));
} else { } else {
client.on(event.name, (...args) => event.execute(...args)); global.client.on(event.name, (...args) => event.execute(...args));
} }
} }
// The ReVanced Helper events. // The ReVanced Helper events.
const helperEventsPath = join(__dirname, 'events/helper'); const helperEventsPath = join(__dirname, 'events/helper');
const helperEventFiles = readdirSync(helperEventsPath).filter(file => file.endsWith('.js')); const helperEventFiles = readdirSync(helperEventsPath).filter((file) =>
file.endsWith('.js')
);
for (const file of helperEventFiles) { for (const file of helperEventFiles) {
const filePath = join(helperEventsPath, file); const filePath = join(helperEventsPath, file);
@@ -61,4 +75,4 @@ for (const file of helperEventFiles) {
} }
} }
client.login(config.discord.token); global.client.login(global.config.discord.token);

View File

@@ -5,7 +5,9 @@ const config = JSON.parse(configJSON);
const commands = []; const commands = [];
// Grab all the command files from the commands directory you created earlier // Grab all the command files from the commands directory you created earlier
const commandFiles = readdirSync('./commands').filter(file => file.endsWith('.js')); const commandFiles = readdirSync('./commands').filter((file) =>
file.endsWith('.js')
);
// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment // Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
for (const file of commandFiles) { for (const file of commandFiles) {
@@ -17,13 +19,14 @@ for (const file of commandFiles) {
const rest = new REST({ version: '10' }).setToken(config.discord.token); const rest = new REST({ version: '10' }).setToken(config.discord.token);
try { try {
console.log(`Started refreshing ${commands.length} application (/) commands.`); console.log(
`Started refreshing ${commands.length} application (/) commands.`
);
// The put method is used to fully refresh all commands in the guild with the current set // The put method is used to fully refresh all commands in the guild with the current set
const data = await rest.put( const data = await rest.put(Routes.applicationCommands(config.discord.id), {
Routes.applicationCommands(config.discord.id), body: commands
{ body: commands }, });
);
console.log(`Successfully reloaded ${data.length} application (/) commands.`); console.log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (error) { } catch (error) {

View File

@@ -7,36 +7,44 @@ class HelperClient extends EventEmitter {
super(); super();
if (!server?.port) throw new Error('You did not specify the server port.'); if (!server?.port) throw new Error('You did not specify the server port.');
this.server = server; this.server = server;
}; }
connect() { connect() {
this.client = createConnection(this.server.port, this.server.host ? this.server.host : 'localhost', () => { this.client = createConnection(
this.server.port,
this.server.host ? this.server.host : 'localhost',
() => {
this.emit('connect'); this.emit('connect');
}); }
);
this.client.on('data', (data) => { this.client.on('data', (data) => {
const eventData = deserialize(data, { allowObjectSmallerThanBufferSize: true }); const eventData = deserialize(data, {
allowObjectSmallerThanBufferSize: true
});
switch (eventData.op) { switch (eventData.op) {
case 2: { case 2: {
// The 'aiResponse' event. // The 'aiResponse' event.
this.emit('aiResponse', eventData); this.emit('aiResponse', eventData);
}; break;
}
case 6: { case 6: {
// The 'ocrResponse' event. // The 'ocrResponse' event.
this.emit('ocrResponse', eventData); this.emit('ocrResponse', eventData);
}; break;
}; }
}
}); });
}; }
sendData(data) { sendData(data) {
this.client.write(serialize(data)); this.client.write(serialize(data));
return; return;
}; }
scanText(text, id) { scanText(text, id) {
this.sendData({ this.sendData({
@@ -46,7 +54,7 @@ class HelperClient extends EventEmitter {
}); });
return; return;
}; }
scanImage(url, id) { scanImage(url, id) {
this.sendData({ this.sendData({
@@ -56,7 +64,7 @@ class HelperClient extends EventEmitter {
}); });
return; return;
}; }
sendTrainData(text, label) { sendTrainData(text, label) {
this.sendData({ this.sendData({
@@ -66,13 +74,13 @@ class HelperClient extends EventEmitter {
}); });
return; return;
}; }
trainAI() { trainAI() {
this.sendData({ op: 4 }); this.sendData({ op: 4 });
return; return;
}; }
}; }
export default HelperClient; export default HelperClient;

1939
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -11,5 +11,12 @@
"bugs": { "bugs": {
"url": "https://github.com/reisxd/revanced-helper/issues" "url": "https://github.com/reisxd/revanced-helper/issues"
}, },
"homepage": "https://github.com/reisxd/revanced-helper#readme" "homepage": "https://github.com/reisxd/revanced-helper#readme",
"scripts": {
"lint": "prettier --write . && eslint --fix ."
},
"devDependencies": {
"eslint": "^8.27.0",
"prettier": "2.7.1"
}
} }

View File

@@ -2,7 +2,10 @@ import { readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path'; import { join } from 'node:path';
export default function addTrainData(eventData) { export default function addTrainData(eventData) {
const file = readFileSync(join(global.__dirname, global.config.fasttext.trainFile), 'utf-8'); const file = readFileSync(
join(global.__dirname, global.config.fasttext.trainFile),
'utf-8'
);
const data = file.split('\n'); const data = file.split('\n');
const { label, text } = eventData; const { label, text } = eventData;
@@ -10,7 +13,10 @@ export default function addTrainData(eventData) {
data.splice(labelIndex === -1 ? 0 : labelIndex, 0, `${label} ${text}`); data.splice(labelIndex === -1 ? 0 : labelIndex, 0, `${label} ${text}`);
writeFileSync(join(global.__dirname, global.config.fasttext.trainFile), data.join('\n')); writeFileSync(
join(global.__dirname, global.config.fasttext.trainFile),
data.join('\n')
);
return; return;
} }

View File

@@ -3,9 +3,4 @@ import trainAI from './trainAI.js';
import runOCR from './ocr.js'; import runOCR from './ocr.js';
import addTrainData from './addTrainData.js'; import addTrainData from './addTrainData.js';
export { export { runAI, trainAI, runOCR, addTrainData };
runAI,
trainAI,
runOCR,
addTrainData
}

View File

@@ -5,7 +5,7 @@ export default async function runOCR(client, eventData) {
const config = { const config = {
lang: 'eng', lang: 'eng',
oem: 3, oem: 3,
psm: 3, psm: 3
}; };
const ocrText = await recognize(eventData.url, config); const ocrText = await recognize(eventData.url, config);

View File

@@ -39,14 +39,17 @@ export default async function trainAI() {
// load pre trained word vectors from unsupervised model // load pre trained word vectors from unsupervised model
pretrainedVectors: '' pretrainedVectors: ''
}, },
serializeTo: join(global.__dirname, global.config.fasttext.loadModel).replace('.bin', ''), serializeTo: join(
global.__dirname,
global.config.fasttext.loadModel
).replace('.bin', ''),
trainFile: join(global.__dirname, global.config.fasttext.trainFile), trainFile: join(global.__dirname, global.config.fasttext.trainFile),
bin: join(global.__dirname, global.config.fasttext.bin) bin: join(global.__dirname, global.config.fasttext.bin)
}); });
global.ft.unload(); global.ft.unload();
await ft.train() await ft.train();
global.ft.load(); global.ft.load();

View File

@@ -1,7 +1,7 @@
import { readFileSync } from 'node:fs'; import { readFileSync } from 'node:fs';
// Fix __dirname not being defined in ES modules. (https://stackoverflow.com/a/64383997) // Fix __dirname not being defined in ES modules. (https://stackoverflow.com/a/64383997)
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path'; import { dirname } from 'node:path';
const __filename = fileURLToPath(import.meta.url); const __filename = fileURLToPath(import.meta.url);
global.__dirname = dirname(__filename); global.__dirname = dirname(__filename);
@@ -23,31 +23,31 @@ global.ft = ft;
const server = createServer(async (client) => { const server = createServer(async (client) => {
client.on('data', async (data) => { client.on('data', async (data) => {
const eventData = deserialize(data, { allowObjectSmallerThanBufferSize: true }); const eventData = deserialize(data, {
allowObjectSmallerThanBufferSize: true
});
switch(eventData.op) { switch (eventData.op) {
case 1: { case 1: {
runAI(client, eventData); runAI(client, eventData);
break; break;
}; }
case 3: { case 3: {
addTrainData(eventData); addTrainData(eventData);
break; break;
}; }
case 4: { case 4: {
trainAI(); trainAI();
break; break;
}
};
case 5: { case 5: {
runOCR(client, eventData); runOCR(client, eventData);
break; break;
}; }
}; }
}); });
}); });