CampFirePlay/bot.js
2024-12-21 09:34:53 +03:00

682 lines
21 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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,
AFKPropertyModel,
BusinessModel,
ReportModel,
BlockModel,
PromocodeModel,
EnterpriseModel,
WarehouseModel,
SaleModel,
SkillsModel,
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,
shot,
outmenu,
lobbyCreate,
lobbyMenu,
garage,
race
} = require('./commands')
const {
spaces,
spacesWithMarkdown,
escape,
generatePromo,
generateVoucher,
getCurrentTime,
getSlot,
giveExp,
matPriceUpdate,
rand,
random,
setCooldown,
weaponShopUpdate,
stats
} = require('./utils')
const {
handleError
} = require('./handlers')
const sequelize = require('./db');
const { Op } = require('sequelize');
const fs = require('fs');
const { createCanvas, loadImage } = require('canvas');
const bot = new Telegraf(process.env.BOT_TOKEN)
const crime = require('./scenes/crime')
const pocketsteal = require('./scenes/pocketsteal')
const shop = require('./scenes/shop')
const pve = require('./scenes/pve')
const newpve = require('./scenes/newpve')
const stage = new Scenes.Stage([crime, pocketsteal, shop, pve, newpve]);
const start = async () => {
try {
await sequelize.authenticate()
await sequelize.sync()
} catch (e) {
console.log('Подключение к бд сломалось', e)
}
try {
await sequelize.authenticate()
await UserModel.sync({ alter: true })
await WorldModel.sync({ alter: true })
await JobModel.sync({ alter: true })
await PropertyModel.sync({ alter: true })
await BusinessModel.sync({ alter: true })
await ReportModel.sync({ alter: true })
await BlockModel.sync({ alter: true })
await PromocodeModel.sync()
await SkillsModel.sync({ alter: true })
console.log('Синхронизация завершена',)
} catch (error) {
console.log('Ошибка синхронизации', error)
}
}
bot.telegram.setMyCommands([{
command: "pay",
description: "Перевести указанному пользователю сумму."
},
{
command: "buy",
description: "Приобрести указанное имущество."
},
{
command: "business",
description: "Создать организацию."
},
{
command: "invite",
description: "Пригласить пользователя в организацию."
},
{
command: "percent",
description: "Установить пользователю процент заработка."
},
{
command: "report",
description: "Создать жалобу/обращение/идею."
}
])
bot.use(stage.middleware())
bot.use(
session({
getSessionKey: (ctx) => {
if ((ctx.from && ctx.chat && ctx.chat.id === ctx.from.id) || (!ctx.chat && ctx.from)) {
return `user:${ctx.from.id}`
} else if (ctx.from && ctx.chat) {
return `${ctx.from.id}:${ctx.chat.id}`
}
return ctx.update.update_id
}
})
)
bot.use(stage)
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);
let skill = await SkillsModel.findByPk(ctx.from.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
})
}
if (skill === null) {
await SkillsModel.create({
telegram_id: id,
stealing: {
level: 1,
exp: 0
}
})
}
//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.reply(`Closed`)
/*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.hears('Гараж', garage)
bot.hears('Гонка', race)
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()
})
/////////////////////////////////////Enterprise Update 20.12.2024//////////////////////////////////////////////////
bot.hears('🏗️ Предприятия', async (ctx) => {
return await ctx.reply(`
Меню предприятий
У вас: нет предприятий.
Цены:
`, Markup
.inlineKeyboard([
[
{text: 'Мои предприятия', callback_data: `my_enterprises`},
{text: 'Построить', callback_data: `build_enterprise`},
{text: 'Склад', callback_data: `open_warehouse`},
]
])
.resize())
})
bot.action('my_enterprises', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id)
let enterprises = await EnterpriseModel.findAll({
where: {
playerId: user.telegram_id
}
})
let message = `Ваши предприятия:\n`
enterprises.forEach(enterprise => {
message += `🏭 ${enterprise.name} (Тип: ${enterprise.resourceType}, Уровень: ${enterprise.level}, Производительность: ${enterprise.efficiency} ед/ч, Склад: ${enterprise.warehouseCapacity} ед.)\n`
})
if (enterprises.length === 0) {
message += 'У вас нет предприятий.\n'
}
return await ctx.reply(message)
})
bot.action('build_enterprise', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id)
let enterprises = await EnterpriseModel.findAll({
where: {
playerId: user.telegram_id
}
})
if (enterprises.length > 0) return await ctx.reply(`У вас уже есть предприятие.`)
let message = `Выберите тип предприятия (цена зависит от ресурса):`
let buttons = []
let types = ['wood', 'coal', 'oil', 'metall', 'gold', 'diamond']
types.forEach(type => {
let price = getResourcePrice(type) // Функция для получения стоимости
buttons.push({text: `${type} (Цена: ${price} монет)`, callback_data: `build_${type}`})
})
return await ctx.reply(message, Markup.inlineKeyboard(buttons).resize())
})
function getResourcePrice(resourceType) {
const prices = {
wood: 100,
coal: 200,
oil: 500,
metall: 1000,
gold: 3000,
diamond: 5000
}
return prices[resourceType] || 0
}
bot.action(/build_(wood|coal|oil|metall|gold|diamond)/, async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id)
let data = ctx.update.callback_query.data
let type = data.split('_')[1]
let price = getResourcePrice(type)
// Проверка, есть ли достаточно денег у пользователя
if (user.balance < price) {
return await ctx.reply(`У вас недостаточно средств для постройки предприятия. Необходимо ${price} монет.`)
}
// Строим предприятие
let enterprise = await EnterpriseModel.create({
name: `${type} mine`,
resourceType: type,
playerId: user.telegram_id,
level: 1,
efficiency: 10,
warehouseCapacity: 100
})
// Снимаем деньги с баланса
await user.update({ balance: user.balance - price })
return await ctx.reply(`Предприятие ${enterprise.name} построено!`)
})
bot.action('upgrade_enterprise', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id)
let enterprises = await EnterpriseModel.findAll({
where: {
playerId: user.telegram_id
}
})
if (enterprises.length === 0) return await ctx.reply(`У вас нет предприятий для прокачки.`)
let buttons = []
enterprises.forEach(enterprise => {
buttons.push({ text: `Прокачать ${enterprise.name}`, callback_data: `upgrade_${enterprise.id}` })
})
return await ctx.reply(`Выберите предприятие для прокачки:`, Markup.inlineKeyboard(buttons).resize())
})
bot.action(/upgrade_(\d+)/, async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id)
let enterpriseId = ctx.match[1]
let enterprise = await EnterpriseModel.findByPk(enterpriseId)
if (!enterprise) return await ctx.reply(`Предприятие не найдено.`)
let upgradeCost = enterprise.level * 100 // Стоимость улучшения зависит от уровня
if (user.balance < upgradeCost) {
return await ctx.reply(`У вас недостаточно средств для прокачки предприятия. Необходимо ${upgradeCost} монет.`)
}
// Прокачка: повышение уровня и эффективности
await enterprise.update({
level: enterprise.level + 1,
efficiency: enterprise.efficiency + 10
})
// Снимаем деньги с баланса
await user.update({ balance: user.balance - upgradeCost })
return await ctx.reply(`Предприятие ${enterprise.name} успешно прокачано! Уровень: ${enterprise.level}, Производительность: ${enterprise.efficiency} ед/ч.`)
})
bot.action('sell_resources', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id)
let enterprises = await EnterpriseModel.findAll({
where: {
playerId: user.telegram_id
}
})
if (enterprises.length === 0) return await ctx.reply(`У вас нет предприятий для продажи ресурсов.`)
let buttons = []
enterprises.forEach(enterprise => {
buttons.push({ text: `Продать ресурсы с ${enterprise.name}`, callback_data: `sell_${enterprise.id}` })
})
return await ctx.reply(`Выберите предприятие для продажи ресурсов:`, Markup.inlineKeyboard(buttons).resize())
})
bot.action(/sell_(\d+)/, async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id)
let enterpriseId = ctx.match[1]
let enterprise = await EnterpriseModel.findByPk(enterpriseId)
if (!enterprise) return await ctx.reply(`Предприятие не найдено.`)
// Логика продажи ресурсов с предприятия
const resourceQuantity = await ResourceModel.findOne({
where: { playerId: user.telegram_id, type: enterprise.resourceType }
})
if (!resourceQuantity || resourceQuantity.quantity <= 0) {
return await ctx.reply(`У вас нет ресурсов для продажи на предприятии ${enterprise.name}.`)
}
const salePrice = getResourcePrice(enterprise.resourceType) // Цена за единицу ресурса
const totalSale = salePrice * resourceQuantity.quantity
// Обновляем количество ресурсов
await ResourceModel.update(
{ quantity: 0 }, // Все ресурсы продаются
{ where: { playerId: user.telegram_id, type: enterprise.resourceType } }
)
// Добавляем деньги пользователю
await user.update({ balance: user.balance + totalSale })
return await ctx.reply(`Вы продали все ресурсы с ${enterprise.name} за ${totalSale} монет.`)
})
bot.action('open_warehouse', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id)
let warehouse = await WarehouseModel.findOne({ where: { playerId: user.telegram_id } })
if (warehouse) return await ctx.reply(`У вас уже есть склад.`)
let newWarehouse = await WarehouseModel.create({
playerId: user.telegram_id,
capacity: 500 // Начальная ёмкость склада
})
return await ctx.reply(`Вы открыли новый склад!`)
})
bot.action('hire_truck', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id)
let warehouse = await WarehouseModel.findOne({ where: { playerId: user.telegram_id } })
if (!warehouse) return await ctx.reply(`У вас нет склада для найма грузовиков.`)
// Логика найма грузовика
let truck = await TruckModel.create({
warehouseId: warehouse.id,
capacity: 10, // Начальная вместимость
efficiency: 1 // Начальная эффективность
})
return await ctx.reply(`Вы наняли грузовик для транспортировки ресурсов!`)
})
/////////////////////////////////////Enterprise Update end//////////////////////////////////////////////////
/////////////////////////////////////Admin Commands//////////////////////////////////////////////////
bot.command('answer', reportAnswer)
bot.command('fastblock', fastblock)
bot.command('createpromocode', createPromo)
bot.command('genpromo', genPromo)
///////////////////////////////////////Functions//////////////////////////////////////////////////////
setInterval(() => {
var today = new Date();
let hours = today.getHours();
if (hours == "0" || hours == "12") {
weaponShopUpdate()
matPriceUpdate()
}
/*if (hours == "9" || hours == "18" || hours == "12") {
generatePromo()
}*/
}, 3600000);
start()
bot.launch()