global refactoring
Все переведено в модули
This commit is contained in:
parent
79b8b4939e
commit
baa0b5f3a9
407
bot.js
Normal file
407
bot.js
Normal file
@ -0,0 +1,407 @@
|
||||
require('dotenv').config()
|
||||
const {
|
||||
Telegraf,
|
||||
Scenes,
|
||||
session,
|
||||
Stage,
|
||||
Markup
|
||||
} = require('telegraf')
|
||||
const {
|
||||
weaponshop,
|
||||
slots,
|
||||
rarecars,
|
||||
simplecars,
|
||||
houses,
|
||||
cars,
|
||||
phones,
|
||||
weapons,
|
||||
equipment,
|
||||
UserModel,
|
||||
WorldModel,
|
||||
JobModel,
|
||||
PropertyModel,
|
||||
BusinessModel,
|
||||
ReportModel,
|
||||
BlockModel,
|
||||
PromocodeModel,
|
||||
mainChat,
|
||||
adminList,
|
||||
expToUp,
|
||||
topSym
|
||||
} = require('./config')
|
||||
const {
|
||||
profile,
|
||||
bonus,
|
||||
pay,
|
||||
getprofile,
|
||||
menu,
|
||||
worldMenu,
|
||||
referal,
|
||||
jobs,
|
||||
chooseJob,
|
||||
casinoMenu,
|
||||
work,
|
||||
top,
|
||||
propertyList,
|
||||
propertyMenu,
|
||||
propertyBuy,
|
||||
propertySell,
|
||||
hatkeisList,
|
||||
organizationMenu,
|
||||
workoff,
|
||||
leaveOrg,
|
||||
leaveOrgAccept,
|
||||
payday,
|
||||
orgMessage,
|
||||
materialsBuy,
|
||||
percentSet,
|
||||
invite,
|
||||
inviteAction,
|
||||
report,
|
||||
slotsMenu,
|
||||
slotsRun,
|
||||
promocodeActivate,
|
||||
carContainers,
|
||||
chooseContainer,
|
||||
reportAnswer,
|
||||
fastblock,
|
||||
createPromo,
|
||||
genPromo,
|
||||
organizationCreate
|
||||
} = require('./commands')
|
||||
const {
|
||||
spaces,
|
||||
spacesWithMarkdown,
|
||||
escape,
|
||||
generatePromo,
|
||||
generateVoucher,
|
||||
getCurrentTime,
|
||||
getSlot,
|
||||
giveExp,
|
||||
matPriceUpdate,
|
||||
rand,
|
||||
random,
|
||||
setCooldown,
|
||||
weaponShopUpdate,
|
||||
stats
|
||||
} = require('./utils')
|
||||
const {
|
||||
handleError
|
||||
} = require('./handlers')
|
||||
const crimeScene = require("./scenes/crime");
|
||||
const heistScene = require("./scenes/heist");
|
||||
const sequelize = require('./db');
|
||||
const { Op } = require('sequelize');
|
||||
const fs = require('fs');
|
||||
const { createCanvas, loadImage } = require('canvas');
|
||||
const shortid = require('shortid');
|
||||
const voucher_codes = require('voucher-code-generator');
|
||||
const bot = new Telegraf(process.env.BOT_TOKEN)
|
||||
const stage = new Scenes.Stage([crimeScene, heistScene]);
|
||||
|
||||
const start = async () => {
|
||||
try {
|
||||
await sequelize.authenticate()
|
||||
await sequelize.sync()
|
||||
} catch (e) {
|
||||
console.log('Подключение к бд сломалось', e)
|
||||
}
|
||||
}
|
||||
|
||||
bot.telegram.setMyCommands([{
|
||||
command: "pay",
|
||||
description: "Перевести указанному пользователю сумму."
|
||||
},
|
||||
{
|
||||
command: "buy",
|
||||
description: "Приобрести указанное имущество."
|
||||
},
|
||||
{
|
||||
command: "business",
|
||||
description: "Создать организацию."
|
||||
},
|
||||
{
|
||||
command: "invite",
|
||||
description: "Пригласить пользователя в организацию."
|
||||
},
|
||||
{
|
||||
command: "percent",
|
||||
description: "Установить пользователю процент заработка."
|
||||
},
|
||||
{
|
||||
command: "report",
|
||||
description: "Создать жалобу/обращение/идею."
|
||||
}
|
||||
])
|
||||
|
||||
bot.use(session({ collectionName: 'sessions' }));
|
||||
bot.use(stage.middleware())
|
||||
bot.use(stats)
|
||||
|
||||
bot.use(async (ctx, next) => {
|
||||
bot.context.config = require('./ctxconfig.json')
|
||||
let id = ctx.from.id
|
||||
let username = ctx.from.username
|
||||
if(username == null) username = ctx.from.id
|
||||
switch(ctx.updateType){
|
||||
case `message`:
|
||||
console.log(getCurrentTime() + `: ` + username + `: ` + ctx.update.message.text)
|
||||
break;
|
||||
case `callback_query`:
|
||||
console.log(getCurrentTime() + `: ${username}: ${ctx.update.callback_query.data}`)
|
||||
break;
|
||||
default:
|
||||
console.log(ctx)
|
||||
}
|
||||
let user = await UserModel.findByPk(id);
|
||||
let block = await BlockModel.findByPk(id);
|
||||
let property = await PropertyModel.findByPk(id);
|
||||
if (!user) ctx.reply(`❕ Первичная регистрация профиля.`);
|
||||
if (user === null) {
|
||||
await UserModel.create({
|
||||
telegram_id: id,
|
||||
username: username,
|
||||
name: ctx.from.first_name
|
||||
})
|
||||
} else {
|
||||
user.name = ctx.from.first_name
|
||||
if(user.username === null) user.username = ctx.from.id
|
||||
user.save()
|
||||
}
|
||||
if (property === null) {
|
||||
await PropertyModel.create({
|
||||
telegram_id: id
|
||||
})
|
||||
} 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)} мин.`)
|
||||
block.isBlocked = false
|
||||
block.save()
|
||||
}
|
||||
const start = Date.now()
|
||||
const timeoutPromise = new Promise((resolve, reject) => {
|
||||
|
||||
setTimeout(() => {
|
||||
reject(new Error('timeout'))
|
||||
}, 1000 * 5)
|
||||
})
|
||||
|
||||
const nextPromise = next()
|
||||
.then(() => {
|
||||
const ms = Date.now() - start
|
||||
})
|
||||
.catch((error) => {
|
||||
handleError(error, ctx)
|
||||
})
|
||||
|
||||
return Promise.race([timeoutPromise, nextPromise])
|
||||
.catch((error) => {
|
||||
if (error.message === 'timeout') {
|
||||
console.error('timeout', ctx.update)
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
})
|
||||
|
||||
})
|
||||
|
||||
bot.command('start', async (ctx) => {
|
||||
if (ctx.payload) {
|
||||
let id = ctx.from.id
|
||||
let user = await UserModel.findByPk(id);
|
||||
if (user.level == 1) {
|
||||
let ref = await UserModel.findByPk(ctx.payload)
|
||||
let world = await WorldModel.findByPk(1)
|
||||
world.balance -= 25000
|
||||
ref.money += Number(25000)
|
||||
await ref.save()
|
||||
await world.save()
|
||||
bot.telegram.sendMessage(ref.telegram_id, `${ctx.from.username} зарегистрировался по вашей реферальной ссылке. Получено ¤25.000`)
|
||||
console.log("Transaction to Ref")
|
||||
} else {
|
||||
console.log("Exist")
|
||||
}
|
||||
}
|
||||
return await ctx.reply('Главное меню', Markup
|
||||
.keyboard([
|
||||
['😎 Профиль'], // Row1 with 2 buttons
|
||||
['🗄️ Работать', '🌐 Организация', '🎁 Бонус', '🏯 Казино'], // Row2 with 2 buttons
|
||||
['📦 Контейнеры'],
|
||||
['📢 Вакансии', '🔵 Имущество', '📞 Пригласить'] // Row3 with 3 buttons
|
||||
])
|
||||
.resize()
|
||||
)
|
||||
})
|
||||
|
||||
bot.hears('Криминал', async (ctx) => {
|
||||
await ctx.scene.enter('Crime')
|
||||
})
|
||||
|
||||
|
||||
bot.hears('промка', async(ctx) => {
|
||||
generatePromo()
|
||||
});
|
||||
|
||||
bot.hears('▶️ Меню', menu);
|
||||
|
||||
bot.hears('Чат', async (ctx) => {
|
||||
ctx.reply(`${ctx.message.chat.id}`)
|
||||
});
|
||||
|
||||
bot.hears('😎 Профиль', profile);
|
||||
|
||||
bot.command('getprofile', getprofile);
|
||||
|
||||
bot.hears('Рандом', async (ctx) => {
|
||||
let users = await UserModel.findAll();
|
||||
let chosenOne = users.random()
|
||||
return ctx.reply(`
|
||||
👤 ${chosenOne.username}
|
||||
🆔: ${chosenOne.telegram_id}
|
||||
`);
|
||||
|
||||
});
|
||||
|
||||
bot.hears('💳 Баланс', async (ctx) => {
|
||||
let user = await UserModel.findByPk(ctx.from.id);
|
||||
return ctx.reply(`
|
||||
⏩ Аккаунт игрока ${user.username}
|
||||
🆔 Игрока: ${user.telegram_id}
|
||||
|
||||
📶 Уровень: ${user.level}
|
||||
⏩ Повышается за различные действия.
|
||||
|
||||
💰 Баланс:
|
||||
¤${user.money}
|
||||
`);
|
||||
})
|
||||
|
||||
bot.hears('🎁 Бонус', bonus)
|
||||
|
||||
bot.command('pay', pay)
|
||||
|
||||
bot.hears('Мир', worldMenu)
|
||||
|
||||
bot.hears('📞 Пригласить', referal)
|
||||
|
||||
bot.hears('📢 Вакансии', jobs)
|
||||
|
||||
bot.action(/job_(1|2|3|4|5|6|7|leave)/, chooseJob)
|
||||
|
||||
bot.hears('🏯 Казино', casinoMenu)
|
||||
|
||||
bot.hears('🗄️ Работать', work)
|
||||
|
||||
bot.hears('Топ', top)
|
||||
|
||||
bot.hears('🔵 Имущество', propertyMenu)
|
||||
|
||||
bot.action('shopmenu', propertyMenu)
|
||||
|
||||
bot.action(/shop_(house|phone|car)/, propertyList)
|
||||
|
||||
bot.action(/{"action": "buy"*/, propertyBuy)
|
||||
|
||||
bot.hears('Поставщик', hatkeisList)
|
||||
|
||||
bot.command('sell', propertySell)
|
||||
|
||||
bot.hears('🌐 Организация', organizationMenu)
|
||||
|
||||
bot.action('workoff', workoff)
|
||||
|
||||
bot.action('покинуть', leaveOrg)
|
||||
|
||||
bot.action('cancel', async (ctx) => {
|
||||
await ctx.deleteMessage()
|
||||
await bot.telegram.answerCbQuery(ctx.callbackQuery.id, `Отмена.`)
|
||||
})
|
||||
|
||||
bot.action('user_leave_business', leaveOrgAccept)
|
||||
|
||||
bot.action('payday', payday)
|
||||
|
||||
bot.command('orgmessage', orgMessage)
|
||||
|
||||
bot.command('materials', materialsBuy)
|
||||
|
||||
bot.command('percent', percentSet)
|
||||
|
||||
bot.command('business', organizationCreate)
|
||||
|
||||
bot.command('invite', invite)
|
||||
|
||||
bot.action(/{"type": "business_invite_(accept|refuse)"*/, inviteAction)
|
||||
|
||||
bot.command('report', report)
|
||||
|
||||
bot.hears('🎰 Слоты', slotsMenu)
|
||||
|
||||
bot.action(/slots(1000|5000|25000|50000|100000)/, slotsRun)
|
||||
|
||||
bot.hears('Помощь', async (ctx) => {
|
||||
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', promocodeActivate)
|
||||
|
||||
bot.hears('📦 Контейнеры', carContainers)
|
||||
|
||||
bot.action(/container_(1|2|3|4|5|6|7|8|9|10)/, chooseContainer)
|
||||
|
||||
bot.action(/{"action": "sueta_*/, async (ctx) => {
|
||||
let data = ctx.update.callback_query.data;
|
||||
data = JSON.parse(data)
|
||||
console.log(data.car)
|
||||
let user = await UserModel.findByPk(ctx.from.id)
|
||||
let property = await PropertyModel.findByPk(ctx.from.id)
|
||||
switch(data.action){
|
||||
case `sueta_accept`:
|
||||
user.money += data.carprice
|
||||
await ctx.editMessageText(`➕ ${data.carprice}`)
|
||||
break;
|
||||
case `sueta_refuse`:
|
||||
user.money += Math.round(property.car.price/2)
|
||||
property.car = {
|
||||
name: data.carname,
|
||||
price: data.carprice
|
||||
}
|
||||
await ctx.editMessageText(`➕ ${data.carname}`)
|
||||
break;
|
||||
}
|
||||
user.save()
|
||||
property.save()
|
||||
})
|
||||
/////////////////////////////////////Admin Commands//////////////////////////////////////////////////
|
||||
|
||||
|
||||
bot.command('answer', reportAnswer)
|
||||
|
||||
bot.command('fastblock', fastblock)
|
||||
|
||||
bot.command('createpromocode', createPromo)
|
||||
|
||||
bot.command('genpromo', genPromo)
|
||||
|
||||
///////////////////////////////////////Functions//////////////////////////////////////////////////////
|
||||
|
||||
setInterval(() => {
|
||||
generatePromo()
|
||||
}, 18000000);
|
||||
|
||||
setInterval(() => {
|
||||
var today = new Date();
|
||||
let hours = today.getHours();
|
||||
if (hours == "0" || hours == "12") {
|
||||
weaponShopUpdate()
|
||||
matPriceUpdate()
|
||||
}
|
||||
}, 360000);
|
||||
|
||||
start()
|
||||
|
||||
bot.launch()
|
29
commands/admin/createPromo.js
Normal file
29
commands/admin/createPromo.js
Normal file
@ -0,0 +1,29 @@
|
||||
const {
|
||||
UserModel,
|
||||
PromocodeModel
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
const {
|
||||
generateVoucher
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/utils')
|
||||
|
||||
module.exports = 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] || !ctx.args[2] || !ctx.args[3]) return ctx.reply(`/createpromo [activations] [money] [code]`)
|
||||
let promocode = await PromocodeModel.findOne({
|
||||
where: {
|
||||
code: ctx.args[3]
|
||||
}
|
||||
})
|
||||
if(promocode === null){
|
||||
await PromocodeModel.create({
|
||||
code: ctx.args[3],
|
||||
activations: ctx.args[1],
|
||||
money: ctx.args[2]
|
||||
})
|
||||
let voucherImage = await generateVoucher(ctx.args[3], ctx.args[1], ctx.args[2])
|
||||
console.log(voucherImage)
|
||||
return await ctx.sendPhoto({source: voucherImage, caption: `Создан промокод ${ctx.args[3]}` })
|
||||
}
|
||||
}
|
23
commands/admin/fastblock.js
Normal file
23
commands/admin/fastblock.js
Normal file
@ -0,0 +1,23 @@
|
||||
const {
|
||||
Telegraf
|
||||
} = require('telegraf')
|
||||
const bot = new Telegraf(process.env.BOT_TOKEN)
|
||||
const {
|
||||
UserModel,
|
||||
BlockModel
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
|
||||
module.exports = 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(user.status != 'admin') return await ctx.reply(`Admin Only.`)
|
||||
await BlockModel.create({
|
||||
telegram_id: blocked,
|
||||
isBlocked: true,
|
||||
reason: `|AutoFastBlock|`,
|
||||
time: Math.trunc(Date.now() / 1000 + 3600)
|
||||
})
|
||||
await bot.telegram.sendMessage(blocked, `Вы были заблокированы администратором ${user.username}.`)
|
||||
return await ctx.reply(`Пользователь заблокирован.`)
|
||||
}
|
36
commands/admin/genPromo.js
Normal file
36
commands/admin/genPromo.js
Normal file
@ -0,0 +1,36 @@
|
||||
const voucher_codes = require('voucher-code-generator');
|
||||
const {
|
||||
UserModel,
|
||||
PromocodeModel
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
const {
|
||||
generateVoucher
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/utils')
|
||||
|
||||
module.exports = 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] || !ctx.args[2]) return ctx.reply(`/genpromo [activations] [money]`)
|
||||
let code = voucher_codes.generate({
|
||||
length: 6,
|
||||
count: 1,
|
||||
prefix: "CMP-",
|
||||
postfix: "-FIRE",
|
||||
charset: voucher_codes.charset("alphanumeric")
|
||||
});
|
||||
let promocode = await PromocodeModel.findOne({
|
||||
where: {
|
||||
code: code[0]
|
||||
}
|
||||
})
|
||||
if(promocode === null){
|
||||
await PromocodeModel.create({
|
||||
code: code[0],
|
||||
activations: ctx.args[1],
|
||||
money: ctx.args[2]
|
||||
})
|
||||
let voucherImage = await generateVoucher(code, ctx.args[1], ctx.args[2])
|
||||
return await ctx.sendPhoto({source: voucherImage, caption: `Создан промокод ${code[0]}` })
|
||||
}
|
||||
}
|
26
commands/admin/reportAnswer.js
Normal file
26
commands/admin/reportAnswer.js
Normal file
@ -0,0 +1,26 @@
|
||||
const {
|
||||
Telegraf
|
||||
} = require('telegraf')
|
||||
const bot = new Telegraf(process.env.BOT_TOKEN)
|
||||
const {
|
||||
UserModel,
|
||||
ReportModel
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
|
||||
module.exports = 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])
|
||||
if (report === null) return await ctx.reply(`Нет обращения с таким ID.`)
|
||||
if (report.status == 0) return await ctx.reply(`Данное обращение уже закрыто.`)
|
||||
let answer = ctx.args
|
||||
answer.shift()
|
||||
answer.shift()
|
||||
answer = answer.join(' ')
|
||||
await bot.telegram.sendMessage(report.author, `Ответ на обращение #${report.id}[${report.uid}]\n\n` + answer)
|
||||
report.status = 0
|
||||
report.save()
|
||||
return await ctx.reply(`Ответ отправлен, обращение закрыто!`)
|
||||
}
|
89
commands/bonus.js
Normal file
89
commands/bonus.js
Normal file
@ -0,0 +1,89 @@
|
||||
const {
|
||||
UserModel,
|
||||
WorldModel,
|
||||
BusinessModel
|
||||
} = require('../config')
|
||||
const {
|
||||
rand,
|
||||
setCooldown
|
||||
} = require('../utils')
|
||||
|
||||
module.exports = async (ctx) => {
|
||||
let user = await UserModel.findByPk(ctx.from.id);
|
||||
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} минут(у/ы)`);
|
||||
user.bonus = 1;
|
||||
user.bonustime = cooldown.endTime
|
||||
let world = await WorldModel.findByPk(1)
|
||||
let text = ``;
|
||||
let money = [100, 200, 300, 400, 500, 1000].random();
|
||||
if (user.level >= 5) {
|
||||
money += money;
|
||||
}
|
||||
let r = rand(1, 2);
|
||||
let x = rand(2, 7);
|
||||
if (r == 1) {
|
||||
text += `⏩ ₽${money}\n`;
|
||||
}
|
||||
if (r == 2) {
|
||||
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){
|
||||
await user.save();
|
||||
await world.save();
|
||||
return ctx.reply(`
|
||||
⭐ Из ежечасного бонуса Вам выпало:
|
||||
${text}
|
||||
`)
|
||||
}
|
||||
let business = await BusinessModel.findOne({
|
||||
where: {
|
||||
owner: user.business.id.toString()
|
||||
}
|
||||
})
|
||||
if(business != null){
|
||||
let mats = rand(3, 10)
|
||||
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 += Number(mats)
|
||||
business.save()
|
||||
}
|
||||
await user.save();
|
||||
await world.save();
|
||||
return ctx.reply(`
|
||||
⭐ Из ежечасного бонуса Вам выпало:
|
||||
${text}
|
||||
`)
|
||||
}
|
32
commands/carcantainers/chooseContainer.js
Normal file
32
commands/carcantainers/chooseContainer.js
Normal file
@ -0,0 +1,32 @@
|
||||
const {
|
||||
rarecars,
|
||||
simplecars,
|
||||
UserModel,
|
||||
PropertyModel
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
const {
|
||||
spaces
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/utils')
|
||||
|
||||
module.exports = async (ctx) => {
|
||||
let data = ctx.update.callback_query.data;
|
||||
let user = await UserModel.findByPk(ctx.from.id)
|
||||
let property = await PropertyModel.findByPk(ctx.from.id)
|
||||
if(user.money < 500000) return ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `Открытие контейнера стоит ₽500.000`, {show_alert: true})
|
||||
if(property.car.name) return ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `У вас уже есть автомобиль\nПродайте текущий автомобиль: /sell car`, {show_alert: true})
|
||||
user.money -= 500000
|
||||
let userWin = null
|
||||
switch(data){
|
||||
case `container_7`:
|
||||
userWin = rarecars.random()
|
||||
break;
|
||||
default:
|
||||
userWin = simplecars.random()
|
||||
break;
|
||||
}
|
||||
property.car = userWin
|
||||
user.save()
|
||||
property.save()
|
||||
ctx.deleteMessage()
|
||||
return await ctx.sendPhoto(userWin.image, { caption: `В контейнере была: ${userWin.name} стоимостью ₽${spaces(userWin.price)}`})
|
||||
}
|
30
commands/carcantainers/containersMenu.js
Normal file
30
commands/carcantainers/containersMenu.js
Normal file
@ -0,0 +1,30 @@
|
||||
const {
|
||||
UserModel
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
|
||||
module.exports = async (ctx) => {
|
||||
let user = await UserModel.findByPk(ctx.from.id)
|
||||
let containers = []
|
||||
let values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
||||
let oneValue = []
|
||||
for(i = 0; i < 10; i++){
|
||||
oneValue = values.random()
|
||||
values = values.filter(value => value != oneValue);
|
||||
containers.push({name: `📦 Контейнер ${i+1}`, value: oneValue})
|
||||
}
|
||||
let keyboardButtons = containers.map(container => {
|
||||
return {text: container.name, callback_data: `container_${container.value}`}
|
||||
})
|
||||
let rows = []
|
||||
while (keyboardButtons.length > 0) {
|
||||
rows.push(keyboardButtons.splice(0, 2)) // разбиваем на подмассивы по 5 кнопок
|
||||
}
|
||||
console.log(containers)
|
||||
await ctx.replyWithMarkdownV2('[Sueta Logistic International](https://telegra.ph/OOO-Sueta-Logistic-International-09-27)\nДоступные контейнеры в порту:',
|
||||
{
|
||||
reply_markup: {
|
||||
inline_keyboard: rows
|
||||
},
|
||||
disable_web_page_preview: true
|
||||
})
|
||||
}
|
13
commands/casino/casinoMenu.js
Normal file
13
commands/casino/casinoMenu.js
Normal file
@ -0,0 +1,13 @@
|
||||
const {
|
||||
Markup
|
||||
} = require('telegraf')
|
||||
|
||||
module.exports = async (ctx) => {
|
||||
return await ctx.reply('🏯 Добро пожаловать в казино "杜明"\n', Markup
|
||||
.keyboard([
|
||||
['🎰 Слоты'],
|
||||
['▶️ Меню']
|
||||
])
|
||||
.resize()
|
||||
)
|
||||
}
|
68
commands/casino/slots.js
Normal file
68
commands/casino/slots.js
Normal file
@ -0,0 +1,68 @@
|
||||
const {
|
||||
slots,
|
||||
UserModel,
|
||||
WorldModel
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
const {
|
||||
spaces,
|
||||
getSlot,
|
||||
giveExp,
|
||||
setCooldown
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/utils')
|
||||
|
||||
module.exports = async (ctx) => {
|
||||
let data = ctx.update.callback_query.data;
|
||||
let bet = 1000
|
||||
switch(data){
|
||||
case `slots1000`:
|
||||
bet = 1000
|
||||
break;
|
||||
case `slots5000`:
|
||||
bet = 5000
|
||||
break;
|
||||
case `slots25000`:
|
||||
bet = 25000
|
||||
break;
|
||||
case `slots50000`:
|
||||
bet = 50000
|
||||
break;
|
||||
case `slots100000`:
|
||||
bet = 100000
|
||||
break;
|
||||
}
|
||||
let user = await UserModel.findByPk(ctx.from.id)
|
||||
let timer = user.slottime
|
||||
let cooldown = setCooldown(user, 10, timer)
|
||||
if (user.slottime > cooldown.currentTime) return ctx.reply(`📛 Слоты будут доступны через пару секунд`);
|
||||
if (user.money < bet) return ctx.reply(`Недостаточно средств.`)
|
||||
user.slottime = cooldown.endTime
|
||||
let world = await WorldModel.findByPk(1)
|
||||
let result = await ctx.replyWithDice({emoji: `🎰`})
|
||||
let slot = slots[result.dice.value]
|
||||
let win = getSlot(result)
|
||||
console.log(user.username + `: Win: x` + win)
|
||||
user.money -= bet
|
||||
world.balance += bet
|
||||
if(win > 4){
|
||||
user.world -= bet*win
|
||||
user.money += bet*win
|
||||
user.save()
|
||||
world.save()
|
||||
return setTimeout(() => {
|
||||
ctx.reply(`➕ Вы выиграли ₽${spaces(bet*win)}`)
|
||||
}, 1700);
|
||||
}
|
||||
if(win > 0 && win <= 4){
|
||||
await giveExp(user, win*2)
|
||||
return setTimeout(() => {
|
||||
ctx.reply(`➕ Вы выиграли ${win*2} опыта.`)
|
||||
}, 1700);
|
||||
}
|
||||
if(win == 0){
|
||||
return setTimeout(() => {
|
||||
world.save()
|
||||
user.save()
|
||||
ctx.reply(`➖ Вы проиграли ₽${spaces(bet)}.`)
|
||||
}, 1700);
|
||||
}
|
||||
}
|
30
commands/casino/slotsMenu.js
Normal file
30
commands/casino/slotsMenu.js
Normal file
@ -0,0 +1,30 @@
|
||||
const {
|
||||
Markup
|
||||
} = require('telegraf')
|
||||
const {
|
||||
UserModel
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
|
||||
module.exports = async (ctx) => {
|
||||
let user = await UserModel.findByPk(ctx.from.id)
|
||||
ctx.args = ctx.update.message.text.split(' ')
|
||||
await ctx.reply('Комбинации слотов:\n7️⃣7️⃣7️⃣ - x25\n🍋🍋🍋 - x20\n🍇🍇🍇 - x15\n🔤🔤🔤 - x10', Markup
|
||||
.inlineKeyboard([
|
||||
[{
|
||||
text: `1000`,
|
||||
callback_data: `slots1000`
|
||||
}, {
|
||||
text: `5000`,
|
||||
callback_data: `slots5000`
|
||||
}, {
|
||||
text: `25000`,
|
||||
callback_data: `slots25000`
|
||||
}, {
|
||||
text: `50000`,
|
||||
callback_data: `slots50000`
|
||||
}, {
|
||||
text: `100000`,
|
||||
callback_data: `slots100000`
|
||||
}]
|
||||
]))
|
||||
}
|
67
commands/erase.js
Normal file
67
commands/erase.js
Normal file
@ -0,0 +1,67 @@
|
||||
const {
|
||||
Telegraf,
|
||||
Scenes,
|
||||
session,
|
||||
Stage,
|
||||
Markup
|
||||
} = require('telegraf')
|
||||
const {
|
||||
weaponshop,
|
||||
slots,
|
||||
rarecars,
|
||||
simplecars,
|
||||
houses,
|
||||
cars,
|
||||
phones,
|
||||
weapons,
|
||||
equipment,
|
||||
UserModel,
|
||||
WorldModel,
|
||||
JobModel,
|
||||
PropertyModel,
|
||||
BusinessModel,
|
||||
ReportModel,
|
||||
BlockModel,
|
||||
PromocodeModel,
|
||||
mainChat,
|
||||
adminList,
|
||||
expToUp,
|
||||
topSym
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
const {
|
||||
spaces,
|
||||
spacesWithMarkdown,
|
||||
escape,
|
||||
generatePromo,
|
||||
generateVoucher,
|
||||
getCurrentTime,
|
||||
getSlot,
|
||||
giveExp,
|
||||
matPriceUpdate,
|
||||
rand,
|
||||
random,
|
||||
setCooldown,
|
||||
weaponShopUpdate,
|
||||
stats
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/utils')
|
||||
|
||||
module.exports = async (ctx) => {
|
||||
// Получаем контекст canvas
|
||||
const canvas = ctx.update.callback_query.message.photo[0].file_id;
|
||||
const ctx = new Canvas(cardWidth, cardHeight);
|
||||
|
||||
// Увеличиваем координаты верхнего слоя
|
||||
topLayerX += 10;
|
||||
topLayerY += 10;
|
||||
|
||||
// Отправляем обновленную карточку
|
||||
ctx.replyWithPhoto({ source: canvas.toBuffer() }, Markup.inlineKeyboard([
|
||||
Markup.callbackButton('Стереть', 'erase'),
|
||||
]).extra());
|
||||
|
||||
// Проверяем, достиг ли верхний слой края карточки
|
||||
if (topLayerX + cardWidth > cardWidth) {
|
||||
// Отправляем сообщение с выигрышем
|
||||
ctx.reply('Поздравляю, вы выиграли!');
|
||||
}
|
||||
}
|
33
commands/getprofile.js
Normal file
33
commands/getprofile.js
Normal file
@ -0,0 +1,33 @@
|
||||
const {
|
||||
UserModel,
|
||||
PropertyModel,
|
||||
expToUp
|
||||
} = require('../config')
|
||||
const {
|
||||
spacesWithMarkdown,
|
||||
escape
|
||||
} = require('../utils')
|
||||
|
||||
module.exports = async (ctx) => {
|
||||
if(!ctx.message.reply_to_message) return await ctx.reply(`Только на пересланное сообщение.`)
|
||||
let id = ctx.message.reply_to_message.from.id
|
||||
let user = await UserModel.findByPk(id);
|
||||
let property = await PropertyModel.findByPk(id);
|
||||
return ctx.replyWithMarkdownV2(`
|
||||
👤${escape(user.username)} ${user.status == 'bronze' ? `\\[🔺\\]` : ""}${user.status == 'silver' ? `\\[🔹\\]` : ""}${user.status == 'gold' ? `\\[🔸\\]` : ""}${user.status == 'admin' ? "✅" : ""}
|
||||
🆔: ${ctx.from.id}
|
||||
|
||||
📶 Уровень: ${user.level} \\| ${user.exp} / ${expToUp[user.level]}
|
||||
⏩ Повышается за различные действия\\.
|
||||
|
||||
💰 Баланс
|
||||
₽${spacesWithMarkdown(user.money)}
|
||||
|
||||
🔵 Имущество
|
||||
🏠 Жилье: ${property.house == 0 ? "Бездомный" : property.house.name}
|
||||
🚗 Автомобиль: ${property.car == 0 ? "Пешком" : escape(property.car.name)}
|
||||
📱 Телефон: ${property.mobile == 0 ? "Нет" : property.mobile.name}
|
||||
🔫 Оружие: ${property.weapon == 0 ? "Безоружный" : property.weapon.name}
|
||||
🥼 Экипировка: ${property.equipment == 0 ? "Нет" : property.equipment.name}
|
||||
`);
|
||||
}
|
40
commands/index.js
Normal file
40
commands/index.js
Normal file
@ -0,0 +1,40 @@
|
||||
module.exports = {
|
||||
profile: require('./profile'),
|
||||
bonus: require('./bonus'),
|
||||
menu: require('./menu'),
|
||||
getprofile: require('./getprofile'),
|
||||
pay: require('./pay'),
|
||||
worldMenu: require('./world'),
|
||||
referal: require('./invite'),
|
||||
jobs: require('./jobs/jobs'),
|
||||
chooseJob: require('./jobs/chooseJob'),
|
||||
casinoMenu: require('./casino/casinoMenu'),
|
||||
work: require('./jobs/work'),
|
||||
top: require('./top'),
|
||||
propertyMenu: require('./property/propertyMenu'),
|
||||
propertyList: require('./property/propertyList'),
|
||||
propertyBuy: require('./property/propertyBuy'),
|
||||
hatkeisList: require('./property/hatkeisList'),
|
||||
propertySell: require('./property/propertySell'),
|
||||
organizationMenu: require('./organization/organizationMenu'),
|
||||
workoff: require('./organization/workoff'),
|
||||
leaveOrg: require('./organization/leaveOrg'),
|
||||
leaveOrgAccept: require('./organization/leaveOrgAccept'),
|
||||
payday: require('./organization/payday'),
|
||||
orgMessage: require('./organization/orgMessage'),
|
||||
materialsBuy: require('./organization/materialsBuy'),
|
||||
percentSet: require('./organization/percentSet'),
|
||||
organizationCreate: require('./organization/organizationCreate'),
|
||||
invite: require('./organization/invite'),
|
||||
inviteAction: require('./organization/inviteAction'),
|
||||
report: require('./report'),
|
||||
slotsMenu: require('./casino/slotsMenu'),
|
||||
slotsRun: require('./casino/slots'),
|
||||
promocodeActivate: require('./promocodeActivate'),
|
||||
carContainers: require('./carcantainers/containersMenu'),
|
||||
chooseContainer: require('./carcantainers/chooseContainer'),
|
||||
reportAnswer: require('./admin/reportAnswer'),
|
||||
fastblock: require('./admin/fastblock'),
|
||||
createPromo: require('./admin/createPromo'),
|
||||
genPromo: require('./admin/genPromo')
|
||||
}
|
49
commands/invite.js
Normal file
49
commands/invite.js
Normal file
@ -0,0 +1,49 @@
|
||||
const {
|
||||
weaponshop,
|
||||
slots,
|
||||
rarecars,
|
||||
simplecars,
|
||||
houses,
|
||||
cars,
|
||||
phones,
|
||||
weapons,
|
||||
equipment,
|
||||
UserModel,
|
||||
WorldModel,
|
||||
JobModel,
|
||||
PropertyModel,
|
||||
BusinessModel,
|
||||
ReportModel,
|
||||
BlockModel,
|
||||
PromocodeModel,
|
||||
mainChat,
|
||||
adminList,
|
||||
expToUp,
|
||||
topSym
|
||||
} = require('../config')
|
||||
const {
|
||||
spaces,
|
||||
spacesWithMarkdown,
|
||||
escape,
|
||||
generatePromo,
|
||||
generateVoucher,
|
||||
getCurrentTime,
|
||||
getSlot,
|
||||
giveExp,
|
||||
matPriceUpdate,
|
||||
rand,
|
||||
random,
|
||||
setCooldown,
|
||||
weaponShopUpdate,
|
||||
stats
|
||||
} = require('../utils')
|
||||
|
||||
module.exports = async (ctx) => {
|
||||
let user = await UserModel.findByPk(ctx.from.id);
|
||||
return ctx.reply(`
|
||||
ℹ️ Для приглашения друга по реферальной системе, отправьте ему ссылку-приглашение
|
||||
Как только он перейдет по ней и начнет игру, Вы получите ₽25.000.
|
||||
|
||||
Ваша ссылка: https://t.me/CampFireGameBot?start=${user.telegram_id}
|
||||
`)
|
||||
}
|
96
commands/jobs/chooseJob.js
Normal file
96
commands/jobs/chooseJob.js
Normal file
@ -0,0 +1,96 @@
|
||||
const {
|
||||
UserModel,
|
||||
JobModel
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
|
||||
module.exports = async (ctx) => {
|
||||
let data = ctx.update.callback_query.data;
|
||||
let user = await UserModel.findByPk(ctx.from.id);
|
||||
let job = null
|
||||
switch(data){
|
||||
case `job_1`:
|
||||
job = await JobModel.findByPk(1);
|
||||
if (user.level < job.level) {
|
||||
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(`❕ Вы уже устроены на другую работу`)
|
||||
case `job_2`:
|
||||
job = await JobModel.findByPk(2);
|
||||
if (user.level < job.level) {
|
||||
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(`❕ Вы уже устроены на другую работу`)
|
||||
case `job_3`:
|
||||
job = await JobModel.findByPk(3);
|
||||
if (user.level < job.level) {
|
||||
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(`❕ Вы уже устроены на другую работу`)
|
||||
case `job_4`:
|
||||
job = await JobModel.findByPk(4);
|
||||
if (user.level < job.level) {
|
||||
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(`❕ Вы уже устроены на другую работу`)
|
||||
case `job_5`:
|
||||
job = await JobModel.findByPk(5);
|
||||
if (user.level < job.level) {
|
||||
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(`ℹ️ Вы уже устроены на другую работу`)
|
||||
case `job_6`:
|
||||
job = await JobModel.findByPk(6);
|
||||
if (user.level < job.level) {
|
||||
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(`❕ Вы уже устроены на другую работу`)
|
||||
case `job_7`:
|
||||
job = await JobModel.findByPk(7);
|
||||
if (user.level < job.level) {
|
||||
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(`❕ Вы уже устроены на другую работу`)
|
||||
case `job_leave`:
|
||||
if (user.job != 0) {
|
||||
user.job = 0
|
||||
user.save()
|
||||
return await ctx.reply(`ℹ️ Теперь вы безработный.`)
|
||||
}
|
||||
return await ctx.reply(`❕ Вы итак безработный.`)
|
||||
}
|
||||
}
|
36
commands/jobs/jobs.js
Normal file
36
commands/jobs/jobs.js
Normal file
@ -0,0 +1,36 @@
|
||||
const {
|
||||
Markup
|
||||
} = require('telegraf')
|
||||
|
||||
module.exports = async (ctx) => {
|
||||
return await ctx.reply('Список работы', Markup
|
||||
.inlineKeyboard([
|
||||
[{
|
||||
text: `Дворник [1 уровень]`,
|
||||
callback_data: 'job_1'
|
||||
}, {
|
||||
text: `Промоутер [1 уровень]`,
|
||||
callback_data: 'job_2'
|
||||
}], [{
|
||||
text: `Официант [2 уровень]`,
|
||||
callback_data: 'job_3'
|
||||
}, {
|
||||
text: `Бармен [3 уровень]`,
|
||||
callback_data: 'job_4'
|
||||
}], [{
|
||||
text: `Кассир [4 уровень] `,
|
||||
callback_data: 'job_5'
|
||||
}, {
|
||||
text: `ПВЗ Дикие Ягоды [4 уровень]`,
|
||||
callback_data: 'job_6'
|
||||
}], [{
|
||||
text: `Слесарь [5 уровень]`,
|
||||
callback_data: 'job_7'
|
||||
}], [{
|
||||
text: `💤 Уволиться`,
|
||||
callback_data: 'job_leave'
|
||||
}]
|
||||
])
|
||||
.resize()
|
||||
)
|
||||
}
|
191
commands/jobs/work.js
Normal file
191
commands/jobs/work.js
Normal file
@ -0,0 +1,191 @@
|
||||
const {
|
||||
UserModel,
|
||||
WorldModel,
|
||||
JobModel
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
const {
|
||||
giveExp,
|
||||
setCooldown
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/utils')
|
||||
|
||||
module.exports = 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.job == 0) {
|
||||
return await ctx.reply(`📛 Вы безработный.`)
|
||||
}
|
||||
user.jobtime = Number(cooldown.endTime)
|
||||
let jobExp = job.exp;
|
||||
user.jobcheck++
|
||||
switch (user.job) {
|
||||
case 1:
|
||||
if (user.jobcheck >= 4) {
|
||||
let paydayfee = job.salary / 100 * world.transactionfee
|
||||
let payday = job.salary - paydayfee
|
||||
world.balance -= payday
|
||||
user.money += payday
|
||||
giveExp(user, jobExp)
|
||||
user.jobcheck = 0
|
||||
user.save()
|
||||
world.save()
|
||||
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`)
|
||||
}
|
||||
break;
|
||||
case 2:
|
||||
if (user.jobcheck >= 2) {
|
||||
let paydayfee = job.salary / 100 * world.transactionfee
|
||||
let payday = job.salary - paydayfee
|
||||
world.balance -= payday
|
||||
user.money += payday
|
||||
giveExp(user, jobExp)
|
||||
user.jobcheck = 0
|
||||
user.save()
|
||||
world.save()
|
||||
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`)
|
||||
}
|
||||
break;
|
||||
case 3:
|
||||
if (user.jobcheck >= 4) {
|
||||
let paydayfee = job.salary / 100 * world.transactionfee
|
||||
let payday = job.salary - paydayfee
|
||||
world.balance -= payday
|
||||
let tips = [50, 100, 200, 500, 1000].random()
|
||||
user.money += tips
|
||||
user.money += payday
|
||||
giveExp(user, jobExp)
|
||||
user.jobcheck = 0
|
||||
user.save()
|
||||
world.save()
|
||||
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`)
|
||||
}
|
||||
break;
|
||||
case 4:
|
||||
if (user.jobcheck >= 5) {
|
||||
let paydayfee = job.salary / 100 * world.transactionfee
|
||||
let payday = job.salary - paydayfee
|
||||
world.balance -= payday
|
||||
let tips = [50, 100, 200, 300, 500, 1000, 2000].random()
|
||||
world.balance -= tips
|
||||
user.money += tips
|
||||
user.money += payday
|
||||
giveExp(user, jobExp)
|
||||
user.jobcheck = 0
|
||||
user.save()
|
||||
world.save()
|
||||
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`)
|
||||
}
|
||||
break;
|
||||
case 5:
|
||||
if (user.jobcheck >= 5) {
|
||||
let paydayfee = job.salary / 100 * world.transactionfee
|
||||
let payday = job.salary - paydayfee
|
||||
world.balance -= payday
|
||||
user.money += payday
|
||||
giveExp(user, jobExp)
|
||||
user.jobcheck = 0
|
||||
user.save()
|
||||
world.save()
|
||||
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`)
|
||||
}
|
||||
break;
|
||||
case 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()
|
||||
world.balance -= payday
|
||||
world.balance -= Number(stealed.price)
|
||||
user.money += payday
|
||||
user.money += Number(stealed.price)
|
||||
giveExp(user, jobExp)
|
||||
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})`)
|
||||
} else {
|
||||
user.save()
|
||||
return ctx.reply(`👔 Вы целый час выдавали заказы в Диких Ягодах. \n⏳ Отработано часов: ${user.jobcheck}/6`)
|
||||
}
|
||||
break;
|
||||
case 7:
|
||||
if (user.jobcheck >= 6) {
|
||||
let paydayfee = job.salary / 100 * world.transactionfee
|
||||
let payday = job.salary - paydayfee
|
||||
world.balance -= payday
|
||||
user.money += payday
|
||||
giveExp(user, jobExp)
|
||||
user.jobcheck = 0
|
||||
user.save()
|
||||
world.save()
|
||||
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`)
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
15
commands/menu.js
Normal file
15
commands/menu.js
Normal file
@ -0,0 +1,15 @@
|
||||
const {
|
||||
Markup
|
||||
} = require('telegraf')
|
||||
|
||||
module.exports = async (ctx) => {
|
||||
return await ctx.reply('Main Menu', Markup
|
||||
.keyboard([
|
||||
['😎 Профиль'],
|
||||
['🗄️ Работать', '🌐 Организация', '🎁 Бонус', '🏯 Казино'],
|
||||
['📦 Контейнеры'],
|
||||
['📢 Вакансии', '🔵 Имущество', '📞 Пригласить']
|
||||
])
|
||||
.resize()
|
||||
)
|
||||
}
|
38
commands/organization/invite.js
Normal file
38
commands/organization/invite.js
Normal file
@ -0,0 +1,38 @@
|
||||
const {
|
||||
Telegraf,
|
||||
Markup
|
||||
} = require('telegraf')
|
||||
const bot = new Telegraf(process.env.BOT_TOKEN)
|
||||
const {
|
||||
UserModel,
|
||||
BusinessModel
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
|
||||
module.exports = async (ctx) => {
|
||||
ctx.args = ctx.update.message.text.split(' ')
|
||||
if (!ctx.args[1]) return ctx.reply(`/invite [Nick]`)
|
||||
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.users.length >= 5) return await ctx.reply(`📛 Достигнуто максимальное количество сотрудников в организации.`)
|
||||
let invited = await UserModel.findOne({
|
||||
where: {
|
||||
username: ctx.args[1]
|
||||
}
|
||||
});
|
||||
await bot.telegram.sendMessage(invited.telegram_id, '⤵️ Приглашение', Markup
|
||||
.inlineKeyboard([
|
||||
[{
|
||||
text: `Принять`,
|
||||
callback_data: `{"type": "business_invite_accept", "invitor": "${user.telegram_id}"}`
|
||||
}, {
|
||||
text: `Отклонить`,
|
||||
callback_data: `{"type": "business_invite_refuse", "invitor": "${user.telegram_id}"}`
|
||||
}]
|
||||
]).oneTime())
|
||||
return await ctx.reply(`Приглашение отправлено.`)
|
||||
}
|
34
commands/organization/inviteAction.js
Normal file
34
commands/organization/inviteAction.js
Normal file
@ -0,0 +1,34 @@
|
||||
const sequelize = require('/workspace/degradin/Dev/Telegram/CampFire Play/db');
|
||||
const { Op } = require('sequelize');
|
||||
const {
|
||||
UserModel,
|
||||
BusinessModel
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
|
||||
module.exports = 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})
|
||||
}
|
||||
}
|
41
commands/organization/leaveOrg.js
Normal file
41
commands/organization/leaveOrg.js
Normal file
@ -0,0 +1,41 @@
|
||||
const {
|
||||
Telegraf
|
||||
} = require('telegraf')
|
||||
const bot = new Telegraf(process.env.BOT_TOKEN)
|
||||
const {
|
||||
UserModel,
|
||||
BusinessModel
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
|
||||
module.exports = 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(`Вы не можете покинуть свою организацию.`)
|
||||
}
|
||||
}
|
28
commands/organization/leaveOrgAccept.js
Normal file
28
commands/organization/leaveOrgAccept.js
Normal file
@ -0,0 +1,28 @@
|
||||
const {
|
||||
Telegraf
|
||||
} = require('telegraf')
|
||||
const bot = new Telegraf(process.env.BOT_TOKEN)
|
||||
const {
|
||||
UserModel,
|
||||
BusinessModel
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
|
||||
module.exports = 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}`)
|
||||
}
|
29
commands/organization/materialsBuy.js
Normal file
29
commands/organization/materialsBuy.js
Normal file
@ -0,0 +1,29 @@
|
||||
const {
|
||||
UserModel,
|
||||
WorldModel,
|
||||
BusinessModel
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
|
||||
module.exports = async (ctx) => {
|
||||
ctx.args = ctx.update.message.text.split(' ')
|
||||
let user = await UserModel.findByPk(ctx.from.id)
|
||||
if (user.business.id == 0) return await ctx.reply(`🚫 Вы не владеете организацией.`)
|
||||
let world = await WorldModel.findByPk(1)
|
||||
let business = await BusinessModel.findOne({
|
||||
where: {
|
||||
owner: ctx.from.id.toString()
|
||||
}
|
||||
})
|
||||
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`)
|
||||
if (ctx.args[1]*world.matPrice > business.balance) return ctx.reply(`🚫 Недостаточно средств на балансе организации.`)
|
||||
if (business.materials >= 700) return ctx.reply(`🚫 Склады полны.`)
|
||||
if (business.materials + Number(ctx.args[1]) > 700) return ctx.reply(`🚫 Нет столько места на складах.\n Можно закупить еще ${700 - business.materials}`)
|
||||
let count = Number(ctx.args[1])
|
||||
business.balance -= world.matPrice*count
|
||||
business.materials += count
|
||||
business.save()
|
||||
return await ctx.reply(`➕ Закуплено ${ctx.args[1]} материалов для организации на сумму ₽${world.matPrice*count}`)
|
||||
}
|
24
commands/organization/orgMessage.js
Normal file
24
commands/organization/orgMessage.js
Normal file
@ -0,0 +1,24 @@
|
||||
const {
|
||||
Telegraf
|
||||
} = require('telegraf')
|
||||
const bot = new Telegraf(process.env.BOT_TOKEN)
|
||||
const {
|
||||
UserModel,
|
||||
BusinessModel
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
|
||||
module.exports = 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(`Сообщение отправлено.`)
|
||||
}
|
45
commands/organization/organizationCreate.js
Normal file
45
commands/organization/organizationCreate.js
Normal file
@ -0,0 +1,45 @@
|
||||
const {
|
||||
UserModel,
|
||||
WorldModel,
|
||||
BusinessModel
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
|
||||
module.exports = async (ctx) => {
|
||||
let user = await UserModel.findByPk(ctx.from.id)
|
||||
if (user.business.id != 0){
|
||||
let business = await BusinessModel.findOne({
|
||||
where: {
|
||||
owner: ctx.from.id.toString()
|
||||
}
|
||||
})
|
||||
}
|
||||
let business = null
|
||||
let world = await WorldModel.findByPk(1)
|
||||
ctx.args = ctx.update.message.text.split(' ')
|
||||
if (business != null) return await ctx.reply(`У вас уже есть организация.`)
|
||||
if (!ctx.args[1]) return ctx.reply(`/business [Название организации]`)
|
||||
if (user.money < 100000) return await ctx.reply(`Регистрация организации стоит ₽100.000`)
|
||||
if (user.level < 5) return await ctx.reply(`Регистрация организации доступна с 5 уровня.`)
|
||||
user.money -= 100000
|
||||
world.balance += 100000
|
||||
let text = ``
|
||||
for (i = 1; i < ctx.args.length; i++) {
|
||||
text += `${ctx.args[i]} `
|
||||
}
|
||||
if (business === null) {
|
||||
BusinessModel.create({
|
||||
name: text,
|
||||
owner: user.telegram_id,
|
||||
balance: 50000,
|
||||
users: [user.telegram_id]
|
||||
})
|
||||
user.business = {
|
||||
id: user.telegram_id,
|
||||
checks: 0,
|
||||
percent: 100
|
||||
}
|
||||
} else {}
|
||||
user.save()
|
||||
world.save()
|
||||
return await ctx.reply(`Организация "${text}" успешно создана!\n Регистрация организации в реестре: ₽50.000 \n Капитал: ₽50.000`)
|
||||
}
|
57
commands/organization/organizationMenu.js
Normal file
57
commands/organization/organizationMenu.js
Normal file
@ -0,0 +1,57 @@
|
||||
const {
|
||||
Markup
|
||||
} = require('telegraf')
|
||||
const {
|
||||
UserModel,
|
||||
BusinessModel
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
const {
|
||||
spaces,
|
||||
escape
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/utils')
|
||||
|
||||
module.exports = 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
|
||||
}
|
||||
})
|
||||
return await ctx.replyWithMarkdownV2(`🏭 Организация\n_${business.name}_\n💹 Баланс: ₽${escape(spaces(business.balance))}\n🧰 Сырье: ${business.materials}\n👥 Рабочих: ${business.users.length}\n\nВаши отработки: ${user.business.checks}`, Markup.inlineKeyboard([
|
||||
[{
|
||||
text: `📶 Отработка`,
|
||||
callback_data: "workoff"
|
||||
}, {
|
||||
text: `⬅️ Покинуть`,
|
||||
callback_data: "покинуть"
|
||||
}]
|
||||
])
|
||||
.oneTime()
|
||||
.resize())
|
||||
}
|
||||
if (business.owner == ctx.from.id){
|
||||
let text = ``
|
||||
for (n = 0; n < business.users.length; n++) { // Процент выплаты участникам
|
||||
users = await UserModel.findByPk(business.users[n])
|
||||
text += `${users.username} - ${users.business.checks} [${users.business.percent}%]\n`
|
||||
}
|
||||
return await ctx.replyWithMarkdownV2(`🏭 Ваша организация\n_${business.name}_\n💹 Баланс: ₽${escape(spaces(business.balance))}\n🧰 Сырье: ${business.materials}\n👥 Рабочих: ${business.users.length}\n🔨 Отработок: ${business.checks}\n${escape(text)}\n\nВаши отработки: ${user.business.checks}`, Markup.inlineKeyboard([
|
||||
[{
|
||||
text: `📶 Отработка`,
|
||||
callback_data: "workoff"
|
||||
}, {
|
||||
text: `💸 Payday`,
|
||||
callback_data: "payday"
|
||||
}]
|
||||
])
|
||||
.oneTime()
|
||||
.resize())
|
||||
}
|
||||
}
|
70
commands/organization/payday.js
Normal file
70
commands/organization/payday.js
Normal file
@ -0,0 +1,70 @@
|
||||
const {
|
||||
Telegraf
|
||||
} = require('telegraf')
|
||||
const bot = new Telegraf(process.env.BOT_TOKEN)
|
||||
const {
|
||||
UserModel,
|
||||
WorldModel,
|
||||
BusinessModel
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
const {
|
||||
spaces,
|
||||
giveExp,
|
||||
rand
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/utils')
|
||||
|
||||
module.exports = async (ctx) => {
|
||||
let user = null
|
||||
let business = await BusinessModel.findOne({
|
||||
where: {
|
||||
owner: ctx.from.id.toString()
|
||||
}
|
||||
})
|
||||
let world = await WorldModel.findByPk(1)
|
||||
if (business === null) return await ctx.reply(`У вас нет организации.`)
|
||||
if (business.checks < 12) return await ctx.reply(`Недостаточно отработок для формирования выплаты.`)
|
||||
let percentSum = 0
|
||||
let text = ``
|
||||
let percentErrorText = ``
|
||||
let profit = 0
|
||||
let piece = 0
|
||||
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)
|
||||
percentErrorText += `ℹ️ ${user.username} ${user.business.percent}% [/percent ${user.username} [проценты]]\n`
|
||||
}
|
||||
if (percentSum > 100) return await ctx.reply(`⚠️ Общий процент всех сотрудников превышает 100%\n ➕ Остаток процентов перенесется в баланс организации.\n\n${percentErrorText}\n`)
|
||||
for (x = 0; x < business.users.length; x++) { // Общая внесенная сумма всеми участниками
|
||||
user = await UserModel.findByPk(business.users[x])
|
||||
profit += user.business.checks * moneyList * user.level
|
||||
text += `ℹ️ ${user.username} отработал ${user.business.checks} раз.\n`
|
||||
user.business = {
|
||||
id: user.business.id,
|
||||
checks: 0,
|
||||
percent: user.business.percent
|
||||
}
|
||||
user.save()
|
||||
}
|
||||
text += ` 💹 Наработка за текущий период: ${profit}\n`
|
||||
let profitCheck = profit
|
||||
for (n = 0; n < business.users.length; n++) { // Процент выплаты участникам
|
||||
user = await UserModel.findByPk(business.users[n])
|
||||
piece = Math.round(profit / 100 * user.business.percent)
|
||||
profitCheck -= piece
|
||||
user.money += piece
|
||||
text += `➕ ${user.username} получает ₽${piece}\n`
|
||||
await bot.telegram.sendMessage(user.telegram_id, `ℹ️ Директор организации сформировал выплаты.\n➕ На ваш баланс поступило: ₽${spaces(piece)}`)
|
||||
giveExp(user, business.checks)
|
||||
user.save()
|
||||
}
|
||||
if (profitCheck > 0) {
|
||||
business.balance += profitCheck
|
||||
text += `➕ На баланс бизнеса поступило ₽${profitCheck}`
|
||||
}
|
||||
business.checks = 0
|
||||
business.save()
|
||||
console.log(`Payday: ${business.name}\n${text}`)
|
||||
return await ctx.reply(text)
|
||||
}
|
34
commands/organization/percentSet.js
Normal file
34
commands/organization/percentSet.js
Normal file
@ -0,0 +1,34 @@
|
||||
const {
|
||||
UserModel,
|
||||
BusinessModel
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
|
||||
module.exports = async (ctx) => {
|
||||
ctx.args = ctx.update.message.text.split(' ')
|
||||
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) return await ctx.reply(`У вас нет организации.`)
|
||||
if (!ctx.args[1] || !ctx.args[2]) return ctx.reply(`Не указан аргумент.`)
|
||||
if (!Number(ctx.args[2])) return ctx.reply(`Процент должен быть числом от 1 до 100.`)
|
||||
if (ctx.args[2] < 1 || ctx.args[2] > 100) return ctx.reply(`Минимальный процент 1 | Максимальный процент 100.`)
|
||||
ctx.args[1] = ctx.args[1]
|
||||
console.log(ctx.args)
|
||||
let change = await UserModel.findOne({
|
||||
where: {
|
||||
username: ctx.args[1]
|
||||
}
|
||||
})
|
||||
if (change === null) return await ctx.reply(`Нет такого игрока.`)
|
||||
change.business = {
|
||||
id: change.business.id,
|
||||
checks: change.business.checks,
|
||||
percent: ctx.args[2]
|
||||
}
|
||||
change.save()
|
||||
return await ctx.reply(`Участнику ${change.username} установлен процент ${ctx.args[2]}`)
|
||||
}
|
71
commands/organization/workoff.js
Normal file
71
commands/organization/workoff.js
Normal file
@ -0,0 +1,71 @@
|
||||
const {
|
||||
UserModel,
|
||||
BusinessModel
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
const {
|
||||
spaces,
|
||||
escape,
|
||||
setCooldown
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/utils')
|
||||
|
||||
module.exports = async (ctx) => {
|
||||
let user = await UserModel.findByPk(ctx.from.id)
|
||||
let business = await BusinessModel.findOne({
|
||||
where: {
|
||||
owner: user.business.id.toString()
|
||||
}
|
||||
})
|
||||
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.telegram.answerCbQuery(ctx.callbackQuery.id, `📛 Работа в организации будет доступна через ${cooldown.timeLeftInMinutes} минут(у/ы)`, {show_alert: true});
|
||||
if (business.materials < 10) return ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `📛 В организации недостаточно материалов для отработки.`);
|
||||
user.worktime = cooldown.endTime
|
||||
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()
|
||||
if (business.owner == ctx.from.id){
|
||||
let text = ``
|
||||
for (n = 0; n < business.users.length; n++) { // Процент выплаты участникам
|
||||
users = await UserModel.findByPk(business.users[n])
|
||||
text += `${users.username} - ${users.business.checks} [${users.business.percent}%]\n`
|
||||
}
|
||||
return await ctx.editMessageText(`🏭 Ваша организация\n_${business.name}_\n💹 Баланс: ₽${escape(spaces(business.balance))}\n🧰 Сырье: ${business.materials} \n👥 Рабочих: ${business.users.length}\n🔨 Отработок: ${business.checks}\n${escape(text)}\n\nВаши отработки: ${user.business.checks}`,
|
||||
{
|
||||
reply_markup: {
|
||||
inline_keyboard: [
|
||||
[{
|
||||
text: `📶 Отработка`,
|
||||
callback_data: "workoff"
|
||||
}, {
|
||||
text: `💸 Payday`,
|
||||
callback_data: "payday"
|
||||
}]
|
||||
]},
|
||||
parse_mode: `MarkdownV2`
|
||||
}
|
||||
)
|
||||
}else{
|
||||
return await ctx.editMessageText(`🏭 Организация\n_${business.name}_\n💹 Баланс: ₽${escape(spaces(business.balance))}\n🧰 Сырье: ${business.materials}\n👥 Рабочих: ${business.users.length}\n\nВаши отработки: ${user.business.checks}`,
|
||||
{
|
||||
reply_markup: {
|
||||
inline_keyboard: [
|
||||
[{
|
||||
text: `📶 Отработка`,
|
||||
callback_data: "workoff"
|
||||
}, {
|
||||
text: `⬅️ Покинуть`,
|
||||
callback_data: "покинуть"
|
||||
}]
|
||||
]},
|
||||
parse_mode: `MarkdownV2`
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
35
commands/pay.js
Normal file
35
commands/pay.js
Normal file
@ -0,0 +1,35 @@
|
||||
const {
|
||||
Telegraf
|
||||
} = require('telegraf')
|
||||
const bot = new Telegraf(process.env.BOT_TOKEN)
|
||||
const {
|
||||
UserModel,
|
||||
WorldModel
|
||||
} = require('../config')
|
||||
|
||||
module.exports = 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(`❕ Сумма должна быть числовая.`)
|
||||
let sender = await UserModel.findByPk(ctx.from.id);
|
||||
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.`)
|
||||
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)
|
||||
await sender.save();
|
||||
await world.save();
|
||||
receiver.money += Number(ctx.args[2])
|
||||
await receiver.save();
|
||||
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(`🔼 Исходящий перевод.\n\n🔽 Получатель: ${receiver.username}\n🆔 Получателя: ${receiver.telegram_id}\n🔢 Сумма: ₽${ctx.args[2]}\nℹ️ Комиссия: ₽${fee}\n🆕 Ваш баланс: ₽${sender.money}`)
|
||||
}
|
32
commands/profile.js
Normal file
32
commands/profile.js
Normal file
@ -0,0 +1,32 @@
|
||||
const {
|
||||
UserModel,
|
||||
PropertyModel,
|
||||
expToUp
|
||||
} = require('../config')
|
||||
const {
|
||||
spacesWithMarkdown,
|
||||
escape
|
||||
} = require('../utils')
|
||||
|
||||
module.exports = 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.replyWithMarkdownV2(`
|
||||
👤${escape(user.username)} ${user.status == 'bronze' ? `\\[🔺\\]` : ""}${user.status == 'silver' ? `\\[🔹\\]` : ""}${user.status == 'gold' ? `\\[🔸\\]` : ""}${user.status == 'admin' ? "✅" : ""}
|
||||
🆔: ${ctx.from.id}
|
||||
|
||||
📶 Уровень: ${user.level} \\| ${user.exp} / ${expToUp[user.level]}
|
||||
⏩ Повышается за различные действия\\.
|
||||
|
||||
💰 Баланс
|
||||
₽${spacesWithMarkdown(user.money)}
|
||||
|
||||
🔵 Имущество
|
||||
🏠 Жилье: ${property.house == 0 ? "Бездомный" : property.house.name}
|
||||
🚗 Автомобиль: ${property.car == 0 ? "Пешком" : escape(property.car.name)}
|
||||
📱 Телефон: ${property.mobile == 0 ? "Нет" : property.mobile.name}
|
||||
🔫 Оружие: ${property.weapon == 0 ? "Безоружный" : property.weapon.name}
|
||||
🥼 Экипировка: ${property.equipment == 0 ? "Нет" : property.equipment.name}
|
||||
`);
|
||||
}
|
34
commands/promocodeActivate.js
Normal file
34
commands/promocodeActivate.js
Normal file
@ -0,0 +1,34 @@
|
||||
const {
|
||||
Telegraf
|
||||
} = require('telegraf')
|
||||
const bot = new Telegraf(process.env.BOT_TOKEN)
|
||||
const {
|
||||
UserModel,
|
||||
PromocodeModel,
|
||||
adminList
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
const {
|
||||
spaces
|
||||
} = require('../utils')
|
||||
const sequelize = require('../db');
|
||||
|
||||
module.exports = async (ctx) => {
|
||||
let user = await UserModel.findByPk(ctx.from.id)
|
||||
ctx.args = ctx.update.message.text.split(' ')
|
||||
if (!ctx.args[1]) return ctx.reply(`/promocode [Code]`)
|
||||
let promocode = await PromocodeModel.findOne({
|
||||
where: {
|
||||
code: ctx.args[1]
|
||||
}
|
||||
})
|
||||
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.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()
|
||||
promocode.save()
|
||||
await bot.telegram.sendMessage(adminList[0], `${user.username} активировал промокод на ₽${spaces(promocode.money)}`)
|
||||
return await ctx.reply(`✅ Вы активировали промокод на ₽${spaces(promocode.money)}`)
|
||||
}
|
18
commands/property/hatkeisList.js
Normal file
18
commands/property/hatkeisList.js
Normal file
@ -0,0 +1,18 @@
|
||||
const {
|
||||
weaponshop
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
const {
|
||||
spaces,
|
||||
escape,
|
||||
weaponShopUpdate
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/utils')
|
||||
|
||||
module.exports = async (ctx) => {
|
||||
let text = `[Hatkeis Gunsmith](https://telegra.ph/Hatkeis-Gunsmith-09-27)`
|
||||
let shop = `\n Вы подходите к зданию с вывеской "Ништяки Хаткейса".\n Вот ассортимент на сегодня\n`
|
||||
for (i = 0; i < 10; i++) {
|
||||
shop += `${i}. ${weaponshop[i].name} (₽${spaces(weaponshop[i].price)})\n`
|
||||
}
|
||||
weaponShopUpdate()
|
||||
return await ctx.replyWithMarkdownV2(text + escape(shop), {disable_web_page_preview: true})
|
||||
}
|
102
commands/property/propertyBuy.js
Normal file
102
commands/property/propertyBuy.js
Normal file
@ -0,0 +1,102 @@
|
||||
const {
|
||||
weaponshop,
|
||||
slots,
|
||||
rarecars,
|
||||
simplecars,
|
||||
houses,
|
||||
cars,
|
||||
phones,
|
||||
weapons,
|
||||
equipment,
|
||||
UserModel,
|
||||
WorldModel,
|
||||
JobModel,
|
||||
PropertyModel,
|
||||
BusinessModel,
|
||||
ReportModel,
|
||||
BlockModel,
|
||||
PromocodeModel,
|
||||
mainChat,
|
||||
adminList,
|
||||
expToUp,
|
||||
topSym
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
const {
|
||||
spaces,
|
||||
spacesWithMarkdown,
|
||||
escape,
|
||||
generatePromo,
|
||||
generateVoucher,
|
||||
getCurrentTime,
|
||||
getSlot,
|
||||
giveExp,
|
||||
matPriceUpdate,
|
||||
rand,
|
||||
random,
|
||||
setCooldown,
|
||||
weaponShopUpdate,
|
||||
stats
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/utils')
|
||||
|
||||
module.exports = 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}`)
|
||||
}
|
||||
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}`)
|
||||
}
|
||||
}
|
42
commands/property/propertyList.js
Normal file
42
commands/property/propertyList.js
Normal file
@ -0,0 +1,42 @@
|
||||
const {
|
||||
Markup
|
||||
} = require('telegraf')
|
||||
const {
|
||||
houses,
|
||||
cars,
|
||||
phones
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
|
||||
module.exports = 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;
|
||||
}
|
||||
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())
|
||||
}
|
19
commands/property/propertyMenu.js
Normal file
19
commands/property/propertyMenu.js
Normal file
@ -0,0 +1,19 @@
|
||||
const {
|
||||
Markup
|
||||
} = require('telegraf')
|
||||
const {
|
||||
UserModel
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
|
||||
module.exports = async (ctx) => {
|
||||
let user = await UserModel.findByPk(ctx.from.id);
|
||||
return await ctx.reply(`Выберите тип`, Markup
|
||||
.inlineKeyboard([
|
||||
[
|
||||
{text: 'Жилье', callback_data: `shop_house`},
|
||||
{text: 'Телефоны', callback_data: `shop_phone`},
|
||||
{text: 'Автосалон', callback_data: `shop_car`}
|
||||
]
|
||||
])
|
||||
.resize())
|
||||
}
|
102
commands/property/propertySell.js
Normal file
102
commands/property/propertySell.js
Normal file
@ -0,0 +1,102 @@
|
||||
const {
|
||||
weaponshop,
|
||||
slots,
|
||||
rarecars,
|
||||
simplecars,
|
||||
houses,
|
||||
cars,
|
||||
phones,
|
||||
weapons,
|
||||
equipment,
|
||||
UserModel,
|
||||
WorldModel,
|
||||
JobModel,
|
||||
PropertyModel,
|
||||
BusinessModel,
|
||||
ReportModel,
|
||||
BlockModel,
|
||||
PromocodeModel,
|
||||
mainChat,
|
||||
adminList,
|
||||
expToUp,
|
||||
topSym
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
const {
|
||||
spaces,
|
||||
spacesWithMarkdown,
|
||||
escape,
|
||||
generatePromo,
|
||||
generateVoucher,
|
||||
getCurrentTime,
|
||||
getSlot,
|
||||
giveExp,
|
||||
matPriceUpdate,
|
||||
rand,
|
||||
random,
|
||||
setCooldown,
|
||||
weaponShopUpdate,
|
||||
stats
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/utils')
|
||||
|
||||
module.exports = 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]) return ctx.reply(`Не указан аргумент.`)
|
||||
if (ctx.args[1] == "house") {
|
||||
if (!property.house.name) return await ctx.reply(`У вас нет дома.`)
|
||||
let name = property.house.name
|
||||
user.money += Math.round(property.house.price/2)
|
||||
world.balance -= Math.round(property.house.price/2)
|
||||
property.house = 0
|
||||
await user.save()
|
||||
await world.save()
|
||||
await property.save()
|
||||
return await ctx.reply(`Вы продали ${name}`)
|
||||
}
|
||||
if (ctx.args[1] == "car") {
|
||||
if (!property.car.name) return await ctx.reply(`У вас нет автомобиля.`)
|
||||
let name = property.car.name
|
||||
user.money += Math.round(property.car.price/2)
|
||||
world.balance -= Math.round(property.car.price/2)
|
||||
property.car = 0
|
||||
await user.save()
|
||||
await world.save()
|
||||
await property.save()
|
||||
return await ctx.reply(`Вы продали ${name}`)
|
||||
}
|
||||
if (ctx.args[1] == "phone") {
|
||||
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()
|
||||
return await ctx.reply(`Вы продали ${name}`)
|
||||
}
|
||||
if (ctx.args[1] == "equipment") {
|
||||
if (!property.equipment.name) return await ctx.reply(`У вас нет экипировки.`)
|
||||
let name = property.equipment.name
|
||||
user.money += Math.round(property.equipment.price/2)
|
||||
world.balance -= Math.round(property.equipment.price/2)
|
||||
property.equipment = 0
|
||||
await user.save()
|
||||
await world.save()
|
||||
await property.save()
|
||||
return await ctx.reply(`Вы продали ${name}`)
|
||||
}
|
||||
if (ctx.args[1] == "weapon") {
|
||||
if (!property.weapon.name) return await ctx.reply(`У вас нет оружия.`)
|
||||
let name = property.weapon.name
|
||||
user.money += Math.round(property.weapon.price/2)
|
||||
world.balance -= Math.round(property.weapon.price/2)
|
||||
property.weapon = 0
|
||||
await user.save()
|
||||
await world.save()
|
||||
await property.save()
|
||||
return await ctx.reply(`Вы продали ${name}`)
|
||||
}
|
||||
}
|
31
commands/report.js
Normal file
31
commands/report.js
Normal file
@ -0,0 +1,31 @@
|
||||
const {
|
||||
Telegraf,
|
||||
Markup
|
||||
} = require('telegraf')
|
||||
const bot = new Telegraf(process.env.BOT_TOKEN)
|
||||
const {
|
||||
UserModel,
|
||||
ReportModel,
|
||||
adminList
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
const shortid = require('shortid');
|
||||
|
||||
module.exports = 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}] создано.`)
|
||||
}
|
7
commands/scratch.js
Normal file
7
commands/scratch.js
Normal file
@ -0,0 +1,7 @@
|
||||
const { createCanvas, loadImage } = require('canvas');
|
||||
const fs = require('fs');
|
||||
|
||||
module.exports = async (ctx) => {
|
||||
|
||||
|
||||
}
|
30
commands/top.js
Normal file
30
commands/top.js
Normal file
@ -0,0 +1,30 @@
|
||||
const {
|
||||
UserModel,
|
||||
topSym
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
const {
|
||||
spaces
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/utils')
|
||||
const sequelize = require('../db');
|
||||
const { Op } = require('sequelize');
|
||||
|
||||
module.exports = async (ctx) => {
|
||||
let topPlayer = await UserModel.findAll({
|
||||
attributes: ['name', [sequelize.fn('sum', sequelize.col('money')), 'money'], 'status'],
|
||||
group: ['name', 'status'],
|
||||
where: {
|
||||
telegram_id: {
|
||||
[Op.ne]: 275416286
|
||||
}
|
||||
},
|
||||
order: [
|
||||
[sequelize.literal('money'), 'DESC']
|
||||
],
|
||||
limit: 10
|
||||
})
|
||||
let text = `🏆 Топ 10 игроков по балансу.\n\n`
|
||||
for(i=0; i<topPlayer.length; i++){
|
||||
text += `${topSym[i]}. ${topPlayer[i].status == 'bronze' ? `[🔺]` : ""}${topPlayer[i].status == 'silver' ? `[🔹]` : ""}${topPlayer[i].status == 'gold' ? `[🔸]` : ""} ${topPlayer[i].name} [₽${spaces(topPlayer[i].money)}]\n`
|
||||
}
|
||||
return await ctx.reply(text)
|
||||
}
|
12
commands/world.js
Normal file
12
commands/world.js
Normal file
@ -0,0 +1,12 @@
|
||||
const {
|
||||
WorldModel
|
||||
} = require('../config')
|
||||
const {
|
||||
spaces
|
||||
} = require('../utils')
|
||||
|
||||
module.exports = async (ctx) => {
|
||||
let world = await WorldModel.findByPk(1)
|
||||
return ctx.reply(`🔰 Баланс мира: ₽${spaces(world.balance)}\nℹ️ Стоимость материалов: ₽${spaces(world.matPrice)}
|
||||
`)
|
||||
}
|
48
config/imports.js
Normal file
48
config/imports.js
Normal file
@ -0,0 +1,48 @@
|
||||
|
||||
const testScene = require("../scenes/test");
|
||||
const weaponshop = require('../json/weaponshop.json')
|
||||
const slots = require('../json/slots.json')
|
||||
const rarecars = require('../json/rarecars.json')
|
||||
const simplecars = require('../json/simplecars.json')
|
||||
const houses = require('../presets/houses.json')
|
||||
const cars = require('../presets/cars.json')
|
||||
const phones = require('../presets/mobiles.json')
|
||||
const weapons = require('../presets/weapons.json')
|
||||
const equipment = require('../presets/equipment.json')
|
||||
const UserModel = require('../models/user.model');
|
||||
const WorldModel = require('../models/world.model');
|
||||
const JobModel = require('../models/job.model');
|
||||
const PropertyModel = require('../models/property.model');
|
||||
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 mainChat = -1001895132127
|
||||
const adminList = [275416286]
|
||||
const expToUp = [0, 10, 20, 40, 60, 100, 250, 370, 450, 575, 666, 777, 860, 999, 1000, 1177, 1234, 1350, 1488, 1515, 1610]
|
||||
const topSym = ['🥇', '🥈', '🥉', '4️⃣', '5️⃣', '6️⃣', '7️⃣', '8️⃣', '9️⃣', '🔟']
|
||||
|
||||
module.exports = [
|
||||
testScene,
|
||||
weaponshop,
|
||||
slots,
|
||||
rarecars,
|
||||
simplecars,
|
||||
houses,
|
||||
cars,
|
||||
phones,
|
||||
weapons,
|
||||
equipment,
|
||||
UserModel,
|
||||
WorldModel,
|
||||
JobModel,
|
||||
PropertyModel,
|
||||
BusinessModel,
|
||||
ReportModel,
|
||||
BlockModel,
|
||||
PromocodeModel,
|
||||
mainChat,
|
||||
adminList,
|
||||
expToUp,
|
||||
topSym
|
||||
]
|
26
config/index.js
Normal file
26
config/index.js
Normal file
@ -0,0 +1,26 @@
|
||||
module.exports = {
|
||||
testScene : require("../scenes/test"),
|
||||
weaponshop : require('../json/weaponshop.json'),
|
||||
slots : require('../json/slots.json'),
|
||||
rarecars : require('../json/rarecars.json'),
|
||||
simplecars : require('../json/simplecars.json'),
|
||||
houses : require('../presets/houses.json'),
|
||||
cars : require('../presets/cars.json'),
|
||||
phones : require('../presets/mobiles.json'),
|
||||
weapons : require('../presets/weapons.json'),
|
||||
equipment : require('../presets/equipment.json'),
|
||||
UserModel : require('../models/user.model'),
|
||||
WorldModel : require('../models/world.model'),
|
||||
JobModel : require('../models/job.model'),
|
||||
PropertyModel : require('../models/property.model'),
|
||||
BusinessModel : require('../models/business.model'),
|
||||
ReportModel : require('../models/report.model'),
|
||||
BlockModel : require('../models/block.model'),
|
||||
PromocodeModel : require('../models/promocode.model'),
|
||||
mainChat : -1001895132127,
|
||||
adminList : [275416286],
|
||||
expToUp : [0, 10, 20, 40, 60, 100, 250, 370, 450, 575, 666, 777, 860, 999, 1000, 1177, 1234, 1350, 1488, 1515, 1610],
|
||||
topSym : ['🥇', '🥈', '🥉', '4️⃣', '5️⃣', '6️⃣', '7️⃣', '8️⃣', '9️⃣', '🔟'],
|
||||
promoTopicId: 1807,
|
||||
gameTopicId: 1808
|
||||
}
|
14
ctxconfig.json
Normal file
14
ctxconfig.json
Normal file
@ -0,0 +1,14 @@
|
||||
{
|
||||
"mainAdminId": 275416286,
|
||||
"logChatId": -1001948614034,
|
||||
"stickerLinkPrefix": "t.me/addstickers/",
|
||||
"emojiLinkPrefix": "t.me/addemoji/",
|
||||
"charTitleMax": 35,
|
||||
"premiumCharTitleMax": 64,
|
||||
"messaging": {
|
||||
"limit": {
|
||||
"max": 20,
|
||||
"duration": 1500
|
||||
}
|
||||
}
|
||||
}
|
15
ecosystem.config.js
Normal file
15
ecosystem.config.js
Normal file
@ -0,0 +1,15 @@
|
||||
module.exports = {
|
||||
apps: [{
|
||||
name: 'CampFireGame',
|
||||
script: './index.js',
|
||||
max_memory_restart: '4000M',
|
||||
watch: true,
|
||||
cron_restart: '0 */6 * * *', // restart every 6 hours
|
||||
env: {
|
||||
NODE_ENV: 'development'
|
||||
},
|
||||
env_production: {
|
||||
NODE_ENV: 'production'
|
||||
}
|
||||
}]
|
||||
}
|
54
handlers/catch.js
Normal file
54
handlers/catch.js
Normal file
@ -0,0 +1,54 @@
|
||||
const util = require('util')
|
||||
const exec = util.promisify(require('child_process').exec)
|
||||
const errorStackParser = require('error-stack-parser')
|
||||
const { escapeHTML } = require('../utils')
|
||||
|
||||
async function errorLog (error, ctx) {
|
||||
const errorInfo = errorStackParser.parse(error)
|
||||
|
||||
let gitBlame
|
||||
|
||||
for (const ei of errorInfo) {
|
||||
if (!gitBlame) gitBlame = await exec(`git blame -L ${ei.lineNumber},${ei.lineNumber} -- ${ei.fileName}`).catch(() => {})
|
||||
}
|
||||
|
||||
let errorText = `<b>error for ${ctx.updateType}:</b>`
|
||||
if (ctx.match) errorText += `\n<code>${ctx.match[0]}</code>`
|
||||
if (ctx.from && ctx.from.id) errorText += `\n\nuser: <a href="tg://user?id=${ctx.from.id}">${escapeHTML(ctx.from.first_name)}</a> #user_${ctx.from.id}`
|
||||
if (ctx?.session?.chainActions && ctx?.session.chainActions.length > 0) errorText += '\n\n🔗 ' + ctx?.session.chainActions.map(v => `<code>${v}</code>`).join(' ➜ ')
|
||||
|
||||
if (gitBlame && !gitBlame.stderr) {
|
||||
const parsedBlame = gitBlame.stdout.match(/^(?<SHA>[0-9a-f]+)\s+\((?<USER>.+)(?<DATE>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} [+-]\d{4}\s+)(?<line>\d+)\) ?(?<code>.*)$/m)
|
||||
|
||||
errorText += `\n\n<u>${parsedBlame.groups.USER.trim()}</u>`
|
||||
errorText += `\n<i>commit:</i> ${parsedBlame.groups.SHA}`
|
||||
errorText += `\n\n<code>${parsedBlame.groups.code}</code>`
|
||||
}
|
||||
|
||||
errorText += `\n\n\n<code>${escapeHTML(error.stack)}</code>`
|
||||
|
||||
if (error.description && error.description.includes('timeout')) return
|
||||
|
||||
if (!ctx.config) return console.error(errorText)
|
||||
|
||||
await ctx.telegram.sendMessage(ctx.config.logChatId, errorText, {
|
||||
parse_mode: 'HTML'
|
||||
}).catch((error) => {
|
||||
console.error('send log error:', error)
|
||||
})
|
||||
|
||||
if (ctx?.chat?.type === 'private') {
|
||||
await ctx.replyWithHTML((`
|
||||
<b>Произошла неизвестная ошибка.</b>
|
||||
Вероятно, о ней уже известно администратору, но вы всё равно можете дополнительно сообщить последовательность, которая привела к ошибке => @Degradin.
|
||||
Пожалуйста, сразу подробно опишите проблему в одном сообщении, можно приложить скрин.`)).catch(() => {})
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = async (error, ctx) => {
|
||||
console.error(error)
|
||||
|
||||
errorLog(error, ctx).catch(e => {
|
||||
console.error('errorLog error:', e)
|
||||
})
|
||||
}
|
3
handlers/index.js
Normal file
3
handlers/index.js
Normal file
@ -0,0 +1,3 @@
|
||||
module.exports = {
|
||||
handleError: require('./catch')
|
||||
}
|
1763
index backup.js
Normal file
1763
index backup.js
Normal file
File diff suppressed because it is too large
Load Diff
2460
json/fastlog.json
Normal file
2460
json/fastlog.json
Normal file
File diff suppressed because it is too large
Load Diff
@ -93,5 +93,10 @@
|
||||
"name": "Ferrari F8",
|
||||
"price": 34000000,
|
||||
"image": "https://avatars.mds.yandex.net/get-autoru-vos/2037331/cd075cbfc2d10c05bb0450dcc889d351/1200x900n"
|
||||
},
|
||||
{
|
||||
"name": "Mercedes-Benz AMG GT S, 2017",
|
||||
"price": 10500000,
|
||||
"image": "https://avatars.mds.yandex.net/get-autoru-vos/2159790/270111424b42001ae010abc3367bcda9/1200x900n"
|
||||
}
|
||||
]
|
@ -53,5 +53,10 @@
|
||||
"name": "Mazda 3",
|
||||
"price": 500000,
|
||||
"image": "https://a.d-cd.net/da371e4s-1920.jpg"
|
||||
},
|
||||
{
|
||||
"name": "Hot Wheels Lamborghini Sian FKP 37 Orange Коллекционная",
|
||||
"price": 1000,
|
||||
"image": "https://ir.ozone.ru/s3/multimedia-4/wc700/6769855444.jpg"
|
||||
}
|
||||
]
|
@ -1,52 +1,57 @@
|
||||
{
|
||||
"0": {
|
||||
"name": "M1911",
|
||||
"price": 13000,
|
||||
"name": "HK UMP",
|
||||
"price": 33999,
|
||||
"damage": 0.028,
|
||||
"type": "weapon"
|
||||
},
|
||||
"1": {
|
||||
"name": "ПМ",
|
||||
"price": 13000,
|
||||
"name": "Glock 17",
|
||||
"price": 7999,
|
||||
"damage": 0.013,
|
||||
"type": "weapon"
|
||||
},
|
||||
"2": {
|
||||
"name": "АКС74У",
|
||||
"price": 34999,
|
||||
"name": "HK UMP",
|
||||
"price": 33999,
|
||||
"damage": 0.028,
|
||||
"type": "weapon"
|
||||
},
|
||||
"3": {
|
||||
"name": "G36C",
|
||||
"price": 38999,
|
||||
"name": "АКС74У",
|
||||
"price": 34999,
|
||||
"damage": 0.031,
|
||||
"type": "weapon"
|
||||
},
|
||||
"4": {
|
||||
"name": "G36C",
|
||||
"price": 38999,
|
||||
"name": "M1911",
|
||||
"price": 13000,
|
||||
"damage": 0.018,
|
||||
"type": "weapon"
|
||||
},
|
||||
"5": {
|
||||
"name": "Бронежилет M1",
|
||||
"price": 25000,
|
||||
"name": "Шлем танкиста",
|
||||
"price": 1000,
|
||||
"type": "equipment"
|
||||
},
|
||||
"6": {
|
||||
"name": "Бронежилет M2",
|
||||
"price": 35000,
|
||||
"name": "Бронежилет M5",
|
||||
"price": 1000,
|
||||
"type": "equipment"
|
||||
},
|
||||
"7": {
|
||||
"name": "Бронежилет M1",
|
||||
"price": 25000,
|
||||
"name": "Бронежилет M4",
|
||||
"price": 1000,
|
||||
"type": "equipment"
|
||||
},
|
||||
"8": {
|
||||
"name": "Бронежилет M2",
|
||||
"price": 35000,
|
||||
"name": "Бронежилет M5",
|
||||
"price": 1000,
|
||||
"type": "equipment"
|
||||
},
|
||||
"9": {
|
||||
"name": "Бронежилет M3",
|
||||
"price": 60000,
|
||||
"name": "Кольчуга",
|
||||
"price": 1000,
|
||||
"type": "equipment"
|
||||
}
|
||||
}
|
BIN
media/Thumbs.db
Normal file
BIN
media/Thumbs.db
Normal file
Binary file not shown.
BIN
media/image.png
BIN
media/image.png
Binary file not shown.
Before Width: | Height: | Size: 117 KiB After Width: | Height: | Size: 118 KiB |
1512
package-lock.json
generated
1512
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -14,11 +14,13 @@
|
||||
"canvas": "^2.11.2",
|
||||
"date-fns": "^2.30.0",
|
||||
"dotenv": "^16.3.1",
|
||||
"error-stack-parser": "^2.1.4",
|
||||
"fs": "^0.0.1-security",
|
||||
"node-telegram-bot-api": "^0.52.0",
|
||||
"nodemon": "^2.0.7",
|
||||
"pg": "^8.6.0",
|
||||
"pg-hstore": "^2.3.3",
|
||||
"pm2": "^5.3.0",
|
||||
"prettytable": "^0.3.1",
|
||||
"sequelize": "^6.6.2",
|
||||
"shortid": "^2.2.16",
|
||||
|
2
run.ps1
Normal file
2
run.ps1
Normal file
@ -0,0 +1,2 @@
|
||||
[System.Console]::Title = 'CampFireGame'
|
||||
nodemon --ignore json/ .\index.js
|
56
scenes/crime.js
Normal file
56
scenes/crime.js
Normal file
@ -0,0 +1,56 @@
|
||||
const {
|
||||
Scenes,
|
||||
Markup
|
||||
} = require('telegraf')
|
||||
|
||||
const crime = new Scenes.BaseScene('Crime');
|
||||
|
||||
crime.enter((ctx) => {
|
||||
ctx.reply('Scene: Выберите ограбление', Markup.inlineKeyboard([
|
||||
[
|
||||
{text: 'Карманные кражи [SOLO]', callback_data: `POCKET_ACTION`},
|
||||
{text: 'Магазин', callback_data: `heist`},
|
||||
{text: 'Банкомат', callback_data: `heist`},
|
||||
{text: 'Банковское отделение', callback_data: `heist`},
|
||||
{text: 'Угон', callback_data: `heist`},
|
||||
{text: 'Ювелирка', callback_data: `heist`},
|
||||
{text: 'Банк', callback_data: `heist`}
|
||||
]
|
||||
]))
|
||||
});
|
||||
|
||||
crime.action(`POCKET_ACTION`, (ctx) => {
|
||||
ctx.editMessageText('Scene: Выберите объект', Markup.inlineKeyboard([
|
||||
[
|
||||
{text: 'Карман', callback_data: `POCKET_TARGET`},
|
||||
{text: 'Бумажник', callback_data: `heist`},
|
||||
{text: 'Сумка', callback_data: `heist`}
|
||||
]
|
||||
]))
|
||||
});
|
||||
|
||||
crime.action(`POCKET_TARGET`, (ctx) => {
|
||||
if(Math.random() < 0.5) return ctx.editMessageText('Scene: Замечен');
|
||||
ctx.editMessageText('Scene: В кармане обнаружено', Markup.inlineKeyboard([
|
||||
[
|
||||
{text: 'Деньги', callback_data: `MONEY`},
|
||||
{text: 'Телефон', callback_data: `PHONE`}
|
||||
]
|
||||
]))
|
||||
});
|
||||
|
||||
crime.action(`MONEY`, (ctx) => {
|
||||
if(Math.random() < 0.5) return ctx.editMessageText('Scene: Замечен');
|
||||
return ctx.editMessageText('Scene: Успех MONEY')
|
||||
});
|
||||
|
||||
crime.action(`PHONE`, (ctx) => {
|
||||
if(Math.random() < 0.5) return ctx.editMessageText('Scene: Замечен');
|
||||
return ctx.editMessageText('Scene: Успех PHONE')
|
||||
});
|
||||
|
||||
crime.leave((ctx) => {
|
||||
console.log('Завершено');
|
||||
});
|
||||
|
||||
module.exports = crime
|
56
scenes/heist.js
Normal file
56
scenes/heist.js
Normal file
@ -0,0 +1,56 @@
|
||||
const {
|
||||
Scenes,
|
||||
Markup
|
||||
} = require('telegraf')
|
||||
|
||||
const heist = new Scenes.BaseScene('HEIST');
|
||||
|
||||
heist.enter((ctx) => {
|
||||
ctx.reply('Scene: Выберите ограбление', Markup.inlineKeyboard([
|
||||
[
|
||||
{text: 'Карманные кражи', callback_data: `POCKET_ACTION`},
|
||||
{text: 'Магазин', callback_data: `heist`},
|
||||
{text: 'Банкомат', callback_data: `heist`},
|
||||
{text: 'Банковское отделение', callback_data: `heist`},
|
||||
{text: 'Угон', callback_data: `heist`},
|
||||
{text: 'Ювелирка', callback_data: `heist`},
|
||||
{text: 'Банк', callback_data: `heist`}
|
||||
]
|
||||
]))
|
||||
});
|
||||
|
||||
heist.action(`POCKET_ACTION`, (ctx) => {
|
||||
ctx.editMessageText('Scene: Выберите объект', Markup.inlineKeyboard([
|
||||
[
|
||||
{text: 'Карман', callback_data: `POCKET_TARGET`},
|
||||
{text: 'Бумажник', callback_data: `heist`},
|
||||
{text: 'Сумка', callback_data: `heist`}
|
||||
]
|
||||
]))
|
||||
});
|
||||
|
||||
heist.action(`POCKET_TARGET`, (ctx) => {
|
||||
if(Math.random() < 0.5) return ctx.editMessageText('Scene: Замечен');
|
||||
ctx.editMessageText('Scene: В кармане обнаружено', Markup.inlineKeyboard([
|
||||
[
|
||||
{text: 'Деньги', callback_data: `MONEY`},
|
||||
{text: 'Телефон', callback_data: `PHONE`}
|
||||
]
|
||||
]))
|
||||
});
|
||||
|
||||
heist.action(`MONEY`, (ctx) => {
|
||||
if(Math.random() < 0.5) return ctx.editMessageText('Scene: Замечен');
|
||||
return ctx.editMessageText('Scene: Успех MONEY')
|
||||
});
|
||||
|
||||
heist.action(`PHONE`, (ctx) => {
|
||||
if(Math.random() < 0.5) return ctx.editMessageText('Scene: Замечен');
|
||||
return ctx.editMessageText('Scene: Успех PHONE')
|
||||
});
|
||||
|
||||
heist.leave((ctx) => {
|
||||
console.log('Завершено');
|
||||
});
|
||||
|
||||
module.exports = heist
|
17
scenes/index.js
Normal file
17
scenes/index.js
Normal file
@ -0,0 +1,17 @@
|
||||
const {
|
||||
Telegraf,
|
||||
Scenes,
|
||||
session,
|
||||
Stage,
|
||||
Markup
|
||||
} = require('telegraf')
|
||||
|
||||
const heistStart = require('./heist')
|
||||
const testStart = require('./test')
|
||||
|
||||
const stage = new Scenes.Stage(
|
||||
[heistStart]
|
||||
)
|
||||
|
||||
|
||||
module.exports = stage
|
40
scenes/test.js
Normal file
40
scenes/test.js
Normal file
@ -0,0 +1,40 @@
|
||||
const {
|
||||
Telegraf,
|
||||
Scenes,
|
||||
Markup
|
||||
} = require('telegraf')
|
||||
|
||||
const test = new Scenes.BaseScene('TEST');
|
||||
|
||||
test.enter((ctx) => {
|
||||
ctx.session.myData = {};
|
||||
ctx.reply('Scene: Выберите ограбление', Markup.inlineKeyboard([
|
||||
[
|
||||
{text: 'Карманные кражи', callback_data: `POCKET_ACTION`},
|
||||
{text: 'Магазин', callback_data: `heist`},
|
||||
{text: 'Банкомат', callback_data: `heist`},
|
||||
{text: 'Банковское отделение', callback_data: `heist`},
|
||||
{text: 'Угон', callback_data: `heist`},
|
||||
{text: 'Ювелирка', callback_data: `heist`},
|
||||
{text: 'Банк', callback_data: `heist`}
|
||||
]
|
||||
]));
|
||||
});
|
||||
|
||||
test.action(`POCKET_ACTION`, (ctx) => {
|
||||
ctx.reply('Выбор');
|
||||
ctx.session.myData.preferenceType = 'Pocket';
|
||||
return ctx.scene.enter('HEIST'); // switch to some other scene
|
||||
});
|
||||
|
||||
test.action(`MOVIE_ACTION`, (ctx) => {
|
||||
ctx.reply('You choose movie, your loss');
|
||||
ctx.session.myData.preferenceType = 'Movie';
|
||||
return ctx.scene.leave(); // exit global namespace
|
||||
});
|
||||
|
||||
test.leave((ctx) => {
|
||||
ctx.reply('Thank you for your time!');
|
||||
});
|
||||
|
||||
module.exports = test
|
22
utils/escape.js
Normal file
22
utils/escape.js
Normal file
@ -0,0 +1,22 @@
|
||||
module.exports = (text) => {
|
||||
text = text
|
||||
.replace(/\_/g, '\\_')
|
||||
.replace(/\*/g, '\\*')
|
||||
.replace(/\[/g, '\\[')
|
||||
.replace(/\]/g, '\\]')
|
||||
.replace(/\(/g, '\\(')
|
||||
.replace(/\)/g, '\\)')
|
||||
.replace(/\~/g, '\\~')
|
||||
.replace(/\`/g, '\\`')
|
||||
.replace(/\>/g, '\\>')
|
||||
.replace(/\#/g, '\\#')
|
||||
.replace(/\+/g, '\\+')
|
||||
.replace(/\-/g, '\\-')
|
||||
.replace(/\=/g, '\\=')
|
||||
.replace(/\|/g, '\\|')
|
||||
.replace(/\{/g, '\\{')
|
||||
.replace(/\}/g, '\\}')
|
||||
.replace(/\./g, '\\.')
|
||||
.replace(/\!/g, '\\!');
|
||||
return text
|
||||
}
|
37
utils/generatePromo.js
Normal file
37
utils/generatePromo.js
Normal file
@ -0,0 +1,37 @@
|
||||
const {
|
||||
Telegraf
|
||||
} = require('telegraf')
|
||||
const bot = new Telegraf(process.env.BOT_TOKEN)
|
||||
const {
|
||||
PromocodeModel,
|
||||
mainChat
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
const voucher_codes = require('voucher-code-generator');
|
||||
const rand = require('./rand')
|
||||
const generateVoucher = require('./generateVoucher');
|
||||
const { promoTopicId } = require('../config');
|
||||
module.exports = async () => {
|
||||
let activs = rand(1, 3)
|
||||
let give = rand(1000, 10000)
|
||||
let code = voucher_codes.generate({
|
||||
length: 6,
|
||||
count: 1,
|
||||
prefix: "CMP-",
|
||||
postfix: "-FIRE",
|
||||
charset: voucher_codes.charset("alphanumeric")
|
||||
});
|
||||
let promocode = await PromocodeModel.findOne({
|
||||
where: {
|
||||
code: code[0]
|
||||
}
|
||||
})
|
||||
if(promocode === null){
|
||||
await PromocodeModel.create({
|
||||
code: code[0],
|
||||
activations: activs,
|
||||
money: give
|
||||
})
|
||||
let voucherImage = await generateVoucher(code[0], activs, give)
|
||||
return await bot.telegram.sendPhoto(mainChat, {source: voucherImage}, {reply_to_message_id: promoTopicId})
|
||||
}
|
||||
}
|
28
utils/generateVoucher.js
Normal file
28
utils/generateVoucher.js
Normal file
@ -0,0 +1,28 @@
|
||||
const { createCanvas, loadImage } = require('canvas');
|
||||
const fs = require('fs');
|
||||
|
||||
module.exports = async(code, activations, money) => {
|
||||
// загружаем изображение фона
|
||||
const background = await loadImage('./media/imageDefault3.png');
|
||||
|
||||
// создаем новый canvas
|
||||
const canvas = createCanvas(background.width, background.height);
|
||||
const ctx = canvas.getContext('2d');
|
||||
|
||||
// рисуем фоновое изображение
|
||||
ctx.drawImage(background, 0, 0);
|
||||
|
||||
// выводим текст на картинку
|
||||
ctx.font = 'bold 30px Srbija Sans';
|
||||
ctx.fillStyle = '#232323';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.fillText(`${code}`, canvas.width/2, canvas.height/1.90);
|
||||
|
||||
// сохраняем картинку в файл
|
||||
const out = fs.createWriteStream('./media/image.png');
|
||||
const stream = canvas.createPNGStream();
|
||||
stream.pipe(out);
|
||||
|
||||
// возвращаем путь к сгенерированной картинке
|
||||
return './media/image.png';
|
||||
}
|
10
utils/getCurrentTime.js
Normal file
10
utils/getCurrentTime.js
Normal file
@ -0,0 +1,10 @@
|
||||
module.exports = () => {
|
||||
const now = new Date();
|
||||
const year = now.getFullYear();
|
||||
const month = now.getMonth() < 9 ? `0${now.getMonth() + 1}` : now.getMonth() + 1;
|
||||
const day = now.getDate() < 10 ? `0${now.getDate()}` : now.getDate();
|
||||
const hours = now.getHours() < 10 ? `0${now.getHours()}` : now.getHours();
|
||||
const minutes = now.getMinutes() < 10 ? `0${now.getMinutes()}` : now.getMinutes();
|
||||
const seconds = now.getSeconds() < 10 ? `0${now.getSeconds()}` : now.getSeconds();
|
||||
return `${day}.${month}.${year} ${hours}:${minutes}:${seconds}`;
|
||||
}
|
22
utils/getSlot.js
Normal file
22
utils/getSlot.js
Normal file
@ -0,0 +1,22 @@
|
||||
module.exports = (result) => {
|
||||
switch(result.dice.value){
|
||||
case 1:
|
||||
return 10
|
||||
case 22:
|
||||
return 15
|
||||
case 43:
|
||||
return 20
|
||||
case 64:
|
||||
return 25
|
||||
case 17: case 33: case 49:
|
||||
return 1
|
||||
case 6: case 38: case 54:
|
||||
return 2
|
||||
case 11: case 27: case 59:
|
||||
return 3
|
||||
case 16: case 32: case 48:
|
||||
return 4
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
20
utils/giveExp.js
Normal file
20
utils/giveExp.js
Normal file
@ -0,0 +1,20 @@
|
||||
const {
|
||||
Telegraf
|
||||
} = require('telegraf')
|
||||
const bot = new Telegraf(process.env.BOT_TOKEN)
|
||||
const {
|
||||
expToUp
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play Dev/config')
|
||||
|
||||
|
||||
module.exports = async (user, experience) => {
|
||||
user.exp += experience
|
||||
for(i in expToUp){
|
||||
if (user.exp >= expToUp[user.level]) {
|
||||
user.exp -= expToUp[user.level]
|
||||
user.level += 1
|
||||
user.save()
|
||||
await bot.telegram.sendMessage(user.telegram_id, `⤴️ Ваш уровень повысился до ${user.level}!`)}
|
||||
}
|
||||
user.save()
|
||||
}
|
10
utils/html-escape.js
Normal file
10
utils/html-escape.js
Normal file
@ -0,0 +1,10 @@
|
||||
module.exports = (str) => str.replace(
|
||||
/[&<>'"]/g,
|
||||
(tag) => ({
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
"'": ''',
|
||||
'"': '"'
|
||||
}[tag] || tag)
|
||||
)
|
33
utils/index.js
Normal file
33
utils/index.js
Normal file
@ -0,0 +1,33 @@
|
||||
const spaces = require('./spaces')
|
||||
const spacesWithMarkdown = require('./spacesV2')
|
||||
const escape = require('./escape')
|
||||
const generatePromo = require('./generatePromo')
|
||||
const generateVoucher = require('./generateVoucher')
|
||||
const getCurrentTime = require('./getCurrentTime')
|
||||
const getSlot = require('./getSlot')
|
||||
const giveExp = require('./giveExp')
|
||||
const matPriceUpdate = require('./matPriceUpdate')
|
||||
const rand = require('./rand')
|
||||
const random = require('./random')
|
||||
const setCooldown = require('./setCooldown')
|
||||
const weaponShopUpdate = require('./weaponShopUpdate')
|
||||
const stats = require('./stats')
|
||||
const escapeHTML = require('./html-escape')
|
||||
|
||||
module.exports = {
|
||||
spaces,
|
||||
spacesWithMarkdown,
|
||||
escape,
|
||||
generatePromo,
|
||||
generateVoucher,
|
||||
getCurrentTime,
|
||||
getSlot,
|
||||
giveExp,
|
||||
matPriceUpdate,
|
||||
rand,
|
||||
random,
|
||||
setCooldown,
|
||||
weaponShopUpdate,
|
||||
stats,
|
||||
escapeHTML
|
||||
}
|
11
utils/matPriceUpdate.js
Normal file
11
utils/matPriceUpdate.js
Normal file
@ -0,0 +1,11 @@
|
||||
const rand = require('./rand')
|
||||
const {
|
||||
WorldModel
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play/config')
|
||||
|
||||
module.exports = async () => {
|
||||
let world = await WorldModel.findByPk(1)
|
||||
let price = rand(35, 170)
|
||||
world.matPrice = price
|
||||
world.save()
|
||||
}
|
3
utils/rand.js
Normal file
3
utils/rand.js
Normal file
@ -0,0 +1,3 @@
|
||||
module.exports = (min, max) => {
|
||||
return Math.round(Math.random() * (max - min)) + min
|
||||
}
|
7
utils/random.js
Normal file
7
utils/random.js
Normal file
@ -0,0 +1,7 @@
|
||||
Array.prototype.random = function() {
|
||||
return this[Math.floor(this.length * Math.random())];
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
randomArray: Array.prototype.random
|
||||
};
|
26
utils/setCooldown.js
Normal file
26
utils/setCooldown.js
Normal file
@ -0,0 +1,26 @@
|
||||
module.exports = (user, seconds, type) => {
|
||||
let cooldown = {}
|
||||
cooldown.currentTime = Math.trunc(Date.now() / 1000)
|
||||
|
||||
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)
|
||||
return cooldown
|
||||
|
||||
}
|
4
utils/spaces.js
Normal file
4
utils/spaces.js
Normal file
@ -0,0 +1,4 @@
|
||||
module.exports = (string) => {
|
||||
if (typeof string !== "string") string = string.toString();
|
||||
return string.split("").reverse().join("").match(/[0-9]{1,3}/g).join(".").split("").reverse().join("");
|
||||
}
|
4
utils/spacesV2.js
Normal file
4
utils/spacesV2.js
Normal file
@ -0,0 +1,4 @@
|
||||
module.exports = (string) => {
|
||||
if (typeof string !== "string") string = string.toString();
|
||||
return string.split("").reverse().join("").match(/[0-9]{1,3}/g).join(".\\").split("").reverse().join("");
|
||||
}
|
61
utils/stats.js
Normal file
61
utils/stats.js
Normal file
@ -0,0 +1,61 @@
|
||||
const io = require('@pm2/io')
|
||||
|
||||
const stats = {
|
||||
rpsAvrg: 0,
|
||||
responseTimeAvrg: 0,
|
||||
times: {}
|
||||
}
|
||||
|
||||
const rtOP = io.metric({
|
||||
name: 'response time',
|
||||
unit: 'ms'
|
||||
})
|
||||
|
||||
// const usersCountIO = io.metric({
|
||||
// name: 'Users count',
|
||||
// unit: 'user'
|
||||
// })
|
||||
|
||||
setInterval(() => {
|
||||
if (Object.keys(stats.times).length > 1) {
|
||||
const time = Object.keys(stats.times).shift()
|
||||
|
||||
const sumResponseTime = stats.times[time].reduce((a, b) => a + b, 0)
|
||||
const lastResponseTimeAvrg = (sumResponseTime / stats.times[time].length) || 0
|
||||
if (stats.responseTimeAvrg > 0) stats.responseTimeAvrg = Math.round((stats.responseTimeAvrg + lastResponseTimeAvrg) / 2)
|
||||
else stats.responseTimeAvrg = lastResponseTimeAvrg
|
||||
|
||||
console.log('response time avrg total:', stats.responseTimeAvrg)
|
||||
|
||||
rtOP.set(stats.responseTimeAvrg)
|
||||
|
||||
// db.Stats.create({
|
||||
// rps,
|
||||
// responseTime: lastResponseTimeAvrg,
|
||||
// date: new Date()
|
||||
// })
|
||||
|
||||
delete stats.times[time]
|
||||
}
|
||||
}, 1000)
|
||||
|
||||
// setInterval(async () => {
|
||||
// const usersCount = await db.User.count({
|
||||
// updatedAt: {
|
||||
// $gte: new Date(Date.now() - 24 * 60 * 60 * 1000)
|
||||
// }
|
||||
// })
|
||||
|
||||
// usersCountIO.set(usersCount)
|
||||
// }, 60 * 1000)
|
||||
|
||||
module.exports = async (ctx, next) => {
|
||||
const startMs = new Date()
|
||||
|
||||
return next().then(() => {
|
||||
const now = Math.floor(new Date() / 1000)
|
||||
|
||||
if (!stats.times[now]) stats.times[now] = []
|
||||
stats.times[now].push(new Date() - startMs)
|
||||
})
|
||||
}
|
28
utils/weaponShopUpdate.js
Normal file
28
utils/weaponShopUpdate.js
Normal file
@ -0,0 +1,28 @@
|
||||
const rand = require('./rand')
|
||||
const {
|
||||
weaponshop,
|
||||
weapons,
|
||||
equipment,
|
||||
} = require('/workspace/degradin/Dev/Telegram/CampFire Play Dev/config')
|
||||
const fs = require('fs');
|
||||
|
||||
module.exports = () => {
|
||||
let weaponId = []
|
||||
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 = equipId.push(rand(1, 10))
|
||||
}
|
||||
for (i = 0; i < 5; i++) {
|
||||
weaponshop[i] = weapons[weaponId[i]]
|
||||
}
|
||||
for (i = 0; i < 5; i++) {
|
||||
weaponshop[counter] = equipment[equipId[i]]
|
||||
counter++
|
||||
}
|
||||
fs.writeFileSync('json/weaponshop.json', JSON.stringify(weaponshop, null, "\t"))
|
||||
}
|
Loading…
Reference in New Issue
Block a user