From 4f1e3943b4657625199af6f637974b984aa74e3c Mon Sep 17 00:00:00 2001 From: Degradin Date: Sun, 12 Jan 2025 23:44:41 +0300 Subject: [PATCH] prettify Visual Enchancements --- bot.js | 204 +++++++++---------- rpg.js | 608 +++++++++++++++++++++++++++++---------------------------- 2 files changed, 407 insertions(+), 405 deletions(-) diff --git a/bot.js b/bot.js index e2fcdd4..9adeb1f 100644 --- a/bot.js +++ b/bot.js @@ -3,7 +3,7 @@ const { Telegraf, Scenes, session, Markup, Stage } = require('telegraf'); const { Op } = require('sequelize'); const schedule = require('node-schedule'); const sequelize = require('./db'); // Подключение базы данных - // Подключаем обработчики +// Подключаем обработчики const commands = require('./commands'); const utils = require('./utils'); const handlers = require('./handlers'); @@ -25,21 +25,21 @@ const { SkillsModel, DailyModel } = global.config - const bot = new Telegraf(process.env.BOT_TOKEN) - const rpg = require('./rpg'); // Подключение RPG-механик - const crime = require('./scenes/crime') - const pocketsteal = require('./scenes/pocketsteal') - const shop = require('./scenes/shop') - const pve = require('./scenes/pve') +const bot = new Telegraf(process.env.BOT_TOKEN) +const rpg = require('./rpg'); // Подключение RPG-механик +const crime = require('./scenes/crime') +const pocketsteal = require('./scenes/pocketsteal') +const shop = require('./scenes/shop') +const pve = require('./scenes/pve') const newpve = require('./scenes/newpve') - const stage = new Scenes.Stage([crime, pocketsteal, shop, pve, newpve]); +const stage = new Scenes.Stage([crime, pocketsteal, shop, pve, newpve]); - const start = async () => { +const start = async () => { try { // Подключаемся к базе данных await sequelize.authenticate(); console.log('Подключение к базе данных успешно!'); - + // Синхронизация моделей, если нужно await sequelize.sync({ alter: true }); console.log('Синхронизация моделей завершена.'); @@ -52,29 +52,29 @@ const newpve = require('./scenes/newpve') } bot.telegram.setMyCommands([{ - command: "pay", - description: "Перевести указанному пользователю сумму." - }, - { - command: "buy", - description: "Приобрести указанное имущество." - }, - { - command: "business", - description: "Создать организацию." - }, - { - command: "invite", - description: "Пригласить пользователя в организацию." - }, - { - command: "percent", - description: "Установить пользователю процент заработка." - }, - { - command: "report", - description: "Создать жалобу/обращение/идею." - } + command: "pay", + description: "Перевести указанному пользователю сумму." +}, +{ + command: "buy", + description: "Приобрести указанное имущество." +}, +{ + command: "business", + description: "Создать организацию." +}, +{ + command: "invite", + description: "Пригласить пользователя в организацию." +}, +{ + command: "percent", + description: "Установить пользователю процент заработка." +}, +{ + command: "report", + description: "Создать жалобу/обращение/идею." +} ]) bot.use(stage.middleware()) @@ -82,25 +82,25 @@ bot.use(rpg) bot.use( session({ - getSessionKey: (ctx) => { - if ((ctx.from && ctx.chat && ctx.chat.id === ctx.from.id) || (!ctx.chat && ctx.from)) { - return `user:${ctx.from.id}` - } else if (ctx.from && ctx.chat) { - return `${ctx.from.id}:${ctx.chat.id}` + getSessionKey: (ctx) => { + if ((ctx.from && ctx.chat && ctx.chat.id === ctx.from.id) || (!ctx.chat && ctx.from)) { + return `user:${ctx.from.id}` + } else if (ctx.from && ctx.chat) { + return `${ctx.from.id}:${ctx.chat.id}` + } + return ctx.update.update_id } - return ctx.update.update_id - } }) - ) - bot.use(stage) +) +bot.use(stage) bot.use(utils.stats) bot.use(async (ctx, next) => { bot.context.config = require('./ctxconfig.json') let id = ctx.from.id let username = ctx.from.username - if(username == null) username = ctx.from.id - switch(ctx.updateType){ + if (username == null) username = ctx.from.id + switch (ctx.updateType) { case `message`: console.log(utils.getCurrentTime() + `: ` + username + `: ` + ctx.update.message.text) break; @@ -124,9 +124,9 @@ bot.use(async (ctx, next) => { name: ctx.from.first_name }) } else { - user.name = ctx.from.first_name - if(user.username === null) user.username = ctx.from.id - user.save() + user.name = ctx.from.first_name + if (user.username === null) user.username = ctx.from.id + user.save() } if (property === null) { await PropertyModel.create({ @@ -145,45 +145,45 @@ bot.use(async (ctx, next) => { //if (whitelist.includes(id) == false) return ctx.reply(`У вас пока нет доступа к боту. Следите за обновлениями в группе: t.me/CampFireGameBotNews`) if (block) { const currentTime = Math.trunc(Date.now() / 1000); // Получаем текущее время в секундах - + if (block.isBlocked && block.time > currentTime) { const remainingTime = Math.trunc((block.time - currentTime) / 60); // Рассчитываем оставшееся время return ctx.reply( `📛 У вас активная блокировка по причине: ${block.reason}.\n⏲️ Оставшееся время: ${remainingTime} мин.` ); } - + // Если блокировка истекла или отключена block.isBlocked = false; await block.save(); // Обязательно используем `await` для сохранения изменений } - + const start = Date.now() const timeoutPromise = new Promise((resolve, reject) => { - + setTimeout(() => { - reject(new Error('timeout')) + reject(new Error('timeout')) }, 1000 * 5) - }) + }) - const nextPromise = next() - .then(() => { - const ms = Date.now() - start + const nextPromise = next() + .then(() => { + const ms = Date.now() - start }) - .catch((error) => { - handleError(error, ctx) - }) - - return Promise.race([timeoutPromise, nextPromise]) .catch((error) => { - if (error.message === 'timeout') { - console.error('timeout', ctx.update) - return false - } - - return true + handleError(error, ctx) }) - + + return Promise.race([timeoutPromise, nextPromise]) + .catch((error) => { + if (error.message === 'timeout') { + console.error('timeout', ctx.update) + return false + } + + return true + }) + }) bot.command('start', async (ctx) => { @@ -221,7 +221,7 @@ bot.hears('Криминал', async (ctx) => { }) -bot.hears('промка', async(ctx) => { +bot.hears('промка', async (ctx) => { generatePromo() }); @@ -343,13 +343,13 @@ bot.action(/{"action": "sueta_*/, async (ctx) => { console.log(data.car) let user = await UserModel.findByPk(ctx.from.id) let property = await PropertyModel.findByPk(ctx.from.id) - switch(data.action){ + switch (data.action) { case `sueta_accept`: user.money += data.carprice await ctx.editMessageText(`➕ ${data.carprice}`) break; case `sueta_refuse`: - user.money += Math.round(property.car.price/2) + user.money += Math.round(property.car.price / 2) property.car = { name: data.carname, price: data.carprice @@ -440,7 +440,7 @@ bot.command('daily_bonus', async (ctx) => { message += `🏗 Материалы: ${reward.materials}\n`; } else { totalMoney += reward.materials; // Материалы заменяются на деньги - } + } // Добавляем деньги user.money += totalMoney; @@ -502,14 +502,14 @@ bot.hears('🏗️ Предприятия', async (ctx) => { bot.action('enterprise_menu', async (ctx) => { const user = await UserModel.findByPk(ctx.from.id); const warehouse = await WarehouseModel.findOne({ where: { playerId: user.telegram_id } }); - + const enterprises = await EnterpriseModel.findAll({ where: { playerId: user.telegram_id } }); let message = `🏗️ Меню предприятий:\n`; message += `У вас: ${enterprises.length} предприятий.\n`; - message += warehouse + message += warehouse ? `🗄️ Единый склад: Доступен (Ёмкость: ${warehouse.capacity} ед.)\n` : `🗄️ Единый склад: Не построен.\n`; @@ -553,11 +553,11 @@ bot.action('my_enterprises', async (ctx) => { return await ctx.reply('У вас нет предприятий.'); } let metallPrice = await ResourcePriceModel.findOne({ - where: { resource: "metall" } - }); + where: { resource: "metall" } + }); let message = `🏭 Мои предприятия:\n\n`; const buttons = []; - + for (const enterprise of enterprises) { const { id, name, level, efficiency, currentResources, resourceType, warehouseCapacity } = enterprise; const resourcePrice = await ResourcePriceModel.findOne({ @@ -574,7 +574,7 @@ bot.action('my_enterprises', async (ctx) => { if (!truck) { enterpriseButtons.push({ text: `🛻 ID: ${id}`, callback_data: `hire_truck_${id}` }); - }else{ + } else { enterpriseButtons.push({ text: `🚛 ID: ${id}`, callback_data: `upgrade_truck_${id}` }); } @@ -586,7 +586,7 @@ bot.action('my_enterprises', async (ctx) => { buttons.push(enterpriseButtons); } - message += `\n\n📈 - Улучшить\n🛻 - Купить грузовик [~${utils.spaces(metallPrice.price*700)} руб.]\n🚛 - Улучшить грузовик\n💰 - Продать ресурсы с предприятия\n🔄 - Перевезти все на склад` + message += `\n\n📈 - Улучшить\n🛻 - Купить грузовик [~${utils.spaces(metallPrice.price * 700)} руб.]\n🚛 - Улучшить грузовик\n💰 - Продать ресурсы с предприятия\n🔄 - Перевезти все на склад` buttons.push([{ text: '⬅️ Назад', callback_data: 'enterprise_menu' }]); return await ctx.editMessageText(message, Markup.inlineKeyboard(buttons).resize()); @@ -605,7 +605,7 @@ bot.action('build_enterprise', async (ctx) => { }); if (enterprises.length >= 5) { - return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, 'Вы достигли максимального числа предприятий.', {show_alert: true}); + return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, 'Вы достигли максимального числа предприятий.', { show_alert: true }); } // Получаем текущие цены из базы данных @@ -642,7 +642,7 @@ bot.action(/build_(wood|coal|oil|metall|gold|diamond)/, async (ctx) => { let user = await UserModel.findByPk(ctx.from.id) let data = ctx.update.callback_query.data let type = data.split('_')[1] - + // Получаем текущие цены из базы данных const resourcePrice = await ResourcePriceModel.findOne({ @@ -652,7 +652,7 @@ bot.action(/build_(wood|coal|oil|metall|gold|diamond)/, async (ctx) => { // Проверка, есть ли достаточно денег у пользователя if (user.money < price) { - return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `У вас недостаточно средств для постройки предприятия. Необходимо ${price} руб.`, {show_alert: true}) + return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `У вас недостаточно средств для постройки предприятия. Необходимо ${price} руб.`, { show_alert: true }) } // Строим предприятие @@ -784,7 +784,7 @@ bot.action('transfer_resources', async (ctx) => { const warehouse = await WarehouseModel.findOne({ where: { playerId: user.telegram_id } }); if (!warehouse) { - return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id,'У вас нет единого склада.'); + return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, 'У вас нет единого склада.'); } const enterprises = await EnterpriseModel.findAll({ @@ -814,20 +814,20 @@ bot.action(/transfer_from_(\d+)/, async (ctx) => { const { currentResources, resourceType, playerId } = enterprise; if (currentResources === 0) { - return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, 'На предприятии нет ресурсов для перевода.'); + return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, 'На предприятии нет ресурсов для перевода.'); } const warehouse = await WarehouseModel.findOne({ where: { playerId } }); if (!warehouse) { - return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, 'У вас нет склада для перевода ресурсов.'); + return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, 'У вас нет склада для перевода ресурсов.'); } const freeCapacity = warehouse.capacity - getWarehouseUsedCapacity(warehouse); const transferAmount = Math.min(currentResources, freeCapacity); if (transferAmount === 0) { - return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, 'Склад заполнен. Перевод невозможен.'); + return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, 'Склад заполнен. Перевод невозможен.'); } // Перевод ресурсов @@ -873,7 +873,7 @@ bot.action(/upgrade_(\d+)/, async (ctx) => { }); let upgradeCost = resourcePrice.price * 1.5 * 10 * 24 * 7 // Стоимость улучшения зависит от уровня if (user.money < upgradeCost) { - return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `У вас недостаточно средств для прокачки предприятия. Необходимо ${upgradeCost} руб.`) + return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `У вас недостаточно средств для прокачки предприятия. Необходимо ${upgradeCost} руб.`) } // Прокачка: повышение уровня и эффективности @@ -994,7 +994,7 @@ bot.action(/sell_all_(\d+)/, async (ctx) => { const totalPrice = currentResources * resourcePrice.price; if (currentResources === 0) { - return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, 'На предприятии нет ресурсов для продажи.'); + return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, 'На предприятии нет ресурсов для продажи.'); } await ctx.reply( @@ -1021,7 +1021,7 @@ bot.action(/confirm_ressell_(\d+)/, async (ctx) => { const totalPrice = currentResources * resourcePrice.price; if (currentResources === 0) { - return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, 'На предприятии нет ресурсов для продажи.'); + return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, 'На предприятии нет ресурсов для продажи.'); } // Обновление баланса игрока @@ -1038,7 +1038,7 @@ bot.action(/confirm_ressell_(\d+)/, async (ctx) => { ); // Гарантируем, что цена не упадет ниже 50% от базовой цены resourcePrice.price = Math.max(resourcePrice.price, Math.round(resourcePrice.basePrice * 0.5)); - + await resourcePrice.save(); updateResourcePricesMessage(); await ctx.editMessageText(`Вы успешно продали ${currentResources} ед. ${getEnterpriseEmoji(resourceType)} за ${totalPrice} руб.`); @@ -1093,7 +1093,7 @@ bot.command('sellstorage', async (ctx) => { // Гарантируем, что цена не упадет ниже 50% от базовой цены resourcePrice.price = Math.max(resourcePrice.price, Math.round(resourcePrice.basePrice * 0.5)); - + await resourcePrice.save(); updateResourcePricesMessage(); return await ctx.reply( @@ -1119,16 +1119,16 @@ bot.action(/hire_truck_(\d+)/, async (ctx) => { }); if (existingTruck) { - return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `У вас уже есть грузовик для предприятия ${enterprise.name}.`); + return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `У вас уже есть грузовик для предприятия ${enterprise.name}.`); } const resourcePrice = await ResourcePriceModel.findOne({ where: { resource: 'metall' } }); if (!resourcePrice) { - return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, 'Не удалось получить цену ресурса.'); + return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, 'Не удалось получить цену ресурса.'); } - if (user.money < resourcePrice.price*700) { - return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `Недостаточно средств. Стоимость грузовика: ${utils.spaces(resourcePrice.price*700)} руб.`); - } - await user.update({ money: user.money - (resourcePrice.price*700) }) + if (user.money < resourcePrice.price * 700) { + return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `Недостаточно средств. Стоимость грузовика: ${utils.spaces(resourcePrice.price * 700)} руб.`); + } + await user.update({ money: user.money - (resourcePrice.price * 700) }) // Создаем новый грузовик const newTruck = await TruckModel.create({ enterpriseId: enterprise.id, @@ -1190,12 +1190,12 @@ const recoverResourcePrices = async () => { if (resource.price > resource.basePrice * 2.1) { resource.price = Math.round(resource.basePrice * 0.79764918); // Устанавливаем цену на уровне 1.5 базовой - } + } // Гарантируем, что цена остаётся в диапазоне [50% basePrice, 150% basePrice] resource.price = Math.max(resource.price, Math.round(resource.basePrice * 0.5)); // Минимум resource.price = Math.min(resource.price, Math.round(resource.basePrice * 3)); // Максимум - + await resource.save(); // Сохраняем после всех корректировок } }; @@ -1408,7 +1408,7 @@ schedule.scheduleJob('5 * * * *', resourceTransportation); // Каждый ча bot.command('force_prod', async (ctx) => { - resourceProduction() + resourceProduction() return await ctx.reply(`Принудительно добыто.`) }) @@ -1447,7 +1447,7 @@ const spinSlots = async (ctx, bet, user) => { let resultMessage = `🎰 Итог:\n${finalIcons.join(' | ')}\n\n`; if (winMultiplier > 0) { const winnings = bet * winMultiplier; - utils.giveExp(user, winMultiplier*10) + utils.giveExp(user, winMultiplier * 10) user.money += winnings; await user.save(); console.log(`Win: ${winnings}`) @@ -1574,7 +1574,7 @@ bot.hears('🎰 Рулетка', async (ctx) => { const redNumbers = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35]; // Все четные числа (черные) const blackNumbers = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36]; - + // Рулетка: делаем случайный выбор const randomIndex = Math.floor(Math.random() * 37); // от 0 до 36 return randomIndex; diff --git a/rpg.js b/rpg.js index 45e6bd3..b56ac04 100644 --- a/rpg.js +++ b/rpg.js @@ -1,39 +1,39 @@ const { Telegraf, Scenes, session, Markup, Stage, Composer } = require('telegraf'); const schedule = require('node-schedule'); -const { faker, fakerRU } = require('@faker-js/faker'); +const { faker, fakerRU } = require('@faker-js/faker'); // Подключаем необходимые библиотеки const { Op } = require('sequelize'); const sequelize = require('./db'); // Подключение базы данных - // Подключаем обработчики +// Подключаем обработчики const utils = require('./utils'); const handlers = require('./handlers'); const { - phones, - expToUp, - UserModel, - CharacterModel, - InventoryModel, - ItemsModel, - Enemy, - Location, - Battle, - StolenCardsModel, - WorldModel, - PropertyModel, - AFKPropertyModel, - BusinessModel, - BlockModel, - EnterpriseModel, - WarehouseModel, - TruckModel, - ResourcePriceModel, - SkillsModel, - DailyModel + phones, + expToUp, + UserModel, + CharacterModel, + InventoryModel, + ItemsModel, + Enemy, + Location, + Battle, + StolenCardsModel, + WorldModel, + PropertyModel, + AFKPropertyModel, + BusinessModel, + BlockModel, + EnterpriseModel, + WarehouseModel, + TruckModel, + ResourcePriceModel, + SkillsModel, + DailyModel } = global.config const rpg = new Composer(); rpg.use(async (ctx, next) => { - if(ctx.update.edited_channel_post) return console.log(`[RPG] Channel post updated`); + if (ctx.update.edited_channel_post) return console.log(`[RPG] Channel post updated`); let id = ctx.from.id let username = ctx.from.username; if (username == null) username = ctx.from.id; @@ -61,27 +61,27 @@ rpg.use(async (ctx, next) => { }); rpg.hears('RPG', async (ctx) => { - let message = `Меню:\n`; - const buttons = []; - buttons.push([{ text: 'Мой Персонаж', callback_data: 'rpg_profile' }]); - return await ctx.reply(message, Markup.inlineKeyboard(buttons).resize()); + let message = `Меню:\n`; + const buttons = []; + buttons.push([{ text: 'Мой Персонаж', callback_data: 'rpg_profile' }]); + return await ctx.reply(message, Markup.inlineKeyboard(buttons).resize()); }); rpg.action('rpg_profile', async (ctx) => { - const telegramId = ctx.from.id; + const telegramId = ctx.from.id; - // Ищем персонажа - const character = await CharacterModel.findOne({ where: { telegram_id: telegramId } }); - const stolenCards = await StolenCardsModel.findAll({ - where: { userId: character.telegram_id } - }); + // Ищем персонажа + const character = await CharacterModel.findOne({ where: { telegram_id: telegramId } }); + const stolenCards = await StolenCardsModel.findAll({ + where: { userId: character.telegram_id } + }); - if (!character) { - return ctx.reply('Персонаж не найден. Создайте нового персонажа, чтобы начать игру!'); - } + if (!character) { + return ctx.reply('Персонаж не найден. Создайте нового персонажа, чтобы начать игру!'); + } - // Формируем профиль - const profile = ` + // Формируем профиль + const profile = ` 🎭 Профиль персонажа 👤 Имя: ${character.name || 'Не указано'} @@ -99,17 +99,17 @@ rpg.action('rpg_profile', async (ctx) => { 💰 Баланс: ${utils.spaces(character.dirtymoney)}Ð 🃏 Украденные карты: ${stolenCards.length} `; - const buttons = [ - [Markup.button.callback('💳 Карточки', 'view_cards')], - [Markup.button.callback('🎒 Инвентарь', 'inventory')], + const buttons = [ + [Markup.button.callback('💳 Карточки', 'view_cards')], + [Markup.button.callback('🎒 Инвентарь', 'inventory')], ]; if (character.firePoints >= 1) { buttons.push([Markup.button.callback('➕ Распределить очки', 'fire_distribute')]); } -buttons.push([Markup.button.callback('🔙 В меню', 'crime_menu')]); - // Отправляем сообщение - ctx.editMessageText(profile.trim(), Markup.inlineKeyboard(buttons)); + buttons.push([Markup.button.callback('🔙 В меню', 'crime_menu')]); + // Отправляем сообщение + ctx.editMessageText(profile.trim(), Markup.inlineKeyboard(buttons)); }); // Основная команда для вывода кнопок распределения F.I.R.E. @@ -209,7 +209,7 @@ const usersCrimeNet = new Set(); rpg.hears('CampFireGG.Crime', async (ctx) => { const userId = ctx.from.id; const character = await CharacterModel.findOne({ where: { telegram_id: userId } }); - if (!usersCrimeNet.has(userId) && character.level === 1){ + if (!usersCrimeNet.has(userId) && character.level === 1) { // Если пользователь вводит команду впервые usersCrimeNet.add(userId); const username = ctx.from.username || 'User'; @@ -218,12 +218,12 @@ rpg.hears('CampFireGG.Crime', async (ctx) => { // Сообщение для симуляции const lines = [ - `${sshCommand}`, - `> Connecting to secure servers with RSA key...`, - `> Authentication in progress...`, - `> User "${username}" identified.`, - `> Accessing CampFireGG.Crime...`, - `> Connection established. Welcome, ${username}.`, + `${sshCommand}`, + `> Connecting to secure servers with RSA key...`, + `> Authentication in progress...`, + `> User "${username}" identified.`, + `> Accessing CampFireGG.Crime...`, + `> Connection established. Welcome, ${username}.`, ]; // Отправляем первое сообщение @@ -234,18 +234,18 @@ rpg.hears('CampFireGG.Crime', async (ctx) => { let index = 0; while (index < lines[0].length) { - const blockSize = Math.floor(Math.random() * 3) + 2; // Генерируем блок от 2 до 4 символов - currentText += lines[0].slice(index, index + blockSize); // Добавляем блок текста - index += blockSize; // Увеличиваем индекс - await ctx.telegram.editMessageText(sentMessage.chat.id, sentMessage.message_id, undefined, currentText); - await delay(100); // Задержка между блоками + const blockSize = Math.floor(Math.random() * 3) + 2; // Генерируем блок от 2 до 4 символов + currentText += lines[0].slice(index, index + blockSize); // Добавляем блок текста + index += blockSize; // Увеличиваем индекс + await ctx.telegram.editMessageText(sentMessage.chat.id, sentMessage.message_id, undefined, currentText); + await delay(100); // Задержка между блоками } // Последующие строки добавляются полностью, по одной for (let i = 1; i < lines.length; i++) { - await delay(1500); // Задержка между строками - currentText += `\n${lines[i]}`; - await ctx.telegram.editMessageText(sentMessage.chat.id, sentMessage.message_id, undefined, currentText); + await delay(1500); // Задержка между строками + currentText += `\n${lines[i]}`; + await ctx.telegram.editMessageText(sentMessage.chat.id, sentMessage.message_id, undefined, currentText); } // Финальное меню после задержки @@ -253,31 +253,32 @@ rpg.hears('CampFireGG.Crime', async (ctx) => { const buttons = [ [Markup.button.callback('💼 Задачи', 'crime_missions')], [Markup.button.callback('📊 Профиль', 'rpg_profile')], - ]; + ]; //buttons.push([Markup.button.callback('💳 Карточки', 'view_cards')]); - // Добавляем кнопку сообщения, если уровень персонажа равен 1 - if (character && character.level === 1) { + // Добавляем кнопку сообщения, если уровень персонажа равен 1 + if (character && character.level === 1) { buttons.push([Markup.button.callback('📩 (1) Сообщение', '1st_message')]); - } - - await ctx.telegram.editMessageText( + } + + await ctx.telegram.editMessageText( sentMessage.chat.id, sentMessage.message_id, undefined, `🚨 Добро пожаловать в CampFireGG.Crime 🚨\n\n`, Markup.inlineKeyboard(buttons) - )} else { + ) + } else { // Показываем только меню, если команда уже была введена await ctx.reply( `🚨 Добро пожаловать в CampFireGG.Crime 🚨\n\n`, - Markup.inlineKeyboard([ + Markup.inlineKeyboard([ [Markup.button.callback('💼 Задачи', 'crime_missions')], [Markup.button.callback('📊 Профиль', 'rpg_profile')], [Markup.button.callback('💰 Магазин', 'shop')], ]) - ); + ); } }); @@ -337,7 +338,7 @@ rpg.action('view_cards', async (ctx) => { stolenCards.forEach(card => { const lastFourDigits = card.cardNumber.slice(-4); // Берем последние 4 цифры карточки - message += `🔒 Карта: *${lastFourDigits}\n`; + message += `🔒 Карта: *${lastFourDigits}\n`; // Генерация кнопок для брутфорса и покупки за лимит buttons.push([ @@ -374,9 +375,9 @@ rpg.action(/limitbuy_/, async (ctx) => { const items = await ItemsModel.findAll({ limit: 10 }); // Если у пользователя нет записей о попытках, создаем их - if (!attempts[ctx.from.id]) { - attempts[ctx.from.id] = 0; - } + if (!attempts[ctx.from.id]) { + attempts[ctx.from.id] = 0; + } // Генерация кнопок с предметами const buttons = []; @@ -406,16 +407,16 @@ rpg.action(/purchase_/, async (ctx) => { } - // Проверяем, не исчерпаны ли попытки - if (attempts[ctx.from.id] >= 3) { - // Сбрасываем попытки и уничтожаем карточку - delete attempts[ctx.from.id]; - await StolenCardsModel.destroy({ where: { id: cardId } }); + // Проверяем, не исчерпаны ли попытки + if (attempts[ctx.from.id] >= 3) { + // Сбрасываем попытки и уничтожаем карточку + delete attempts[ctx.from.id]; + await StolenCardsModel.destroy({ where: { id: cardId } }); - return ctx.editMessageText( - '❌ Все попытки исчерпаны! Карточка стала недействительной.' - ); - } + return ctx.editMessageText( + '❌ Все попытки исчерпаны! Карточка стала недействительной.' + ); + } // Если баланс карты меньше, чем цена товара, увеличиваем количество попыток if (card.balance < item.price) { @@ -536,7 +537,7 @@ rpg.action(/brutecard_/, async (ctx) => { "Эмулятор картридера" был использован.`, keyboard ); - + }); @@ -606,7 +607,7 @@ rpg.action(/brute_fail_/, async (ctx) => { // Обработка успешной попытки взлома rpg.action(/brute_success_/, async (ctx) => { - + const cardId = ctx.match.input.split('_')[2]; const card = await StolenCardsModel.findByPk(cardId); if (!card) { @@ -644,27 +645,27 @@ rpg.action(/brute_success_/, async (ctx) => { // Обработчики кнопок rpg.action('crime_missions', async (ctx) => { - await ctx.answerCbQuery(); - await ctx.editMessageText(`💼 **Задачи:**\n Для карманных краж тебе не нужно ничего, главное не попадись.\n А вот после ограбления магазина в переулке не спрячешься, без тачки на миссию нельзя.`, - Markup.inlineKeyboard([ - [{text: 'Карманные кражи [1 lvl.]', callback_data: `POCKET_ACTION`}], - [{text: 'Магазин [5 lvl.]', callback_data: `SHOP_ACTION`}], - //[{text: 'Банкомат', callback_data: `WIP`}], - // [{text: 'Банковское отделение', callback_data: `WIP`}], - //[{text: 'Угон', callback_data: `WIP`}], - // [{text: 'Ювелирка', callback_data: `WIP`}], - //[{text: 'Банк', callback_data: `WIP`}], - [{text: '🔙 В меню', callback_data: `crime_menu`}] - ]), - ); + await ctx.answerCbQuery(); + await ctx.editMessageText(`💼 **Задачи:**\n Для карманных краж тебе не нужно ничего, главное не попадись.\n А вот после ограбления магазина в переулке не спрячешься, без тачки на миссию нельзя.`, + Markup.inlineKeyboard([ + [{ text: 'Карманные кражи [1 lvl.]', callback_data: `POCKET_ACTION` }], + [{ text: 'Магазин [5 lvl.]', callback_data: `SHOP_ACTION` }], + //[{text: 'Банкомат', callback_data: `WIP`}], + // [{text: 'Банковское отделение', callback_data: `WIP`}], + //[{text: 'Угон', callback_data: `WIP`}], + // [{text: 'Ювелирка', callback_data: `WIP`}], + //[{text: 'Банк', callback_data: `WIP`}], + [{ text: '🔙 В меню', callback_data: `crime_menu` }] + ]), + ); }); rpg.action(`POCKET_ACTION`, async (ctx) => { let user = await UserModel.findByPk(ctx.from.id) let character = await CharacterModel.findByPk(ctx.from.id); let pocketsteal = character.pocketstealcd - if(character.level < 1) return ctx.editMessageText('Доступно с 1 уровня!') - if(character.stamina < 10) return ctx.editMessageText('Вы устали!') + if (character.level < 1) return ctx.editMessageText('Доступно с 1 уровня!') + if (character.stamina < 10) return ctx.editMessageText('Вы устали!') let cooldown = utils.setCooldown(character, 3600, pocketsteal) if (character.pocketstealcd > cooldown.currentTime) return ctx.editMessageText(`📛 Данное действие будет доступно через ${cooldown.timeLeftInMinutes} мин.`); character.pocketstealcd = cooldown.endTime @@ -672,20 +673,20 @@ rpg.action(`POCKET_ACTION`, async (ctx) => { character.save() ctx.editMessageText('Выберите объект', Markup.inlineKeyboard([ [ - {text: 'Карман', callback_data: `POCKET_TARGET`}, - {text: 'Бумажник', callback_data: `POCKET_WALLET`}, - {text: 'Сумка', callback_data: `POCKET_BAG`} - ] -])) + { text: 'Карман', callback_data: `POCKET_TARGET` }, + { text: 'Бумажник', callback_data: `POCKET_WALLET` }, + { text: 'Сумка', callback_data: `POCKET_BAG` } + ] + ])) }); rpg.action(`POCKET_TARGET`, async (ctx) => { ctx.editMessageText('В кармане обнаружено', Markup.inlineKeyboard([ [ - {text: 'Деньги', callback_data: `MONEY_IN_POCKET`}, - {text: 'Телефон', callback_data: `PHONE`} - ] -])) + { text: 'Деньги', callback_data: `MONEY_IN_POCKET` }, + { text: 'Телефон', callback_data: `PHONE` } + ] + ])) }); rpg.action(`MONEY_IN_POCKET`, async (ctx) => { @@ -694,7 +695,7 @@ rpg.action(`MONEY_IN_POCKET`, async (ctx) => { let character = await CharacterModel.findByPk(ctx.from.id); if (!character) { - return ctx.editMessageText('У вас нет персонажа. Создайте его перед началом.'); + return ctx.editMessageText('У вас нет персонажа. Создайте его перед началом.'); } // Расчёт шанса на успешную кражу @@ -702,8 +703,8 @@ rpg.action(`MONEY_IN_POCKET`, async (ctx) => { let chance = baseChance + character.intelligence * 2; // Увеличиваем шанс на 2% за каждый пункт "Разума". let randomRoll = utils.rand(0, 100); // Случайное число от 0 до 100 if (randomRoll > chance) { - Exp(ctx, character, 1) - return ctx.editMessageText('Вы были замечены во время кражи.'); + Exp(ctx, character, 1) + return ctx.editMessageText('Вы были замечены во время кражи.'); } // Успешная кража let moneyIn = utils.rand(5, 1000); @@ -722,30 +723,30 @@ rpg.action(`PHONE`, async (ctx) => { let baseChance = 20; // Базовый шанс let chance = baseChance + character.intelligence * 2; // Увеличиваем шанс на 2% за каждый пункт "Разума". let randomRoll = utils.rand(0, 100); // Случайное число от 0 до 100 - if(chance < randomRoll) { + if (chance < randomRoll) { Exp(ctx, character, 1) return ctx.editMessageText('Вы были замечены во время кражи.') } - let randPhone = utils.rand(1,10) + let randPhone = utils.rand(1, 10) if (property.mobile.name) { - let dirtyMoney = Math.round(phones[randPhone].price/100*70) + let dirtyMoney = Math.round(phones[randPhone].price / 100 * 70) Exp(ctx, character, character.intelligence + 10) character.dirtymoney += dirtyMoney return await ctx.reply(`Вы сбыли украденный ${phones[randPhone].name} за Ð${utils.spaces(dirtyMoney)}`) } - property.mobile = phones[randPhone] - await character.save() - await property.save() + property.mobile = phones[randPhone] + await character.save() + await property.save() return ctx.editMessageText(`Вы успешно украли ${phones[randPhone].name} из кармана.`) }); rpg.action(`POCKET_WALLET`, async (ctx) => { ctx.editMessageText('В бумажнике обнаружено', Markup.inlineKeyboard([ [ - {text: 'Деньги', callback_data: `MONEY_IN_WALLET`}, - {text: 'Карточка', callback_data: `CARD_IN_WALLET`} - ] -])) + { text: 'Деньги', callback_data: `MONEY_IN_WALLET` }, + { text: 'Карточка', callback_data: `CARD_IN_WALLET` } + ] + ])) }); rpg.action(`MONEY_IN_WALLET`, async (ctx) => { @@ -755,7 +756,7 @@ rpg.action(`MONEY_IN_WALLET`, async (ctx) => { let baseChance = 35; // Базовый шанс let chance = baseChance + character.intelligence * 2; // Увеличиваем шанс на 2% за каждый пункт "Разума". let randomRoll = utils.rand(0, 100); // Случайное число от 0 до 100 - if(chance < randomRoll) { + if (chance < randomRoll) { Exp(ctx, character, 1) return ctx.editMessageText('Вы были замечены во время кражи.') } @@ -772,7 +773,7 @@ rpg.action(`CARD_IN_WALLET`, async (ctx) => { let baseChance = 20; // Базовый шанс let chance = baseChance + character.intelligence * 2; // Увеличиваем шанс на 2% за каждый пункт "Разума". let randomRoll = utils.rand(0, 100); // Случайное число от 0 до 100 - if(chance < randomRoll) { + if (chance < randomRoll) { Exp(ctx, character, 2) return ctx.editMessageText('Вы были замечены во время кражи.') } @@ -788,18 +789,18 @@ rpg.action(`POCKET_BAG`, async (ctx) => { let baseChance = 20; // Базовый шанс let chance = baseChance + character.intelligence * 2; // Увеличиваем шанс на 2% за каждый пункт "Разума". let randomRoll = utils.rand(0, 100); // Случайное число от 0 до 100 - if(chance < randomRoll) { + if (chance < randomRoll) { Exp(ctx, character, 1) return ctx.editMessageText('Вы были замечены во время кражи.') } - let times = utils.rand(2,20) + let times = utils.rand(2, 20) let moneyIn = 0 let text = `` let values = 0 - - for(i=1; i<=times; i++){ - randomize = utils.rand(1,100) - switch(randomize) { + + for (i = 1; i <= times; i++) { + randomize = utils.rand(1, 100) + switch (randomize) { case 2: values = utils.rand(10000, 50000) moneyIn += values @@ -824,24 +825,24 @@ rpg.action(`POCKET_BAG`, async (ctx) => { }); rpg.action('crime_menu', async (ctx) => { - await ctx.answerCbQuery(); - await ctx.editMessageText( - `💻 CampFireGG.Crime Menu`, - Markup.inlineKeyboard([ - [Markup.button.callback('💼 Задачи', 'crime_missions')], - [Markup.button.callback('📊 Профиль', 'rpg_profile')], - [Markup.button.callback('💰 Магазин', 'shop')], - ]) - ); + await ctx.answerCbQuery(); + await ctx.editMessageText( + `💻 CampFireGG.Crime Menu`, + Markup.inlineKeyboard([ + [Markup.button.callback('💼 Задачи', 'crime_missions')], + [Markup.button.callback('📊 Профиль', 'rpg_profile')], + [Markup.button.callback('💰 Магазин', 'shop')], + ]) + ); }); rpg.action('SHOP_ACTION', async (ctx) => { let user = await UserModel.findByPk(ctx.from.id) let character = await CharacterModel.findByPk(ctx.from.id); let property = await PropertyModel.findByPk(ctx.from.id); - if(character.level < 5) return ctx.editMessageText('Доступно с 5 уровня!') - if(property.car1 == 0) return ctx.editMessageText('Для данного задания нужна тачка.') - if(character.stamina < 25) return ctx.editMessageText('Вы устали!') + if (character.level < 5) return ctx.editMessageText('Доступно с 5 уровня!') + if (property.car1 == 0) return ctx.editMessageText('Для данного задания нужна тачка.') + if (character.stamina < 25) return ctx.editMessageText('Вы устали!') let shoprobcd = character.shoprobcd let cooldown = utils.setCooldown(character, 3600, shoprobcd) if (character.shoprobcd > cooldown.currentTime) return ctx.editMessageText(`📛 Данное действие будет доступно через ${cooldown.timeLeftInMinutes} мин.`); @@ -849,9 +850,9 @@ rpg.action('SHOP_ACTION', async (ctx) => { character.stamina -= 25 character.save() return ctx.editMessageText('Стадии:', Markup.inlineKeyboard([ - [{text: 'Взлом кассы', callback_data: `SHOP_CASH_BREAK`}], - [{text: 'Разбить кассу', callback_data: `SHOP_CASH_SMASH`}] -])) + [{ text: 'Взлом кассы', callback_data: `SHOP_CASH_BREAK` }], + [{ text: 'Разбить кассу', callback_data: `SHOP_CASH_SMASH` }] + ])) }); rpg.action(`SHOP_CASH_BREAK`, async (ctx) => { @@ -861,28 +862,28 @@ rpg.action(`SHOP_CASH_BREAK`, async (ctx) => { let randomRoll = utils.rand(0, 100); // Случайное число от 0 до 100 let cashIn = utils.rand(1000, 10000) let timer = 1000 - if(chance < randomRoll) { + if (chance < randomRoll) { const keyboard = generateKeyboard(); ctx.deleteMessage() return ctx.reply('Касса закрыта, вы начали взлом замка:', keyboard); //ctx.editMessageText('Вы начали взлом кассы.'); //return ctx.scene.enter('LOCKPICK') } - for(i=0; i { - cashIn += utils.rand(1000, 10000) - ctx.editMessageText(`⏏️ Вы достали из кассы: Ð${utils.spaces(cashIn)}`) - }, timer) - timer += 500 + cashIn += utils.rand(1000, 10000) + ctx.editMessageText(`⏏️ Вы достали из кассы: Ð${utils.spaces(cashIn)}`) + }, timer) + timer += 500 } -setTimeout(() => { - Exp(ctx, character, character.intelligence + 25) - character.dirtymoney += cashIn - character.save() -return ctx.editMessageText(`Вы достали из кассы Ð${utils.spaces(cashIn)}, пора валить.`, Markup.inlineKeyboard([ - [{text: 'Завершить ограбление', callback_data: `SHOP_END`}] -])) -}, timer+300) + setTimeout(() => { + Exp(ctx, character, character.intelligence + 25) + character.dirtymoney += cashIn + character.save() + return ctx.editMessageText(`Вы достали из кассы Ð${utils.spaces(cashIn)}, пора валить.`, Markup.inlineKeyboard([ + [{ text: 'Завершить ограбление', callback_data: `SHOP_END` }] + ])) + }, timer + 300) }); rpg.action(`SHOP_CASH_SMASH`, async (ctx) => { @@ -892,26 +893,26 @@ rpg.action(`SHOP_CASH_SMASH`, async (ctx) => { let randomRoll = utils.rand(0, 100); // Случайное число от 0 до 100 let cashIn = utils.rand(1000, 10000) let timer = 1000 - if(chance < randomRoll) { + if (chance < randomRoll) { Exp(ctx, character, 1) return ctx.editMessageText('Вы разбили кассовый аппарат, и сработала сигнализация. Вы сбежали.') } ctx.editMessageText('Вы разбили кассовый аппарат, и сработала сигнализация.') - for(i=0; i { - cashIn += utils.rand(500, 5000) - ctx.editMessageText(`⏏️ Вы в спешке достали из кассы: Ð${utils.spaces(cashIn)}`) - }, timer) - timer += 500 + cashIn += utils.rand(500, 5000) + ctx.editMessageText(`⏏️ Вы в спешке достали из кассы: Ð${utils.spaces(cashIn)}`) + }, timer) + timer += 500 } -setTimeout(() => { - Exp(ctx, character, character.intelligence + 10) - character.dirtymoney += cashIn - character.save() -return ctx.editMessageText(`Вы в спешке достали из кассы Ð${utils.spaces(cashIn)}, пора валить.`, Markup.inlineKeyboard([ - [{text: 'Завершить ограбление', callback_data: `SHOP_END`}] -])) -}, timer+300) + setTimeout(() => { + Exp(ctx, character, character.intelligence + 10) + character.dirtymoney += cashIn + character.save() + return ctx.editMessageText(`Вы в спешке достали из кассы Ð${utils.spaces(cashIn)}, пора валить.`, Markup.inlineKeyboard([ + [{ text: 'Завершить ограбление', callback_data: `SHOP_END` }] + ])) + }, timer + 300) }); rpg.action(`SHOP_CASH_BREAK_SUCCESS`, async (ctx) => { @@ -920,21 +921,21 @@ rpg.action(`SHOP_CASH_BREAK_SUCCESS`, async (ctx) => { delete attempts[ctx.from.id]; let cashIn = utils.rand(1000, 10000) let timer = 100 - for(i=0; i { + for (i = 0; i < utils.rand(character.endurance, character.endurance + 15); i++) { + setTimeout(() => { cashIn += utils.rand(3000, 10000) ctx.editMessageText(`⏏️ Вы достали из кассы: Ð${utils.spaces(cashIn)}`) }, timer) timer += 500 - } + } setTimeout(() => { Exp(ctx, character, character.intelligence + 30) character.dirtymoney += cashIn character.save() - return ctx.editMessageText(`Вы достали из кассы Ð${utils.spaces(cashIn)}, пора валить.`, Markup.inlineKeyboard([ - [{text: 'Завершить ограбление', callback_data: `SHOP_END`}] -])) -}, timer+300) + return ctx.editMessageText(`Вы достали из кассы Ð${utils.spaces(cashIn)}, пора валить.`, Markup.inlineKeyboard([ + [{ text: 'Завершить ограбление', callback_data: `SHOP_END` }] + ])) + }, timer + 300) }); rpg.action(`SHOP_END`, async (ctx) => { @@ -944,26 +945,26 @@ rpg.action(`SHOP_END`, async (ctx) => { const attempts = {}; // Храним количество попыток взлома для каждого пользователя rpg.action(/lock_*/, async (ctx) => { - const userId = ctx.from.id; - const buttonId = ctx.update.callback_query.data; + const userId = ctx.from.id; + const buttonId = ctx.update.callback_query.data; - // Если пользователя нет в списке попыток, добавляем его - if (!attempts[userId]) { - attempts[userId] = 0; - } + // Если пользователя нет в списке попыток, добавляем его + if (!attempts[userId]) { + attempts[userId] = 0; + } - // Увеличиваем количество попыток - attempts[userId] += 1; + // Увеличиваем количество попыток + attempts[userId] += 1; - // Проверяем, не исчерпаны ли попытки - if (attempts[userId] >= 5) { - delete attempts[userId]; // Сбрасываем попытки после провала - return ctx.editMessageText('Взлом провалился. Замок остается нетронутым.'); - } + // Проверяем, не исчерпаны ли попытки + if (attempts[userId] >= 5) { + delete attempts[userId]; // Сбрасываем попытки после провала + return ctx.editMessageText('Взлом провалился. Замок остается нетронутым.'); + } - // Ответ на нажатие кнопки - ctx.answerCbQuery(`Штифт не сдвинулся. Попыток осталось: ${5 - attempts[userId]}`); - removeButton(ctx, buttonId); + // Ответ на нажатие кнопки + ctx.answerCbQuery(`Штифт не сдвинулся. Попыток осталось: ${5 - attempts[userId]}`); + removeButton(ctx, buttonId); }); rpg.action('inventory', async (ctx) => { @@ -1041,13 +1042,13 @@ rpg.action(/view_item_(\d+)/, async (ctx) => { const buttons = [] let message = `ℹ️ ${item.name}\n` message += ` 📜 ${item.description}\n\n 〰️Редкость: ${item.rarity}\n 🔤Тип: ${item.type}` - if (!item.equipped){ + if (!item.equipped) { buttons.push([Markup.button.callback(`🎯 Использовать ${item.name}`, `use_item_${item.id}`)]); } if (item.equipped && item.canBeEquipped) { buttons.push([Markup.button.callback(`🚫 Снять ${item.name}`, `unequip_item_${item.id}`)]); } - + await ctx.replyWithMarkdown(message, Markup.inlineKeyboard(buttons, { columns: 2 })); }); @@ -1076,7 +1077,7 @@ rpg.action(/use_item_(\d+)/, async (ctx) => { // Применяем эффекты предмета if (item.effectData) { const resultMessages = processEffects(character, item.effectData, true); - await ctx.answerCbQuery(resultMessages, {show_alert: true}); + await ctx.answerCbQuery(resultMessages, { show_alert: true }); } if (item.canBeEquipped && item.type != 'consumable') { @@ -1118,28 +1119,28 @@ rpg.action('shop', async (ctx) => { // Получаем текущую запись мира const world = await WorldModel.findOne({ where: { id: 1 } }); if (!world) { - return ctx.reply('Магазин недоступен.'); + return ctx.reply('Магазин недоступен.'); } // Получаем ID предметов, доступных в магазине const { itemsInCrimeShop } = world; if (!itemsInCrimeShop || itemsInCrimeShop.length === 0) { - return ctx.reply('Магазин пуст!'); + return ctx.reply('Магазин пуст!'); } // Загружаем только те предметы, ID которых есть в массиве const items = await ItemsModel.findAll({ where: { id: itemsInCrimeShop } }); if (items.length === 0) { - return ctx.reply('Магазин пуст!'); + return ctx.reply('Магазин пуст!'); } let message = 'Добро пожаловать в магазин! Здесь вы можете купить предметы:\n\n'; // Генерируем кнопки, каждая кнопка будет в отдельной строке const buttons = items.map((item) => [ - Markup.button.callback(`${item.name} - ${item.price}₽`, `buy_item_${item.id}`) + Markup.button.callback(`${item.name} - ${item.price}₽`, `buy_item_${item.id}`) ]); buttons.push([Markup.button.callback('🔙 В меню', 'crime_menu')]); @@ -1153,7 +1154,7 @@ rpg.action(/buy_item_(\d+)/, async (ctx) => { const inventory = await InventoryModel.findAll({ where: { telegram_id: ctx.from.id } }); if (inventory.length >= 15) { - return ctx.answerCbQuery('Инвентарь полон.', {show_alert: true}); + return ctx.answerCbQuery('Инвентарь полон.', { show_alert: true }); } if (!item) { @@ -1167,7 +1168,7 @@ rpg.action(/buy_item_(\d+)/, async (ctx) => { } if (character.balance < item.price) { - return ctx.answerCbQuery('У вас недостаточно средств для покупки этого предмета.', {show_alert: true}); + return ctx.answerCbQuery('У вас недостаточно средств для покупки этого предмета.', { show_alert: true }); } // Снимаем деньги с баланса @@ -1189,7 +1190,7 @@ rpg.action(/buy_item_(\d+)/, async (ctx) => { }); await character.save(); - ctx.answerCbQuery(`Вы успешно купили ${item.name} за ${item.price}₽!`, {show_alert: true}); + ctx.answerCbQuery(`Вы успешно купили ${item.name} за ${item.price}₽!`, { show_alert: true }); }); //////////////////////////////////////////////////////////////////////////////////////////// @@ -1330,77 +1331,77 @@ const processEffects = (character, effects, isEquipping) => { }; function generateKeyboard() { - const buttonsCount = 10; - const buttons = []; - const winButton = utils.rand(1, 10); + const buttonsCount = 10; + const buttons = []; + const winButton = utils.rand(1, 10); - for (let i = 1; i <= buttonsCount; i++) { - if (i === winButton) { - buttons.push({ text: `🔒`, callback_data: `SHOP_CASH_BREAK_SUCCESS` }); - } else { - buttons.push({ text: `🔒`, callback_data: `lock_${i}` }); - } + for (let i = 1; i <= buttonsCount; i++) { + if (i === winButton) { + buttons.push({ text: `🔒`, callback_data: `SHOP_CASH_BREAK_SUCCESS` }); + } else { + buttons.push({ text: `🔒`, callback_data: `lock_${i}` }); } + } - const rows = []; - while (buttons.length > 0) { - rows.push(buttons.splice(0, 5)); // Разбиваем на подмассивы по 5 кнопок - } - console.log(rows) - return { - reply_markup: { - inline_keyboard: rows, - }, - }; + const rows = []; + while (buttons.length > 0) { + rows.push(buttons.splice(0, 5)); // Разбиваем на подмассивы по 5 кнопок + } + console.log(rows) + return { + reply_markup: { + inline_keyboard: rows, + }, + }; } function removeButton(ctx, buttonId) { - const keyboard = ctx.update.callback_query.message.reply_markup.inline_keyboard; + const keyboard = ctx.update.callback_query.message.reply_markup.inline_keyboard; - for (let row of keyboard) { - for (let i = 0; i < row.length; i++) { - if (row[i].callback_data === buttonId) { - row[i].text = `🔓`; - break; - } - } + for (let row of keyboard) { + for (let i = 0; i < row.length; i++) { + if (row[i].callback_data === buttonId) { + row[i].text = `🔓`; + break; + } } + } - ctx.editMessageText('Взлом замка:', Markup.inlineKeyboard(keyboard).resize()); + ctx.editMessageText('Взлом замка:', Markup.inlineKeyboard(keyboard).resize()); } // Восстановление здоровья (HP) async function recoverHealth() { - const characters = await CharacterModel.findAll({ - where: { - hp: { - [Op.lt]: 100, // Восстанавливаем только тем, у кого HP меньше 100 - }, - }, - }); + const characters = await CharacterModel.findAll({ + where: { + hp: { + [Op.lt]: 100, // Восстанавливаем только тем, у кого HP меньше 100 + }, + }, + }); - for (const character of characters) { - const recoveryRate = character.resilience; // Восстановление 10 HP за интервал - character.hp = Math.min(character.hp + recoveryRate, 100); // Не превышаем максимум - await character.save(); - } + for (const character of characters) { + const recoveryRate = character.resilience; // Восстановление 10 HP за интервал + character.hp = Math.min(character.hp + recoveryRate, 100); // Не превышаем максимум + await character.save(); + } } // Восстановление выносливости (стамины) async function recoverStamina() { - const characters = await CharacterModel.findAll({ - where: { - stamina: { - [Op.lt]: 100, // Восстанавливаем только тем, у кого стамина меньше 100 - }, - }, - }); + const characters = await CharacterModel.findAll({ + where: { + stamina: { + [Op.lt]: 100, // Восстанавливаем только тем, у кого стамина меньше 100 + }, + }, + }); - for (const character of characters) { - const recoveryRate = character.endurance; // Восстановление 5 стамины за интервал - character.stamina = Math.min(character.stamina + recoveryRate, 100); // Не превышаем максимум - await character.save(); - } + for (const character of characters) { + const recoveryRate = character.endurance; // Восстановление 5 стамины за интервал + character.stamina = Math.min(character.stamina + recoveryRate, 100); // Не превышаем максимум + await character.save(); + } } const reduceStealedCards = async () => { @@ -1422,7 +1423,7 @@ const reduceStealedCards = async () => { // Удаляем половину карточек const cardsToDelete = Math.ceil(stolenCards.length / 2); const cardsToRemove = stolenCards.slice(0, cardsToDelete); - + for (const card of cardsToRemove) { await card.destroy(); // Удаляем карточки } @@ -1439,10 +1440,10 @@ const reduceStealedCards = async () => { async function generateCard(userId, balance) { - if(!Number(balance)){ - balance = faker.finance.amount({dec: 0})*100 + if (!Number(balance)) { + balance = faker.finance.amount({ dec: 0 }) * 100 console.log('Random balance: ' + balance) - }else{ + } else { balance = Math.floor(balance); console.log('Set balance: ' + balance) } @@ -1469,28 +1470,29 @@ async function Exp(ctx, character, experience) { character.exp += experience await ctx.sendMessage(`❇️ +${experience} exp.`) await character.save() - for(i in expToUp){ - if (character.exp >= expToUp[character.level]) { - character.exp -= expToUp[character.level] - character.level += 1 - character.firePoints += 1 - await character.save() - await ctx.sendMessage(`⤴️ Уровень вашего персонажа повысился до ${character.level}!`)} - } + for (i in expToUp) { + if (character.exp >= expToUp[character.level]) { + character.exp -= expToUp[character.level] + character.level += 1 + character.firePoints += 1 + await character.save() + await ctx.sendMessage(`⤴️ Уровень вашего персонажа повысился до ${character.level}!`) + } + } } // Периодическое выполнение задач function startRecoveryIntervals() { - const interval = 60000; // 1 мин Интервал в миллисекундах (например, 1 минута) - setInterval(recoverHealth, interval); - setInterval(recoverStamina, interval); + const interval = 60000; // 1 мин Интервал в миллисекундах (например, 1 минута) + setInterval(recoverHealth, interval); + setInterval(recoverStamina, interval); } // Планируем выполнение задачи каждый день в 12 ночи schedule.scheduleJob('0 0 * * *', reduceStealedCards); rpg.command('force_reduce', async (ctx) => { - reduceStealedCards() + reduceStealedCards() return await ctx.reply(`Принудительно`) }) @@ -1521,21 +1523,21 @@ const fillEnemies = async () => { const fillLocations = async () => { const locations = [ - { - name: "Заброшенный склад", - description: "Темный склад с кучей мусора.", - enemies: [1, 2, 3], - level: 1, - loot: [6, 7], - rarity: 1 + { + name: "Заброшенный склад", + description: "Темный склад с кучей мусора.", + enemies: [1, 2, 3], + level: 1, + loot: [6, 7], + rarity: 1 }, - { - name: "Лесопосадка", - description: "Густой лес с опасными тропами.", - enemies: [2, 3, 4], - level: 2, - loot: [8, 9], - rarity: 2 + { + name: "Лесопосадка", + description: "Густой лес с опасными тропами.", + enemies: [2, 3, 4], + level: 2, + loot: [8, 9], + rarity: 2 }, ]; @@ -1781,10 +1783,10 @@ rpg.action(/attack_\d+/, async (ctx) => { // Сообщение с информацией await ctx.editMessageText( `⚔️ Сражение с ${enemy.name}\n\n` + - `❤️ Здоровье врага: ${battle.enemy_hp}/${enemy.hp}\n` + - `⚔️ Урон врага: ${enemy.damage}\n\n` + - `📜 Логи битвы:\n${logMessage || "Пока ничего не произошло."}\n\n` + - `🎯 Выберите цель для атаки:`, + `❤️ Здоровье врага: ${battle.enemy_hp}/${enemy.hp}\n` + + `⚔️ Урон врага: ${enemy.damage}\n\n` + + `📜 Логи битвы:\n${logMessage || "Пока ничего не произошло."}\n\n` + + `🎯 Выберите цель для атаки:`, keyboard ); }); @@ -1833,10 +1835,10 @@ rpg.action(/hit_\d+/, async (ctx) => { await ctx.editMessageText( `⚔️ Сражение с ${enemy.name}\n\n` + - `❤️ Здоровье врага: ${battle.enemy_hp}/${enemy.hp}\n` + - `⚔️ Урон врага: ${enemy.damage}\n\n` + - `📜 Логи битвы:\n${logs || "Пока ничего не произошло."}\n\n` + - `🎯 Выберите цель для атаки:`, + `❤️ Здоровье врага: ${battle.enemy_hp}/${enemy.hp}\n` + + `⚔️ Урон врага: ${enemy.damage}\n\n` + + `📜 Логи битвы:\n${logs || "Пока ничего не произошло."}\n\n` + + `🎯 Выберите цель для атаки:`, keyboard ); }); @@ -1930,10 +1932,10 @@ rpg.action(/critical_\d+/, async (ctx) => { await ctx.editMessageText( `⚔️ Сражение с ${enemy.name}\n\n` + - `❤️ Здоровье врага: ${battle.enemy_hp}/${enemy.hp}\n` + - `⚔️ Урон врага: ${enemy.damage}\n\n` + - `📜 Логи битвы:\n${logs || "Пока ничего не произошло."}\n\n` + - `🎯 Выберите цель для атаки:`, + `❤️ Здоровье врага: ${battle.enemy_hp}/${enemy.hp}\n` + + `⚔️ Урон врага: ${enemy.damage}\n\n` + + `📜 Логи битвы:\n${logs || "Пока ничего не произошло."}\n\n` + + `🎯 Выберите цель для атаки:`, keyboard ); }); @@ -1972,10 +1974,10 @@ rpg.action(/miss_\d+/, async (ctx) => { await ctx.editMessageText( `⚔️ Сражение с ${enemy.name}\n\n` + - `❤️ Здоровье врага: ${battle.enemy_hp}/${enemy.hp}\n` + - `⚔️ Урон врага: ${enemy.damage}\n\n` + - `📜 Логи битвы:\n${logs || "Пока ничего не произошло."}\n\n` + - `🎯 Выберите цель для атаки:`, + `❤️ Здоровье врага: ${battle.enemy_hp}/${enemy.hp}\n` + + `⚔️ Урон врага: ${enemy.damage}\n\n` + + `📜 Логи битвы:\n${logs || "Пока ничего не произошло."}\n\n` + + `🎯 Выберите цель для атаки:`, keyboard ); });