v.0.1.1-rc
This commit is contained in:
parent
b5ef5f0eda
commit
edac4d8761
154
bot.js
154
bot.js
@ -350,35 +350,58 @@ bot.action(/{"action": "sueta_*/, async (ctx) => {
|
|||||||
|
|
||||||
// Обновление меню "Предприятия"
|
// Обновление меню "Предприятия"
|
||||||
bot.hears('🏗️ Предприятия', async (ctx) => {
|
bot.hears('🏗️ Предприятия', async (ctx) => {
|
||||||
const user = await UserModel.findByPk(ctx.from.id);
|
try {
|
||||||
const warehouse = await WarehouseModel.findOne({ where: { playerId: user.telegram_id } });
|
const user = await UserModel.findByPk(ctx.from.id);
|
||||||
|
if (!user) {
|
||||||
|
console.error('Ошибка: пользователь не найден');
|
||||||
|
return await ctx.reply('Ошибка: пользователь не найден.');
|
||||||
|
}
|
||||||
|
|
||||||
const enterprises = await EnterpriseModel.findAll({
|
console.log('ID пользователя:', user.telegram_id);
|
||||||
where: { playerId: user.telegram_id }
|
|
||||||
});
|
|
||||||
|
|
||||||
let message = `🏗️ Меню предприятий:\n`;
|
const warehouse = await WarehouseModel.findOne({ where: { playerId: user.telegram_id } });
|
||||||
message += `У вас: ${enterprises.length} предприятий.\n`;
|
|
||||||
message += warehouse
|
|
||||||
? `🗄️ Единый склад: Доступен (Ёмкость: ${warehouse.capacity} ед.)\n`
|
|
||||||
: `🗄️ Единый склад: Не построен.\n`;
|
|
||||||
|
|
||||||
const buttons = [];
|
if (!warehouse) {
|
||||||
|
console.log('Склад не найден для пользователя:', user.telegram_id);
|
||||||
|
} else {
|
||||||
|
console.log('Найден склад:', warehouse);
|
||||||
|
}
|
||||||
|
|
||||||
// Добавляем кнопки для предприятий
|
const enterprises = await EnterpriseModel.findAll({
|
||||||
buttons.push([{ text: '🏭 Мои предприятия', callback_data: 'my_enterprises' }]);
|
where: { playerId: user.telegram_id }
|
||||||
buttons.push([{ text: '🛠️ Построить предприятие', callback_data: 'build_enterprise' }]);
|
});
|
||||||
|
|
||||||
// Кнопка для управления или постройки склада
|
if (!enterprises.length) {
|
||||||
if (warehouse) {
|
console.log('Предприятия не найдены для пользователя:', user.telegram_id);
|
||||||
buttons.push([{ text: '🚛 Управление складом', callback_data: 'manage_warehouse' }]);
|
} else {
|
||||||
} else {
|
console.log('Количество предприятий:', enterprises.length);
|
||||||
buttons.push([{ text: '🗄️ Построить склад', callback_data: 'buy_warehouse' }]);
|
}
|
||||||
|
|
||||||
|
let message = `🏗️ Меню предприятий:\n`;
|
||||||
|
message += `У вас: ${enterprises.length} предприятий.\n`;
|
||||||
|
message += warehouse
|
||||||
|
? `🗄️ Единый склад: Доступен (Ёмкость: ${warehouse.capacity} ед.)\n`
|
||||||
|
: `🗄️ Единый склад: Не построен.\n`;
|
||||||
|
|
||||||
|
const buttons = [];
|
||||||
|
buttons.push([{ text: '🏭 Мои предприятия', callback_data: 'my_enterprises' }]);
|
||||||
|
buttons.push([{ text: '🛠️ Построить предприятие', callback_data: 'build_enterprise' }]);
|
||||||
|
|
||||||
|
if (warehouse) {
|
||||||
|
buttons.push([{ text: '🚛 Управление складом', callback_data: 'manage_warehouse' }]);
|
||||||
|
} else {
|
||||||
|
buttons.push([{ text: '🗄️ Построить склад', callback_data: 'buy_warehouse' }]);
|
||||||
|
}
|
||||||
|
|
||||||
|
buttons.push([{ text: '💰 Продать ресурсы', callback_data: 'sell_resources' }]);
|
||||||
|
|
||||||
|
return await ctx.reply(message, Markup.inlineKeyboard(buttons).resize());
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Ошибка при выполнении команды "🏗️ Предприятия":', error);
|
||||||
|
return await ctx.reply('Произошла ошибка при выполнении команды. Попробуйте позже.');
|
||||||
}
|
}
|
||||||
buttons.push([{ text: '💰 Продать ресурсы', callback_data: 'sell_resources' }])
|
|
||||||
// Возвращаем меню с кнопками
|
|
||||||
return await ctx.reply(message, Markup.inlineKeyboard(buttons).resize());
|
|
||||||
});
|
});
|
||||||
|
|
||||||
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,28 +601,60 @@ 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})
|
}
|
||||||
}
|
|
||||||
|
|
||||||
await WarehouseModel.create({
|
// Получаем цены на металл и дерево
|
||||||
playerId: user.telegram_id,
|
const woodPrice = await ResourcePriceModel.findOne({ where: { resource: 'wood' } });
|
||||||
capacity: 1000, // Начальная ёмкость
|
const metallPrice = await ResourcePriceModel.findOne({ where: { resource: 'metall' } });
|
||||||
wood: 0,
|
|
||||||
coal: 0,
|
|
||||||
oil: 0,
|
|
||||||
metall: 0,
|
|
||||||
gold: 0,
|
|
||||||
diamond: 0
|
|
||||||
})
|
|
||||||
|
|
||||||
await user.update({ money: user.money - 500000 })
|
if (!woodPrice || !metallPrice) {
|
||||||
return await ctx.reply(`Вы успешно купили единый склад!`)
|
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({
|
||||||
|
playerId: user.telegram_id,
|
||||||
|
capacity: 1000, // Начальная ёмкость
|
||||||
|
wood: 0,
|
||||||
|
coal: 0,
|
||||||
|
oil: 0,
|
||||||
|
metall: 0,
|
||||||
|
gold: 0,
|
||||||
|
diamond: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Списываем деньги
|
||||||
|
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 = {}; // Объект для хранения предыдущих цен
|
||||||
|
|
||||||
|
@ -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'
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -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,
|
||||||
|
Loading…
Reference in New Issue
Block a user