diff --git a/bot.js b/bot.js new file mode 100644 index 0000000..c3358b5 --- /dev/null +++ b/bot.js @@ -0,0 +1,66 @@ +/** __ __ __ ___ ___ __ __ ___ + * / ' / \ |__) | |__ \_/ |__) / \ | + * \__. \__/ | \ | |___ / \ |__) \__/ | + * + * @copyright © 2021 hepller + */ + +// Импорт модулей +const {VK} = require('vk-io') +const Markov = require('markov-generator') + +// Импорт функций +const Utils = require('./utils.js') + +// Конфиг, паттерн и файл проекта +const config = require('./config') +const data = require('./data') +const project = require('./package') + +// Инициализация vk-io +const vk = new VK({token: config.token, v: 5.131}) + +// Сообщения при запуске +console.log(`Cortex Bot v${project.version}`) +console.log('VK API connection ...') + +// Запуск обработчика событий ВК +vk.updates.startPolling() + .then(() => console.log('Successfully connected')) + +// Обработчик сообщений ВК +vk.updates.on('message_new', async ctx => { + + // Игнорирование лишних сообщений + if (!ctx.isChat || ctx.isOutbox || ctx.isGroup) return + + // Генерация сообщения с определенным шансом + if (Utils.getWithChance(config.chance)) { + + // Сообщение в консоль о начале генеарции + console.log(`Generation started <#${ctx.chatId}> ${Utils.getTimeString()}`) + + // Статус набора текста + await ctx.setActivity() + + // Время в начале генерации + const start_time = Date.now() + + // Генерация текста + const sentence = new Markov({input: data, minLenght: config.min_words}).makeChain() + + // Предупреждение при превышении лимита символов + if (sentence.split('').length > config.max_symbols) return console.log(`#${ctx.chatId} Symbols limit exceeded (${sentence.split('').length}/${config.max_symbols})`) + + // Время в конце генерации (преобразованное в милисекунды) + const final_time = (Date.now() - start_time) % 1000 + + // Отправка сообщения + await ctx.send(config.format ? Utils.formatText(sentence) : sentence) + .then(() => console.log(`Text generated <#${ctx.chatId}> ${final_time}ms`)) + } +}) + +// Обработка возможных ошибок +process.on('uncaughtException', error => console.error(`Error: ${error.message}`)) +process.on('unhandledRejection', error => console.error(`Error: ${error.message}`)) \ No newline at end of file diff --git a/config.json b/config.json index a7295f3..6b10b78 100644 --- a/config.json +++ b/config.json @@ -2,5 +2,6 @@ "token": "TOKEN", "chance": 10, "min_words": 2, - "max_symbols": 250 + "max_symbols": 250, + "format": true } \ No newline at end of file diff --git a/core/core.js b/core/core.js deleted file mode 100644 index b84350c..0000000 --- a/core/core.js +++ /dev/null @@ -1,61 +0,0 @@ -/** __ __ __ ___ ___ - * / ' / \ |__) | |__ \_/ - * \__. \__/ | \ | |___ / \ - * - * @copyright © 2021 hepller - */ - -// Импорт модулей и функций -const {VK} = require('vk-io') -const Markov = require('markov-generator') - -/** Функции */ -const Utils = require('./utils') - -// Конфиг, паттерн и файл проекта -const config = require('../config') -const data = require('../data') -const project = require('../package') - -/** VK API */ -const vk = new VK({token: config.token, v: 5.131}) - -// Префиксы для логирования -const succes_prefix = '\u001B[32m>\u001B[0m' -const warn_prefix = '\u001B[33m>\u001B[0m' -const error_prefix = '\u001B[31m>\u001B[0m' - -// Сообщения при запуске -console.log(succes_prefix, `Cortex Bot v${project.version}`) -console.log(succes_prefix, 'VK API connection ...') - -// Запуск обработчика событий ВК -vk.updates.startPolling().then(() => console.log(succes_prefix, 'Successfully connected')) - -// Обработчик сообщений ВК -vk.updates.on('message_new', async ctx => { - - // Игнорирование лишних сообщений - if (!ctx.isChat || ctx.isOutbox || ctx.isGroup) return - - // Генерация сообщения с определенным шансом - if (Utils.getWithChance(config.chance)) { - - // Статус набора текста - await ctx.setActivity() - - /** Сгенерированный текст */ - const sentence = new Markov({input: data, minLenght: config.min_words}).makeChain() - - // Предупреждение при превышении лимита символов - if (sentence.split('').length > config.max_symbols) return console.warn(warn_prefix, `#${ctx.chatId} Symbols limit exceeded (${sentence.split('').length}/${config.max_symbols})`) - - // Отправка сообщения - await ctx.send(sentence) - .then(() => console.log(succes_prefix, `#${ctx.chatId} Text generated (${Utils.getTimeString()})`)) - } -}) - -// Обработка возможных ошибок -process.on('uncaughtException', error => console.error(error_prefix, `Error: ${error.message}`)) -process.on('unhandledRejection', error => console.error(error_prefix, `Error: ${error.message}`)) \ No newline at end of file diff --git a/package.json b/package.json index f124edc..25a1ab0 100644 --- a/package.json +++ b/package.json @@ -1,8 +1,8 @@ { "name": "cortex-bot", - "version": "0.7.2", + "version": "0.7.3", "description": "vk text generator bot", - "main": "core/core.js", + "main": "bot.js", "repository": { "type": "git", "url": "git+https://github.com/hepller/cortex-bot.git" diff --git a/readme.md b/readme.md index c5e07c3..32148dd 100644 --- a/readme.md +++ b/readme.md @@ -10,6 +10,7 @@ - `chance` - Шанс генерации сообщения - `min_words` - Минимальное кол-во слов в сгенерированном сообщении - `max_symbols` - Максимальное кол-во символов в сообщении +- `format` - Форматирование текста (заглавная буква и точка в конце) --- diff --git a/core/utils.js b/utils.js similarity index 65% rename from core/utils.js rename to utils.js index 5430141..ff2888f 100644 --- a/core/utils.js +++ b/utils.js @@ -1,13 +1,13 @@ -/** __ __ __ ___ ___ - * / ' / \ |__) | |__ \_/ - * \__. \__/ | \ | |___ / \ +/** __ __ __ ___ ___ __ __ ___ + * / ' / \ |__) | |__ \_/ |__) / \ | + * \__. \__/ | \ | |___ / \ |__) \__/ | * * @copyright © 2021 hepller */ /** Функции */ module.exports = class Utils { - + /** Получает текущее время в формате `hh:mm:ss` */ static getTimeString() { @@ -24,7 +24,7 @@ module.exports = class Utils { // Возвращение строки return `${hours}:${minutes}:${seconds}` } - + /** * Возвращает `true` с определенным шансом * @param {number} likelihood Вероятность (%) @@ -32,4 +32,12 @@ module.exports = class Utils { static getWithChance(likelihood) { return Math.random() * 100 < likelihood } + + /** + * Форматирует текст (устанавливает заглавную букву и точку в конце) + * @param {string} text Текст для форматирования + */ + static formatText(text) { + return text.charAt(0).toUpperCase() + text.slice(1) + '.' + } } \ No newline at end of file