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

217
index.js
View File

@ -1,5 +1,8 @@
require('dotenv').config() require('dotenv').config()
const { Telegraf, Markup } = require('telegraf') const {
Telegraf,
Markup
} = require('telegraf')
const shortid = require('shortid'); const shortid = require('shortid');
const fs = require('fs') const fs = require('fs')
const bot = new Telegraf(process.env.BOT_TOKEN) const bot = new Telegraf(process.env.BOT_TOKEN)
@ -30,13 +33,30 @@ const start = async () => {
} }
} }
bot.telegram.setMyCommands([ bot.telegram.setMyCommands([{
{command: "pay", description:"Перевести указанному пользователю сумму."}, command: "pay",
{command: "buy", description:"Приобрести указанное имущество."}, description: "Перевести указанному пользователю сумму."
{command: "business", description:"Создать организацию."}, },
{command: "invite", description:"Пригласить пользователя в организацию."}, {
{command: "percent", description:"Установить пользователю процент заработка."}, command: "buy",
{command: "report", description:"Создать жалобу/обращение/идею."} description: "Приобрести указанное имущество."
},
{
command: "business",
description: "Создать организацию."
},
{
command: "invite",
description: "Пригласить пользователя в организацию."
},
{
command: "percent",
description: "Установить пользователю процент заработка."
},
{
command: "report",
description: "Создать жалобу/обращение/идею."
}
]) ])
bot.use(async (ctx, next) => { bot.use(async (ctx, next) => {
@ -87,11 +107,11 @@ bot.command('start', async (ctx) => {
console.log("Exist") console.log("Exist")
} }
} }
return await ctx.reply('Main Menu', Markup return await ctx.reply('Главное меню', Markup
.keyboard([ .keyboard([
['😎 Профиль', '💳 Баланс'], // Row1 with 2 buttons ['😎 Профиль', '💳 Баланс'], // Row1 with 2 buttons
['Работать', 'Бонус'], // Row2 with 2 buttons ['🗄️ Работать', '🎁 Бонус'], // Row2 with 2 buttons
['📢 Вакансии', 'Мир', '📞 Пригласить'] // Row3 with 3 buttons ['📢 Вакансии', '🔵 Имущество', '📞 Пригласить'] // Row3 with 3 buttons
]) ])
.oneTime() .oneTime()
.resize() .resize()
@ -102,8 +122,8 @@ bot.command('start', async (ctx) => {
return await ctx.reply('Main Menu', Markup return await ctx.reply('Main Menu', Markup
.keyboard([ .keyboard([
['😎 Профиль', '💳 Баланс'], // Row1 with 2 buttons ['😎 Профиль', '💳 Баланс'], // Row1 with 2 buttons
['Работать', 'Бонус'], // Row2 with 2 buttons ['🗄️ Работать', '🎁 Бонус'], // Row2 with 2 buttons
['📢 Вакансии', 'Мир', '📞 Пригласить'] // Row3 with 3 buttons ['📢 Вакансии', '🔵 Имущество', '📞 Пригласить'] // Row3 with 3 buttons
]) ])
.oneTime() .oneTime()
.resize() .resize()
@ -150,7 +170,7 @@ bot.command('start', async (ctx) => {
`); `);
}) })
bot.hears('Бонус', async (ctx) => { bot.hears('🎁 Бонус', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id); 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 bonustime = user.bonustime
@ -192,7 +212,11 @@ ${text}
if (!ctx.args[1] || !ctx.args[2]) return ctx.reply(`Не указан аргумент.`) if (!ctx.args[1] || !ctx.args[2]) return ctx.reply(`Не указан аргумент.`)
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 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 world = await WorldModel.findByPk(1)
let fee = Number(Math.trunc(ctx.args[2] / 100 * world.transactionfee)) 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 (ctx.args[2] == 0 || ctx.args[2] < 100) return ctx.reply(`Минимальная сумма перевода ¤100.`)
@ -350,7 +374,7 @@ ${text}
return await ctx.reply(`Вы уже устроены на другую работу`) return await ctx.reply(`Вы уже устроены на другую работу`)
}) })
bot.hears('Работать', async (ctx) => { bot.hears('🗄️ Работать', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id); let user = await UserModel.findByPk(ctx.from.id);
let job = await JobModel.findByPk(user.job); let job = await JobModel.findByPk(user.job);
let world = await WorldModel.findByPk(1) let world = await WorldModel.findByPk(1)
@ -459,7 +483,46 @@ ${text}
if (user.jobcheck == 6) { if (user.jobcheck == 6) {
let paydayfee = job.salary / 100 * world.transactionfee let paydayfee = job.salary / 100 * world.transactionfee
let payday = job.salary - paydayfee 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 -= payday
world.balance -= Number(stealed.price) world.balance -= Number(stealed.price)
user.money += payday user.money += payday
@ -493,7 +556,7 @@ ${text}
} }
}) })
bot.hears('Уволиться', async (ctx) => { bot.hears('💤 Уволиться', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id); let user = await UserModel.findByPk(ctx.from.id);
if (user.job != 0) { if (user.job != 0) {
user.job = 0 user.job = 0
@ -507,7 +570,9 @@ ${text}
let topPlayer = await UserModel.findAll({ let topPlayer = await UserModel.findAll({
attributes: ['username', [sequelize.fn('sum', sequelize.col('money')), 'money']], attributes: ['username', [sequelize.fn('sum', sequelize.col('money')), 'money']],
group: ['username'], group: ['username'],
order: [[sequelize.literal('money'), 'DESC']], order: [
[sequelize.literal('money'), 'DESC']
],
limit: 10 limit: 10
}) })
if (!topPlayer[9]) { if (!topPlayer[9]) {
@ -535,9 +600,14 @@ ${text}
}) })
bot.hears('Имущество', async (ctx) => { bot.hears('🔵 Имущество', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id); 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) => {
@ -630,7 +700,9 @@ ${text}
bot.hears('Организация', async (ctx) => { bot.hears('Организация', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id) 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 (business === null) return await ctx.reply(`У вас нет организации.`)
console.log(business) console.log(business)
return await ctx.reply(`Ваша организация\n${business.name}\nБаланс: ¤${business.balance}\nСырье: ${business.materials}\nРабочих: ${business.users.length}`) return await ctx.reply(`Ваша организация\n${business.name}\nБаланс: ¤${business.balance}\nСырье: ${business.materials}\nРабочих: ${business.users.length}`)
@ -638,16 +710,20 @@ ${text}
bot.hears('Отработка', async (ctx) => { bot.hears('Отработка', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id) 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(`Вы не работаете в организации.`) if (user.business == null) return await ctx.reply(`Вы не работаете в организации.`)
let timer = user.worktime let timer = user.worktime
let cooldown = setCooldown(user, 3600, timer) 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 = { user.business = {
id: user.business.id, id: user.business.id,
checks: user.business.checks + 1, checks: user.business.checks + 1,
percent: user.business.percent percent: user.business.percent
} }
business.materials -= 10
business.checks += 1 business.checks += 1
await user.save() await user.save()
await business.save() await business.save()
@ -656,7 +732,9 @@ ${text}
bot.hears('Payday', async (ctx) => { bot.hears('Payday', async (ctx) => {
let user = null 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) let world = await WorldModel.findByPk(1)
if (business === null) return await ctx.reply(`У вас нет организации.`) if (business === null) return await ctx.reply(`У вас нет организации.`)
if (business.checks < 12) return await ctx.reply(`Недостаточно отработок для формирования выплаты.`) if (business.checks < 12) return await ctx.reply(`Недостаточно отработок для формирования выплаты.`)
@ -684,21 +762,41 @@ ${text}
piece = Math.round(profit / 100 * user.business.percent) piece = Math.round(profit / 100 * user.business.percent)
profitCheck -= piece profitCheck -= piece
user.money += piece user.money += piece
giveExp(user, business.checks)
user.save() user.save()
text += `${user.username} получает ¤${piece}\nОстаток выплат: ¤${profitCheck}\n` text += `${user.username} получает ¤${piece}\nОстаток выплат: ¤${profitCheck}\n`
} }
if (profitCheck > 0) { if (profitCheck > 0) {
business.balance += profitCheck business.balance += profitCheck
business.save()
text += `На баланс бизнеса поступило ¤${profitCheck}` text += `На баланс бизнеса поступило ¤${profitCheck}`
} }
business.checks = 0
business.save()
return await ctx.reply(text) return await ctx.reply(text)
}) })
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
})
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) => { bot.command('percent', async (ctx) => {
ctx.args = ctx.update.message.text.split(' ') ctx.args = ctx.update.message.text.split(' ')
let user = await UserModel.findByPk(ctx.from.id) 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 (business === null) return await ctx.reply(`У вас нет организации.`)
if (!ctx.args[1] || !ctx.args[2]) return ctx.reply(`Не указан аргумент.`) if (!ctx.args[1] || !ctx.args[2]) return ctx.reply(`Не указан аргумент.`)
if (!Number(ctx.args[2])) return ctx.reply(`Процент должен быть числом от 1 до 100.`) if (!Number(ctx.args[2])) return ctx.reply(`Процент должен быть числом от 1 до 100.`)
@ -715,7 +813,9 @@ ${text}
bot.command('business', async (ctx) => { bot.command('business', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id) 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) let world = await WorldModel.findByPk(1)
ctx.args = ctx.update.message.text.split(' ') ctx.args = ctx.update.message.text.split(' ')
if (business !== null) return await ctx.reply(`У вас уже есть организация.`) if (business !== null) return await ctx.reply(`У вас уже есть организация.`)
@ -750,18 +850,55 @@ ${text}
ctx.args = ctx.update.message.text.split(' ') ctx.args = ctx.update.message.text.split(' ')
if (!ctx.args[1]) return ctx.reply(`/invite [ID]`) if (!ctx.args[1]) return ctx.reply(`/invite [ID]`)
let user = await UserModel.findByPk(ctx.from.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 await bot.telegram.sendMessage(invited.telegram_id, 'Приглашение', Markup
.inlineKeyboard([ .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(`Приглашение отправлено.`) return await ctx.reply(`Приглашение отправлено.`)
}) })
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 => { bot.on('callback_query', async ctx => {
const data = ctx.update.callback_query.data; const data = ctx.update.callback_query.data;
let user = await UserModel.findByPk(ctx.update.callback_query.from.id) let user = await UserModel.findByPk(ctx.update.callback_query.from.id)
if (data != 0) { if (data != 0) {
let business = await BusinessModel.findOne({owner: data}) let business = await BusinessModel.findOne({
owner: data
})
user.business = { user.business = {
id: data, id: data,
checks: 0, checks: 0,
@ -779,21 +916,6 @@ ${text}
/////////////////////////////////////Admin Commands////////////////////////////////////////////////// /////////////////////////////////////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) let user = await UserModel.findByPk(ctx.from.id)
@ -827,8 +949,11 @@ ${text}
///////////////////////////////////////Functions////////////////////////////////////////////////////// ///////////////////////////////////////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")); var parserInt = (str) => parseInt(str.replace(/k|к/ig, "000"));
function spaces(string) { function spaces(string) {
if (typeof string !== "string") string = string.toString(); if (typeof string !== "string") string = string.toString();
return string.split("").reverse().join("").match(/[0-9]{1,3}/g).join(".").split("").reverse().join(""); return string.split("").reverse().join("").match(/[0-9]{1,3}/g).join(".").split("").reverse().join("");

View File

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