This commit is contained in:
Degradin 2025-01-05 02:29:56 +03:00
parent fb8771109a
commit e02402a394
4 changed files with 120 additions and 30 deletions

101
bot.js
View File

@ -107,7 +107,9 @@ bot.use(async (ctx, next) => {
console.log(ctx)
}
let user = await UserModel.findByPk(id);
let block = await BlockModel.findByPk(id);
let block = await BlockModel.findOne({
where: { telegram_id: id }, // Здесь id — это значение telegram_id, переданное в функцию
});
let property = await PropertyModel.findByPk(id);
let skill = await SkillsModel.findByPk(ctx.from.id)
if (!user) ctx.reply(`❕ Первичная регистрация профиля.`);
@ -137,11 +139,21 @@ bot.use(async (ctx, next) => {
})
}
//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()
if (block) {
const currentTime = Math.trunc(Date.now() / 1000); // Получаем текущее время в секундах
if (block.isBlocked && block.time > currentTime) {
const remainingTime = Math.trunc((block.time - currentTime) / 60); // Рассчитываем оставшееся время
return ctx.reply(
`📛 У вас активная блокировка по причине: ${block.reason}.\n⏲️ Оставшееся время: ${remainingTime} мин.`
);
}
// Если блокировка истекла или отключена
block.isBlocked = false;
await block.save(); // Обязательно используем `await` для сохранения изменений
}
const start = Date.now()
const timeoutPromise = new Promise((resolve, reject) => {
@ -466,7 +478,7 @@ bot.action('my_enterprises', async (ctx) => {
const resourcePrice = await ResourcePriceModel.findOne({
where: { resource: resourceType }
});
let price = resourcePrice.price * 2 * 10 * 24 * 7 // Стоимость улучшения зависит от уровня
let price = resourcePrice.price * 1.5 * 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 warehouse = await WarehouseModel.findOne({ where: { playerId: user.telegram_id } });
@ -523,7 +535,7 @@ bot.action('build_enterprise', async (ctx) => {
for (const resource of resourcePrices) {
const resourceName = getReadableType(resource.resource);
const resourceEmoji = getEnterpriseEmoji(resource.resource);
message += `${resourceEmoji} ${resourceName}: ${utils.spaces(Math.round(resource.price * 2 * 10 * 24 * 7))} руб.\n`;
message += `${resourceEmoji} ${resourceName}: ${utils.spaces(Math.round(resource.price * 1.5 * 10 * 24 * 7))} руб.\n`;
// Генерируем кнопки для каждого ресурса
buttons.push([
@ -551,7 +563,7 @@ bot.action(/build_(wood|coal|oil|metall|gold|diamond)/, async (ctx) => {
const resourcePrice = await ResourcePriceModel.findOne({
where: { resource: type }
});
let price = resourcePrice.price * 2 * 10 * 24 * 7
let price = resourcePrice.price * 1.5 * 10 * 24 * 7
// Проверка, есть ли достаточно денег у пользователя
if (user.money < price) {
@ -774,7 +786,7 @@ bot.action(/upgrade_(\d+)/, async (ctx) => {
const resourcePrice = await ResourcePriceModel.findOne({
where: { resource: enterprise.resourceType }
});
let upgradeCost = resourcePrice.price * 2 * 10 * 24 * 7 // Стоимость улучшения зависит от уровня
let upgradeCost = resourcePrice.price * 1.5 * 10 * 24 * 7 // Стоимость улучшения зависит от уровня
if (user.money < upgradeCost) {
return await ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `У вас недостаточно средств для прокачки предприятия. Необходимо ${upgradeCost} руб.`)
}
@ -1308,6 +1320,10 @@ bot.command('force_hour', async (ctx) => {
return await ctx.reply(`Принудительный час.`)
})
bot.command('force_mat', async (ctx) => {
utils.matPriceUpdate()
return await ctx.reply(`Принудительный материал.`)
})
/////////////////////////////////////Enterprise Update end//////////////////////////////////////////////////
/////////////////////////////////////Admin Commands//////////////////////////////////////////////////
@ -1323,16 +1339,63 @@ bot.command('genpromo', commands.genPromo)
bot.command('ban', async (ctx) => {
const user = await UserModel.findByPk(ctx.from.id);
const [blocked] = ctx.message.text.split(' ').slice(1);
if(user.status != 'admin') return await ctx.reply(`Admin Only.`)
await BlockModel.create({
telegram_id: blocked,
// Проверка прав администратора
if (user.status !== 'admin') {
return await ctx.reply(`У вас нет прав для выполнения этой команды.`);
}
// Разбор аргументов команды
const args = ctx.message.text.split(' ').slice(1);
if (args.length < 3) {
return await ctx.reply(`⚠️ Использование: /ban <ID|username> <время в минутах> <причина>.`);
}
const identifier = args[0]; // ID или username пользователя
const blockTimeMinutes = parseInt(args[1], 10); // Время блокировки в минутах
const reason = args.slice(2).join(' '); // Причина блокировки
// Проверка времени блокировки
if (isNaN(blockTimeMinutes) || blockTimeMinutes <= 0) {
return await ctx.reply(`❌ Укажите корректное время блокировки в минутах.`);
}
// Ищем пользователя по Telegram ID или никнейму
let targetUser;
if (identifier.startsWith('@')) {
// Если передан username
targetUser = await UserModel.findOne({ where: { username: identifier.slice(1) } });
} else {
// Если передан Telegram ID
targetUser = await UserModel.findOne({ where: { telegram_id: identifier } });
}
if (!targetUser) {
return await ctx.reply(`❌ Пользователь с идентификатором "${identifier}" не найден.`);
}
// Создаём запись о блокировке
const block = await BlockModel.create({
telegram_id: targetUser.telegram_id,
isBlocked: true,
reason: `|AutoFastBlock|`,
time: Math.trunc(Date.now() / 1000 + 3600)
})
await bot.telegram.sendMessage(blocked, `Вы были заблокированы администратором ${user.username}.`)
return await ctx.reply(`Пользователь заблокирован.`)
reason: reason,
time: Math.trunc(Date.now() / 1000 + blockTimeMinutes * 60) // Время блокировки в секундах
});
// Уведомляем заблокированного пользователя
try {
await bot.telegram.sendMessage(
targetUser.telegram_id,
`❌ Вы были заблокированы администратором ${user.username}.\nПричина: ${reason}\nСрок: ${blockTimeMinutes} минут(ы).`
);
} catch (error) {
console.error(`Ошибка отправки уведомления пользователю ${targetUser.telegram_id}:`, error);
}
// Уведомляем администратора
return await ctx.reply(
`✅ Пользователь ${targetUser.username || targetUser.telegram_id} был успешно заблокирован.\nПричина: ${reason}\nСрок: ${blockTimeMinutes} минут(ы).`
);
});
///////////////////////////////////////Functions//////////////////////////////////////////////////////
@ -1342,7 +1405,7 @@ setInterval(() => {
let hours = today.getHours();
if (hours == "0" || hours == "12") {
//weaponShopUpdate()
//matPriceUpdate()
matPriceUpdate()
}
/*if (hours == "9" || hours == "18" || hours == "12") {
generatePromo()

View File

@ -28,8 +28,6 @@ module.exports = async (ctx) => {
let percentErrorText = ``
let profit = 0
let piece = 0
let moneyList = rand(1000, 3000)
moneyList = moneyList*business.users.length
for (i = 0; i < business.users.length; i++) { // Summary percent
user = await UserModel.findByPk(business.users[i])
percentSum += Number(user.business.percent)
@ -38,7 +36,7 @@ module.exports = async (ctx) => {
if (percentSum > 100) return await ctx.reply(`⚠️ Общий процент всех сотрудников превышает 100%\n Остаток процентов перенесется в баланс организации.\n\n${percentErrorText}\n`)
for (x = 0; x < business.users.length; x++) { // Общая внесенная сумма всеми участниками
user = await UserModel.findByPk(business.users[x])
profit += user.business.checks * moneyList * user.level
profit += user.business.checks * world.matPrice * 10 * user.level
text += ` ${user.username} отработал ${user.business.checks} раз.\n`
user.business = {
id: user.business.id,

View File

@ -2,10 +2,22 @@ const sequelize = require('../db');
const {DataTypes} = require('sequelize');
const Block = sequelize.define('block', {
telegram_id: {type: DataTypes.BIGINT, primaryKey: true, unique: true}, uid: {type: DataTypes.STRING, unique: true},
isBlocked: {type: DataTypes.BOOLEAN, defaultValue: false},
reason: {type: DataTypes.STRING, defaultValue: "Не указана."},
time: {type: DataTypes.INTEGER, defaultValue: 0}
telegram_id: {
type: DataTypes.BIGINT,
allowNull: false,
},
isBlocked: {
type: DataTypes.BOOLEAN,
defaultValue: true,
},
reason: {
type: DataTypes.STRING,
allowNull: false,
},
time: {
type: DataTypes.BIGINT, // UNIX-время окончания блокировки
allowNull: false,
}
})
module.exports = Block;

View File

@ -1,11 +1,28 @@
const rand = require('./rand')
const {
WorldModel
WorldModel,
ResourcePriceModel
} = global.config
module.exports = async () => {
let world = await WorldModel.findByPk(1)
let price = rand(35, 170)
world.matPrice = price
world.save()
// Получаем все ресурсы и их цены
let resources = await ResourcePriceModel.findAll();
if (resources.length === 0) {
return console.error('Ресурсы не найдены в базе данных.');
}
// Считаем среднюю стоимость ресурсов
let totalPrice = resources.reduce((sum, resource) => sum + resource.price, 0);
let averagePrice = totalPrice / resources.length;
// Рассчитываем стоимость материала
let materialPrice = Math.round(averagePrice / 10); // Округляем до целого числа
// Обновляем модель World
world.matPrice = materialPrice;
await world.save();
console.log(`Стоимость материала обновлена: ${materialPrice}`);
}