v0.0.41
This commit is contained in:
parent
487799b12a
commit
2337121d54
149
bot.js
149
bot.js
@ -432,14 +432,17 @@ bot.action('my_enterprises', async (ctx) => {
|
|||||||
if (enterprises.length === 0) {
|
if (enterprises.length === 0) {
|
||||||
return await ctx.reply('У вас нет предприятий.');
|
return await ctx.reply('У вас нет предприятий.');
|
||||||
}
|
}
|
||||||
|
let price = 0
|
||||||
let message = `🏭 Мои предприятия:\n\n`;
|
let message = `🏭 Мои предприятия:\n\n`;
|
||||||
const buttons = [];
|
const buttons = [];
|
||||||
|
|
||||||
for (const enterprise of enterprises) {
|
for (const enterprise of enterprises) {
|
||||||
const { id, name, level, efficiency, currentResources, resourceType, warehouseCapacity } = enterprise;
|
const { id, name, level, efficiency, currentResources, resourceType, warehouseCapacity } = enterprise;
|
||||||
|
const resourcePrice = await ResourcePriceModel.findOne({
|
||||||
message += `🔹 [ID: ${id}] ${getEnterpriseEmoji(resourceType)} ${name} st. ${level}\n └── ${currentResources}/${warehouseCapacity} [${efficiency} ед/ч]\n\n`;
|
where: { resource: resourceType }
|
||||||
|
});
|
||||||
|
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`;
|
||||||
|
|
||||||
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 } });
|
||||||
@ -494,16 +497,18 @@ bot.action('build_enterprise', async (ctx) => {
|
|||||||
const buttons = [];
|
const buttons = [];
|
||||||
|
|
||||||
for (const resource of resourcePrices) {
|
for (const resource of resourcePrices) {
|
||||||
const resourceName = getEnterpriseEmoji(resource.resource);
|
const resourceName = getReadableType(resource.resource);
|
||||||
message += `${resourceName}: ${Math.round(resource.price)} руб.\n`;
|
const resourceEmoji = getEnterpriseEmoji(resource.resource);
|
||||||
|
message += `${resourceEmoji} ${resourceName}: ${utils.spaces(Math.round(resource.price * 2 * 10 * 24 * 7))} руб.\n`;
|
||||||
|
|
||||||
// Генерируем кнопки для каждого ресурса
|
// Генерируем кнопки для каждого ресурса
|
||||||
buttons.push([
|
buttons.push([
|
||||||
{ text: resourceName, callback_data: `build_${resource.resource}` }
|
{ text: resourceEmoji, callback_data: `build_${resource.resource}` }
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
message += '\nВыберите тип предприятия:';
|
message += '\nВыберите тип предприятия:';
|
||||||
|
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());
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Ошибка в build_enterprise:', error);
|
console.error('Ошибка в build_enterprise:', error);
|
||||||
@ -516,7 +521,13 @@ bot.action(/build_(wood|coal|oil|metall|gold|diamond)/, async (ctx) => {
|
|||||||
let user = await UserModel.findByPk(ctx.from.id)
|
let user = await UserModel.findByPk(ctx.from.id)
|
||||||
let data = ctx.update.callback_query.data
|
let data = ctx.update.callback_query.data
|
||||||
let type = data.split('_')[1]
|
let type = data.split('_')[1]
|
||||||
let price = getEnterprisePrice(type)
|
|
||||||
|
|
||||||
|
// Получаем текущие цены из базы данных
|
||||||
|
const resourcePrice = await ResourcePriceModel.findOne({
|
||||||
|
where: { resource: type }
|
||||||
|
});
|
||||||
|
let price = resourcePrice.price * 2 * 10 * 24 * 7
|
||||||
|
|
||||||
// Проверка, есть ли достаточно денег у пользователя
|
// Проверка, есть ли достаточно денег у пользователя
|
||||||
if (user.balance < price) {
|
if (user.balance < price) {
|
||||||
@ -540,19 +551,6 @@ bot.action(/build_(wood|coal|oil|metall|gold|diamond)/, async (ctx) => {
|
|||||||
return await ctx.editMessageText(`Предприятие ${enterprise.name} (ID: ${enterprise.id}) построено!`)
|
return await ctx.editMessageText(`Предприятие ${enterprise.name} (ID: ${enterprise.id}) построено!`)
|
||||||
})
|
})
|
||||||
|
|
||||||
// Функция для расчета стоимости предприятия
|
|
||||||
function getEnterprisePrice(resourceType) {
|
|
||||||
const prices = {
|
|
||||||
wood: 5000,
|
|
||||||
coal: 10000,
|
|
||||||
oil: 20000,
|
|
||||||
metall: 50000,
|
|
||||||
gold: 150000,
|
|
||||||
diamond: 250000
|
|
||||||
}
|
|
||||||
return prices[resourceType] || 0
|
|
||||||
}
|
|
||||||
|
|
||||||
// Функция для преобразования типа ресурса в читаемое название
|
// Функция для преобразования типа ресурса в читаемое название
|
||||||
function getReadableType(type) {
|
function getReadableType(type) {
|
||||||
const names = {
|
const names = {
|
||||||
@ -566,6 +564,18 @@ function getReadableType(type) {
|
|||||||
return names[type] || type
|
return names[type] || type
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function getReadableResourceType(type) {
|
||||||
|
const names = {
|
||||||
|
wood: 'Дерево',
|
||||||
|
coal: 'Уголь',
|
||||||
|
oil: 'Нефть',
|
||||||
|
metall: 'Металл',
|
||||||
|
gold: 'Золото',
|
||||||
|
diamond: 'Алмазы'
|
||||||
|
}
|
||||||
|
return names[type] || type
|
||||||
|
}
|
||||||
|
|
||||||
bot.action('buy_warehouse', async (ctx) => {
|
bot.action('buy_warehouse', async (ctx) => {
|
||||||
let user = await UserModel.findByPk(ctx.from.id)
|
let user = await UserModel.findByPk(ctx.from.id)
|
||||||
if (user.money < 500000) {
|
if (user.money < 500000) {
|
||||||
@ -696,44 +706,29 @@ bot.command('ent_rename', async (ctx) => {
|
|||||||
return await ctx.reply(`Предприятие (ID: ${enterprise.id}) переименовано в "${newName}".`)
|
return await ctx.reply(`Предприятие (ID: ${enterprise.id}) переименовано в "${newName}".`)
|
||||||
})
|
})
|
||||||
|
|
||||||
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.editMessageText(`Выберите предприятие для прокачки:`, Markup.inlineKeyboard(buttons).resize())
|
|
||||||
})
|
|
||||||
|
|
||||||
bot.action(/upgrade_(\d+)/, async (ctx) => {
|
bot.action(/upgrade_(\d+)/, async (ctx) => {
|
||||||
let user = await UserModel.findByPk(ctx.from.id)
|
let user = await UserModel.findByPk(ctx.from.id)
|
||||||
let enterpriseId = ctx.match[1]
|
let enterpriseId = ctx.match[1]
|
||||||
let enterprise = await EnterpriseModel.findByPk(enterpriseId)
|
let enterprise = await EnterpriseModel.findByPk(enterpriseId)
|
||||||
|
|
||||||
if (!enterprise) return await ctx.reply(`Предприятие не найдено.`)
|
if (!enterprise) return await ctx.reply(`Предприятие не найдено.`)
|
||||||
|
const resourcePrice = await ResourcePriceModel.findOne({
|
||||||
let upgradeCost = enterprise.level * 100 // Стоимость улучшения зависит от уровня
|
where: { resource: enterprise.resourceType }
|
||||||
if (user.balance < upgradeCost) {
|
});
|
||||||
|
let upgradeCost = resourcePrice.price * 2 * 10 * 24 * 7 // Стоимость улучшения зависит от уровня
|
||||||
|
if (user.money < upgradeCost) {
|
||||||
return await ctx.reply(`У вас недостаточно средств для прокачки предприятия. Необходимо ${upgradeCost} руб.`)
|
return await ctx.reply(`У вас недостаточно средств для прокачки предприятия. Необходимо ${upgradeCost} руб.`)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Прокачка: повышение уровня и эффективности
|
// Прокачка: повышение уровня и эффективности
|
||||||
await enterprise.update({
|
await enterprise.update({
|
||||||
level: enterprise.level + 1,
|
level: enterprise.level + 1,
|
||||||
efficiency: enterprise.efficiency + 10
|
efficiency: enterprise.efficiency + 10,
|
||||||
|
warehouseCapacity: enterprise.warehouseCapacity + 110
|
||||||
})
|
})
|
||||||
|
|
||||||
// Снимаем деньги с баланса
|
// Снимаем деньги с баланса
|
||||||
await user.update({ balance: user.balance - upgradeCost })
|
await user.update({ money: user.money - upgradeCost })
|
||||||
|
|
||||||
return await ctx.editMessageText(`Предприятие ${enterprise.name} успешно прокачано! Уровень: ${enterprise.level}, Производительность: ${enterprise.efficiency} ед/ч.`)
|
return await ctx.editMessageText(`Предприятие ${enterprise.name} успешно прокачано! Уровень: ${enterprise.level}, Производительность: ${enterprise.efficiency} ед/ч.`)
|
||||||
})
|
})
|
||||||
@ -869,7 +864,7 @@ const recoverResourcePrices = async () => {
|
|||||||
|
|
||||||
|
|
||||||
// Запускаем процесс восстановления цен каждые 15 минут
|
// Запускаем процесс восстановления цен каждые 15 минут
|
||||||
setInterval(recoverResourcePrices, 5 * 1000);
|
setInterval(recoverResourcePrices, 60 * 1000);
|
||||||
|
|
||||||
bot.action(/sell_all_(\d+)/, async (ctx) => {
|
bot.action(/sell_all_(\d+)/, async (ctx) => {
|
||||||
const enterpriseId = ctx.match[1];
|
const enterpriseId = ctx.match[1];
|
||||||
@ -921,14 +916,13 @@ bot.action(/confirm_ressell_(\d+)/, async (ctx) => {
|
|||||||
|
|
||||||
await user.save();
|
await user.save();
|
||||||
await enterprise.save();
|
await enterprise.save();
|
||||||
|
console.log(resourcePrice.price * Math.exp(-resourcePrice.fluctuationRate * (currentResources / 10)))
|
||||||
// Ослабленная инфляция
|
// Ослабленная инфляция
|
||||||
resourcePrice.price = Math.round(
|
resourcePrice.price = Math.round(
|
||||||
resourcePrice.price * Math.exp(-resourcePrice.fluctuationRate * (amount / 10)) // Дробное уменьшение инфляции
|
resourcePrice.price * Math.exp(-resourcePrice.fluctuationRate * (currentResources / 10)) // Дробное уменьшение инфляции
|
||||||
);
|
);
|
||||||
|
|
||||||
// Гарантируем, что цена не упадет ниже 50% от базовой цены
|
// Гарантируем, что цена не упадет ниже 50% от базовой цены
|
||||||
resourcePrice.price = Math.max(resourcePrice.price, Math.round(resourcePrice.basePrice * 0.5));
|
resourcePrice.price = Math.max(resourcePrice.price, Math.round(resourcePrice.basePrice * 0.5));
|
||||||
|
|
||||||
await resourcePrice.save();
|
await resourcePrice.save();
|
||||||
|
|
||||||
await ctx.editMessageText(`Вы успешно продали ${currentResources} ед. ${resourceType} за ${totalPrice} руб.`);
|
await ctx.editMessageText(`Вы успешно продали ${currentResources} ед. ${resourceType} за ${totalPrice} руб.`);
|
||||||
@ -1195,6 +1189,65 @@ 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 вашего канала
|
||||||
|
let resourceMessageId = 4; // Хранение ID сообщения
|
||||||
|
|
||||||
|
const previousPrices = {}; // Объект для хранения предыдущих цен
|
||||||
|
|
||||||
|
const getResourcePricesText = async () => {
|
||||||
|
const resources = await ResourcePriceModel.findAll(); // Получаем данные из базы
|
||||||
|
let message = '💰 **Актуальные цены на ресурсы:**\n\n';
|
||||||
|
|
||||||
|
resources.forEach((resource) => {
|
||||||
|
const currentPrice = resource.price;
|
||||||
|
const previousPrice = previousPrices[resource.resource] || currentPrice; // Берем предыдущую цену или текущую, если нет данных
|
||||||
|
|
||||||
|
// Определяем эмодзи изменения цены
|
||||||
|
let trendEmoji = '⚖️'; // По умолчанию стабильность
|
||||||
|
if (currentPrice > previousPrice) {
|
||||||
|
trendEmoji = '📈'; // Рост
|
||||||
|
} else if (currentPrice < previousPrice) {
|
||||||
|
trendEmoji = '📉'; // Падение
|
||||||
|
}
|
||||||
|
|
||||||
|
// Сохраняем текущую цену как предыдущую для следующего сравнения
|
||||||
|
previousPrices[resource.resource] = currentPrice;
|
||||||
|
|
||||||
|
// Добавляем строку с ценой и эмодзи
|
||||||
|
message += `• ${getEnterpriseEmoji(resource.resource)} ${getReadableResourceType(resource.resource)}: ${trendEmoji} ${utils.spaces(currentPrice)} руб/ед.\n`;
|
||||||
|
});
|
||||||
|
|
||||||
|
message += '\n⚙️ Цены обновляются каждые 15 минут.';
|
||||||
|
return message;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Функция для отправки/обновления сообщения
|
||||||
|
const updateResourcePricesMessage = async () => {
|
||||||
|
const pricesText = await getResourcePricesText();
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (resourceMessageId) {
|
||||||
|
// Если сообщение существует, обновляем его
|
||||||
|
await bot.telegram.editMessageText(CHANNEL_ID, resourceMessageId, null, pricesText, {
|
||||||
|
parse_mode: 'Markdown',
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// Если сообщения нет, отправляем новое
|
||||||
|
const sentMessage = await bot.telegram.sendMessage(CHANNEL_ID, pricesText, {
|
||||||
|
parse_mode: 'Markdown',
|
||||||
|
});
|
||||||
|
resourceMessageId = sentMessage.message_id; // Сохраняем ID нового сообщения
|
||||||
|
console.log("ID сообщения с котировками: " + sentMessage.message_id)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Ошибка при обновлении сообщения с ценами ресурсов:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Запускаем функцию
|
||||||
|
updateResourcePricesMessage();
|
||||||
|
// Запускаем обновление каждые 15 минут
|
||||||
|
setInterval(updateResourcePricesMessage, 15 * 60 * 1000);
|
||||||
// Запускаем процессы каждый час
|
// Запускаем процессы каждый час
|
||||||
setInterval(resourceProduction, 60 * 60 * 1000);
|
setInterval(resourceProduction, 60 * 60 * 1000);
|
||||||
setInterval(resourceTransportation, 60 * 60 * 1000);
|
setInterval(resourceTransportation, 60 * 60 * 1000);
|
||||||
|
Loading…
Reference in New Issue
Block a user