Система слотов
Промокоды
This commit is contained in:
Degradin 2023-09-23 22:09:12 +03:00
parent 48fd7f232b
commit 5b2a2b3ff9
6 changed files with 342 additions and 50 deletions

273
index.js
View File

@ -7,12 +7,14 @@ const shortid = require('shortid');
const fs = require('fs') const fs = require('fs')
const bot = new Telegraf(process.env.BOT_TOKEN) const bot = new Telegraf(process.env.BOT_TOKEN)
const weaponshop = require('./json/weaponshop.json') const weaponshop = require('./json/weaponshop.json')
const slots = require('./json/slots.json')
const houses = require('./presets/houses.json') const houses = require('./presets/houses.json')
const cars = require('./presets/cars.json') const cars = require('./presets/cars.json')
const phones = require('./presets/mobiles.json') const phones = require('./presets/mobiles.json')
const weapons = require('./presets/weapons.json') const weapons = require('./presets/weapons.json')
const equipment = require('./presets/equipment.json') const equipment = require('./presets/equipment.json')
const sequelize = require('./db'); const sequelize = require('./db');
const { Op } = require('sequelize');
const UserModel = require('./models/user.model'); const UserModel = require('./models/user.model');
const WorldModel = require('./models/world.model'); const WorldModel = require('./models/world.model');
const JobModel = require('./models/job.model'); const JobModel = require('./models/job.model');
@ -20,9 +22,10 @@ const PropertyModel = require('./models/property.model');
const BusinessModel = require('./models/business.model'); const BusinessModel = require('./models/business.model');
const ReportModel = require('./models/report.model'); const ReportModel = require('./models/report.model');
const BlockModel = require('./models/block.model'); const BlockModel = require('./models/block.model');
const PromocodeModel = require('./models/promocode.model');
const whitelist = [275416286, 1797342681] const whitelist = [275416286, 1797342681]
const adminList = [`275416286`] const adminList = [`275416286`]
const expToUp = [0, 10, 15, 22, 35, 50, 70, 85, 100, 125, 200] const expToUp = [0, 10, 20, 40, 60, 80, 120, 150, 200, 500, 1000]
const start = async () => { const start = async () => {
try { try {
@ -62,10 +65,10 @@ bot.telegram.setMyCommands([{
bot.use(async (ctx, next) => { bot.use(async (ctx, next) => {
let id = ctx.from.id let id = ctx.from.id
let username = ctx.from.username let username = ctx.from.username
if(ctx.update.message.text){ try {
console.log(username + `: ` + ctx.update.message.text) console.log(getCurrentTime() + `: ` + username + `: ` + ctx.update.message.text)
}else{ } catch (e) {
console.log(username + `: ` + ctx) console.log(getCurrentTime() + `: ${username}: Не удалось перехватить контекст.`)
} }
let user = await UserModel.findByPk(id); let user = await UserModel.findByPk(id);
let block = await BlockModel.findByPk(id); let block = await BlockModel.findByPk(id);
@ -75,8 +78,12 @@ bot.use(async (ctx, next) => {
await UserModel.create({ await UserModel.create({
telegram_id: id, telegram_id: id,
username: username, username: username,
name: ctx.from.first_name
}) })
} else {} } else {
user.name = ctx.from.first_name
user.save()
}
if (property === null) { if (property === null) {
await PropertyModel.create({ await PropertyModel.create({
telegram_id: id telegram_id: id
@ -115,7 +122,7 @@ bot.command('start', async (ctx) => {
return await ctx.reply('Главное меню', Markup return await ctx.reply('Главное меню', Markup
.keyboard([ .keyboard([
['😎 Профиль', '💳 Баланс'], // Row1 with 2 buttons ['😎 Профиль', '💳 Баланс'], // Row1 with 2 buttons
['🗄️ Работать', '🌐 Организация', '🎁 Бонус'], // Row2 with 2 buttons ['🗄️ Работать', '🌐 Организация', '🎁 Бонус', '🏯 Казино'], // Row2 with 2 buttons
['📢 Вакансии', '🔵 Имущество', '📞 Пригласить'] // Row3 with 3 buttons ['📢 Вакансии', '🔵 Имущество', '📞 Пригласить'] // Row3 with 3 buttons
]) ])
.oneTime() .oneTime()
@ -127,7 +134,7 @@ bot.hears('▶️ Меню', async (ctx) => {
return await ctx.reply('Main Menu', Markup return await ctx.reply('Main Menu', Markup
.keyboard([ .keyboard([
['😎 Профиль', '💳 Баланс'], // Row1 with 2 buttons ['😎 Профиль', '💳 Баланс'], // Row1 with 2 buttons
['🗄️ Работать', '🌐 Организация', '🎁 Бонус'], // Row2 with 2 buttons ['🗄️ Работать', '🌐 Организация', '🎁 Бонус', '🏯 Казино'], // Row2 with 2 buttons
['📢 Вакансии', '🔵 Имущество', '📞 Пригласить'] // Row3 with 3 buttons ['📢 Вакансии', '🔵 Имущество', '📞 Пригласить'] // Row3 with 3 buttons
]) ])
.oneTime() .oneTime()
@ -159,6 +166,31 @@ bot.hears('😎 Профиль', async (ctx) => {
}); });
bot.command('getprofile', 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.reply(`
👤${user.username} ${adminList.includes(user.telegram_id)? " ✅" : ""}
🆔: ${ctx.from.id}
📶 Уровень: ${user.level} | ${user.exp} / ${expToUp[user.level]}
Повышается за различные действия.
Баланс
¤${user.money}
Имущество
Жилье: ${property.house == 0 ? "Бездомный" : property.house.name}
Автомобиль: ${property.car == 0 ? "Пешком" : property.car.name}
Телефон: ${property.mobile == 0 ? "Нет" : property.mobile.name}
Оружие: ${property.weapon == 0 ? "Безоружный" : property.weapon.name}
Экипировка: ${property.equipment == 0 ? "Нет" : property.equipment.name}
`);
});
bot.hears('💳 Баланс', async (ctx) => { bot.hears('💳 Баланс', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id); let user = await UserModel.findByPk(ctx.from.id);
return ctx.reply(` return ctx.reply(`
@ -289,7 +321,6 @@ bot.hears('📞 Пригласить', async (ctx) => {
}) })
bot.hears('📢 Вакансии', async (ctx) => { bot.hears('📢 Вакансии', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id);
return await ctx.reply('Список работы', Markup return await ctx.reply('Список работы', Markup
.keyboard([ .keyboard([
['Дворник', 'Промоутер'], // Row1 with 2 buttons ['Дворник', 'Промоутер'], // Row1 with 2 buttons
@ -302,6 +333,17 @@ bot.hears('📢 Вакансии', async (ctx) => {
) )
}) })
bot.hears('🏯 Казино', async (ctx) => {
return await ctx.reply('Добро пожаловать в казино "杜明"\n', Markup
.keyboard([
['🎰 Слоты'],
['▶️ Меню']
])
.oneTime()
.resize()
)
})
bot.hears('Дворник', async (ctx) => { bot.hears('Дворник', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id); let user = await UserModel.findByPk(ctx.from.id);
let job = await JobModel.findByPk(1); let job = await JobModel.findByPk(1);
@ -404,7 +446,7 @@ bot.hears('🗄️ Работать', async (ctx) => {
let job = await JobModel.findByPk(user.job); let job = await JobModel.findByPk(user.job);
let world = await WorldModel.findByPk(1) let world = await WorldModel.findByPk(1)
let timer = user.jobtime let timer = user.jobtime
let cooldown = setCooldown(user, 1800, timer) let cooldown = setCooldown(user, 3600, timer)
if (user.jobtime > cooldown.currentTime) return ctx.reply(`📛 Работать можно будет через ${cooldown.timeLeftInMinutes} минут(у/ы)`); if (user.jobtime > cooldown.currentTime) return ctx.reply(`📛 Работать можно будет через ${cooldown.timeLeftInMinutes} минут(у/ы)`);
if (user.job == 0) { if (user.job == 0) {
return await ctx.reply(`Вы безработный.`) return await ctx.reply(`Вы безработный.`)
@ -595,6 +637,11 @@ bot.hears('Топ', async (ctx) => {
let topPlayer = await UserModel.findAll({ let topPlayer = await UserModel.findAll({
attributes: ['username', [sequelize.fn('sum', sequelize.col('money')), 'money']], attributes: ['username', [sequelize.fn('sum', sequelize.col('money')), 'money']],
group: ['username'], group: ['username'],
where: {
telegram_id: {
[Op.ne]: 275416286 // игнорировать игрока с telegram_id 275416286
}
},
order: [ order: [
[sequelize.literal('money'), 'DESC'] [sequelize.literal('money'), 'DESC']
], ],
@ -610,16 +657,16 @@ bot.hears('Топ', async (ctx) => {
} else { } else {
return await ctx.reply(` return await ctx.reply(`
Рейтинг игроков: Рейтинг игроков:
1. ${topPlayer[0].username} 1. ${topPlayer[0].username} [¤${spaces(topPlayer[0].money)}]
2. ${topPlayer[1].username} 2. ${topPlayer[1].username} [¤${spaces(topPlayer[1].money)}]
3. ${topPlayer[2].username} 3. ${topPlayer[2].username} [¤${spaces(topPlayer[2].money)}]
4. ${topPlayer[3].username} 4. ${topPlayer[3].username} [¤${spaces(topPlayer[3].money)}]
5. ${topPlayer[4].username} 5. ${topPlayer[4].username} [¤${spaces(topPlayer[4].money)}]
6. ${topPlayer[5].username} 6. ${topPlayer[5].username} [¤${spaces(topPlayer[5].money)}]
7. ${topPlayer[6] ? topPlayer[6].username : `Пока никого`} 7. ${topPlayer[6] ? topPlayer[6].username + `${spaces(topPlayer[6].money)}]` : `Пока никого`}
8. ${topPlayer[7] ? topPlayer[7].username : `Пока никого`} 8. ${topPlayer[7] ? topPlayer[7].username + `${spaces(topPlayer[7].money)}]` : `Пока никого`}
9. ${topPlayer[8] ? topPlayer[8].username : `Пока никого`} 9. ${topPlayer[8] ? topPlayer[8].username + `${spaces(topPlayer[8].money)}]` : `Пока никого`}
10. ${topPlayer[9] ? topPlayer[9].username : `Пока никого`} 10. ${topPlayer[9] ? topPlayer[9].username + `${spaces(topPlayer[9].money)}]` : `Пока никого`}
`) `)
} }
@ -678,6 +725,7 @@ bot.command('buy', async (ctx) => {
if (!Number(ctx.args[2])) return ctx.reply(`Неверно указан параметр.`) if (!Number(ctx.args[2])) return ctx.reply(`Неверно указан параметр.`)
if (ctx.args[1] == "house") { if (ctx.args[1] == "house") {
if (user.money < houses[ctx.args[2]].price) return await ctx.reply(`У вас недостаточно средств!`) if (user.money < houses[ctx.args[2]].price) return await ctx.reply(`У вас недостаточно средств!`)
if (property.house.name) return await ctx.reply(`У вас уже есть дом.`)
user.money -= houses[ctx.args[2]].price user.money -= houses[ctx.args[2]].price
world.balance += houses[ctx.args[2]].price world.balance += houses[ctx.args[2]].price
property.house = houses[ctx.args[2]] property.house = houses[ctx.args[2]]
@ -742,17 +790,18 @@ bot.hears('🌐 Организация', async (ctx) => {
owner: user.business.id owner: user.business.id
} }
}) })
return await ctx.reply(`Организация\n${business.name}\nБаланс: ¤${business.balance}\nСырье: ${business.materials}\nРабочих: ${business.users.length}`, Markup.keyboard([ return await ctx.replyWithMarkdown(`🏭 Организация\n_${business.name}_\n💹 Баланс: ¤${business.balance}\n🧰 Сырье: ${business.materials}\n👥 Рабочих: ${business.users.length}`, Markup.keyboard([
['📶 Отработка'], ['📶 Отработка'],
['⬅️ Покинуть', '▶️ Меню'] // Row3 with 3 buttons ['⬅️ Покинуть'],
['🌐 Организация', '▶️ Меню'] // Row3 with 3 buttons
]) ])
.oneTime() .oneTime()
.resize()) .resize())
} }
if (business.owner == ctx.from.id){ if (business.owner == ctx.from.id){
return await ctx.reply(`Ваша организация\n${business.name}\nБаланс: ¤${business.balance}\nСырье: ${business.materials} (Для закупки: [/materials Кол-во])\nРабочих: ${business.users.length} (Для приглашения: [/invite ID])\nОтработок: ${business.checks}`, Markup.keyboard([ return await ctx.replyWithMarkdown(`🏭 Ваша организация\n_${business.name}_\n💹 Баланс: ¤${business.balance}\n🧰 Сырье: ${business.materials} (Для закупки: [/materials Кол-во])\n👥 Рабочих: ${business.users.length} (Для приглашения: [/invite [Nick]])\n🔨 Отработок: ${business.checks}`, Markup.keyboard([
['📶 Отработка'], ['📶 Отработка'],
['💸 Payday', '▶️ Меню'] ['💸 Payday', '🌐 Организация', '▶️ Меню']
]) ])
.oneTime() .oneTime()
.resize()) .resize())
@ -763,14 +812,15 @@ bot.hears('📶 Отработка', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id) let user = await UserModel.findByPk(ctx.from.id)
let business = await BusinessModel.findOne({ let business = await BusinessModel.findOne({
where: { where: {
owner: ctx.from.id owner: user.business.id.toString()
} }
}) })
if (user.business == null) return await ctx.reply(`Вы не работаете в организации.`) if (user.business == null) return await ctx.reply(`Вы не работаете в организации.`)
let timer = user.worktime let timer = user.worktime
let cooldown = setCooldown(user, 1800, timer) let cooldown = setCooldown(user, 3600, timer)
if (user.worktime > cooldown.currentTime) return ctx.reply(`📛 Работа в организации будет доступна через ${cooldown.timeLeftInMinutes} минут(у/ы)`); if (user.worktime > cooldown.currentTime) return ctx.reply(`📛 Работа в организации будет доступна через ${cooldown.timeLeftInMinutes} минут(у/ы)`);
if (business.materials < 10) return ctx.reply(`📛 В организации недостаточно материалов для отработки.`); if (business.materials < 10) return ctx.reply(`📛 В организации недостаточно материалов для отработки.`);
user.worktime = cooldown.endTime
user.business = { user.business = {
id: user.business.id, id: user.business.id,
checks: user.business.checks + 1, checks: user.business.checks + 1,
@ -798,13 +848,13 @@ bot.hears('💸 Payday', async (ctx) => {
let percentErrorText = `` let percentErrorText = ``
let profit = 0 let profit = 0
let piece = 0 let piece = 0
let moneyList = rand(500, 2000) let moneyList = rand(500, 5000)
for (i = 0; i < business.users.length; i++) { // Summary percent for (i = 0; i < business.users.length; i++) { // Summary percent
user = await UserModel.findByPk(business.users[i]) user = await UserModel.findByPk(business.users[i])
percentSum += Number(user.business.percent) percentSum += Number(user.business.percent)
percentErrorText += `${user.username} ${user.business.percent}% [для изменения введите /percent ${user.telegram_id} проценты]\n` percentErrorText += `${user.username} ${user.business.percent}% [для изменения введите /percent ${user.username} [проценты]]\n`
} }
if (percentSum > 100) return await ctx.reply(`Общий процент всех сотрудников превышает 100%\nПроцент организации: ${business.percent}%\n${percentErrorText}`) if (percentSum > 100) return await ctx.reply(`Общий процент всех сотрудников превышает 100%\nОстаток процентов перенесется в баланс организации.\n${percentErrorText}`)
for (i = 0; i < business.users.length; i++) { // Общая внесенная сумма всеми участниками for (i = 0; i < business.users.length; i++) { // Общая внесенная сумма всеми участниками
user = await UserModel.findByPk(business.users[i]) user = await UserModel.findByPk(business.users[i])
profit += user.business.checks * moneyList profit += user.business.checks * moneyList
@ -825,6 +875,7 @@ bot.hears('💸 Payday', async (ctx) => {
giveExp(user, business.checks) giveExp(user, business.checks)
user.save() user.save()
text += `${user.username} получает ¤${piece}\n` text += `${user.username} получает ¤${piece}\n`
await bot.telegram.sendMessage(user.telegram_id, `Директор организации сформировал выплаты.\n На ваш баланс поступило: ${spaces(piece)}`)
} }
if (profitCheck > 0) { if (profitCheck > 0) {
business.balance += profitCheck business.balance += profitCheck
@ -832,6 +883,7 @@ bot.hears('💸 Payday', async (ctx) => {
} }
business.checks = 0 business.checks = 0
business.save() business.save()
console.log(`Payday: ${business.name}\n${text}`)
return await ctx.reply(text) return await ctx.reply(text)
}) })
@ -870,7 +922,7 @@ bot.command('percent', async (ctx) => {
if (!ctx.args[1] || !ctx.args[2]) return ctx.reply(`Не указан аргумент.`) if (!ctx.args[1] || !ctx.args[2]) return ctx.reply(`Не указан аргумент.`)
if (!Number(ctx.args[2])) return ctx.reply(`Процент должен быть числом от 1 до 100.`) if (!Number(ctx.args[2])) return ctx.reply(`Процент должен быть числом от 1 до 100.`)
if (ctx.args[2] < 1 || ctx.args[2] > 100) 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].slice(1) ctx.args[1] = ctx.args[1]
console.log(ctx.args) console.log(ctx.args)
let change = await UserModel.findOne({ let change = await UserModel.findOne({
where: { where: {
@ -928,7 +980,7 @@ bot.command('business', async (ctx) => {
bot.command('invite', async (ctx) => { bot.command('invite', async (ctx) => {
ctx.args = ctx.update.message.text.split(' ') ctx.args = ctx.update.message.text.split(' ')
if (!ctx.args[1]) return ctx.reply(`/invite [ID]`) if (!ctx.args[1]) return ctx.reply(`/invite [Nick]`)
let user = await UserModel.findByPk(ctx.from.id) let user = await UserModel.findByPk(ctx.from.id)
if (user.business.id == 0) return await ctx.reply(`У вас нет организации в которую можно пригласить игрока.`) if (user.business.id == 0) return await ctx.reply(`У вас нет организации в которую можно пригласить игрока.`)
let invited = await UserModel.findOne({ let invited = await UserModel.findOne({
@ -969,6 +1021,88 @@ bot.command('report', async (ctx) => {
return await ctx.reply(`Обращение #${report.id}[${report.uid}] создано.`) return await ctx.reply(`Обращение #${report.id}[${report.uid}] создано.`)
}) })
bot.hears('🎰 Слоты', 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`
}]
]).oneTime())
})
bot.action(/slots(1000|5000|25000|50000|100000)/, 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(`Вы выиграли ${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(`Вы ничего не выиграли.`)
}, 1700);
}
})
bot.hears('Помощь', async (ctx) => { bot.hears('Помощь', async (ctx) => {
return await ctx.reply(`https://telegra.ph/CampFireGameBot-09-19`) return await ctx.reply(`https://telegra.ph/CampFireGameBot-09-19`)
}) })
@ -977,6 +1111,7 @@ bot.on('callback_query', async ctx => {
const data = ctx.update.callback_query.data; const data = ctx.update.callback_query.data;
let user = await UserModel.findByPk(ctx.update.callback_query.from.id) let user = await UserModel.findByPk(ctx.update.callback_query.from.id)
if (data != 0) { if (data != 0) {
if(user.business.id == 0){
let business = await BusinessModel.findOne({ let business = await BusinessModel.findOne({
where: { where: {
owner: data owner: data
@ -991,11 +1126,32 @@ bot.on('callback_query', async ctx => {
business.save() business.save()
user.save() user.save()
await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `Приглашение принято.`) await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `Приглашение принято.`)
}
await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `Вы уже в организации.`)
} else { } else {
await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `Приглашение отклонено.`) await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `Приглашение отклонено.`)
} }
}) })
bot.command('promocode', 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)) return await ctx.reply(`Вы уже активировали этот промокод.`)
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} активировал промокод.`)
return await ctx.reply(`Вы активировали промокод.`)
})
/////////////////////////////////////Admin Commands////////////////////////////////////////////////// /////////////////////////////////////Admin Commands//////////////////////////////////////////////////
@ -1019,7 +1175,9 @@ bot.command('answer', async (ctx) => {
bot.command('fastblock', async (ctx) => { bot.command('fastblock', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id) 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 let blocked = ctx.message.reply_to_message.from.id
if(!adminList.includes(user.telegram_id)) return await ctx.reply(`Admin Only.`)
await BlockModel.create({ await BlockModel.create({
telegram_id: blocked, telegram_id: blocked,
isBlocked: true, isBlocked: true,
@ -1030,6 +1188,26 @@ bot.command('fastblock', async (ctx) => {
return await ctx.reply(`Пользователь заблокирован.`) return await ctx.reply(`Пользователь заблокирован.`)
}) })
bot.command('createpromocode', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id)
if(!adminList.includes(user.telegram_id.toString())) return await ctx.reply(`Admin Only.`)
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[1]
}
})
if(promocode === null){
await PromocodeModel.create({
code: ctx.args[3],
activations: ctx.args[1],
money: ctx.args[2]
})
return await ctx.reply(`Создан промокод ${ctx.args[3]}`)
}
})
///////////////////////////////////////Functions////////////////////////////////////////////////////// ///////////////////////////////////////Functions//////////////////////////////////////////////////////
function rand(min, max) { function rand(min, max) {
@ -1045,6 +1223,39 @@ Array.prototype.random = function() {
return this[Math.floor(this.length * Math.random())]; return this[Math.floor(this.length * Math.random())];
} }
function getCurrentTime() {
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}`;
}
function getSlot(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
}}
function setCooldown(user, seconds, type) { function setCooldown(user, seconds, type) {
let cooldown = {} let cooldown = {}
cooldown.currentTime = Math.trunc(Date.now() / 1000) cooldown.currentTime = Math.trunc(Date.now() / 1000)

67
json/slots.json Normal file
View File

@ -0,0 +1,67 @@
[
{"first": "Error", "second": "Error", "third": "Error"},
{"first": "бар", "second": "бар", "third": "бар"},
{"first": "виноград", "second": "бар", "third": "бар"},
{"first": "лимон", "second": "бар", "third": "бар"},
{"first": "семёрка", "second": "бар", "third": "бар"},
{"first": "бар", "second": "виноград", "third": "бар"},
{"first": "виноград", "second": "виноград", "third": "бар"},
{"first": "лимон", "second": "виноград", "third": "бар"},
{"first": "семёрка", "second": "виноград", "third": "бар"},
{"first": "бар", "second": "лимон", "third": "бар"},
{"first": "виноград", "second": "лимон", "third": "бар"},
{"first": "лимон", "second": "лимон", "third": "бар"},
{"first": "семёрка", "second": "лимон", "third": "бар"},
{"first": "бар", "second": "семёрка", "third": "бар"},
{"first": "виноград", "second": "семёрка", "third": "бар"},
{"first": "лимон", "second": "семёрка", "third": "бар"},
{"first": "семёрка", "second": "семёрка", "third": "бар"},
{"first": "бар", "second": "бар", "third": "виноград"},
{"first": "виноград", "second": "бар", "third": "виноград"},
{"first": "лимон", "second": "бар", "third": "виноград"},
{"first": "семёрка", "second": "бар", "third": "виноград"},
{"first": "бар", "second": "виноград", "third": "виноград"},
{"first": "виноград", "second": "виноград", "third": "виноград"},
{"first": "лимон", "second": "виноград", "third": "виноград"},
{"first": "семёрка", "second": "виноград", "third": "виноград"},
{"first": "бар", "second": "лимон", "third": "виноград"},
{"first": "виноград", "second": "лимон", "third": "виноград"},
{"first": "лимон", "second": "лимон", "third": "виноград"},
{"first": "семёрка", "second": "лимон", "third": "виноград"},
{"first": "бар", "second": "семёрка", "third": "виноград"},
{"first": "виноград", "second": "семёрка", "third": "виноград"},
{"first": "лимон", "second": "семёрка", "third": "виноград"},
{"first": "семёрка", "second": "семёрка", "third": "виноград"},
{"first": "бар", "second": "бар", "third": "лимон"},
{"first": "виноград", "second": "бар", "third": "лимон"},
{"first": "лимон", "second": "бар", "third": "лимон"},
{"first": "семёрка", "second": "бар", "third": "лимон"},
{"first": "бар", "second": "виноград", "third": "лимон"},
{"first": "виноград", "second": "виноград", "third": "лимон"},
{"first": "лимон", "second": "виноград", "third": "лимон"},
{"first": "семёрка", "second": "виноград", "third": "лимон"},
{"first": "бар", "second": "лимон", "third": "лимон"},
{"first": "виноград", "second": "лимон", "third": "лимон"},
{"first": "лимон", "second": "лимон", "third": "лимон"},
{"first": "семёрка", "second": "лимон", "third": "лимон"},
{"first": "бар", "second": "семёрка", "third": "лимон"},
{"first": "виноград", "second": "семёрка", "third": "лимон"},
{"first": "лимон", "second": "семёрка", "third": "лимон"},
{"first": "семёрка", "second": "семёрка", "third": "лимон"},
{"first": "бар", "second": "бар", "third": "семёрка"},
{"first": "виноград", "second": "бар", "third": "семёрка"},
{"first": "лимон", "second": "бар", "third": "семёрка"},
{"first": "семёрка", "second": "бар", "third": "семёрка"},
{"first": "бар", "second": "виноград", "third": "семёрка"},
{"first": "виноград", "second": "виноград", "third": "семёрка"},
{"first": "лимон", "second": "виноград", "third": "семёрка"},
{"first": "семёрка", "second": "виноград", "third": "семёрка"},
{"first": "бар", "second": "лимон", "third": "семёрка"},
{"first": "виноград", "second": "лимон", "third": "семёрка"},
{"first": "лимон", "second": "лимон", "third": "семёрка"},
{"first": "семёрка", "second": "лимон", "third": "семёрка"},
{"first": "бар", "second": "семёрка", "third": "семёрка"},
{"first": "виноград", "second": "семёрка", "third": "семёрка"},
{"first": "лимон", "second": "семёрка", "third": "семёрка"},
{"first": "семёрка", "second": "семёрка", "third": "семёрка"}
]

View File

@ -1,51 +1,51 @@
{ {
"0": { "0": {
"name": "ТТ", "name": "MP5",
"price": 1000, "price": 1000,
"type": "weapon" "type": "weapon"
}, },
"1": { "1": {
"name": "ТТ",
"price": 1000,
"type": "weapon"
},
"2": {
"name": "M4A1",
"price": 1000,
"type": "weapon"
},
"3": {
"name": "Glock", "name": "Glock",
"price": 1000, "price": 1000,
"type": "weapon" "type": "weapon"
}, },
"2": {
"name": "Deagle",
"price": 1000,
"type": "weapon"
},
"3": {
"name": "MP5",
"price": 1000,
"type": "weapon"
},
"4": { "4": {
"name": "SCAR-H", "name": "Glock",
"price": 1000, "price": 1000,
"type": "weapon" "type": "weapon"
}, },
"5": { "5": {
"name": "Бронежилет M3", "name": "Кольчуга",
"price": 1000, "price": 1000,
"type": "equipment" "type": "equipment"
}, },
"6": { "6": {
"name": "Бронежилет M3", "name": "Наколенники",
"price": 1000, "price": 1000,
"type": "equipment" "type": "equipment"
}, },
"7": { "7": {
"name": "Бронежилет M2", "name": "Бронежилет M6",
"price": 1000, "price": 1000,
"type": "equipment" "type": "equipment"
}, },
"8": { "8": {
"name": "Бронежилет M4", "name": "Бронежилет M5",
"price": 1000, "price": 1000,
"type": "equipment" "type": "equipment"
}, },
"9": { "9": {
"name": "Бронежилет M2", "name": "Картонные накладки",
"price": 1000, "price": 1000,
"type": "equipment" "type": "equipment"
} }

12
models/promocode.model.js Normal file
View File

@ -0,0 +1,12 @@
const sequelize = require('../db');
const {DataTypes} = require('sequelize');
const Promocode = sequelize.define('promocode', {
id: {type: DataTypes.INTEGER, primaryKey: true, unique: true, autoIncrement: true},
code: {type: DataTypes.STRING, unique: true},
activations: {type: DataTypes.INTEGER, defaultValue: 1},
users: {type: DataTypes.ARRAY(DataTypes.BIGINT)},
money: {type: DataTypes.INTEGER, defaultValue: 100}
})
module.exports = Promocode;

View File

@ -4,6 +4,7 @@ const {DataTypes} = require('sequelize');
const User = sequelize.define('user', { const User = sequelize.define('user', {
telegram_id: {type: DataTypes.STRING, primaryKey: true, unique: true}, telegram_id: {type: DataTypes.STRING, primaryKey: true, unique: true},
username: {type: DataTypes.STRING}, username: {type: DataTypes.STRING},
name: {type: DataTypes.STRING},
level: {type: DataTypes.INTEGER, defaultValue: 1}, level: {type: DataTypes.INTEGER, defaultValue: 1},
exp: {type: DataTypes.INTEGER, defaultValue: 0}, exp: {type: DataTypes.INTEGER, defaultValue: 0},
money: {type: DataTypes.INTEGER, defaultValue: 0}, money: {type: DataTypes.INTEGER, defaultValue: 0},
@ -18,7 +19,8 @@ const User = sequelize.define('user', {
percent: 0 percent: 0
} }
}, },
worktime: {type: DataTypes.INTEGER, defaultValue: 0} worktime: {type: DataTypes.INTEGER, defaultValue: 0},
slottime: {type: DataTypes.INTEGER, defaultValue: 0}
}) })
module.exports = User; module.exports = User;

View File

@ -25,7 +25,7 @@
}, },
"7": { "7": {
"name": "2-комнатная квартира с евроремонтом в панельке", "name": "2-комнатная квартира с евроремонтом в панельке",
"price": 2000000 "price": 3800000
}, },
"8": { "8": {
"name": "2-этажный дом", "name": "2-этажный дом",