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, 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 shortid = require('shortid'); const voucher_codes = require('voucher-code-generator'); 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() }) /////////////////////////////////////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()