v0.1-rc
Release candidate
This commit is contained in:
parent
2337121d54
commit
b5ef5f0eda
85
bot.js
85
bot.js
@ -432,7 +432,7 @@ bot.action('my_enterprises', async (ctx) => {
|
||||
if (enterprises.length === 0) {
|
||||
return await ctx.reply('У вас нет предприятий.');
|
||||
}
|
||||
let price = 0
|
||||
let metallPrice = 0
|
||||
let message = `🏭 Мои предприятия:\n\n`;
|
||||
const buttons = [];
|
||||
|
||||
@ -443,7 +443,7 @@ bot.action('my_enterprises', async (ctx) => {
|
||||
});
|
||||
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`;
|
||||
|
||||
if (resourcePrice.resource == "metall") metallPrice = resourcePrice.price
|
||||
const truck = await TruckModel.findOne({ where: { enterpriseId: id } });
|
||||
const warehouse = await WarehouseModel.findOne({ where: { playerId: user.telegram_id } });
|
||||
|
||||
@ -465,7 +465,7 @@ bot.action('my_enterprises', async (ctx) => {
|
||||
|
||||
buttons.push(enterpriseButtons);
|
||||
}
|
||||
message += '\n\n[📈 - Улучшить]\n[🛻 - Нанять грузовик]\n 🚛 - Улучшить грузовик\n[💰 - Продать ресурсы с предприятия]\n[🔄 - Перевезти все на склад]'
|
||||
message += `\n\n📈 - Улучшить\n🛻 - Купить грузовик [~${utils.spaces(metallPrice*700)} руб.]\n🚛 - Улучшить грузовик\n💰 - Продать ресурсы с предприятия\n🔄 - Перевезти все на склад`
|
||||
buttons.push([{ text: '⬅️ Назад', callback_data: 'enterprise_menu' }]);
|
||||
|
||||
return await ctx.editMessageText(message, Markup.inlineKeyboard(buttons).resize());
|
||||
@ -484,7 +484,7 @@ bot.action('build_enterprise', async (ctx) => {
|
||||
});
|
||||
|
||||
if (enterprises.length >= 5) {
|
||||
return await ctx.reply('Вы достигли максимального числа предприятий.');
|
||||
return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, 'Вы достигли максимального числа предприятий.', {show_alert: true});
|
||||
}
|
||||
|
||||
// Получаем текущие цены из базы данных
|
||||
@ -531,7 +531,7 @@ bot.action(/build_(wood|coal|oil|metall|gold|diamond)/, async (ctx) => {
|
||||
|
||||
// Проверка, есть ли достаточно денег у пользователя
|
||||
if (user.balance < price) {
|
||||
return await ctx.reply(`У вас недостаточно средств для постройки предприятия. Необходимо ${price} руб.`)
|
||||
return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `У вас недостаточно средств для постройки предприятия. Необходимо ${price} руб.`, {show_alert: true})
|
||||
}
|
||||
|
||||
// Строим предприятие
|
||||
@ -578,8 +578,11 @@ function getReadableResourceType(type) {
|
||||
|
||||
bot.action('buy_warehouse', async (ctx) => {
|
||||
let user = await UserModel.findByPk(ctx.from.id)
|
||||
if (user.status != 'admin') {
|
||||
return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `Мы работаем над этим.`, {show_alert: true})
|
||||
}
|
||||
if (user.money < 500000) {
|
||||
return await ctx.reply(`У вас недостаточно средств для покупки склада.`)
|
||||
return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id,`У вас недостаточно средств для покупки склада.`, {show_alert: true})
|
||||
}
|
||||
|
||||
await WarehouseModel.create({
|
||||
@ -628,7 +631,7 @@ bot.action('transfer_resources', async (ctx) => {
|
||||
const warehouse = await WarehouseModel.findOne({ where: { playerId: user.telegram_id } });
|
||||
|
||||
if (!warehouse) {
|
||||
return await ctx.reply('У вас нет единого склада.');
|
||||
return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id,'У вас нет единого склада.');
|
||||
}
|
||||
|
||||
const enterprises = await EnterpriseModel.findAll({
|
||||
@ -658,20 +661,20 @@ bot.action(/transfer_from_(\d+)/, async (ctx) => {
|
||||
const { currentResources, resourceType, playerId } = enterprise;
|
||||
|
||||
if (currentResources === 0) {
|
||||
return await ctx.reply('На предприятии нет ресурсов для перевода.');
|
||||
return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, 'На предприятии нет ресурсов для перевода.');
|
||||
}
|
||||
|
||||
const warehouse = await WarehouseModel.findOne({ where: { playerId } });
|
||||
|
||||
if (!warehouse) {
|
||||
return await ctx.reply('У вас нет склада для перевода ресурсов.');
|
||||
return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, 'У вас нет склада для перевода ресурсов.');
|
||||
}
|
||||
|
||||
const freeCapacity = warehouse.capacity - getWarehouseUsedCapacity(warehouse);
|
||||
const transferAmount = Math.min(currentResources, freeCapacity);
|
||||
|
||||
if (transferAmount === 0) {
|
||||
return await ctx.reply('Склад заполнен. Перевод невозможен.');
|
||||
return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, 'Склад заполнен. Перевод невозможен.');
|
||||
}
|
||||
|
||||
// Перевод ресурсов
|
||||
@ -717,7 +720,7 @@ bot.action(/upgrade_(\d+)/, async (ctx) => {
|
||||
});
|
||||
let upgradeCost = resourcePrice.price * 2 * 10 * 24 * 7 // Стоимость улучшения зависит от уровня
|
||||
if (user.money < upgradeCost) {
|
||||
return await ctx.reply(`У вас недостаточно средств для прокачки предприятия. Необходимо ${upgradeCost} руб.`)
|
||||
return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `У вас недостаточно средств для прокачки предприятия. Необходимо ${upgradeCost} руб.`)
|
||||
}
|
||||
|
||||
// Прокачка: повышение уровня и эффективности
|
||||
@ -819,7 +822,7 @@ bot.command('sellres', async (ctx) => {
|
||||
resourcePrice.price = Math.max(resourcePrice.price, Math.round(resourcePrice.basePrice * 0.5));
|
||||
|
||||
await resourcePrice.save();
|
||||
|
||||
updateResourcePricesMessage();
|
||||
return await ctx.reply(
|
||||
`Вы продали ${amount} единиц ${enterprise.resourceType} с предприятия ${enterprise.name} за ${totalSale} руб.\nТекущая цена за единицу: ${resourcePrice.price.toFixed(0)} руб.`
|
||||
);
|
||||
@ -861,11 +864,6 @@ const recoverResourcePrices = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
// Запускаем процесс восстановления цен каждые 15 минут
|
||||
setInterval(recoverResourcePrices, 60 * 1000);
|
||||
|
||||
bot.action(/sell_all_(\d+)/, async (ctx) => {
|
||||
const enterpriseId = ctx.match[1];
|
||||
const enterprise = await EnterpriseModel.findByPk(enterpriseId);
|
||||
@ -879,7 +877,7 @@ bot.action(/sell_all_(\d+)/, async (ctx) => {
|
||||
const totalPrice = currentResources * resourcePrice.price;
|
||||
|
||||
if (currentResources === 0) {
|
||||
return await ctx.reply('На предприятии нет ресурсов для продажи.');
|
||||
return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, 'На предприятии нет ресурсов для продажи.');
|
||||
}
|
||||
|
||||
await ctx.reply(
|
||||
@ -906,7 +904,7 @@ bot.action(/confirm_ressell_(\d+)/, async (ctx) => {
|
||||
const totalPrice = currentResources * resourcePrice.price;
|
||||
|
||||
if (currentResources === 0) {
|
||||
return await ctx.reply('На предприятии нет ресурсов для продажи.');
|
||||
return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, 'На предприятии нет ресурсов для продажи.');
|
||||
}
|
||||
|
||||
// Обновление баланса игрока
|
||||
@ -923,8 +921,9 @@ bot.action(/confirm_ressell_(\d+)/, async (ctx) => {
|
||||
);
|
||||
// Гарантируем, что цена не упадет ниже 50% от базовой цены
|
||||
resourcePrice.price = Math.max(resourcePrice.price, Math.round(resourcePrice.basePrice * 0.5));
|
||||
await resourcePrice.save();
|
||||
|
||||
await resourcePrice.save();
|
||||
updateResourcePricesMessage();
|
||||
await ctx.editMessageText(`Вы успешно продали ${currentResources} ед. ${resourceType} за ${totalPrice} руб.`);
|
||||
});
|
||||
|
||||
@ -979,36 +978,12 @@ bot.command('sellstorage', async (ctx) => {
|
||||
resourcePrice.price = Math.max(resourcePrice.price, Math.round(resourcePrice.basePrice * 0.5));
|
||||
|
||||
await resourcePrice.save();
|
||||
|
||||
updateResourcePricesMessage();
|
||||
return await ctx.reply(
|
||||
`Вы продали ${amount} ед. ${resourceType} со склада за ${totalSale} руб.\nТекущая цена за единицу: ${resourcePrice.price.toFixed(0)} руб.`
|
||||
);
|
||||
});
|
||||
|
||||
// Найм грузовика
|
||||
bot.action('hire_truck', async (ctx) => {
|
||||
const user = await UserModel.findByPk(ctx.from.id);
|
||||
|
||||
// Получаем список предприятий пользователя
|
||||
const enterprises = await EnterpriseModel.findAll({
|
||||
where: { playerId: user.telegram_id }
|
||||
});
|
||||
|
||||
if (enterprises.length === 0) {
|
||||
return await ctx.reply('У вас нет предприятий для найма грузовиков.');
|
||||
}
|
||||
|
||||
// Создаем кнопки для выбора предприятия
|
||||
const buttons = enterprises.map((enterprise) => [
|
||||
{ text: `Нанять для ${enterprise.name}`, callback_data: `hire_truck_${enterprise.id}` }
|
||||
]);
|
||||
|
||||
return await ctx.reply(
|
||||
'Выберите предприятие для найма грузовика:',
|
||||
Markup.inlineKeyboard(buttons).resize()
|
||||
);
|
||||
});
|
||||
|
||||
// Обработка найма грузовика для выбранного предприятия
|
||||
bot.action(/hire_truck_(\d+)/, async (ctx) => {
|
||||
const user = await UserModel.findByPk(ctx.from.id);
|
||||
@ -1027,16 +1002,22 @@ bot.action(/hire_truck_(\d+)/, async (ctx) => {
|
||||
});
|
||||
|
||||
if (existingTruck) {
|
||||
return await ctx.reply(`У вас уже есть грузовик для предприятия ${enterprise.name}.`);
|
||||
return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `У вас уже есть грузовик для предприятия ${enterprise.name}.`);
|
||||
}
|
||||
|
||||
const resourcePrice = await ResourcePriceModel.findOne({ where: { resource: 'metall' } });
|
||||
if (!resourcePrice) {
|
||||
return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, 'Не удалось получить цену ресурса.');
|
||||
}
|
||||
if (user.money < resourcePrice.price*700) {
|
||||
return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `Недостаточно средств. Стоимость грузовика: ${utils.spaces(resourcePrice.price*700)} руб.`);
|
||||
}
|
||||
await user.update({ money: user.money - (resourcePrice.price*700) })
|
||||
// Создаем новый грузовик
|
||||
const newTruck = await TruckModel.create({
|
||||
enterpriseId: enterprise.id,
|
||||
capacity: 10, // Начальная вместимость
|
||||
efficiency: 1 // Начальная эффективность
|
||||
});
|
||||
|
||||
return await ctx.reply(
|
||||
`Вы успешно наняли грузовик для предприятия ${enterprise.name}!`
|
||||
);
|
||||
@ -1217,7 +1198,7 @@ const getResourcePricesText = async () => {
|
||||
message += `• ${getEnterpriseEmoji(resource.resource)} ${getReadableResourceType(resource.resource)}: ${trendEmoji} ${utils.spaces(currentPrice)} руб/ед.\n`;
|
||||
});
|
||||
|
||||
message += '\n⚙️ Цены обновляются каждые 15 минут.';
|
||||
message += `\n🔁 Последнее обновление цены: ${utils.getCurrentTime()}`;
|
||||
return message;
|
||||
};
|
||||
|
||||
@ -1246,6 +1227,8 @@ const updateResourcePricesMessage = async () => {
|
||||
|
||||
// Запускаем функцию
|
||||
updateResourcePricesMessage();
|
||||
// Запускаем процесс восстановления цен каждые 15 минут
|
||||
setInterval(recoverResourcePrices, 15 * 60 * 1000);
|
||||
// Запускаем обновление каждые 15 минут
|
||||
setInterval(updateResourcePricesMessage, 15 * 60 * 1000);
|
||||
// Запускаем процессы каждый час
|
||||
@ -1288,8 +1271,8 @@ setInterval(() => {
|
||||
var today = new Date();
|
||||
let hours = today.getHours();
|
||||
if (hours == "0" || hours == "12") {
|
||||
weaponShopUpdate()
|
||||
matPriceUpdate()
|
||||
//weaponShopUpdate()
|
||||
//matPriceUpdate()
|
||||
}
|
||||
/*if (hours == "9" || hours == "18" || hours == "12") {
|
||||
generatePromo()
|
||||
|
@ -1,3 +1,8 @@
|
||||
const {
|
||||
UserModel,
|
||||
JobModel
|
||||
} = global.config
|
||||
|
||||
module.exports = async (ctx) => {
|
||||
let data = ctx.update.callback_query.data;
|
||||
let user = await UserModel.findByPk(ctx.from.id);
|
||||
|
@ -1,3 +1,15 @@
|
||||
const {
|
||||
UserModel,
|
||||
WorldModel,
|
||||
JobModel
|
||||
} = global.config
|
||||
|
||||
const {
|
||||
random,
|
||||
setCooldown,
|
||||
giveExp
|
||||
} = global.utils
|
||||
|
||||
module.exports = async (ctx) => {
|
||||
let user = await UserModel.findByPk(ctx.from.id);
|
||||
let job = await JobModel.findByPk(user.job);
|
||||
|
Loading…
Reference in New Issue
Block a user