From bbe91b03c3a4170d53574c3494ef441caaba9aaf Mon Sep 17 00:00:00 2001 From: Degradin Date: Wed, 27 Sep 2023 01:24:38 +0300 Subject: [PATCH] v0.0.73-79 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit • После отработки пишется общее количество отработок. • Добавлена система промокодов. • Добавлен список правил в "Помощь". • Добавлена система привелегий. • Обновлен вывод пользователей в "Топ" • Общие исправления. Переработан магазин. Проработка внешнего вида команд. --- index.js | 664 +++++++++++++++++++++++---------------- json/weaponshop.json | 18 +- models/business.model.js | 5 +- models/user.model.js | 1 + package-lock.json | 14 + package.json | 1 + presets/cars.json | 2 +- presets/houses.json | 8 +- presets/weapons.json | 8 +- 9 files changed, 427 insertions(+), 294 deletions(-) diff --git a/index.js b/index.js index e767814..4d68d51 100644 --- a/index.js +++ b/index.js @@ -23,9 +23,9 @@ const BusinessModel = require('./models/business.model'); const ReportModel = require('./models/report.model'); const BlockModel = require('./models/block.model'); const PromocodeModel = require('./models/promocode.model'); -const whitelist = [275416286, 1797342681] -const adminList = [`275416286`] +const adminList = [275416286] const expToUp = [0, 10, 20, 40, 60, 80, 120, 150, 200, 500, 1000] +const topSym = ['🥇', '🥈', '🥉', '4️⃣', '5️⃣', '6️⃣', '7️⃣', '8️⃣', '9️⃣', '🔟'] const start = async () => { try { @@ -73,7 +73,7 @@ bot.use(async (ctx, next) => { let user = await UserModel.findByPk(id); let block = await BlockModel.findByPk(id); let property = await PropertyModel.findByPk(id); - if (!user) ctx.reply(`Первичная регистрация профиля.`); + if (!user) ctx.reply(`❕ Первичная регистрация профиля.`); if (user === null) { await UserModel.create({ telegram_id: id, @@ -91,7 +91,7 @@ bot.use(async (ctx, next) => { } else {} //if (whitelist.includes(id) == false) return ctx.reply(`У вас пока нет доступа к боту. Следите за обновлениями в группе: t.me/CampFireGameBotNews`) if (block !== null) { - if (block.isBlocked == true && block.time > Date.now() / 1000) return ctx.reply(`У вас активная блокировка по причине: ${block.reason}.\nОставшееся время: ${Math.trunc((block.time - Date.now()/1000)/60)} мин.`) + if (block.isBlocked == true && block.time > Date.now() / 1000) return ctx.reply(`📛 У вас активная блокировка по причине: ${block.reason}.\n⏲️ Оставшееся время: ${Math.trunc((block.time - Date.now()/1000)/60)} мин.`) block.isBlocked = false block.save() } @@ -125,7 +125,6 @@ bot.command('start', async (ctx) => { ['🗄️ Работать', '🌐 Организация', '🎁 Бонус', '🏯 Казино'], // Row2 with 2 buttons ['📢 Вакансии', '🔵 Имущество', '📞 Пригласить'] // Row3 with 3 buttons ]) - .oneTime() .resize() ) }) @@ -137,7 +136,6 @@ bot.hears('▶️ Меню', async (ctx) => { ['🗄️ Работать', '🌐 Организация', '🎁 Бонус', '🏯 Казино'], // Row2 with 2 buttons ['📢 Вакансии', '🔵 Имущество', '📞 Пригласить'] // Row3 with 3 buttons ]) - .oneTime() .resize() ) }); @@ -146,22 +144,22 @@ bot.hears('😎 Профиль', async (ctx) => { let user = await UserModel.findByPk(ctx.from.id); let property = await PropertyModel.findByPk(ctx.from.id); if (!user) return ctx.reply(`Ошибка #1`); - return ctx.reply(` - 👤${user.username} ${adminList.includes(user.telegram_id)? " ✅" : ""} + return ctx.replyWithMarkdownV2(` + 👤${escape(user.username)} ${user.status == 'bronze' ? `\\[_*Bronze Status*_\\]` : ""}${user.status == 'silver' ? `\\[_*Silver Status*_\\]` : ""}${user.status == 'gold' ? `\\[_*Gold Status*_\\]` : ""}${user.status == 'admin' ? "✅" : ""} 🆔: ${ctx.from.id} - 📶 Уровень: ${user.level} | ${user.exp} / ${expToUp[user.level]} - ⏩ Повышается за различные действия. + 📶 Уровень: ${user.level} \\| ${user.exp} / ${expToUp[user.level]} + ⏩ Повышается за различные действия\\. - Баланс - ¤${user.money} + 💰 Баланс + ¤${spacesWithMarkdown(user.money)} - Имущество - Жилье: ${property.house == 0 ? "Бездомный" : property.house.name} - Автомобиль: ${property.car == 0 ? "Пешком" : property.car.name} - Телефон: ${property.mobile == 0 ? "Нет" : property.mobile.name} - Оружие: ${property.weapon == 0 ? "Безоружный" : property.weapon.name} - Экипировка: ${property.equipment == 0 ? "Нет" : property.equipment.name} + 🔵 Имущество + 🏠 Жилье: ${property.house == 0 ? "Бездомный" : property.house.name} + 🚗 Автомобиль: ${property.car == 0 ? "Пешком" : property.car.name} + 📱 Телефон: ${property.mobile == 0 ? "Нет" : property.mobile.name} + 🔫 Оружие: ${property.weapon == 0 ? "Безоружный" : property.weapon.name} + 🥼 Экипировка: ${property.equipment == 0 ? "Нет" : property.equipment.name} `); }); @@ -171,22 +169,32 @@ bot.command('getprofile', async (ctx) => { let id = ctx.message.reply_to_message.from.id let user = await UserModel.findByPk(id); let property = await PropertyModel.findByPk(id); - return ctx.reply(` - 👤${user.username} ${adminList.includes(user.telegram_id)? " ✅" : ""} + return ctx.replyWithMarkdownV2(` + 👤${escape(user.username)} ${user.status == 'bronze' ? `\\[_*Bronze Status*_\\]` : ""}${user.status == 'silver' ? `\\[_*Silver Status*_\\]` : ""}${user.status == 'gold' ? `\\[_*Gold Status*_\\]` : ""}${user.status == 'admin' ? "Administrator" : ""} 🆔: ${ctx.from.id} - 📶 Уровень: ${user.level} | ${user.exp} / ${expToUp[user.level]} - ⏩ Повышается за различные действия. + 📶 Уровень: ${user.level} \\| ${user.exp} / ${expToUp[user.level]} + ⏩ Повышается за различные действия\\. - Баланс - ¤${user.money} + 💰 Баланс + ¤${spacesWithMarkdown(user.money)} - Имущество - Жилье: ${property.house == 0 ? "Бездомный" : property.house.name} - Автомобиль: ${property.car == 0 ? "Пешком" : property.car.name} - Телефон: ${property.mobile == 0 ? "Нет" : property.mobile.name} - Оружие: ${property.weapon == 0 ? "Безоружный" : property.weapon.name} - Экипировка: ${property.equipment == 0 ? "Нет" : property.equipment.name} + 🔵 Имущество + 🏠 Жилье: ${property.house == 0 ? "Бездомный" : property.house.name} + 🚗 Автомобиль: ${property.car == 0 ? "Пешком" : property.car.name} + 📱 Телефон: ${property.mobile == 0 ? "Нет" : property.mobile.name} + 🔫 Оружие: ${property.weapon == 0 ? "Безоружный" : property.weapon.name} + 🥼 Экипировка: ${property.equipment == 0 ? "Нет" : property.equipment.name} + `); + +}); + +bot.hears('Рандом', async (ctx) => { + let users = await UserModel.findAll(); + let chosenOne = users.random() + return ctx.reply(` + 👤 ${chosenOne.username} + 🆔: ${chosenOne.telegram_id} `); }); @@ -200,10 +208,8 @@ bot.hears('💳 Баланс', async (ctx) => { 📶 Уровень: ${user.level} ⏩ Повышается за различные действия. - Баланс: + 💰 Баланс: ¤${user.money} - - `); }) @@ -230,6 +236,20 @@ bot.hears('🎁 Бонус', async (ctx) => { money = money*x text += `⏩ ¤${money}\n`; } + switch(user.status){ + case 'bronze': + user.money += 5000 + text += `⭐ Дополнительный бонус за Bronze:\n⏩ ¤5.000\n` + break; + case 'silver': + user.money += 15000 + text += `⭐ Дополнительный бонус за Silver:\n⏩ ¤15.000\n` + break; + case 'gold': + user.money += 30000 + text += `⭐ Дополнительный бонус за Gold:\n⏩ ¤30.000\n` + break; + } user.money += money; world.balance -= money if (user.business.id == 0){ @@ -247,7 +267,21 @@ ${text} }) if(business != null){ let mats = rand(3, 10) - text += `⏩ ${mats} Материалов в организацию\n` + switch(user.status){ + case 'bronze': + business.materials += 5 + text += `⭐ Дополнительный бонус за Bronze:\n⏩ 5 материалов\n` + break; + case 'silver': + business.materials += 10 + text += `⭐ Дополнительный бонус за Silver:\n⏩ 10 материалов\n` + break; + case 'gold': + business.materials += 20 + text += `⭐ Дополнительный бонус за Gold:\n⏩ 20 материалов\n` + break; + } + text += `⏩ ${mats} материалов в организацию\n` business.materials += mats business.save() } @@ -262,7 +296,7 @@ ${text} bot.command('pay', async (ctx) => { ctx.args = ctx.update.message.text.split(' ') if (!ctx.args[1] || !ctx.args[2]) return ctx.reply(`/pay [Никнейм] [Сумма]`) - if (!Number(ctx.args[2])) return ctx.reply(`Сумма должна быть числовая.`) + if (!Number(ctx.args[2])) return ctx.reply(`❕ Сумма должна быть числовая.`) let sender = await UserModel.findByPk(ctx.from.id); let receiver = await UserModel.findOne({ where: { @@ -271,9 +305,9 @@ bot.command('pay', async (ctx) => { }); let world = await WorldModel.findByPk(1) let fee = Number(Math.trunc(ctx.args[2] / 100 * world.transactionfee)) - if (ctx.args[2] == 0 || ctx.args[2] < 100) return ctx.reply(`Минимальная сумма перевода ¤100.`) - if (sender.money < ctx.args[2]) return ctx.reply(`Недостаточно средств!`) - if (sender.money < Number(ctx.args[2]) + fee) return ctx.reply(`Недостаточно средств для перевода с комиссией!`) + if (ctx.args[2] == 0 || ctx.args[2] < 100) return ctx.reply(`❕ Минимальная сумма перевода ¤100.`) + if (sender.money < ctx.args[2]) return ctx.reply(`❕ Недостаточно средств!`) + if (sender.money < Number(ctx.args[2]) + fee) return ctx.reply(`❕ Недостаточно средств для перевода с комиссией!`) sender.money -= Number(ctx.args[2]) sender.money -= Number(fee) world.balance += Number(fee) @@ -281,36 +315,23 @@ bot.command('pay', async (ctx) => { await world.save(); receiver.money += Number(ctx.args[2]) await receiver.save(); - let pmToReceiver = ` - Входящий перевод. -Отправитель: ${sender.username} -Идентификатор отправителя: ${sender.telegram_id} -Сумма: ¤${ctx.args[2]} -Ваш баланс: ¤${receiver.money} + let pmToReceiver = `🔽 Входящий перевод.\n\n🔼 Отправитель: ${sender.username}\n🆔 Отправителя: ${sender.telegram_id}\n🔢 Сумма: ¤${ctx.args[2]}\n🆕 Ваш баланс: ¤${receiver.money} ` bot.telegram.sendMessage(receiver.telegram_id, pmToReceiver) - return ctx.reply(` - Операция. -Получатель: ${receiver.username} -Идентификатор получателя: ${receiver.telegram_id} -Сумма: ¤${ctx.args[2]} -Комиссия: ¤${fee} -Ваш баланс: ¤${sender.money} + return ctx.reply(`🔼 Исходящий перевод.\n\n🔽 Получатель: ${receiver.username}\n🆔 Получателя: ${receiver.telegram_id}\n🔢 Сумма: ¤${ctx.args[2]}\nℹ️ Комиссия: ¤${fee}\n🆕 Ваш баланс: ¤${sender.money} `) }) bot.hears('Мир', async (ctx) => { let world = await WorldModel.findByPk(1) - return ctx.reply(` -Баланс мира: ¤${spaces(world.balance)} -Стоимость материалов: ¤${spaces(world.matPrice)} + return ctx.reply(`🔰 Баланс мира: ¤${spaces(world.balance)}\nℹ️ Стоимость материалов: ¤${spaces(world.matPrice)} `) }) bot.hears('📞 Пригласить', async (ctx) => { let user = await UserModel.findByPk(ctx.from.id); return ctx.reply(` -Для приглашения друга по реферальной системе, отправьте ему ссылку-приглашение + ℹ️ Для приглашения друга по реферальной системе, отправьте ему ссылку-приглашение Как только он перейдет по ней и начнет игру, Вы получите ¤25.000. Ваша ссылка: https://t.me/CampFireGameBot?start=${user.telegram_id} @@ -346,7 +367,6 @@ bot.hears('📢 Вакансии', async (ctx) => { callback_data: 'job_leave' }] ]) - .oneTime() .resize() ) }) @@ -359,97 +379,96 @@ bot.action(/job_(1|2|3|4|5|6|7|leave)/, async (ctx) => { case `job_1`: job = await JobModel.findByPk(1); if (user.level < job.level) { - return await ctx.reply(`У вас не хватает уровня для этой работы.`) + return await ctx.reply(`❕ У вас не хватает уровня для этой работы.`) } if (user.job == 0) { user.job = 1 user.save() - return await ctx.reply(`Вы устроились на работу дворником. \nВаш оклад: ¤${job.salary}\nПриступайте к работе командой "Работать"`) + return await ctx.reply(`ℹ️ Вы устроились на работу дворником.\nВаш оклад: ¤${job.salary}\nПриступайте к работе командой "Работать"`) } - return await ctx.reply(`Вы уже устроены на другую работу`) + return await ctx.reply(`❕ Вы уже устроены на другую работу`) case `job_2`: job = await JobModel.findByPk(2); if (user.level < job.level) { - return await ctx.reply(`У вас не хватает уровня для этой работы.`) + return await ctx.reply(`❕ У вас не хватает уровня для этой работы.`) } if (user.job == 0) { user.job = 2 user.save() - return await ctx.reply(`Вы устроились на работу промоутером. \nВаш оклад: ¤${job.salary}\nПриступайте к работе командой "Работать"`) + return await ctx.reply(`ℹ️ Вы устроились на работу промоутером. \nВаш оклад: ¤${job.salary}\nПриступайте к работе командой "Работать"`) } - return await ctx.reply(`Вы уже устроены на другую работу`) + return await ctx.reply(`❕ Вы уже устроены на другую работу`) case `job_3`: job = await JobModel.findByPk(3); if (user.level < job.level) { - return await ctx.reply(`У вас не хватает уровня для этой работы.`) + return await ctx.reply(`❕ У вас не хватает уровня для этой работы.`) } if (user.job == 0) { user.job = 3 user.save() - return await ctx.reply(`Вы устроились на работу официантом. \nВаш оклад: ¤${job.salary}\nПриступайте к работе командой "Работать"`) + return await ctx.reply(`ℹ️ Вы устроились на работу официантом. \nВаш оклад: ¤${job.salary}\nПриступайте к работе командой "Работать"`) } - return await ctx.reply(`Вы уже устроены на другую работу`) + return await ctx.reply(`❕ Вы уже устроены на другую работу`) case `job_4`: job = await JobModel.findByPk(4); if (user.level < job.level) { - return await ctx.reply(`У вас не хватает уровня для этой работы.`) + return await ctx.reply(`❕ У вас не хватает уровня для этой работы.`) } if (user.job == 0) { user.job = 4 user.save() - return await ctx.reply(`Вы устроились на работу барменом. \nВаш оклад: ¤${job.salary}\nПриступайте к работе командой "Работать"`) + return await ctx.reply(`ℹ️ Вы устроились на работу барменом. \nВаш оклад: ¤${job.salary}\nПриступайте к работе командой "Работать"`) } - return await ctx.reply(`Вы уже устроены на другую работу`) + return await ctx.reply(`❕ Вы уже устроены на другую работу`) case `job_5`: job = await JobModel.findByPk(5); if (user.level < job.level) { - return await ctx.reply(`У вас не хватает уровня для этой работы.`) + return await ctx.reply(`❕ У вас не хватает уровня для этой работы.`) } if (user.job == 0) { user.job = 5 user.save() - return await ctx.reply(`Вы устроились на работу кассир. \nВаш оклад: ¤${job.salary}\nПриступайте к работе командой "Работать"`) + return await ctx.reply(`❕ Вы устроились на работу кассиром. \nВаш оклад: ¤${job.salary}\nПриступайте к работе командой "Работать"`) } - return await ctx.reply(`Вы уже устроены на другую работу`) + return await ctx.reply(`ℹ️ Вы уже устроены на другую работу`) case `job_6`: job = await JobModel.findByPk(6); if (user.level < job.level) { - return await ctx.reply(`У вас не хватает уровня для этой работы.`) + return await ctx.reply(`❕ У вас не хватает уровня для этой работы.`) } if (user.job == 0) { user.job = 6 user.save() - return await ctx.reply(`Вы устроились на работу в ПВЗ Дикие Ягоды. \nВаш оклад: ¤${job.salary}\nПриступайте к работе командой "Работать"`) + return await ctx.reply(`ℹ️ Вы устроились на работу в ПВЗ Дикие Ягоды. \nВаш оклад: ¤${job.salary}\nПриступайте к работе командой "Работать"`) } - return await ctx.reply(`Вы уже устроены на другую работу`) + return await ctx.reply(`❕ Вы уже устроены на другую работу`) case `job_7`: job = await JobModel.findByPk(7); if (user.level < job.level) { - return await ctx.reply(`У вас не хватает уровня для этой работы.`) + return await ctx.reply(`❕ У вас не хватает уровня для этой работы.`) } if (user.job == 0) { user.job = 7 user.save() - return await ctx.reply(`Вы устроились на работу слесарем. \nВаш оклад: ¤${job.salary}\nПриступайте к работе командой "Работать"`) + return await ctx.reply(`ℹ️ Вы устроились на работу слесарем. \nВаш оклад: ¤${job.salary}\nПриступайте к работе командой "Работать"`) } - return await ctx.reply(`Вы уже устроены на другую работу`) + return await ctx.reply(`❕ Вы уже устроены на другую работу`) case `job_leave`: if (user.job != 0) { user.job = 0 user.save() - return await ctx.reply(`Теперь вы безработный.`) + return await ctx.reply(`ℹ️ Теперь вы безработный.`) } - return await ctx.reply(`Вы итак безработный.`) + return await ctx.reply(`❕ Вы итак безработный.`) } }) bot.hears('🏯 Казино', async (ctx) => { - return await ctx.reply('Добро пожаловать в казино "杜明"\n', Markup + return await ctx.reply('🏯 Добро пожаловать в казино "杜明"\n', Markup .keyboard([ ['🎰 Слоты'], ['▶️ Меню'] ]) - .oneTime() .resize() ) }) @@ -462,14 +481,14 @@ bot.hears('🗄️ Работать', async (ctx) => { let cooldown = setCooldown(user, 3600, timer) if (user.jobtime > cooldown.currentTime) return ctx.reply(`📛 Работать можно будет через ${cooldown.timeLeftInMinutes} минут(у/ы)`); if (user.job == 0) { - return await ctx.reply(`Вы безработный.`) + return await ctx.reply(`📛 Вы безработный.`) } user.jobtime = Number(cooldown.endTime) let jobExp = job.exp; user.jobcheck++ switch (user.job) { case 1: - if (user.jobcheck == 4) { + if (user.jobcheck >= 4) { let paydayfee = job.salary / 100 * world.transactionfee let payday = job.salary - paydayfee world.balance -= payday @@ -478,14 +497,14 @@ bot.hears('🗄️ Работать', async (ctx) => { user.jobcheck = 0 user.save() world.save() - return ctx.reply(`Вы отработали смену дворника. \n Расчетный лист: \n Отработано часов: 4/4 \n Оклад: ¤${job.salary} \n Подоходный налог: ${world.transactionfee}% \n К выплате: ¤${payday}`) + return ctx.reply(`👔 Вы отработали смену дворника. \n🧾 Расчетный лист: \n⏳ Отработано часов: 4/4 \n💸 Оклад: ¤${job.salary} \nℹ️ Подоходный налог: ${world.transactionfee}% \n💹 К выплате: ¤${payday}`) } else { user.save() - return ctx.reply(`Вы подмели дворы. \n Отработано часов: ${user.jobcheck}/4`) + return ctx.reply(`👔 Вы подмели дворы. \n⏳ Отработано часов: ${user.jobcheck}/4`) } break; case 2: - if (user.jobcheck == 2) { + if (user.jobcheck >= 2) { let paydayfee = job.salary / 100 * world.transactionfee let payday = job.salary - paydayfee world.balance -= payday @@ -494,14 +513,14 @@ bot.hears('🗄️ Работать', async (ctx) => { user.jobcheck = 0 user.save() world.save() - return ctx.reply(`Вы отработали смену промоутера. \n Расчетный лист: \n Отработано часов: 2/2 \n Оклад: ¤${job.salary} \n Подоходный налог: ${world.transactionfee}% \n К выплате: ¤${payday}`) + return ctx.reply(`👔 Вы отработали смену промоутера. \n🧾 Расчетный лист: \n⏳ Отработано часов: 2/2 \n💸 Оклад: ¤${job.salary} \nℹ️ Подоходный налог: ${world.transactionfee}% \n💹 К выплате: ¤${payday}`) } else { user.save() - return ctx.reply(`Вы раздавали листовки целый час. \n Отработано часов: ${user.jobcheck}/2`) + return ctx.reply(`👔 Вы раздавали листовки целый час. \n⏳ Отработано часов: ${user.jobcheck}/2`) } break; case 3: - if (user.jobcheck == 4) { + if (user.jobcheck >= 4) { let paydayfee = job.salary / 100 * world.transactionfee let payday = job.salary - paydayfee world.balance -= payday @@ -512,16 +531,16 @@ bot.hears('🗄️ Работать', async (ctx) => { user.jobcheck = 0 user.save() world.save() - return ctx.reply(`Вы отработали смену официанта. \n Расчетный лист: \n Отработано часов: 4/4 \n Оклад: ¤${job.salary} \n Подоходный налог: ${world.transactionfee}% \n К выплате: ¤${payday} \n Получено чаевых: ¤${tips}`) + return ctx.reply(`👔 Вы отработали смену официанта. \n🧾 Расчетный лист: \n⏳ Отработано часов: 4/4 \n💸 Оклад: ¤${job.salary} \nℹ️ Подоходный налог: ${world.transactionfee}% \n💹 К выплате: ¤${payday} \n💰 Получено чаевых: ¤${tips}`) } else { let tips = [50, 100, 200, 500, 1000].random() user.money += tips user.save() - return ctx.reply(`Вы целый час бегали и отрабатывали заказы. \n Получено чаевых: ¤${tips} \n Отработано часов: ${user.jobcheck}/4`) + return ctx.reply(`👔 Вы целый час бегали и отрабатывали заказы. \n🧾 Получено чаевых: ¤${tips} \n⏳ Отработано часов: ${user.jobcheck}/4`) } break; case 4: - if (user.jobcheck == 5) { + if (user.jobcheck >= 5) { let paydayfee = job.salary / 100 * world.transactionfee let payday = job.salary - paydayfee world.balance -= payday @@ -533,18 +552,18 @@ bot.hears('🗄️ Работать', async (ctx) => { user.jobcheck = 0 user.save() world.save() - return ctx.reply(`Вы отработали смену бармена. \n Расчетный лист: \n Отработано часов: 5/5 \n Оклад: ¤${job.salary} \n Подоходный налог: ${world.transactionfee}% \n К выплате: ¤${payday} \n Получено чаевых: ¤${tips}`) + return ctx.reply(`👔 Вы отработали смену бармена. \n🧾 Расчетный лист: \n⏳ Отработано часов: 5/5 \n💸 Оклад: ¤${job.salary} \nℹ️ Подоходный налог: ${world.transactionfee}% \n💹 К выплате: ¤${payday} \n💰 Получено чаевых: ¤${tips}`) } else { let tips = [50, 100, 200, 300, 500, 1000, 2000].random() world.balance -= tips user.money += tips user.save() world.save() - return ctx.reply(`Вы целый час стояли за стойкой и разливали пойло. \n Получено чаевых: ¤${tips} \n Отработано часов: ${user.jobcheck}/5`) + return ctx.reply(`👔 Вы целый час стояли за стойкой и разливали пойло. \n🧾 Получено чаевых: ¤${tips} \n⏳ Отработано часов: ${user.jobcheck}/5`) } break; case 5: - if (user.jobcheck == 5) { + if (user.jobcheck >= 5) { let paydayfee = job.salary / 100 * world.transactionfee let payday = job.salary - paydayfee world.balance -= payday @@ -553,14 +572,14 @@ bot.hears('🗄️ Работать', async (ctx) => { user.jobcheck = 0 user.save() world.save() - return ctx.reply(`Вы отработали смену кассира. \n Расчетный лист: \n Отработано часов: 5/5 \n Оклад: ¤${job.salary} \n Подоходный налог: ${world.transactionfee}% \n К выплате: ¤${payday}`) + return ctx.reply(`👔 Вы отработали смену кассира. \n🧾 Расчетный лист: \n⏳ Отработано часов: 5/5 \n💸 Оклад: ¤${job.salary} \nℹ️ Подоходный налог: ${world.transactionfee}% \n💹 К выплате: ¤${payday}`) } else { user.save() - return ctx.reply(`Вы целый час обслуживали покупателей и кричали: "Гаааляяя, отмена!". \n Отработано часов: ${user.jobcheck}/5`) + return ctx.reply(`👔 Вы целый час обслуживали покупателей и кричали: "Гаааляяя, отмена!". \n⏳ Отработано часов: ${user.jobcheck}/5`) } break; case 6: - if (user.jobcheck == 6) { + if (user.jobcheck >= 6) { let paydayfee = job.salary / 100 * world.transactionfee let payday = job.salary - paydayfee let stealed = [{ @@ -611,14 +630,14 @@ bot.hears('🗄️ Работать', async (ctx) => { user.jobcheck = 0 user.save() world.save() - return ctx.reply(`Вы отработали смену в Диких Ягодах. \n Расчетный лист: \n Отработано часов: 6/6 \n Оклад: ¤${job.salary} \n Подоходный налог: ${world.transactionfee}% \n К выплате: ¤${payday} \n Вы украли и продали со склада: ${stealed.name} (¤${stealed.price})`) + return ctx.reply(`👔 Вы отработали смену в Диких Ягодах. \n🧾 Расчетный лист: \n⏳ Отработано часов: 6/6 \n💸 Оклад: ¤${job.salary} \nℹ️ Подоходный налог: ${world.transactionfee}% \n💹 К выплате: ¤${payday} \n💰 Вы украли и продали со склада: ${stealed.name} (¤${stealed.price})`) } else { user.save() - return ctx.reply(`Вы целый час выдавали заказы в Диких Ягодах. \n Отработано часов: ${user.jobcheck}/6`) + return ctx.reply(`👔 Вы целый час выдавали заказы в Диких Ягодах. \n⏳ Отработано часов: ${user.jobcheck}/6`) } break; case 7: - if (user.jobcheck == 6) { + if (user.jobcheck >= 6) { let paydayfee = job.salary / 100 * world.transactionfee let payday = job.salary - paydayfee world.balance -= payday @@ -627,29 +646,19 @@ bot.hears('🗄️ Работать', async (ctx) => { user.jobcheck = 0 user.save() world.save() - return ctx.reply(`Вы отработали смену слесарем. \n Расчетный лист: \n Отработано часов: 6/6 \n Оклад: ¤${job.salary} \n Подоходный налог: ${world.transactionfee}% \n К выплате: ¤${payday}`) + return ctx.reply(`👔 Вы отработали смену слесарем. \n🧾 Расчетный лист: \n⏳ Отработано часов: 6/6 \n💸 Оклад: ¤${job.salary} \nℹ️ Подоходный налог: ${world.transactionfee}% \n💹 К выплате: ¤${payday}`) } else { user.save() - return ctx.reply(`Вы целый час работали на заводе, вы молодец! \n Отработано часов: ${user.jobcheck}/6`) + return ctx.reply(`👔 Вы целый час работали на заводе, вы молодец! \n⏳ Отработано часов: ${user.jobcheck}/6`) } break; } }) -bot.hears('💤 Уволиться', async (ctx) => { - let user = await UserModel.findByPk(ctx.from.id); - if (user.job != 0) { - user.job = 0 - user.save() - return await ctx.reply(`Теперь вы безработный.`) - } - return await ctx.reply(`Вы итак безработный.`) -}) - bot.hears('Топ', async (ctx) => { let topPlayer = await UserModel.findAll({ - attributes: ['username', [sequelize.fn('sum', sequelize.col('money')), 'money']], - group: ['username'], + attributes: ['username', [sequelize.fn('sum', sequelize.col('money')), 'money'], 'status'], + group: ['username', 'status'], where: { telegram_id: { [Op.ne]: 275416286 // игнорировать игрока с telegram_id 275416286 @@ -660,64 +669,135 @@ bot.hears('Топ', async (ctx) => { ], limit: 10 }) - if (!topPlayer[1]) { - console.log(topPlayer[0]) - return await ctx.reply(` - В данный момент недостаточно игроков для составления топ 10, показывается только топ 1. - Игрок с наибольшим балансом: - 1. ${topPlayer[0].username} [¤${topPlayer[0].money}] - `) - } else { - return await ctx.reply(` - Рейтинг игроков: - 1. ${topPlayer[0].username} [¤${spaces(topPlayer[0].money)}] - 2. ${topPlayer[1].username} [¤${spaces(topPlayer[1].money)}] - 3. ${topPlayer[2].username} [¤${spaces(topPlayer[2].money)}] - 4. ${topPlayer[3].username} [¤${spaces(topPlayer[3].money)}] - 5. ${topPlayer[4].username} [¤${spaces(topPlayer[4].money)}] - 6. ${topPlayer[5].username} [¤${spaces(topPlayer[5].money)}] - 7. ${topPlayer[6] ? topPlayer[6].username + `[¤${spaces(topPlayer[6].money)}]` : `Пока никого`} - 8. ${topPlayer[7] ? topPlayer[7].username + `[¤${spaces(topPlayer[7].money)}]` : `Пока никого`} - 9. ${topPlayer[8] ? topPlayer[8].username + `[¤${spaces(topPlayer[8].money)}]` : `Пока никого`} - 10. ${topPlayer[9] ? topPlayer[9].username + `[¤${spaces(topPlayer[9].money)}]` : `Пока никого`} - `) + let text = `🏆 Топ 10 игроков по балансу.\n\n` + for(i=0; i { let user = await UserModel.findByPk(ctx.from.id); - return await ctx.reply(`Места для покупки`, Markup - .keyboard([ - ['Жилье', 'Телефоны', 'Автосалон'], - ['▶️ Меню'] // Row3 with 3 buttons + return await ctx.reply(`Выберите тип`, Markup + .inlineKeyboard([ + [ + {text: 'Жилье', callback_data: `shop_house`}, + {text: 'Телефоны', callback_data: `shop_phone`}, + {text: 'Автосалон', callback_data: `shop_car`} + ] ]) - .oneTime() .resize()) }) -bot.hears('Жилье', async (ctx) => { - let text = `Вы зашли на сайт с предложениями жилья:\n` - for (i in houses) { - text += i + `. ${houses[i].name} (¤${houses[i].price}) [/buy house ${i}]\n` - } - return await ctx.reply(text) +bot.action('shopmenu', async (ctx) => { + let user = await UserModel.findByPk(ctx.from.id); + return await ctx.editMessageText(`Выберите тип`, Markup + .inlineKeyboard([ + [ + {text: 'Жилье', callback_data: `shop_house`}, + {text: 'Телефоны', callback_data: `shop_phone`}, + {text: 'Автосалон', callback_data: `shop_car`} + ] + ]) + .resize()) }) -bot.hears('Телефоны', async (ctx) => { - let text = `Вы зашли в магазин электроники:\n` - for (i in phones) { - text += i + `. ${phones[i].name} (¤${phones[i].price}) [/buy phone ${i}]\n` +bot.action(/shop_(house|phone|car)/, async (ctx) => { + let data = ctx.update.callback_query.data; + let prodArray = [] + let text = `Доступно к покупке:\n` + switch(data){ + case `shop_house`: + for (i in houses) { + prodArray.push({text: i, callback_data: `{"action": "buy", "type": "house", "value": "${i}"}`}) + text += i + `. ${houses[i].name} (¤${houses[i].price})\n` + } + break; + case `shop_phone`: + for (i in phones) { + prodArray.push({text: i, callback_data: `{"action": "buy", "type": "phone", "value": "${i}"}`}) + text += i + `. ${phones[i].name} (¤${phones[i].price})\n` + } + break; + case `shop_car`: + for (i in cars) { + prodArray.push({text: i, callback_data: `{"action": "buy", "type": "car", "value": "${i}"}`}) + text += i + `. ${cars[i].name} (¤${cars[i].price})\n` + } + break; } - return await ctx.reply(text) + prodArray.push({text: `Назад`, callback_data: `shopmenu`}) + let rows = [] + while (prodArray.length > 0) { + rows.push(prodArray.splice(0, 5)) // разбиваем на подмассивы по 5 кнопок + } + return await ctx.editMessageText(text, Markup + .inlineKeyboard(rows) + .resize()) }) -bot.hears('Автосалон', async (ctx) => { - let text = `Автомобили доступные в автосалоне:\n` - for (i in cars) { - text += i + `. ${cars[i].name} (¤${cars[i].price}) [/buy car ${i}]\n` +bot.action(/{"action": "buy"*/, async (ctx) => { + let data = ctx.update.callback_query.data; + data = JSON.parse(data) + let user = await UserModel.findByPk(ctx.from.id) + let property = await PropertyModel.findByPk(ctx.from.id); + let world = await WorldModel.findByPk(1) + if (data.type == "house") { + if (user.money < houses[data.value].price) return await ctx.reply(`У вас недостаточно средств!`) + if (property.house.name) return await ctx.reply(`У вас уже есть дом.`) + user.money -= houses[data.value].price + world.balance += houses[data.value].price + property.house = houses[data.value] + await user.save() + await world.save() + await property.save() + return await ctx.reply(`Вы купили ${houses[data.value].name}`) } - return await ctx.reply(text) + if (data.type == "car") { + if (user.money < cars[data.value].price) return await ctx.reply(`У вас недостаточно средств!`) + if (property.car.name) return await ctx.reply(`У вас уже есть автомобиль.`) + if (!property.house.name) return await ctx.reply(`Для покупки автомобиля, у Вас должен быть дом.`) + user.money -= cars[data.value].price + world.balance += cars[data.value].price + property.car = cars[data.value] + await user.save() + await world.save() + await property.save() + return await ctx.reply(`Вы купили ${cars[data.value].name}`) + } + if (data.type == "phone") { + if (user.money < phones[data.value].price) return await ctx.reply(`У вас недостаточно средств!`) + if (property.mobile.name) return await ctx.reply(`У вас уже есть телефон.`) + user.money -= phones[data.value].price + world.balance += phones[data.value].price + property.mobile = phones[data.value] + await user.save() + await world.save() + await property.save() + return await ctx.reply(`Вы купили ${phones[data.value].name}`) + } + if (data.type == "equipment") { + if (user.money < weaponshop[data.value].price) return await ctx.reply(`У вас недостаточно средств!`) + if (data.type == weaponshop[data.value].type) { + if (property.equipment.name) return await ctx.reply(`У вас уже есть экипировка.`) + user.money -= weaponshop[data.value].price + world.balance += weaponshop[data.value].price + property.equipment = weaponshop[data.value] + await user.save() + await world.save() + await property.save() + return await ctx.reply(`Вы купили ${weaponshop[data.value].name}`) + } + if (property.weapon.name) return await ctx.reply(`У вас уже есть оружие.`) + user.money -= weaponshop[data.value].price + world.balance += weaponshop[data.value].price + property.weapon = weaponshop[data.value] + await user.save() + await world.save() + await property.save() + return await ctx.reply(`Вы купили ${weaponshop[data.value].name}`) + } }) bot.hears('Поставщик', async (ctx) => { @@ -729,70 +809,6 @@ bot.hears('Поставщик', async (ctx) => { return await ctx.reply(text) }) -bot.command('buy', async (ctx) => { - ctx.args = ctx.update.message.text.split(' ') - let user = await UserModel.findByPk(ctx.from.id) - let property = await PropertyModel.findByPk(ctx.from.id); - let world = await WorldModel.findByPk(1) - if (!ctx.args[1] || !ctx.args[2]) return ctx.reply(`Не указан аргумент.`) - if (!Number(ctx.args[2])) return ctx.reply(`Неверно указан параметр.`) - if (ctx.args[1] == "house") { - if (user.money < houses[ctx.args[2]].price) return await ctx.reply(`У вас недостаточно средств!`) - if (property.house.name) return await ctx.reply(`У вас уже есть дом.`) - user.money -= houses[ctx.args[2]].price - world.balance += houses[ctx.args[2]].price - property.house = houses[ctx.args[2]] - await user.save() - await world.save() - await property.save() - return await ctx.reply(`Вы купили ${houses[ctx.args[2]].name}`) - } - if (ctx.args[1] == "car") { - if (user.money < cars[ctx.args[2]].price) return await ctx.reply(`У вас недостаточно средств!`) - if (property.car.name) return await ctx.reply(`У вас уже есть автомобиль.`) - user.money -= cars[ctx.args[2]].price - world.balance += cars[ctx.args[2]].price - property.car = cars[ctx.args[2]] - await user.save() - await world.save() - await property.save() - return await ctx.reply(`Вы купили ${cars[ctx.args[2]].name}`) - } - if (ctx.args[1] == "phone") { - if (user.money < phones[ctx.args[2]].price) return await ctx.reply(`У вас недостаточно средств!`) - if (property.phone.name) return await ctx.reply(`У вас уже есть телефон.`) - user.money -= phones[ctx.args[2]].price - world.balance += phones[ctx.args[2]].price - property.mobile = phones[ctx.args[2]] - await user.save() - await world.save() - await property.save() - return await ctx.reply(`Вы купили ${phones[ctx.args[2]].name}`) - } - if (ctx.args[1] == "equipment") { - if (user.money < weaponshop[ctx.args[2]].price) return await ctx.reply(`У вас недостаточно средств!`) - if (ctx.args[1] == weaponshop[ctx.args[2]].type) { - if (property.equipment.name) return await ctx.reply(`У вас уже есть экипировка.`) - user.money -= weaponshop[ctx.args[2]].price - world.balance += weaponshop[ctx.args[2]].price - property.equipment = weaponshop[ctx.args[2]] - await user.save() - await world.save() - await property.save() - return await ctx.reply(`Вы купили ${weaponshop[ctx.args[2]].name}`) - } - if (property.weapon.name) return await ctx.reply(`У вас уже есть оружие.`) - user.money -= weaponshop[ctx.args[2]].price - world.balance += weaponshop[ctx.args[2]].price - property.weapon = weaponshop[ctx.args[2]] - await user.save() - await world.save() - await property.save() - return await ctx.reply(`Вы купили ${weaponshop[ctx.args[2]].name}`) - } - return await ctx.reply(`Вы купили.`) -}) - bot.command('sell', async (ctx) => { ctx.args = ctx.update.message.text.split(' ') let user = await UserModel.findByPk(ctx.from.id) @@ -822,11 +838,11 @@ bot.command('sell', async (ctx) => { return await ctx.reply(`Вы продали ${name}`) } if (ctx.args[1] == "phone") { - if (!property.phone.name) return await ctx.reply(`У вас нет телефона.`) - let name = property.phone.name - user.money += Math.round(property.phone.price/2) - world.balance -= Math.round(property.phone.price/2) - property.phone = 0 + if (!property.mobile.name) return await ctx.reply(`У вас нет телефона.`) + let name = property.mobile.name + user.money += Math.round(property.mobile.price/2) + world.balance -= Math.round(property.mobile.price/2) + property.mobile = 0 await user.save() await world.save() await property.save() @@ -875,7 +891,6 @@ bot.hears('🌐 Организация', async (ctx) => { ['⬅️ Покинуть'], ['🌐 Организация', '▶️ Меню'] // Row3 with 3 buttons ]) - .oneTime() .resize()) } if (business.owner == ctx.from.id){ @@ -883,11 +898,63 @@ bot.hears('🌐 Организация', async (ctx) => { ['📶 Отработка'], ['💸 Payday', '🌐 Организация', '▶️ Меню'] ]) - .oneTime() .resize()) } }) +bot.hears('⬅️ Покинуть', async (ctx) => { + let user = await UserModel.findByPk(ctx.from.id) + if (user.business.id == 0) return await ctx.reply(`Вы не состоите в организации.`) + let business = await BusinessModel.findOne({ + where: { + owner: ctx.from.id.toString() + } + }) + if(business === null){ + business = await BusinessModel.findOne({ + where: { + owner: user.business.id + } + }) + await ctx.reply(`Подтвердите в личных сообщениях.`) + return await bot.telegram.sendMessage(ctx.from.id, `🏭 Вы действительно хотите покинуть ${business.name}`, Markup.inlineKeyboard([ + [{ + text: `Да`, + callback_data: "user_leave_business" + }, { + text: `Нет`, + callback_data: "cancel" + }] + ]) + .oneTime() + .resize() + ) + } + if (business.owner == ctx.from.id){ + return await ctx.reply(`Вы не можете покинуть свою организацию.`) + } +}) + +bot.action('user_leave_business', async (ctx) => { + let data = ctx.update.callback_query.data; + let user = await UserModel.findByPk(ctx.from.id) + if (user.business.id == 0) return await ctx.reply(`Вы не состоите в организации.`) + let business = await BusinessModel.findOne({ + where: { + owner: user.business.id + } + }) + user.business = { + id: 0, + checks: 0, + percent: 0 + } + business.users = business.users.filter(value => value != ctx.from.id); + business.save() + user.save() + return await bot.telegram.sendMessage(ctx.from.id, `🏭 Вы покинули ${business.name}`) +}) + bot.hears('📶 Отработка', async (ctx) => { let user = await UserModel.findByPk(ctx.from.id) let business = await BusinessModel.findOne({ @@ -910,7 +977,7 @@ bot.hears('📶 Отработка', async (ctx) => { business.checks += 1 await user.save() await business.save() - return await ctx.reply(`Вы отработали час на ${business.name}`) + return await ctx.reply(`Вы отработали час на ${business.name}\nВсего отработок ${user.business.checks}`) }) bot.hears('💸 Payday', async (ctx) => { @@ -928,7 +995,8 @@ bot.hears('💸 Payday', async (ctx) => { let percentErrorText = `` let profit = 0 let piece = 0 - let moneyList = rand(500, 5000) + let moneyList = rand(1000, 3000) + moneyList = moneyList*business.users.length for (i = 0; i < business.users.length; i++) { // Summary percent user = await UserModel.findByPk(business.users[i]) percentSum += Number(user.business.percent) @@ -938,11 +1006,13 @@ bot.hears('💸 Payday', async (ctx) => { for (i = 0; i < business.users.length; i++) { // Общая внесенная сумма всеми участниками user = await UserModel.findByPk(business.users[i]) profit += user.business.checks * moneyList + text += `${user.username} отработал ${user.business.checks} раз.\n` user.business = { - id: user.business.id, - checks: 0, - percent: user.business.percent - } + id: user.business.id, + checks: 0, + percent: user.business.percent + } + user.save() } text += `Наработка за текущий период: ${profit}\n` @@ -967,6 +1037,22 @@ bot.hears('💸 Payday', async (ctx) => { return await ctx.reply(text) }) +bot.command('orgmessage', async (ctx) => { + if (!ctx.args[1]) return ctx.reply(`Не указан аргумент.`) + let business = await BusinessModel.findOne({ + where: { + owner: ctx.from.id.toString() + } + }) + if (business === null) return await ctx.reply(`У вас нет организации.`) + for (i = 0; i < business.users.length; i++) { + user = await UserModel.findByPk(business.users[i]) + await bot.telegram.sendMessage(user.telegram_id, `Директор организации сообщает:\n ${ctx.payload}`) + } + console.log(`Директор организации сообщает:\n ${ctx.payload}`) + return await ctx.reply(`Сообщение отправлено.`) +}) + bot.command('materials', async (ctx) => { ctx.args = ctx.update.message.text.split(' ') let user = await UserModel.findByPk(ctx.from.id) @@ -1009,6 +1095,7 @@ bot.command('percent', async (ctx) => { username: ctx.args[1] } }) + if (change === null) return await ctx.reply(`Нет такого игрока.`) change.business = { id: change.business.id, checks: change.business.checks, @@ -1071,16 +1158,44 @@ bot.command('invite', async (ctx) => { await bot.telegram.sendMessage(invited.telegram_id, 'Приглашение', Markup .inlineKeyboard([ [{ - text: `Принять ${user.username}`, - callback_data: ctx.from.id + text: `Принять`, + callback_data: `{"type": "business_invite_accept", "invitor": "${user.telegram_id}"}` }, { - text: `Отклонить ${user.username}`, - callback_data: '0' + text: `Отклонить`, + callback_data: `{"type": "business_invite_refuse", "invitor": "${user.telegram_id}"}` }] ]).oneTime()) return await ctx.reply(`Приглашение отправлено.`) }) +bot.action(/{"type": "business_invite_(accept|refuse)"*/, async ctx => { + let data = ctx.update.callback_query.data; + data = JSON.parse(data) + let user = await UserModel.findByPk(ctx.update.callback_query.from.id) + if (data.type == 'business_invite_accept') { + if(user.business.id == 0){ + let business = await BusinessModel.findOne({ + where: { + owner: data.invitor + } + }) + user.business = { + id: data.invitor, + checks: 0, + percent: 10 + } + business.users = sequelize.fn('array_append', sequelize.col('users'), ctx.update.callback_query.from.id); + business.save() + user.save() + await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `Приглашение принято.`, {show_alert: true}) + } + await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `Вы уже в организации.`, {show_alert: true}) + } + if (data.type == 'business_invite_refuse'){ + await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `Приглашение отклонено.`, {show_alert: true}) + } +}) + bot.command('report', async (ctx) => { let user = await UserModel.findByPk(ctx.from.id) ctx.args = ctx.update.message.text.split(' ') @@ -1122,7 +1237,7 @@ bot.hears('🎰 Слоты', async (ctx) => { text: `100000`, callback_data: `slots100000` }] - ]).oneTime()) + ])) }) bot.action(/slots(1000|5000|25000|50000|100000)/, async (ctx) => { @@ -1184,33 +1299,9 @@ bot.action(/slots(1000|5000|25000|50000|100000)/, async (ctx) => { }) bot.hears('Помощь', async (ctx) => { - return await ctx.reply(`https://telegra.ph/CampFireGameBot-09-19`) -}) - -bot.on('callback_query', async ctx => { - const data = ctx.update.callback_query.data; - let user = await UserModel.findByPk(ctx.update.callback_query.from.id) - if (data != 0) { - if(user.business.id == 0){ - let business = await BusinessModel.findOne({ - where: { - owner: data - } - }) - user.business = { - id: data, - checks: 0, - percent: 10 - } - business.users = sequelize.fn('array_append', sequelize.col('users'), ctx.update.callback_query.from.id); - business.save() - user.save() - await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `Приглашение принято.`) - } - await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `Вы уже в организации.`) - } else { - await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `Приглашение отклонено.`) - } + return await ctx.replyWithMarkdownV2(`• [Функционал](https://telegra.ph/CampFire-Bot-Info-09-25)\n• [Правила](https://telegra.ph/PRAVILA-BOTA-09-25)`, { + disable_web_page_preview: true + }) }) bot.command('promocode', async (ctx) => { @@ -1224,7 +1315,8 @@ bot.command('promocode', async (ctx) => { }) if(promocode === null) return await ctx.reply(`Нет такого кода.`) if(promocode.users.length-1 >= promocode.activations && promocode.users != null) return await ctx.reply(`Промокод уже активировали максимальное количество раз.`) - if(promocode.users.includes(ctx.from.id)) return await ctx.reply(`Вы уже активировали этот промокод.`) + if(promocode.users.includes(ctx.from.id.toString())) return await ctx.reply(`Вы уже активировали этот промокод.`) + console.log(promocode.users) promocode.users = sequelize.fn('array_append', sequelize.col('users'), ctx.from.id.toString()); user.money += promocode.money user.save() @@ -1238,6 +1330,7 @@ bot.command('promocode', async (ctx) => { bot.command('answer', async (ctx) => { let user = await UserModel.findByPk(ctx.from.id) + if(user.status != 'admin') return await ctx.reply(`Admin Only.`) ctx.args = ctx.update.message.text.split(' ') if (!ctx.args[1]) return ctx.reply(`Нужен номер обращения`) let report = await ReportModel.findByPk(ctx.args[1]) @@ -1257,7 +1350,7 @@ bot.command('fastblock', async (ctx) => { let user = await UserModel.findByPk(ctx.from.id) if(!ctx.message.reply_to_message) return await ctx.reply(`Только на пересланное сообщение.`) let blocked = ctx.message.reply_to_message.from.id - if(!adminList.includes(user.telegram_id)) return await ctx.reply(`Admin Only.`) + if(user.status != 'admin') return await ctx.reply(`Admin Only.`) await BlockModel.create({ telegram_id: blocked, isBlocked: true, @@ -1270,7 +1363,7 @@ bot.command('fastblock', async (ctx) => { bot.command('createpromocode', async (ctx) => { let user = await UserModel.findByPk(ctx.from.id) - if(!adminList.includes(user.telegram_id.toString())) return await ctx.reply(`Admin Only.`) + if(user.status != 'admin') return await ctx.reply(`Admin Only.`) ctx.args = ctx.update.message.text.split(' ') if (!ctx.args[1] || !ctx.args[2] || !ctx.args[3]) return ctx.reply(`/createpromo [activations] [money] [code]`) let promocode = await PromocodeModel.findOne({ @@ -1299,6 +1392,18 @@ function spaces(string) { if (typeof string !== "string") string = string.toString(); return string.split("").reverse().join("").match(/[0-9]{1,3}/g).join(".").split("").reverse().join(""); }; +function spacesWithMarkdown(string) { + if (typeof string !== "string") string = string.toString(); + return string.split("").reverse().join("").match(/[0-9]{1,3}/g).join(".\\").split("").reverse().join(""); +}; +function escape(string) { + string = string + .replace("_", "\\_") + .replace("*", "\\*") + .replace("[", "\\[") + .replace("`", "\\`"); + return string +}; Array.prototype.random = function() { return this[Math.floor(this.length * Math.random())]; } @@ -1339,10 +1444,23 @@ function getSlot(result) { function setCooldown(user, seconds, type) { let cooldown = {} cooldown.currentTime = Math.trunc(Date.now() / 1000) - if (adminList.includes(user.telegram_id)) { - cooldown.endTime = Math.trunc(Date.now() / 1000) - } else { - cooldown.endTime = Math.trunc(Date.now() / 1000 + seconds) + + switch(user.status){ + case `user`: + cooldown.endTime = Math.trunc(Date.now() / 1000 + seconds) + break; + case `bronze`: + cooldown.endTime = Math.trunc(Date.now() / 1000 + (seconds/100*85)) + break; + case `silver`: + cooldown.endTime = Math.trunc(Date.now() / 1000 + (seconds/100*75)) + break; + case `gold`: + cooldown.endTime = Math.trunc(Date.now() / 1000 + (seconds/100*50)) + break; + case `admin`: + cooldown.endTime = Math.trunc(Date.now() / 1000) + break; } cooldown.timeLeft = cooldown.endTime - cooldown.currentTime cooldown.timeLeftInMinutes = Math.ceil((type - cooldown.currentTime) / 60) diff --git a/json/weaponshop.json b/json/weaponshop.json index 6aed8d3..3533f99 100644 --- a/json/weaponshop.json +++ b/json/weaponshop.json @@ -1,31 +1,31 @@ { "0": { - "name": "Deagle", + "name": "SCAR L", "price": 1000, "type": "weapon" }, "1": { - "name": "AK-47", + "name": "Deagle", "price": 1000, "type": "weapon" }, "2": { - "name": "SCAR-H", + "name": "ПМ", "price": 1000, "type": "weapon" }, "3": { - "name": "SCAR-H", + "name": "Deagle", "price": 1000, "type": "weapon" }, "4": { - "name": "Five-Seven", + "name": "SCAR L", "price": 1000, "type": "weapon" }, "5": { - "name": "Наколенники", + "name": "Бронежилет M4", "price": 1000, "type": "equipment" }, @@ -35,17 +35,17 @@ "type": "equipment" }, "7": { - "name": "Бронежилет M4", + "name": "Бронежилет M5", "price": 1000, "type": "equipment" }, "8": { - "name": "Шлем танкиста", + "name": "Картонные накладки", "price": 1000, "type": "equipment" }, "9": { - "name": "Бронежилет M5", + "name": "Бронежилет M6", "price": 1000, "type": "equipment" } diff --git a/models/business.model.js b/models/business.model.js index 0050958..58df49b 100644 --- a/models/business.model.js +++ b/models/business.model.js @@ -7,9 +7,8 @@ const Business = sequelize.define('business', { owner: {type: DataTypes.STRING, defaultValue: 0}, balance: {type: DataTypes.INTEGER, defaultValue: 0}, materials: {type: DataTypes.INTEGER, defaultValue: 0}, - users: {type: DataTypes.ARRAY(DataTypes.INTEGER)}, - checks: {type: DataTypes.INTEGER, defaultValue: 0}, - percent: {type: DataTypes.INTEGER, defaultValue: 10} + users: {type: DataTypes.ARRAY(DataTypes.BIGINT)}, + checks: {type: DataTypes.INTEGER, defaultValue: 0} }) module.exports = Business; diff --git a/models/user.model.js b/models/user.model.js index 667a977..0c08407 100644 --- a/models/user.model.js +++ b/models/user.model.js @@ -5,6 +5,7 @@ const User = sequelize.define('user', { telegram_id: {type: DataTypes.STRING, primaryKey: true, unique: true}, username: {type: DataTypes.STRING}, name: {type: DataTypes.STRING}, + status: {type: DataTypes.STRING, defaultValue: 'user'}, level: {type: DataTypes.INTEGER, defaultValue: 1}, exp: {type: DataTypes.INTEGER, defaultValue: 0}, money: {type: DataTypes.INTEGER, defaultValue: 0}, diff --git a/package-lock.json b/package-lock.json index 4728f35..22d3230 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,6 +16,7 @@ "nodemon": "^2.0.7", "pg": "^8.6.0", "pg-hstore": "^2.3.3", + "prettytable": "^0.3.1", "sequelize": "^6.6.2", "shortid": "^2.2.16", "telegraf": "^4.13.1", @@ -508,6 +509,11 @@ "node": ">=8" } }, + "node_modules/csv-parse": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/csv-parse/-/csv-parse-5.5.0.tgz", + "integrity": "sha512-RxruSK3M4XgzcD7Trm2wEN+SJ26ChIb903+IWxNOcB5q4jT2Cs+hFr6QP39J05EohshRFEvyzEBoZ/466S2sbw==" + }, "node_modules/dashdash": { "version": "1.14.1", "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", @@ -1767,6 +1773,14 @@ "node": ">=4" } }, + "node_modules/prettytable": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/prettytable/-/prettytable-0.3.1.tgz", + "integrity": "sha512-gQNaAPovyDhe/D0ziwad9ULsKcTvOdgv7iIxOSxGWunMaWYdXJLZNdF0Kmke9rn6qPScn/ipbtTlj/X3H3allg==", + "dependencies": { + "csv-parse": "latest" + } + }, "node_modules/process-nextick-args": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", diff --git a/package.json b/package.json index 6917315..953bceb 100644 --- a/package.json +++ b/package.json @@ -18,6 +18,7 @@ "nodemon": "^2.0.7", "pg": "^8.6.0", "pg-hstore": "^2.3.3", + "prettytable": "^0.3.1", "sequelize": "^6.6.2", "shortid": "^2.2.16", "telegraf": "^4.13.1", diff --git a/presets/cars.json b/presets/cars.json index dc6bbb3..b8344e6 100644 --- a/presets/cars.json +++ b/presets/cars.json @@ -36,7 +36,7 @@ "price": 1450000 }, "10": { - "name": "Mercedes Benz E-200", + "name": "Mercedes Benz E200", "price": 2000000 } } \ No newline at end of file diff --git a/presets/houses.json b/presets/houses.json index 79bbe48..36efdd3 100644 --- a/presets/houses.json +++ b/presets/houses.json @@ -12,11 +12,11 @@ "price": 150000 }, "4": { - "name": "1-комнатная квартира в сталинке", + "name": "1 комнатная квартира в сталинке", "price": 300000 }, "5": { - "name": "3-комнатная квартира в сталинке", + "name": "3 комнатная квартира в сталинке", "price": 500000 }, "6": { @@ -24,11 +24,11 @@ "price": 2000000 }, "7": { - "name": "2-комнатная квартира с евроремонтом в панельке", + "name": "2 комнатная квартира с евроремонтом в панельке", "price": 3800000 }, "8": { - "name": "2-этажный дом", + "name": "2 этажный дом", "price": 5000000 }, "9": { diff --git a/presets/weapons.json b/presets/weapons.json index faff54e..ec04b6f 100644 --- a/presets/weapons.json +++ b/presets/weapons.json @@ -10,7 +10,7 @@ "type": "weapon" }, "3": { - "name": "Five-Seven", + "name": "FiveSeven", "price": 1000, "type": "weapon" }, @@ -20,7 +20,7 @@ "type": "weapon" }, "5": { - "name": "AK-47", + "name": "AK47", "price": 1000, "type": "weapon" }, @@ -30,7 +30,7 @@ "type": "weapon" }, "7": { - "name": "SCAR-H", + "name": "SCAR H", "price": 1000, "type": "weapon" }, @@ -40,7 +40,7 @@ "type": "weapon" }, "9": { - "name": "SCAR-L", + "name": "SCAR L", "price": 1000, "type": "weapon" },