v.0.1.1-rc

This commit is contained in:
Degradin 2025-01-01 15:25:27 +03:00
parent b5ef5f0eda
commit edac4d8761
3 changed files with 109 additions and 56 deletions

102
bot.js
View File

@ -350,13 +350,33 @@ bot.action(/{"action": "sueta_*/, async (ctx) => {
// Обновление меню "Предприятия" // Обновление меню "Предприятия"
bot.hears('🏗️ Предприятия', async (ctx) => { bot.hears('🏗️ Предприятия', async (ctx) => {
try {
const user = await UserModel.findByPk(ctx.from.id); const user = await UserModel.findByPk(ctx.from.id);
if (!user) {
console.error('Ошибка: пользователь не найден');
return await ctx.reply('Ошибка: пользователь не найден.');
}
console.log('ID пользователя:', user.telegram_id);
const warehouse = await WarehouseModel.findOne({ where: { playerId: user.telegram_id } }); const warehouse = await WarehouseModel.findOne({ where: { playerId: user.telegram_id } });
if (!warehouse) {
console.log('Склад не найден для пользователя:', user.telegram_id);
} else {
console.log('Найден склад:', warehouse);
}
const enterprises = await EnterpriseModel.findAll({ const enterprises = await EnterpriseModel.findAll({
where: { playerId: user.telegram_id } where: { playerId: user.telegram_id }
}); });
if (!enterprises.length) {
console.log('Предприятия не найдены для пользователя:', user.telegram_id);
} else {
console.log('Количество предприятий:', enterprises.length);
}
let message = `🏗️ Меню предприятий:\n`; let message = `🏗️ Меню предприятий:\n`;
message += `У вас: ${enterprises.length} предприятий.\n`; message += `У вас: ${enterprises.length} предприятий.\n`;
message += warehouse message += warehouse
@ -364,21 +384,24 @@ bot.hears('🏗️ Предприятия', async (ctx) => {
: `🗄️ Единый склад: Не построен.\n`; : `🗄️ Единый склад: Не построен.\n`;
const buttons = []; const buttons = [];
// Добавляем кнопки для предприятий
buttons.push([{ text: '🏭 Мои предприятия', callback_data: 'my_enterprises' }]); buttons.push([{ text: '🏭 Мои предприятия', callback_data: 'my_enterprises' }]);
buttons.push([{ text: '🛠️ Построить предприятие', callback_data: 'build_enterprise' }]); buttons.push([{ text: '🛠️ Построить предприятие', callback_data: 'build_enterprise' }]);
// Кнопка для управления или постройки склада
if (warehouse) { if (warehouse) {
buttons.push([{ text: '🚛 Управление складом', callback_data: 'manage_warehouse' }]); buttons.push([{ text: '🚛 Управление складом', callback_data: 'manage_warehouse' }]);
} else { } else {
buttons.push([{ text: '🗄️ Построить склад', callback_data: 'buy_warehouse' }]); buttons.push([{ text: '🗄️ Построить склад', callback_data: 'buy_warehouse' }]);
} }
buttons.push([{ text: '💰 Продать ресурсы', callback_data: 'sell_resources' }])
// Возвращаем меню с кнопками buttons.push([{ text: '💰 Продать ресурсы', callback_data: 'sell_resources' }]);
return await ctx.reply(message, Markup.inlineKeyboard(buttons).resize()); return await ctx.reply(message, Markup.inlineKeyboard(buttons).resize());
} catch (error) {
console.error('Ошибка при выполнении команды "🏗️ Предприятия":', error);
return await ctx.reply('Произошла ошибка при выполнении команды. Попробуйте позже.');
}
}); });
bot.action('enterprise_menu', async (ctx) => { bot.action('enterprise_menu', async (ctx) => {
const user = await UserModel.findByPk(ctx.from.id); const user = await UserModel.findByPk(ctx.from.id);
const warehouse = await WarehouseModel.findOne({ where: { playerId: user.telegram_id } }); const warehouse = await WarehouseModel.findOne({ where: { playerId: user.telegram_id } });
@ -432,7 +455,9 @@ bot.action('my_enterprises', async (ctx) => {
if (enterprises.length === 0) { if (enterprises.length === 0) {
return await ctx.reply('У вас нет предприятий.'); return await ctx.reply('У вас нет предприятий.');
} }
let metallPrice = 0 let metallPrice = await ResourcePriceModel.findOne({
where: { resource: "metall" }
});
let message = `🏭 Мои предприятия:\n\n`; let message = `🏭 Мои предприятия:\n\n`;
const buttons = []; const buttons = [];
@ -443,7 +468,6 @@ bot.action('my_enterprises', async (ctx) => {
}); });
let price = resourcePrice.price * 2 * 10 * 24 * 7 // Стоимость улучшения зависит от уровня let price = resourcePrice.price * 2 * 10 * 24 * 7 // Стоимость улучшения зависит от уровня
message += `🔹 [ID: ${id}] ${getEnterpriseEmoji(resourceType)} ${name} st. ${level}\n └── ${currentResources}/${warehouseCapacity} [${efficiency} ед/ч]\n └──📈 ${utils.spaces(price)} руб.\n\n`; message += `🔹 [ID: ${id}] ${getEnterpriseEmoji(resourceType)} ${name} st. ${level}\n └── ${currentResources}/${warehouseCapacity} [${efficiency} ед/ч]\n └──📈 ${utils.spaces(price)} руб.\n\n`;
if (resourcePrice.resource == "metall") metallPrice = resourcePrice.price
const truck = await TruckModel.findOne({ where: { enterpriseId: id } }); const truck = await TruckModel.findOne({ where: { enterpriseId: id } });
const warehouse = await WarehouseModel.findOne({ where: { playerId: user.telegram_id } }); const warehouse = await WarehouseModel.findOne({ where: { playerId: user.telegram_id } });
@ -465,7 +489,7 @@ bot.action('my_enterprises', async (ctx) => {
buttons.push(enterpriseButtons); buttons.push(enterpriseButtons);
} }
message += `\n\n📈 - Улучшить\n🛻 - Купить грузовик [~${utils.spaces(metallPrice*700)} руб.]\n🚛 - Улучшить грузовик\n💰 - Продать ресурсы с предприятия\n🔄 - Перевезти все на склад` message += `\n\n📈 - Улучшить\n🛻 - Купить грузовик [~${utils.spaces(metallPrice.price*700)} руб.]\n🚛 - Улучшить грузовик\n💰 - Продать ресурсы с предприятия\n🔄 - Перевезти все на склад`
buttons.push([{ text: '⬅️ Назад', callback_data: 'enterprise_menu' }]); buttons.push([{ text: '⬅️ Назад', callback_data: 'enterprise_menu' }]);
return await ctx.editMessageText(message, Markup.inlineKeyboard(buttons).resize()); return await ctx.editMessageText(message, Markup.inlineKeyboard(buttons).resize());
@ -530,7 +554,7 @@ bot.action(/build_(wood|coal|oil|metall|gold|diamond)/, async (ctx) => {
let price = resourcePrice.price * 2 * 10 * 24 * 7 let price = resourcePrice.price * 2 * 10 * 24 * 7
// Проверка, есть ли достаточно денег у пользователя // Проверка, есть ли достаточно денег у пользователя
if (user.balance < price) { if (user.money < price) {
return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `У вас недостаточно средств для постройки предприятия. Необходимо ${price} руб.`, {show_alert: true}) return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `У вас недостаточно средств для постройки предприятия. Необходимо ${price} руб.`, {show_alert: true})
} }
@ -577,14 +601,37 @@ function getReadableResourceType(type) {
} }
bot.action('buy_warehouse', async (ctx) => { bot.action('buy_warehouse', async (ctx) => {
let user = await UserModel.findByPk(ctx.from.id) try {
if (user.status != 'admin') { // Получаем пользователя
return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `Мы работаем над этим.`, {show_alert: true}) let user = await UserModel.findByPk(ctx.from.id);
} if (!user) {
if (user.money < 500000) { return await ctx.reply('Произошла ошибка. Пользователь не найден.');
return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id,`У вас недостаточно средств для покупки склада.`, {show_alert: true})
} }
// Получаем цены на металл и дерево
const woodPrice = await ResourcePriceModel.findOne({ where: { resource: 'wood' } });
const metallPrice = await ResourcePriceModel.findOne({ where: { resource: 'metall' } });
if (!woodPrice || !metallPrice) {
return await ctx.reply('Не удалось получить цены на ресурсы. Попробуйте позже.');
}
// Формируем стоимость склада
const warehouseBaseCost = 10; // Коэффициент для расчёта
const warehouseCost = Math.round(
(woodPrice.price + metallPrice.price) * warehouseBaseCost * 10 * 24 * 7
);
// Проверяем, хватает ли денег у пользователя
if (user.money < warehouseCost) {
return await ctx.telegram.answerCbQuery(
ctx.callbackQuery.id,
`У вас недостаточно средств для покупки склада. Необходимо: ${utils.spaces(warehouseCost)} руб.`,
{ show_alert: true }
);
}
// Создаём склад
await WarehouseModel.create({ await WarehouseModel.create({
playerId: user.telegram_id, playerId: user.telegram_id,
capacity: 1000, // Начальная ёмкость capacity: 1000, // Начальная ёмкость
@ -593,12 +640,21 @@ bot.action('buy_warehouse', async (ctx) => {
oil: 0, oil: 0,
metall: 0, metall: 0,
gold: 0, gold: 0,
diamond: 0 diamond: 0,
}) });
await user.update({ money: user.money - 500000 }) // Списываем деньги
return await ctx.reply(`Вы успешно купили единый склад!`) await user.update({ money: user.money - warehouseCost });
})
// Уведомление об успешной покупке
return await ctx.reply(
`Вы успешно купили единый склад за ${warehouseCost} руб!`
);
} catch (error) {
console.error('Ошибка при покупке склада:', error);
return await ctx.reply('Произошла ошибка при покупке склада. Попробуйте позже.');
}
});
// Управление складом // Управление складом
bot.action('manage_warehouse', async (ctx) => { bot.action('manage_warehouse', async (ctx) => {
@ -924,7 +980,7 @@ bot.action(/confirm_ressell_(\d+)/, async (ctx) => {
await resourcePrice.save(); await resourcePrice.save();
updateResourcePricesMessage(); updateResourcePricesMessage();
await ctx.editMessageText(`Вы успешно продали ${currentResources} ед. ${resourceType} за ${totalPrice} руб.`); await ctx.editMessageText(`Вы успешно продали ${currentResources} ед. ${getEnterpriseEmoji(resourceType)} за ${totalPrice} руб.`);
}); });
// Продажа ресурсов со склада // Продажа ресурсов со склада
@ -1170,8 +1226,8 @@ const getWarehouseUsedCapacity = (warehouse) => {
return resources.reduce((sum, resource) => sum + (warehouse[resource] || 0), 0); return resources.reduce((sum, resource) => sum + (warehouse[resource] || 0), 0);
}; };
const CHANNEL_ID = '@campfiregg'; // Замените на username вашего канала const CHANNEL_ID = '@CampFireGameBotNews'; // Замените на username вашего канала
let resourceMessageId = 4; // Хранение ID сообщения let resourceMessageId = 18; // Хранение ID сообщения
const previousPrices = {}; // Объект для хранения предыдущих цен const previousPrices = {}; // Объект для хранения предыдущих цен

View File

@ -27,11 +27,8 @@ const Enterprise = sequelize.define('enterprise', {
defaultValue: 0 // Начальное количество ресурсов defaultValue: 0 // Начальное количество ресурсов
}, },
playerId: { playerId: {
type: Sequelize.INTEGER, type: Sequelize.BIGINT,
references: { allowNull: false
model: 'users',
key: 'telegram_id'
}
} }
}); });

View File

@ -2,7 +2,7 @@ const sequelize = require('../db');
const {DataTypes} = require('sequelize'); const {DataTypes} = require('sequelize');
const Warehouse = sequelize.define('warehouse', { const Warehouse = sequelize.define('warehouse', {
playerId: DataTypes.INTEGER, playerId: DataTypes.BIGINT,
capacity: DataTypes.INTEGER, // Общая ёмкость склада capacity: DataTypes.INTEGER, // Общая ёмкость склада
wood: DataTypes.INTEGER, wood: DataTypes.INTEGER,
coal: DataTypes.INTEGER, coal: DataTypes.INTEGER,