Code Beautify

code beautify
materials buying
This commit is contained in:
Degradin 2023-09-20 01:09:39 +03:00
parent 98afe19dd6
commit bf8d59b0f7
2 changed files with 611 additions and 486 deletions

419
index.js
View File

@ -1,5 +1,8 @@
require('dotenv').config()
const { Telegraf, Markup } = require('telegraf')
const {
Telegraf,
Markup
} = require('telegraf')
const shortid = require('shortid');
const fs = require('fs')
const bot = new Telegraf(process.env.BOT_TOKEN)
@ -30,13 +33,30 @@ const start = async () => {
}
}
bot.telegram.setMyCommands([
{command: "pay", description:"Перевести указанному пользователю сумму."},
{command: "buy", description:"Приобрести указанное имущество."},
{command: "business", description:"Создать организацию."},
{command: "invite", description:"Пригласить пользователя в организацию."},
{command: "percent", description:"Установить пользователю процент заработка."},
{command: "report", description:"Создать жалобу/обращение/идею."}
bot.telegram.setMyCommands([{
command: "pay",
description: "Перевести указанному пользователю сумму."
},
{
command: "buy",
description: "Приобрести указанное имущество."
},
{
command: "business",
description: "Создать организацию."
},
{
command: "invite",
description: "Пригласить пользователя в организацию."
},
{
command: "percent",
description: "Установить пользователю процент заработка."
},
{
command: "report",
description: "Создать жалобу/обращение/идею."
}
])
bot.use(async (ctx, next) => {
@ -45,7 +65,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) {
UserModel.create({
telegram_id: id,
@ -58,8 +78,8 @@ 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 !== null) {
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()
}
@ -87,33 +107,33 @@ bot.command('start', async (ctx) => {
console.log("Exist")
}
}
return await ctx.reply('Main Menu', Markup
return await ctx.reply('Главное меню', Markup
.keyboard([
['😎 Профиль', '💳 Баланс'], // Row1 with 2 buttons
['Работать', 'Бонус'], // Row2 with 2 buttons
['📢 Вакансии', 'Мир', '📞 Пригласить'] // Row3 with 3 buttons
['🗄️ Работать', '🎁 Бонус'], // Row2 with 2 buttons
['📢 Вакансии', '🔵 Имущество', '📞 Пригласить'] // Row3 with 3 buttons
])
.oneTime()
.resize()
)
})
bot.hears('Меню', async (ctx) => {
bot.hears('Меню', async (ctx) => {
return await ctx.reply('Main Menu', Markup
.keyboard([
['😎 Профиль', '💳 Баланс'], // Row1 with 2 buttons
['Работать', 'Бонус'], // Row2 with 2 buttons
['📢 Вакансии', 'Мир', '📞 Пригласить'] // Row3 with 3 buttons
['🗄️ Работать', '🎁 Бонус'], // Row2 with 2 buttons
['📢 Вакансии', '🔵 Имущество', '📞 Пригласить'] // Row3 with 3 buttons
])
.oneTime()
.resize()
)
});
});
bot.hears('😎 Профиль', async (ctx) => {
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`);
if (!user) return ctx.reply(`Ошибка #1`);
return ctx.reply(`
👤 ${user.username} ${adminList.includes(ctx.from.id)? " ✅" : ""}
🆔 ID: ${ctx.from.id}
@ -132,9 +152,9 @@ bot.command('start', async (ctx) => {
Экипировка: ${property.equipment == 0 ? "Нет" : property.equipment.name}
`);
});
});
bot.hears('💳 Баланс', async (ctx) => {
bot.hears('💳 Баланс', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id);
return ctx.reply(`
Аккаунт игрока ${user.username}
@ -150,29 +170,29 @@ bot.command('start', async (ctx) => {
`);
})
bot.hears('Бонус', async (ctx) => {
bot.hears('🎁 Бонус', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id);
if(!user) return ctx.reply(`Ошибка #1`);
if (!user) return ctx.reply(`Ошибка #1`);
let bonustime = user.bonustime
let cooldown = setCooldown(user, 3600, bonustime)
if(user.bonustime > cooldown.currentTime) return ctx.reply(`📛 Забрать бонус можно будет через ${cooldown.timeLeftInMinutes} минут(у/ы)`);
if (user.bonustime > cooldown.currentTime) return ctx.reply(`📛 Забрать бонус можно будет через ${cooldown.timeLeftInMinutes} минут(у/ы)`);
user.bonus = 1;
user.bonustime = cooldown.endTime
let world = await WorldModel.findByPk(1)
let text = ``;
let count = rand(2,3)
for(i=0;i<count;i++){
let count = rand(2, 3)
for (i = 0; i < count; i++) {
let money = [100, 200, 300, 400, 500, 1000].random();
if(user.level >= 1){
if (user.level >= 1) {
money += money;
}
let r = rand(1,2);
if(r == 1) {
let r = rand(1, 2);
if (r == 1) {
user.money += money;
world.balance -= money
text += `⏩ ¤${money}\n`;
}
if(r == 2){
if (r == 2) {
user.money += money * 2;
world.balance -= money * 2
text += `⏩ ¤${money*2}\n`;
@ -187,12 +207,16 @@ ${text}
`)
})
bot.command('pay', async (ctx) => {
bot.command('pay', async (ctx) => {
ctx.args = ctx.update.message.text.split(' ')
if (!ctx.args[1] || !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: { username: ctx.args[1] } });
let receiver = await UserModel.findOne({
where: {
username: ctx.args[1]
}
});
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.`)
@ -223,14 +247,14 @@ ${text}
`)
})
bot.hears('Мир', async (ctx) => {
bot.hears('Мир', async (ctx) => {
let world = await WorldModel.findByPk(1)
return ctx.reply(`
Баланс мира: ¤${spaces(world.balance)}
`)
})
bot.hears('📞 Пригласить', async (ctx) => {
bot.hears('📞 Пригласить', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id);
return ctx.reply(`
Для приглашения друга по реферальной системе, отправьте ему ссылку-приглашение
@ -240,7 +264,7 @@ ${text}
`)
})
bot.hears('📢 Вакансии', async (ctx) => {
bot.hears('📢 Вакансии', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id);
return await ctx.reply('Список работы', Markup
.keyboard([
@ -253,26 +277,26 @@ ${text}
)
})
bot.hears('Дворник', async (ctx) => {
bot.hears('Дворник', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id);
let job = await JobModel.findByPk(1);
if (user.level < job.level) {
return await ctx.reply(`У вас не хватает уровня для этой работы.`)
}
if (user.job == 0){
if (user.job == 0) {
user.job = 1
user.save()
return await ctx.reply(`Вы устроились на работу дворником. \nВаш оклад: ¤${job.salary}\nПриступайте к работе командой "Работать"`)
}
return await ctx.reply(`Вы уже устроены на другую работу`)
})
bot.hears('Промоутер', async (ctx) => {
bot.hears('Промоутер', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id);
let job = await JobModel.findByPk(2);
if (user.level < job.level) {
return await ctx.reply(`У вас не хватает уровня для этой работы.`)
}
if (user.job == 0){
if (user.job == 0) {
user.job = 2
user.save()
return await ctx.reply(`Вы устроились на работу промоутером. \nВаш оклад: ¤${job.salary}\nПриступайте к работе командой "Работать"`)
@ -280,13 +304,13 @@ ${text}
return await ctx.reply(`Вы уже устроены на другую работу`)
})
bot.hears('Официант', async (ctx) => {
bot.hears('Официант', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id);
let job = await JobModel.findByPk(3);
if (user.level < job.level) {
return await ctx.reply(`У вас не хватает уровня для этой работы.`)
}
if (user.job == 0){
if (user.job == 0) {
user.job = 3
user.save()
return await ctx.reply(`Вы устроились на работу официантом. \nВаш оклад: ¤${job.salary}\nПриступайте к работе командой "Работать"`)
@ -294,13 +318,13 @@ ${text}
return await ctx.reply(`Вы уже устроены на другую работу`)
})
bot.hears('Бармен', async (ctx) => {
bot.hears('Бармен', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id);
let job = await JobModel.findByPk(4);
if (user.level < job.level) {
return await ctx.reply(`У вас не хватает уровня для этой работы.`)
}
if (user.job == 0){
if (user.job == 0) {
user.job = 4
user.save()
return await ctx.reply(`Вы устроились на работу барменом. \nВаш оклад: ¤${job.salary}\nПриступайте к работе командой "Работать"`)
@ -308,13 +332,13 @@ ${text}
return await ctx.reply(`Вы уже устроены на другую работу`)
})
bot.hears('Слесарь', async (ctx) => {
bot.hears('Слесарь', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id);
let job = await JobModel.findByPk(7);
if (user.level < job.level) {
return await ctx.reply(`У вас не хватает уровня для этой работы.`)
}
if (user.job == 0){
if (user.job == 0) {
user.job = 7
user.save()
return await ctx.reply(`Вы устроились на работу слесарем. \nВаш оклад: ¤${job.salary}\nПриступайте к работе командой "Работать"`)
@ -322,13 +346,13 @@ ${text}
return await ctx.reply(`Вы уже устроены на другую работу`)
})
bot.hears('Кассир', async (ctx) => {
bot.hears('Кассир', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id);
let job = await JobModel.findByPk(5);
if (user.level < job.level) {
return await ctx.reply(`У вас не хватает уровня для этой работы.`)
}
if (user.job == 0){
if (user.job == 0) {
user.job = 5
user.save()
return await ctx.reply(`Вы устроились на работу кассир. \nВаш оклад: ¤${job.salary}\nПриступайте к работе командой "Работать"`)
@ -336,13 +360,13 @@ ${text}
return await ctx.reply(`Вы уже устроены на другую работу`)
})
bot.hears('ПВЗ Дикие Ягоды', async (ctx) => {
bot.hears('ПВЗ Дикие Ягоды', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id);
let job = await JobModel.findByPk(6);
if (user.level < job.level) {
return await ctx.reply(`У вас не хватает уровня для этой работы.`)
}
if (user.job == 0){
if (user.job == 0) {
user.job = 6
user.save()
return await ctx.reply(`Вы устроились на работу в ПВЗ Дикие Ягоды. \nВаш оклад: ¤${job.salary}\nПриступайте к работе командой "Работать"`)
@ -350,22 +374,22 @@ ${text}
return await ctx.reply(`Вы уже устроены на другую работу`)
})
bot.hears('Работать', async (ctx) => {
bot.hears('🗄️ Работать', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id);
let job = await JobModel.findByPk(user.job);
let world = await WorldModel.findByPk(1)
let timer = user.jobtime
let cooldown = setCooldown(user, 3600, timer)
if(user.jobtime > cooldown.currentTime) return ctx.reply(`📛 Работать можно будет через ${cooldown.timeLeftInMinutes} минут(у/ы)`);
if (user.jobtime > cooldown.currentTime) return ctx.reply(`📛 Работать можно будет через ${cooldown.timeLeftInMinutes} минут(у/ы)`);
if (user.job == 0) {
return await ctx.reply(`Вы безработный.`)
}
user.jobtime = Number(cooldown.endTime)
let jobExp = job.exp;
user.jobcheck++
switch(user.job){
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
@ -375,13 +399,13 @@ ${text}
user.save()
world.save()
return ctx.reply(`Вы отработали смену дворника. \n Расчетный лист: \n Отработано часов: 4/4 \n Оклад: ¤${job.salary} \n Подоходный налог: ${world.transactionfee}% \n К выплате: ¤${payday}`)
}else{
} else {
user.save()
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
@ -391,13 +415,13 @@ ${text}
user.save()
world.save()
return ctx.reply(`Вы отработали смену промоутера. \n Расчетный лист: \n Отработано часов: 2/2 \n Оклад: ¤${job.salary} \n Подоходный налог: ${world.transactionfee}% \n К выплате: ¤${payday}`)
}else{
} else {
user.save()
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
@ -409,7 +433,7 @@ ${text}
user.save()
world.save()
return ctx.reply(`Вы отработали смену официанта. \n Расчетный лист: \n Отработано часов: 4/4 \n Оклад: ¤${job.salary} \n Подоходный налог: ${world.transactionfee}% \n К выплате: ¤${payday} \n Получено чаевых: ¤${tips}`)
}else{
} else {
let tips = [50, 100, 200, 500, 1000].random()
user.money += tips
user.save()
@ -417,7 +441,7 @@ ${text}
}
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
@ -430,7 +454,7 @@ ${text}
user.save()
world.save()
return ctx.reply(`Вы отработали смену бармена. \n Расчетный лист: \n Отработано часов: 5/5 \n Оклад: ¤${job.salary} \n Подоходный налог: ${world.transactionfee}% \n К выплате: ¤${payday} \n Получено чаевых: ¤${tips}`)
}else{
} else {
let tips = [50, 100, 200, 300, 500, 1000, 2000].random()
world.balance -= tips
user.money += tips
@ -440,7 +464,7 @@ ${text}
}
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
@ -450,16 +474,55 @@ ${text}
user.save()
world.save()
return ctx.reply(`Вы отработали смену кассира. \n Расчетный лист: \n Отработано часов: 5/5 \n Оклад: ¤${job.salary} \n Подоходный налог: ${world.transactionfee}% \n К выплате: ¤${payday}`)
}else{
} else {
user.save()
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 = [{name: "Помада", price: 200}, {name: "Бюстгалтер", price: 1300}, {name: "Прокладки", price: 250}, {name: "Перцовый балончик", price: 600}, {name: "Гитара", price: 6500}, {name: "Комбик", price: 9000}, {name: "Кроссовки", price: 2000}, {name: "Шампунь", price: 180}, {name: "Смартфон Texno", price: 6999}, {name: "TWS Гарнитура", price: 2800}, {name: "Геймпад GameStation 5", price: 1400}, {name: "Дилдо", price: 600}, {name: "Вагиноимитатор", price: "600"}].random()
let stealed = [{
name: "Помада",
price: 200
}, {
name: "Бюстгалтер",
price: 1300
}, {
name: "Прокладки",
price: 250
}, {
name: "Перцовый балончик",
price: 600
}, {
name: "Гитара",
price: 6500
}, {
name: "Комбик",
price: 9000
}, {
name: "Кроссовки",
price: 2000
}, {
name: "Шампунь",
price: 180
}, {
name: "Смартфон Texno",
price: 6999
}, {
name: "TWS Гарнитура",
price: 2800
}, {
name: "Геймпад GameStation 5",
price: 1400
}, {
name: "Дилдо",
price: 600
}, {
name: "Вагиноимитатор",
price: "600"
}].random()
world.balance -= payday
world.balance -= Number(stealed.price)
user.money += payday
@ -469,13 +532,13 @@ ${text}
user.save()
world.save()
return ctx.reply(`Вы отработали смену в Диких Ягодах. \n Расчетный лист: \n Отработано часов: 6/6 \n Оклад: ¤${job.salary} \n Подоходный налог: ${world.transactionfee}% \n К выплате: ¤${payday} \n Вы украли и продали со склада: ${stealed.name}${stealed.price})`)
}else{
} else {
user.save()
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
@ -485,17 +548,17 @@ ${text}
user.save()
world.save()
return ctx.reply(`Вы отработали смену слесарем. \n Расчетный лист: \n Отработано часов: 6/6 \n Оклад: ¤${job.salary} \n Подоходный налог: ${world.transactionfee}% \n К выплате: ¤${payday}`)
}else{
} else {
user.save()
return ctx.reply(`Вы целый час работали на заводе, вы молодец! \n Отработано часов: ${user.jobcheck}/6`)
}
break;
}
})
})
bot.hears('Уволиться', async (ctx) => {
bot.hears('💤 Уволиться', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id);
if (user.job != 0){
if (user.job != 0) {
user.job = 0
user.save()
return await ctx.reply(`Теперь вы безработный.`)
@ -503,11 +566,13 @@ ${text}
return await ctx.reply(`Вы итак безработный.`)
})
bot.hears('Топ', async (ctx) => {
bot.hears('Топ', async (ctx) => {
let topPlayer = await UserModel.findAll({
attributes: ['username', [sequelize.fn('sum', sequelize.col('money')), 'money']],
group: ['username'],
order: [[sequelize.literal('money'), 'DESC']],
order: [
[sequelize.literal('money'), 'DESC']
],
limit: 10
})
if (!topPlayer[9]) {
@ -535,52 +600,57 @@ ${text}
})
bot.hears('Имущество', async (ctx) => {
bot.hears('🔵 Имущество', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id);
return await ctx.reply(`Тестовое внесение данных `)
return await ctx.reply(`Места для покупки`, Markup
.keyboard([
['Жилье', 'Телефоны', 'Автосалон'] // Row3 with 3 buttons
])
.oneTime()
.resize())
})
bot.hears('Жилье', async (ctx) => {
bot.hears('Жилье', async (ctx) => {
let text = `Вы зашли на сайт с предложениями жилья:\n`
for(i in houses){
for (i in houses) {
text += i + `. ${houses[i].name}${houses[i].price}) [/buy house ${i}]\n`
}
return await ctx.reply(text)
})
bot.hears('Телефоны', async (ctx) => {
bot.hears('Телефоны', async (ctx) => {
let text = `Вы зашли в магазин электроники:\n`
for(i in phones){
for (i in phones) {
text += i + `. ${phones[i].name}${phones[i].price}) [/buy phone ${i}]\n`
}
return await ctx.reply(text)
})
bot.hears('Автосалон', async (ctx) => {
bot.hears('Автосалон', async (ctx) => {
let text = `Автомобили доступные в автосалоне:\n`
for(i in cars){
for (i in cars) {
text += i + `. ${cars[i].name}${cars[i].price}) [/buy car ${i}]\n`
}
return await ctx.reply(text)
})
bot.hears('Поставщик', async (ctx) => {
bot.hears('Поставщик', async (ctx) => {
let text = `Вы подходите к зданию с вывеской "Ништяки Хаткейса".\nВлад Хаткейс: "Вот мой ассортимент на сегодня:"\n`
for(i = 0; i < 10; i++){
for (i = 0; i < 10; i++) {
text += `${i}. ${weaponshop[i].name}${weaponshop[i].price}) [/buy equipment ${i}]\n`
}
weaponShopUpdate()
return await ctx.reply(text)
})
bot.command('buy', async (ctx) => {
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 (ctx.args[1] == "house") {
user.money -= houses[ctx.args[2]].price
world.balance += houses[ctx.args[2]].price
property.house = houses[ctx.args[2]]
@ -589,7 +659,7 @@ ${text}
await property.save()
return await ctx.reply(`Вы купили ${houses[ctx.args[2]].name}`)
}
if (ctx.args[1] == "car"){
if (ctx.args[1] == "car") {
user.money -= cars[ctx.args[2]].price
world.balance += cars[ctx.args[2]].price
property.car = cars[ctx.args[2]]
@ -598,7 +668,7 @@ ${text}
await property.save()
return await ctx.reply(`Вы купили ${cars[ctx.args[2]].name}`)
}
if (ctx.args[1] == "phone"){
if (ctx.args[1] == "phone") {
user.money -= phones[ctx.args[2]].price
world.balance += phones[ctx.args[2]].price
property.mobile = phones[ctx.args[2]]
@ -607,8 +677,8 @@ ${text}
await property.save()
return await ctx.reply(`Вы купили ${phones[ctx.args[2]].name}`)
}
if (ctx.args[1] == "equipment"){
if (ctx.args[1] == weaponshop[ctx.args[2]].type){
if (ctx.args[1] == "equipment") {
if (ctx.args[1] == weaponshop[ctx.args[2]].type) {
user.money -= weaponshop[ctx.args[2]].price
world.balance += weaponshop[ctx.args[2]].price
property.equipment = weaponshop[ctx.args[2]]
@ -628,35 +698,43 @@ ${text}
return await ctx.reply(`Вы купили.`)
})
bot.hears('Организация', async (ctx) => {
bot.hears('Организация', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id)
let business = await BusinessModel.findOne({owner: ctx.from.id})
let business = await BusinessModel.findOne({
owner: ctx.from.id
})
if (business === null) return await ctx.reply(`У вас нет организации.`)
console.log(business)
return await ctx.reply(`Ваша организация\n${business.name}\nБаланс: ¤${business.balance}\nСырье: ${business.materials}\nРабочих: ${business.users.length}`)
})
bot.hears('Отработка', async (ctx) => {
bot.hears('Отработка', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id)
let business = await BusinessModel.findOne({owner: ctx.from.id})
let business = await BusinessModel.findOne({
owner: ctx.from.id
})
if (user.business == null) return await ctx.reply(`Вы не работаете в организации.`)
let timer = user.worktime
let cooldown = setCooldown(user, 3600, timer)
if(user.worktime > cooldown.currentTime) return ctx.reply(`📛 Работа в организации будет доступна через ${cooldown.timeLeftInMinutes} минут(у/ы)`);
if (user.worktime > cooldown.currentTime) return ctx.reply(`📛 Работа в организации будет доступна через ${cooldown.timeLeftInMinutes} минут(у/ы)`);
if (business.materials <= 10) return ctx.reply(`📛 В организации недостаточно материалов для отработки.`);
user.business = {
id: user.business.id,
checks: user.business.checks + 1,
percent: user.business.percent
}
business.materials -= 10
business.checks += 1
await user.save()
await business.save()
return await ctx.reply(`Вы отработали час на ${business.name}`)
})
bot.hears('Payday', async (ctx) => {
bot.hears('Payday', async (ctx) => {
let user = null
let business = await BusinessModel.findOne({owner: ctx.from.id})
let business = await BusinessModel.findOne({
owner: ctx.from.id
})
let world = await WorldModel.findByPk(1)
if (business === null) return await ctx.reply(`У вас нет организации.`)
if (business.checks < 12) return await ctx.reply(`Недостаточно отработок для формирования выплаты.`)
@ -666,39 +744,59 @@ ${text}
let profit = 0
let piece = 0
let moneyList = rand(500, 2000)
for (i=0; i < business.users.length; i++){ // Summary percent
for (i = 0; i < business.users.length; i++) { // Summary percent
user = await UserModel.findByPk(business.users[i])
percentSum += Number(user.business.percent)
percentErrorText += `${user.username} ${user.business.percent}% [для изменения введите /percent ${user.telegram_id} проценты]\n`
}
if (percentSum > 100) return await ctx.reply(`Общий процент всех сотрудников превышает 100%\nПроцент организации: ${business.percent}%\n${percentErrorText}`)
for (i=0; i < business.users.length; i++){ // Общая внесенная сумма всеми участниками
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 * moneyList}${moneyList}*${user.business.checks}] в баланс организации.\n`
}
text +=`Профит: ${profit}\n`
text += `Профит: ${profit}\n`
let profitCheck = profit
for (i=0; i < business.users.length; i++){ // Процент выплаты участникам
for (i = 0; i < business.users.length; i++) { // Процент выплаты участникам
user = await UserModel.findByPk(business.users[i])
piece = Math.round(profit / 100 * user.business.percent)
profitCheck -= piece
user.money += piece
giveExp(user, business.checks)
user.save()
text += `${user.username} получает ¤${piece}\nОстаток выплат: ¤${profitCheck}\n`
}
if (profitCheck > 0) {
business.balance += profitCheck
business.save()
text += `На баланс бизнеса поступило ¤${profitCheck}`
}
business.checks = 0
business.save()
return await ctx.reply(text)
})
bot.command('percent', async (ctx) => {
bot.command('materials', async (ctx) => {
ctx.args = ctx.update.message.text.split(' ')
let user = await UserModel.findByPk(ctx.from.id)
let business = await BusinessModel.findOne({owner: ctx.from.id})
let business = await BusinessModel.findOne({
owner: ctx.from.id
})
if (business === null) return await ctx.reply(`У вас нет организации.`)
if (!ctx.args[1]) return ctx.reply(`Не указан аргумент.`)
if (!Number(ctx.args[1])) return ctx.reply(`Количество должно быть числом.`)
if (ctx.args[1] < 1) return ctx.reply(`Минимальное количество для покупки - 1`)
business.balance -= Number(world.matPrice*ctx.args[1])
business.materials += ctx.args[1]
business.save()
return await ctx.reply(`Закуплено ${ctx.args[1]} материалов для организации`)
})
bot.command('percent', async (ctx) => {
ctx.args = ctx.update.message.text.split(' ')
let user = await UserModel.findByPk(ctx.from.id)
let business = await BusinessModel.findOne({
owner: ctx.from.id
})
if (business === null) return await ctx.reply(`У вас нет организации.`)
if (!ctx.args[1] || !ctx.args[2]) return ctx.reply(`Не указан аргумент.`)
if (!Number(ctx.args[2])) return ctx.reply(`Процент должен быть числом от 1 до 100.`)
@ -713,9 +811,11 @@ ${text}
return await ctx.reply(`Участнику ${change.username} установлен процент ${ctx.args[2]}`)
})
bot.command('business', async (ctx) => {
bot.command('business', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id)
let business = await BusinessModel.findOne({owner: ctx.from.id})
let business = await BusinessModel.findOne({
owner: ctx.from.id
})
let world = await WorldModel.findByPk(1)
ctx.args = ctx.update.message.text.split(' ')
if (business !== null) return await ctx.reply(`У вас уже есть организация.`)
@ -725,7 +825,7 @@ ${text}
user.money -= 100000
world.balance += 100000
let text = ``
for (i=1; i<ctx.args.length; i++){
for (i = 1; i < ctx.args.length; i++) {
text += `${ctx.args[i]} `
}
if (business === null) {
@ -746,22 +846,59 @@ ${text}
return await ctx.reply(`Организация "${text}" успешно создана!\n Регистрация организации в реестре: ¤50.000 \n Капитал: ¤50.000`)
})
bot.command('invite', async (ctx) => {
bot.command('invite', async (ctx) => {
ctx.args = ctx.update.message.text.split(' ')
if (!ctx.args[1]) return ctx.reply(`/invite [ID]`)
let user = await UserModel.findByPk(ctx.from.id)
let invited = await UserModel.findOne({ where: { username: ctx.args[1] } });
let invited = await UserModel.findOne({
where: {
username: ctx.args[1]
}
});
await bot.telegram.sendMessage(invited.telegram_id, 'Приглашение', Markup
.inlineKeyboard([
[{text: `Принять ${user.username}`, callback_data: ctx.from.id}, {text: `Отклонить ${user.username}`, callback_data: '0'}]]).oneTime())
[{
text: `Принять ${user.username}`,
callback_data: ctx.from.id
}, {
text: `Отклонить ${user.username}`,
callback_data: '0'
}]
]).oneTime())
return await ctx.reply(`Приглашение отправлено.`)
})
bot.on('callback_query', async ctx => {
bot.command('report', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id)
ctx.args = ctx.update.message.text.split(' ')
if (!ctx.args[1]) return ctx.reply(`/report [Текст обращения]`)
let uID = shortid.generate()
await ReportModel.create({
uid: uID,
author: user.telegram_id,
text: ctx.payload,
status: 1
})
let report = await ReportModel.findOne({
where: {
uid: uID
}
})
await bot.telegram.sendMessage(adminList[0], `Обращение от пользователя ${user.username}\nТекст обращения:\n${ctx.payload}\n\nДля ответа /answer ${report.id} [Ответ]`)
return await ctx.reply(`Обращение #${report.id}[${report.uid}] создано.`)
})
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) {
let business = await BusinessModel.findOne({owner: data})
let business = await BusinessModel.findOne({
owner: data
})
user.business = {
id: data,
checks: 0,
@ -774,28 +911,13 @@ ${text}
} else {
await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `Приглашение отклонено.`)
}
})
})
/////////////////////////////////////Admin Commands//////////////////////////////////////////////////
bot.command('report', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id)
ctx.args = ctx.update.message.text.split(' ')
if (!ctx.args[1]) return ctx.reply(`/report [Текст обращения]`)
let uID = shortid.generate()
await ReportModel.create({
uid: uID,
author: user.telegram_id,
text: ctx.payload,
status: 1
})
let report = await ReportModel.findOne({ where: { uid: uID } })
await bot.telegram.sendMessage(adminList[0], `Обращение от пользователя ${user.username}\nТекст обращения:\n${ctx.payload}\n\nДля ответа /answer ${report.id} [Ответ]`)
return await ctx.reply(`Обращение #${report.id}[${report.uid}] создано.`)
})
bot.command('answer', async (ctx) => {
bot.command('answer', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id)
ctx.args = ctx.update.message.text.split(' ')
if (!ctx.args[1]) return ctx.reply(`Нужен номер обращения`)
@ -812,14 +934,14 @@ ${text}
return await ctx.reply(`Ответ отправлен, обращение закрыто!`)
})
bot.command('fastblock', async (ctx) => {
bot.command('fastblock', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id)
let blocked = ctx.message.reply_to_message.from.id
await BlockModel.create({
telegram_id: blocked,
isBlocked: true,
reason: `|AutoFastBlock|`,
time: Math.trunc(Date.now()/1000 + 3600)
time: Math.trunc(Date.now() / 1000 + 3600)
})
await bot.telegram.sendMessage(blocked, `Вы были заблокированы администратором ${user.username}.`)
return await ctx.reply(`Пользователь заблокирован.`)
@ -827,8 +949,11 @@ ${text}
///////////////////////////////////////Functions//////////////////////////////////////////////////////
function rand(min, max) {return Math.round(Math.random() * (max - min)) + min}
function rand(min, max) {
return Math.round(Math.random() * (max - min)) + min
}
var parserInt = (str) => parseInt(str.replace(/k|к/ig, "000"));
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("");
@ -839,20 +964,20 @@ Array.prototype.random = function() {
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)
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)
}
cooldown.timeLeft = cooldown.endTime - cooldown.currentTime
cooldown.timeLeftInMinutes = Math.ceil((type - cooldown.currentTime)/60)
cooldown.timeLeftInMinutes = Math.ceil((type - cooldown.currentTime) / 60)
return cooldown
}
}
function giveExp(user, experience) {
user.exp += experience
if (user.exp >= expToUp[user.level]){
if (user.exp >= expToUp[user.level]) {
user.level += 1
user.exp = 0
user.save()
@ -866,16 +991,16 @@ function weaponShopUpdate() {
let equipId = []
let drop = 1
let counter = 5
for(i = 0; i < 5; i++){
drop = weaponId.push(rand(1,10))
for (i = 0; i < 5; i++) {
drop = weaponId.push(rand(1, 10))
}
for(i = 0; i < 5; i++){
drop = equipId.push(rand(1,10))
for (i = 0; i < 5; i++) {
drop = equipId.push(rand(1, 10))
}
for(i = 0; i < 5; i++){
for (i = 0; i < 5; i++) {
weaponshop[i] = weapons[weaponId[i]]
}
for(i = 0; i < 5; i++){
for (i = 0; i < 5; i++) {
weaponshop[counter] = equipment[equipId[i]]
counter++
}
@ -885,10 +1010,10 @@ function weaponShopUpdate() {
setInterval(() => {
var today = new Date();
let hours = today.getHours();
if(hours == "0" || hours == "12" || hours == "23"){
if (hours == "0" || hours == "12" || hours == "23") {
weaponShopUpdate()
}
}, 360000);
}, 360000);
weaponShopUpdate()

View File

@ -1,51 +1,51 @@
{
"0": {
"name": "Five-Seven",
"name": "AK-47",
"price": 1000,
"type": "weapon"
},
"1": {
"name": "ПМ",
"price": 1000,
"type": "weapon"
},
"2": {
"name": "Glock",
"price": 1000,
"type": "weapon"
},
"3": {
"name": "M4A1",
"price": 1000,
"type": "weapon"
},
"2": {
"name": "M4A1",
"price": 1000,
"type": "weapon"
},
"3": {
"name": "Five-Seven",
"price": 1000,
"type": "weapon"
},
"4": {
"name": "ПМ",
"name": "M4A1",
"price": 1000,
"type": "weapon"
},
"5": {
"name": "Бронежилет M6",
"name": "Картонные накладки",
"price": 1000,
"type": "equipment"
},
"6": {
"name": "Бронежилет M1",
"price": 1000,
"type": "equipment"
},
"7": {
"name": "Бронежилет M5",
"price": 1000,
"type": "equipment"
},
"7": {
"name": "Бронежилет M6",
"price": 1000,
"type": "equipment"
},
"8": {
"name": "Шлем танкиста",
"name": "Кольчуга",
"price": 1000,
"type": "equipment"
},
"9": {
"name": "Кольчуга",
"name": "Бронежилет M2",
"price": 1000,
"type": "equipment"
}