Comments (4)
soft runnig, but not ask me and other users
from prisma.
scheme prisma:
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}
model Account {
id Int @id @default(autoincrement())
idvk Int
crdate DateTime @default(now())
select_user Int @default(0)
User User[]
}
model User {
id Int @id @default(autoincrement())
name String
class String
idvk Int
spec String
id_alliance Int?
lvl Int @default(0)
medal Int @default(5)
gold Int @default(0)
xp Int @default(0)
private Boolean @default(false)
crdate DateTime @default(now())
id_role Int @default(1)
role Role @relation(fields: [id_role], references: [id], onDelete: Cascade)
id_account Int @default(1)
account Account @relation(fields: [id_account], references: [id], onDelete: Cascade)
Artefact Artefact[]
Inventory Inventory[]
Trigger Trigger[]
Achievement Achievement[]
Analyzer Analyzer[]
}
model BlackBox {
id Int @id @default(autoincrement())
idvk Int @unique
}
model Role {
id Int @id @default(autoincrement())
name String
User User[]
}
model Artefact {
id Int @id @default(autoincrement())
id_user Int
name String
label String
description String
type String
user User @relation(fields: [id_user], references: [id], onDelete: Cascade)
}
model Inventory {
id Int @id @default(autoincrement())
id_user Int
id_item Int
item Item @relation(fields: [id_item], references: [id], onDelete: Cascade)
user User @relation(fields: [id_user], references: [id], onDelete: Cascade)
}
model Item {
id Int @id @default(autoincrement())
name String
description String?
price Int
id_category Int
type String
category Category @relation(fields: [id_category], references: [id], onDelete: Cascade)
Inventory Inventory[]
}
model Category {
id Int @id @default(autoincrement())
name String
Item Item[]
}
model Trigger {
id Int @id @default(autoincrement())
name String
value Boolean
user User @relation(fields: [id_user], references: [id], onDelete: Cascade, onUpdate: Cascade)
id_user Int
crdate DateTime @default(now())
}
model Achievement {
id Int @id @default(autoincrement())
name String
uid Int
user User @relation(fields: [id_user], references: [id], onDelete: Cascade, onUpdate: Cascade)
id_user Int
crdate DateTime @default(now())
}
model Analyzer {
id Int @id @default(autoincrement())
buying Int @default(0)
quest Int @default(0)
underwear Int @default(0)
convert_mo Int @default(0)
beer Int @default(0)
beer_premiun Int @default(0)
birthday Int @default(0)
gold_lost Int @default(0)
gold_got Int @default(65)
xp_got Int @default(0)
xp_lost Int @default(0)
user User @relation(fields: [id_user], references: [id], onDelete: Cascade, onUpdate: Cascade)
id_user Int
crdate DateTime @default(now())
}
model Alliance {
id Int @id @default(autoincrement())
name String
idvk Int
}
from prisma.
index.ts:
import { VK, Keyboard } from 'vk-io';
import { HearManager } from '@vk-io/hear';
import {
QuestionManager,
IQuestionMessageContext
} from 'vk-io-question';
import { registerUserRoutes } from './engine/player'
import { InitGameRoutes } from './engine/init';
import { Keyboard_Index, Logger, Worker_Checker } from './engine/core/helper';
import * as dotenv from 'dotenv' // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import
import prisma from './engine/events/module/prisma_client';
import { Exit, Main_Menu_Init } from './engine/events/contoller';
import { Admin_Enter, Artefact_Enter, Birthday_Enter, Card_Enter, Inventory_Enter, Rank_Enter, Statistics_Enter} from './engine/events/module/info';
import { Operation_Enter, Right_Enter, User_Info } from './engine/events/module/tool';
import { Service_Beer_Open, Service_Beer_Premium_Open, Service_Cancel, Service_Convert_Galleon, Service_Convert_Galleon_Change, Service_Convert_Magic_Experience, Service_Convert_Magic_Experience_Change, Service_Enter, Service_Level_Up, Service_Level_Up_Change, Service_Quest_Open, Service_Underwear_Open } from './engine/events/module/service';
import { Shop_Bought, Shop_Buy, Shop_Cancel, Shop_Category_Enter, Shop_Enter } from './engine/events/module/shop';
import { Person_Detector } from './engine/core/person';
import { Alliance_Control, Alliance_Control_Multi, Alliance_Controller } from './engine/events/module/alliance';
dotenv.config()
export const token: string = String(process.env.token)
export const root: number = Number(process.env.root) //root user
export const chat_id: number = Number(process.env.chat_id) //chat for logs
export const group_id: number = Number(process.env.group_id)//clear chat group
export const timer_text = { answerTimeLimit: 300_000 } // ожидать пять минут
export const timer_text_oper = { answerTimeLimit: 60_000 } // ожидать пять минут
export const answerTimeLimit = 300_000 // ожидать пять минут
export const starting_date = new Date(); // время работы бота
//авторизация
async function Group_Id_Get() {
const vk = new VK({ token: token, apiLimit: 1 });
const [group] = await vk.api.groups.getById(vk);
const groupId = group.id;
return groupId
}
export const vk = new VK({ token: token, pollingGroupId: Number(Group_Id_Get()), apiLimit: 1 });
//инициализация
const questionManager = new QuestionManager();
const hearManager = new HearManager();
/prisma.$use(async (params, next) => {
console.log('This is middleware!')
// Modify or interrogate params here
console.log(params)
return next(params)
})/
//настройка
vk.updates.use(questionManager.middleware);
vk.updates.on('message_new', hearManager.middleware);
//регистрация роутов из других классов
InitGameRoutes(hearManager)
registerUserRoutes(hearManager)
//миддлевар для предварительной обработки сообщений
vk.updates.on('message_new', async (context: any, next: any) => {
if (context.peerType == 'chat') {
try {
await vk.api.messages.delete({'peer_id': context.peerId, 'delete_for_all': 1, 'cmids': context.conversationMessageId, 'group_id': group_id})
await Logger(`In chat received a message from the user ${context.senderId} and was deleted`)
//await vk.api.messages.send({ peer_id: chat_id, random_id: 0, message: `✅🚫 @id${context.senderId} ${context.text}`})
} catch (error) {
await Logger(`In chat received a message from the user ${context.senderId} and wasn't deleted`)
//await vk.api.messages.send({ peer_id: chat_id, random_id: 0, message: `⛔🚫 @id${context.senderId} ${context.text}`})
}
return
}
//проверяем есть ли пользователь в базах данных
const user_check = await prisma.account.findFirst({ where: { idvk: context.senderId } })
//если пользователя нет, то начинаем регистрацию
if (!user_check) {
//согласие на обработку
const answer = await context.question(`⌛ Вы входите в Центробанк Министерства Магии 🏦, из ниоткуда перед вами предстали два орка и произнесли: \n — Министр Магии говорил нам о вас. Но прежде чем продолжить, распишитесь здесь о своем согласии на обработку персональных данных. \n В тот же миг в их руках магическим образом появился пергамент. \n 💡 У вас есть 5 минут на принятие решения!`,
{
keyboard: Keyboard.builder()
.textButton({ label: '✏', payload: { command: 'Согласиться' }, color: 'positive' }).row()
.textButton({ label: '👣', payload: { command: 'Отказаться' }, color: 'negative' }).oneTime(),
answerTimeLimit
}
);
if (answer.isTimeout) { return await context.send(`⏰ Время ожидания подтверждения согласия истекло!`) }
if (!/да|yes|Согласиться|конечно|✏/i.test(answer.text|| '{}')) {
await context.send('⌛ Вы отказались дать свое согласие, а живым отсюда никто не уходил, вас упаковали!');
return;
}
//приветствие игрока
const visit = await context.question(`⌛ Поставив свою подпись, вы, стараясь не смотреть косо на орков, вошли в личный кабинет Центробанка, и увидели домашнего эльфа, наводящего порядок, ужас и страх.`,
{
keyboard: Keyboard.builder()
.textButton({ label: 'Подойти и поздороваться', payload: { command: 'Согласиться' }, color: 'positive' }).row()
.textButton({ label: 'Ждать, пока эльф закончит', payload: { command: 'Отказаться' }, color: 'negative' }).oneTime().inline(),
answerTimeLimit
}
);
if (visit.isTimeout) { return await context.send(`⏰ Время ожидания активности истекло!`) }
const save = await prisma.account.create({ data: { idvk: context.senderId } })
const info = await User_Info(context)
await context.send(`⌛ Эльф отвлекся от дел, заприметив вас, подошел и сказал.\n - Добро пожаловать в мир меча и магии! \n И протянул вам вашу карточку.\n ⚖Вы получили картотеку, ${info.first_name}\n 🕯 GUID: ${save.id}. \n 🎥 idvk: ${save.idvk}\n ⚰ Дата Регистрации: ${save.crdate}\n`)
await Logger(`In database created new user with uid [${save.id}] and idvk [${context.senderId}]`)
const check_bbox = await prisma.blackBox.findFirst({ where: { idvk: context.senderId } })
const ans_selector = `⁉ @id${save.idvk}(${info.first_name}) ${!check_bbox ? "легально" : "НЕЛЕГАЛЬНО"} получает банковскую карту GUID: ${save.id}!`
await vk.api.messages.send({
peer_id: chat_id,
random_id: 0,
message: ans_selector
})
await Person_Detector(context)
await Keyboard_Index(context, `💡 Подсказка: Когда все операции вы успешно завершили, напишите [!банк] без квадратных скобочек, а затем нажмите кнопку: ✅Подтвердить авторизацию!`)
} else {
await Person_Detector(context)
await Keyboard_Index(context, `⌛ Загрузка, пожалуйста подождите...`)
}
return next();
})
vk.updates.on('message_event', async (context: any, next: any) => {
await Person_Detector(context)
const config: any = {
"system_call": Main_Menu_Init,
"card_enter": Card_Enter,
"birthday_enter": Birthday_Enter,
"exit": Exit,
"artefact_enter": Artefact_Enter,
"inventory_enter": Inventory_Enter,
"admin_enter": Admin_Enter,
"service_enter": Service_Enter,
"service_cancel": Service_Cancel,
"service_convert_galleon": Service_Convert_Galleon,
"service_convert_galleon_change": Service_Convert_Galleon_Change,
"service_convert_magic_experience": Service_Convert_Magic_Experience,
"service_convert_magic_experience_change": Service_Convert_Magic_Experience_Change,
"service_level_up": Service_Level_Up,
"service_level_up_change": Service_Level_Up_Change,
"shop_category_enter": Shop_Category_Enter,
"shop_enter": Shop_Enter,
"shop_cancel": Shop_Cancel,
"shop_bought": Shop_Bought,
"shop_buy": Shop_Buy,
"operation_enter": Operation_Enter, // заглушки
"right_enter": Right_Enter, // заглушки
"service_beer_open": Service_Beer_Open,
"service_beer_premium_open": Service_Beer_Premium_Open,
"service_quest_open": Service_Quest_Open,
"service_underwear_open": Service_Underwear_Open,
"statistics_enter": Statistics_Enter,
"rank_enter": Rank_Enter,
"alliance_control_multi": Alliance_Control_Multi,
"alliance_control": Alliance_Control,
"alliance_controller": Alliance_Controller
}
try {
await configcontext.eventPayload.command
} catch (e) {
await Logger(Error event detected for callback buttons: ${e}
)
}
return await next();
})
vk.updates.start().then(() => {
Logger('running succes')
}).catch(console.error);
setInterval(Worker_Checker, 86400000);
process.on('warning', e => console.warn(e.stack))
from prisma.
reloaded server and while all work in normal mode
from prisma.
Related Issues (20)
- [BUG] [PRISMA STUDIO] [PRISMA GENERATE]
- Promise.all in interactive $transaction unexpectedly merges operations
- Bug when compiling prisma using custom output
- Crash in command generate. internal error: entered unreachable code
- Postgres `Oid` fails with `relationJoins`
- `internal error: entered unreachable code` in end-to-end playwright tests run over sqlite database HOT 3
- Server has closed the connection in long transactions with ?pgbouncer=true
- Send custom batch/bulk queries
- "Not Authorised" when directly applying Prisma generated migrations to Cloudflare D1 with `PRAGMA foreign_key_check;` HOT 3
- Can NOT run prisma for a month, Windows 11, VSCode
- Crash when insert data to SQLite `createMany` using Bun - thread 'tokio-runtime-worker' panicked
- Prisma Client should never create empty SQLite databases
- Improve Developer Experience when working with multiple providers.
- Support for SQL-level `DISTINCT` operation for more database (MySQL, SQLite, SQL Server)
- Postgres: Allow using `= ANY($1)` for filtering instead of `IN ($1, $2, ...)` for large arrays HOT 2
- primsa generate HOT 1
- Prisma 5.12.1 client has errors accessing postgress db when using with cloudflare workers and the new `{ previewFeatures = ["driverAdapters"] }` HOT 9
- For JSON columns in postres the prisma client returns a string instead of an object for that column when performing update operation
- I get this error while querying data: `JSON.stringify cannot serialize BigInt.` HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from prisma.