v0.0.54
added shortid added ReportModel added BlockModel & BlockSystem commandlist help replies
This commit is contained in:
parent
6b7bd04df3
commit
98afe19dd6
129
index.js
129
index.js
@ -1,6 +1,6 @@
|
||||
require('dotenv').config()
|
||||
const { Telegraf, Markup } = require('telegraf')
|
||||
const { formatDistanceToNowStrict } = require('date-fns');
|
||||
const shortid = require('shortid');
|
||||
const fs = require('fs')
|
||||
const bot = new Telegraf(process.env.BOT_TOKEN)
|
||||
const weaponshop = require('./json/weaponshop.json')
|
||||
@ -15,6 +15,8 @@ const WorldModel = require('./models/world.model');
|
||||
const JobModel = require('./models/job.model');
|
||||
const PropertyModel = require('./models/property.model');
|
||||
const BusinessModel = require('./models/business.model');
|
||||
const ReportModel = require('./models/report.model');
|
||||
const BlockModel = require('./models/block.model');
|
||||
const whitelist = [275416286, 1797342681]
|
||||
const adminList = [275416286]
|
||||
const expToUp = [0, 10, 15, 22, 35, 50, 70, 85, 100, 125, 200]
|
||||
@ -28,11 +30,22 @@ const start = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
bot.telegram.setMyCommands([
|
||||
{command: "pay", description:"Перевести указанному пользователю сумму."},
|
||||
{command: "buy", description:"Приобрести указанное имущество."},
|
||||
{command: "business", description:"Создать организацию."},
|
||||
{command: "invite", description:"Пригласить пользователя в организацию."},
|
||||
{command: "percent", description:"Установить пользователю процент заработка."},
|
||||
{command: "report", description:"Создать жалобу/обращение/идею."}
|
||||
])
|
||||
|
||||
bot.use(async (ctx, next) => {
|
||||
let id = ctx.from.id
|
||||
let username = ctx.from.username
|
||||
let user = await UserModel.findByPk(id);
|
||||
let block = await BlockModel.findByPk(id);
|
||||
let property = await PropertyModel.findByPk(id);
|
||||
if(!user) ctx.reply(`Первичная регистрация профиля.`);
|
||||
if (user === null) {
|
||||
UserModel.create({
|
||||
telegram_id: id,
|
||||
@ -44,8 +57,12 @@ bot.use(async (ctx, next) => {
|
||||
telegram_id: id
|
||||
})
|
||||
} else {}
|
||||
if(id == 1045983457) return ctx.reply(`Резчиков detected...`)
|
||||
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()
|
||||
}
|
||||
const start = Date.now()
|
||||
return next().then(() => {
|
||||
const ms = Date.now() - start
|
||||
@ -172,12 +189,12 @@ ${text}
|
||||
|
||||
bot.command('pay', async (ctx) => {
|
||||
ctx.args = ctx.update.message.text.split(' ')
|
||||
if (!ctx.args[1] || !ctx.args[2]) return ctx.reply(`Не указан аргумент.`)
|
||||
if (!Number(ctx.args[2])) return ctx.reply(`Сумма должна быть числовая.`)
|
||||
let sender = await UserModel.findByPk(ctx.from.id);
|
||||
let receiver = await UserModel.findOne({ where: { username: ctx.args[1] } });
|
||||
let world = await WorldModel.findByPk(1)
|
||||
let fee = Number(Math.trunc(ctx.args[2] / 100 * world.transactionfee))
|
||||
if (!ctx.args[1] || !ctx.args[2]) return ctx.reply(`Не указан аргумент.`)
|
||||
if (!Number(ctx.args[2])) return ctx.reply(`Сумма должна быть числовая.`)
|
||||
if (ctx.args[2] == 0 || ctx.args[2] < 100) return ctx.reply(`Минимальная сумма перевода ¤100.`)
|
||||
if (sender.money < ctx.args[2]) return ctx.reply(`Недостаточно средств!`)
|
||||
if (sender.money < Number(ctx.args[2]) + fee) return ctx.reply(`Недостаточно средств для перевода с комиссией!`)
|
||||
@ -616,7 +633,7 @@ ${text}
|
||||
let business = await BusinessModel.findOne({owner: ctx.from.id})
|
||||
if (business === null) return await ctx.reply(`У вас нет организации.`)
|
||||
console.log(business)
|
||||
return await ctx.reply(`Ваша организация\n${business.name}\nБаланс: ${business.balance}\nСырье: ${business.materials}\nРабочих: ${business.users.length}`)
|
||||
return await ctx.reply(`Ваша организация\n${business.name}\nБаланс: ¤${business.balance}\nСырье: ${business.materials}\nРабочих: ${business.users.length}`)
|
||||
})
|
||||
|
||||
bot.hears('Отработка', async (ctx) => {
|
||||
@ -629,7 +646,7 @@ ${text}
|
||||
user.business = {
|
||||
id: user.business.id,
|
||||
checks: user.business.checks + 1,
|
||||
percent: 100
|
||||
percent: user.business.percent
|
||||
}
|
||||
business.checks += 1
|
||||
await user.save()
|
||||
@ -637,50 +654,74 @@ ${text}
|
||||
return await ctx.reply(`Вы отработали час на ${business.name}`)
|
||||
})
|
||||
|
||||
bot.command('payday', async (ctx) => {
|
||||
bot.hears('Payday', async (ctx) => {
|
||||
let user = null
|
||||
let business = await BusinessModel.findOne({owner: ctx.from.id})
|
||||
let world = await WorldModel.findByPk(1)
|
||||
if (business === null) return await ctx.reply(`У вас нет организации.`)
|
||||
if (business.checks < 12) return await ctx.reply(`Недостаточно отработок для формирования выплаты.`)
|
||||
let percentSum = business.percent
|
||||
let percentSum = 0
|
||||
let text = ``
|
||||
let percentErrorText = ``
|
||||
let profit = 0
|
||||
let piece = 0
|
||||
let businessPercent = 0
|
||||
let moneyList = rand(500, 2000)
|
||||
for (i=0; i < business.users.length; i++){ // Summary percent
|
||||
user = await UserModel.findByPk(business.users[i])
|
||||
console.log(business.users[i])
|
||||
percentSum += user.business.percent
|
||||
text += `${user.username} ${user.business.percent}%\n`
|
||||
percentSum += Number(user.business.percent)
|
||||
percentErrorText += `${user.username} ${user.business.percent}% [для изменения введите /percent ${user.telegram_id} проценты]\n`
|
||||
}
|
||||
if (percentSum > 100) return await ctx.reply(`Общий процент всех сотрудников превышает 100%\nПроцент организации: ${business.percent}%\n${text}`)
|
||||
if (percentSum > 100) return await ctx.reply(`Общий процент всех сотрудников превышает 100%\nПроцент организации: ${business.percent}%\n${percentErrorText}`)
|
||||
for (i=0; i < business.users.length; i++){ // Общая внесенная сумма всеми участниками
|
||||
user = await UserModel.findByPk(business.users[i])
|
||||
profit = user.business.checks * moneyList
|
||||
business.balance += profit
|
||||
text += `${user.username} нарабатывает ${profit} [${moneyList}*${user.business.checks}] в баланс организации.\n`
|
||||
profit += user.business.checks * moneyList
|
||||
text += `${user.username} нарабатывает ¤${user.business.checks * moneyList} [¤${moneyList}*${user.business.checks}] в баланс организации.\n`
|
||||
}
|
||||
businessPercent = profit / 100 * business.percent
|
||||
text +=`Профит: ${profit}\n`
|
||||
let profitCheck = profit
|
||||
for (i=0; i < business.users.length; i++){ // Процент выплаты участникам
|
||||
user = await UserModel.findByPk(business.users[i])
|
||||
piece = Math.trunc(profit / 100 * user.business.percent)
|
||||
business.balance -= piece
|
||||
text += `${user.username} получает ${piece}\n`
|
||||
piece = Math.round(profit / 100 * user.business.percent)
|
||||
profitCheck -= piece
|
||||
user.money += piece
|
||||
user.save()
|
||||
text += `${user.username} получает ¤${piece}\nОстаток выплат: ¤${profitCheck}\n`
|
||||
}
|
||||
if (profitCheck > 0) {
|
||||
business.balance += profitCheck
|
||||
business.save()
|
||||
text += `На баланс бизнеса поступило ¤${profitCheck}`
|
||||
}
|
||||
return await ctx.reply(text)
|
||||
})
|
||||
|
||||
bot.command('percent', async (ctx) => {
|
||||
ctx.args = ctx.update.message.text.split(' ')
|
||||
let user = await UserModel.findByPk(ctx.from.id)
|
||||
let business = await BusinessModel.findOne({owner: ctx.from.id})
|
||||
if (business === null) return await ctx.reply(`У вас нет организации.`)
|
||||
if (!ctx.args[1] || !ctx.args[2]) return ctx.reply(`Не указан аргумент.`)
|
||||
if (!Number(ctx.args[2])) return ctx.reply(`Процент должен быть числом от 1 до 100.`)
|
||||
if (ctx.args[2] < 1 || ctx.args[2] > 100) return ctx.reply(`Минимальный процент 1 | Максимальный процент 100.`)
|
||||
let change = await UserModel.findByPk(ctx.args[1])
|
||||
change.business = {
|
||||
id: change.business.id,
|
||||
checks: change.business.checks,
|
||||
percent: ctx.args[2]
|
||||
}
|
||||
change.save()
|
||||
return await ctx.reply(`Участнику ${change.username} установлен процент ${ctx.args[2]}`)
|
||||
})
|
||||
|
||||
bot.command('business', async (ctx) => {
|
||||
let user = await UserModel.findByPk(ctx.from.id)
|
||||
let business = await BusinessModel.findOne({owner: ctx.from.id})
|
||||
let world = await WorldModel.findByPk(1)
|
||||
ctx.args = ctx.update.message.text.split(' ')
|
||||
if (business !== null) return await ctx.reply(`У вас уже есть организация.`)
|
||||
if (!ctx.args[1]) return ctx.reply(`Не указан аргумент.`)
|
||||
if (user.money < 100000) return await ctx.reply(`Регистрация организации стоит ¤100.000`)
|
||||
if (user.level < 5) return await ctx.reply(`Регистрация организации доступна с 5 уровня.`)
|
||||
ctx.args = ctx.update.message.text.split(' ')
|
||||
user.money -= 100000
|
||||
world.balance += 100000
|
||||
let text = ``
|
||||
@ -707,6 +748,7 @@ ${text}
|
||||
|
||||
bot.command('invite', async (ctx) => {
|
||||
ctx.args = ctx.update.message.text.split(' ')
|
||||
if (!ctx.args[1]) return ctx.reply(`/invite [ID]`)
|
||||
let user = await UserModel.findByPk(ctx.from.id)
|
||||
let invited = await UserModel.findOne({ where: { username: ctx.args[1] } });
|
||||
await bot.telegram.sendMessage(invited.telegram_id, 'Приглашение', Markup
|
||||
@ -735,10 +777,55 @@ ${text}
|
||||
})
|
||||
|
||||
|
||||
/////////////////////////////////////Admin Commands//////////////////////////////////////////////////
|
||||
|
||||
bot.command('report', async (ctx) => {
|
||||
let user = await UserModel.findByPk(ctx.from.id)
|
||||
ctx.args = ctx.update.message.text.split(' ')
|
||||
if (!ctx.args[1]) return ctx.reply(`/report [Текст обращения]`)
|
||||
let uID = shortid.generate()
|
||||
await ReportModel.create({
|
||||
uid: uID,
|
||||
author: user.telegram_id,
|
||||
text: ctx.payload,
|
||||
status: 1
|
||||
})
|
||||
let report = await ReportModel.findOne({ where: { uid: uID } })
|
||||
await bot.telegram.sendMessage(adminList[0], `Обращение от пользователя ${user.username}\nТекст обращения:\n${ctx.payload}\n\nДля ответа /answer ${report.id} [Ответ]`)
|
||||
return await ctx.reply(`Обращение #${report.id}[${report.uid}] создано.`)
|
||||
})
|
||||
|
||||
bot.command('answer', async (ctx) => {
|
||||
let user = await UserModel.findByPk(ctx.from.id)
|
||||
ctx.args = ctx.update.message.text.split(' ')
|
||||
if (!ctx.args[1]) return ctx.reply(`Нужен номер обращения`)
|
||||
let report = await ReportModel.findByPk(ctx.args[1])
|
||||
if (report === null) return await ctx.reply(`Нет обращения с таким ID.`)
|
||||
if (report.status == 0) return await ctx.reply(`Данное обращение уже закрыто.`)
|
||||
let answer = ctx.args
|
||||
answer.shift()
|
||||
answer.shift()
|
||||
answer = answer.join(' ')
|
||||
await bot.telegram.sendMessage(report.author, `Ответ на обращение #${report.id}[${report.uid}]\n\n` + answer)
|
||||
report.status = 0
|
||||
report.save()
|
||||
return await ctx.reply(`Ответ отправлен, обращение закрыто!`)
|
||||
})
|
||||
|
||||
bot.command('fastblock', async (ctx) => {
|
||||
let user = await UserModel.findByPk(ctx.from.id)
|
||||
let blocked = ctx.message.reply_to_message.from.id
|
||||
await BlockModel.create({
|
||||
telegram_id: blocked,
|
||||
isBlocked: true,
|
||||
reason: `|AutoFastBlock|`,
|
||||
time: Math.trunc(Date.now()/1000 + 3600)
|
||||
})
|
||||
await bot.telegram.sendMessage(blocked, `Вы были заблокированы администратором ${user.username}.`)
|
||||
return await ctx.reply(`Пользователь заблокирован.`)
|
||||
})
|
||||
|
||||
///////////////////////////////////////Functions//////////////////////////////////////////////////////
|
||||
|
||||
function rand(min, max) {return Math.round(Math.random() * (max - min)) + min}
|
||||
var parserInt = (str) => parseInt(str.replace(/k|к/ig, "000"));
|
||||
|
@ -1,26 +1,26 @@
|
||||
{
|
||||
"0": {
|
||||
"name": "SCAR-L",
|
||||
"name": "Five-Seven",
|
||||
"price": 1000,
|
||||
"type": "weapon"
|
||||
},
|
||||
"1": {
|
||||
"name": "Glock",
|
||||
"name": "ПМ",
|
||||
"price": 1000,
|
||||
"type": "weapon"
|
||||
},
|
||||
"2": {
|
||||
"name": "ТТ",
|
||||
"name": "Glock",
|
||||
"price": 1000,
|
||||
"type": "weapon"
|
||||
},
|
||||
"3": {
|
||||
"name": "ТТ",
|
||||
"name": "M4A1",
|
||||
"price": 1000,
|
||||
"type": "weapon"
|
||||
},
|
||||
"4": {
|
||||
"name": "Glock",
|
||||
"name": "ПМ",
|
||||
"price": 1000,
|
||||
"type": "weapon"
|
||||
},
|
||||
@ -30,7 +30,7 @@
|
||||
"type": "equipment"
|
||||
},
|
||||
"6": {
|
||||
"name": "Кольчуга",
|
||||
"name": "Бронежилет M1",
|
||||
"price": 1000,
|
||||
"type": "equipment"
|
||||
},
|
||||
@ -40,12 +40,12 @@
|
||||
"type": "equipment"
|
||||
},
|
||||
"8": {
|
||||
"name": "Картонные накладки",
|
||||
"name": "Шлем танкиста",
|
||||
"price": 1000,
|
||||
"type": "equipment"
|
||||
},
|
||||
"9": {
|
||||
"name": "Бронежилет M2",
|
||||
"name": "Кольчуга",
|
||||
"price": 1000,
|
||||
"type": "equipment"
|
||||
}
|
||||
|
11
models/block.model.js
Normal file
11
models/block.model.js
Normal file
@ -0,0 +1,11 @@
|
||||
const sequelize = require('../db');
|
||||
const {DataTypes} = require('sequelize');
|
||||
|
||||
const Block = sequelize.define('block', {
|
||||
telegram_id: {type: DataTypes.INTEGER, 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}
|
||||
})
|
||||
|
||||
module.exports = Block;
|
12
models/report.model.js
Normal file
12
models/report.model.js
Normal file
@ -0,0 +1,12 @@
|
||||
const sequelize = require('../db');
|
||||
const {DataTypes} = require('sequelize');
|
||||
|
||||
const Report = sequelize.define('report', {
|
||||
id: {type: DataTypes.INTEGER, primaryKey: true, unique: true, autoIncrement: true},
|
||||
uid: {type: DataTypes.STRING, unique: true},
|
||||
author: {type: DataTypes.INTEGER, defaultValue: 0},
|
||||
text: {type: DataTypes.STRING, defaultValue: 0},
|
||||
status: {type: DataTypes.INTEGER, defaultValue: 1}
|
||||
})
|
||||
|
||||
module.exports = Report;
|
40
package-lock.json
generated
40
package-lock.json
generated
@ -17,7 +17,9 @@
|
||||
"pg": "^8.6.0",
|
||||
"pg-hstore": "^2.3.3",
|
||||
"sequelize": "^6.6.2",
|
||||
"telegraf": "^4.13.1"
|
||||
"shortid": "^2.2.16",
|
||||
"telegraf": "^4.13.1",
|
||||
"uuid": "^9.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/runtime": {
|
||||
@ -1426,6 +1428,11 @@
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
||||
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="
|
||||
},
|
||||
"node_modules/nanoid": {
|
||||
"version": "2.1.11",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-2.1.11.tgz",
|
||||
"integrity": "sha512-s/snB+WGm6uwi0WjsZdaVcuf3KJXlfGl2LcxgwkEwJF0D/BWzVWAZW/XY4bFaiR7s0Jk3FPvlnepg1H1b1UwlA=="
|
||||
},
|
||||
"node_modules/node-fetch": {
|
||||
"version": "2.7.0",
|
||||
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",
|
||||
@ -1945,6 +1952,15 @@
|
||||
"request": "^2.34"
|
||||
}
|
||||
},
|
||||
"node_modules/request/node_modules/uuid": {
|
||||
"version": "3.4.0",
|
||||
"resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz",
|
||||
"integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==",
|
||||
"deprecated": "Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.",
|
||||
"bin": {
|
||||
"uuid": "bin/uuid"
|
||||
}
|
||||
},
|
||||
"node_modules/responselike": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/responselike/-/responselike-1.0.2.tgz",
|
||||
@ -2122,6 +2138,15 @@
|
||||
"uuid": "dist/bin/uuid"
|
||||
}
|
||||
},
|
||||
"node_modules/shortid": {
|
||||
"version": "2.2.16",
|
||||
"resolved": "https://registry.npmjs.org/shortid/-/shortid-2.2.16.tgz",
|
||||
"integrity": "sha512-Ugt+GIZqvGXCIItnsL+lvFJOiN7RYqlGy7QE41O3YC1xbNSeDGIRO7xg2JJXIAj1cAGnOeC1r7/T9pgrtQbv4g==",
|
||||
"deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.",
|
||||
"dependencies": {
|
||||
"nanoid": "^2.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/signal-exit": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.3.tgz",
|
||||
@ -2531,12 +2556,15 @@
|
||||
"integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8="
|
||||
},
|
||||
"node_modules/uuid": {
|
||||
"version": "3.4.0",
|
||||
"resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz",
|
||||
"integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==",
|
||||
"deprecated": "Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.",
|
||||
"version": "9.0.1",
|
||||
"resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz",
|
||||
"integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==",
|
||||
"funding": [
|
||||
"https://github.com/sponsors/broofa",
|
||||
"https://github.com/sponsors/ctavan"
|
||||
],
|
||||
"bin": {
|
||||
"uuid": "bin/uuid"
|
||||
"uuid": "dist/bin/uuid"
|
||||
}
|
||||
},
|
||||
"node_modules/validator": {
|
||||
|
@ -19,6 +19,8 @@
|
||||
"pg": "^8.6.0",
|
||||
"pg-hstore": "^2.3.3",
|
||||
"sequelize": "^6.6.2",
|
||||
"telegraf": "^4.13.1"
|
||||
"shortid": "^2.2.16",
|
||||
"telegraf": "^4.13.1",
|
||||
"uuid": "^9.0.1"
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user