-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
272 lines (230 loc) · 8.08 KB
/
index.js
File metadata and controls
272 lines (230 loc) · 8.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
// Lucy Bot - Metodologia KISS (Keep It Simple, Stupid)
// Arquivo principal ultra-simplificado
const { Client, GatewayIntentBits } = require('discord.js');
const { loadEvents } = require('./handlers/events');
const { prisma } = require('./utils/database');
const { startAPI, setBotClient } = require('./api/admin');
const BugHuntScheduler = require('./utils/bugHuntScheduler');
require('dotenv').config();
// Configuração básica do cliente
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent
]
});
// Iniciar API do painel admin (KISS: simples e opcional)
if (process.env.ENABLE_ADMIN_PANEL === 'true') {
setBotClient(client);
startAPI();
}
// Inicializar Bug Hunt Scheduler
let bugHuntScheduler;
// Carregar eventos (KISS: um handler para todos os eventos)
loadEvents(client);
// Lista de atividades simples
const activities = [
{ name: 'l~help | Lucy Bot', type: 0 }, // Jogando
{ name: 'docker compose up', type: 3 }, // Assistindo
{ name: 'a vida passar', type: 2 }, // Ouvindo
{ name: 'café e código', type: 0 }, // Jogando
{ name: 'o mercado de ações', type: 3 }, // Assistindo
{ name: 'bugs se esconderem', type: 2 }, // Ouvindo
{ name: 'a concorrência', type: 0 }, // Jogando
{ name: 'running on docker', type: 3 }, // Assistindo
{ name: 'a comunidade crescer', type: 2 }, // Ouvindo
{ name: 'lucy is awesome', type: 0 }, // Jogando
{ name: `${client.users.cache.size} users`, type: 3 }, // Assistindo usuários
{ name: 'prayse for lucy', type: 2 } // Ouvindo
];
// Inicializar scheduler quando bot estiver pronto
client.once('clientReady', () => {
console.log(`✅ ${client.user.tag} está online!`);
// Definir um uma atividade aleatória a cada 10 minutos
setInterval(() => {
const activity = activities[Math.floor(Math.random() * activities.length)];
client.user.setActivity(activity);
}, 10 * 60 * 1000);
// Iniciar Bug Hunt Scheduler
bugHuntScheduler = new BugHuntScheduler(client);
bugHuntScheduler.start();
console.log('🎯 Bug Hunt Scheduler ativado');
});
// Tratamento de erros simples
client.on('error', console.error);
process.on('unhandledRejection', (error) => {
console.error('Erro não tratado:', error);
});
// Inicializar bot (KISS: simples e direto)
client.login(process.env.DISCORD_TOKEN)
.then(() => {
// Conectar API com o cliente do bot
if (process.env.ENABLE_ADMIN_PANEL !== 'false') {
setBotClient(client);
}
// Iniciar sistema de atualização automática da bolsa
startStockMarketUpdater();
})
.catch((error) => {
console.error('❌ Erro ao fazer login:', error);
process.exit(1);
});
// Sistema de atualização automática da bolsa de valores
function startStockMarketUpdater() {
// Atualizar preços das ações a cada 5 minutos
setInterval(async () => {
try {
console.log('📈 Atualizando preços da bolsa...');
await updateStockPrices();
} catch (error) {
console.error('❌ Erro ao atualizar bolsa:', error);
}
}, 5 * 60 * 1000); // 5 minutos
// Gerar novas notícias a cada 30 minutos
setInterval(async () => {
try {
console.log('📰 Gerando notícias da bolsa...');
await generateStockNews();
} catch (error) {
console.error('❌ Erro ao gerar notícias:', error);
}
}, 30 * 60 * 1000); // 30 minutos
console.log('✅ Sistema de atualização automática da bolsa iniciado');
}
async function updateStockPrices() {
const stocks = await prisma.stock.findMany({
where: { isActive: true }
});
for (const stock of stocks) {
// Gerar mudança de preço baseada na volatilidade
const randomFactor = (Math.random() - 0.5) * 2; // -1 a 1
const priceChange = stock.currentPrice * stock.volatility * randomFactor * 0.3; // Reduzir impacto automático
let newPrice = stock.currentPrice + priceChange;
// Evitar preços muito baixos ou muito altos
const minPrice = stock.basePrice * 0.1; // Mínimo 10% do preço base
const maxPrice = stock.basePrice * 5.0; // Máximo 500% do preço base
newPrice = Math.max(minPrice, Math.min(maxPrice, newPrice));
const changePercent = ((newPrice - stock.currentPrice) / stock.currentPrice) * 100;
// Atualizar no banco apenas se a mudança for significativa (>0.5%)
if (Math.abs(changePercent) > 0.5) {
await prisma.stock.update({
where: { id: stock.id },
data: {
currentPrice: newPrice,
lastUpdate: new Date()
}
});
// Salvar no histórico
await prisma.stockHistory.create({
data: {
stockId: stock.id,
price: newPrice,
change: changePercent
}
});
}
}
}
async function generateStockNews() {
// Verificar se já existem notícias recentes
const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000);
const recentNews = await prisma.stockNews.count({
where: {
createdAt: { gte: oneHourAgo },
isActive: true
}
});
// Se já tem notícias recentes, não gerar mais
if (recentNews >= 2) return;
// Chance de 30% de gerar notícia
if (Math.random() > 0.3) return;
const stocks = await prisma.stock.findMany({
where: { isActive: true }
});
if (stocks.length === 0) return;
// Templates genéricos de notícias
const newsTemplates = [
{
title: "Mercado Reage a Mudanças Econômicas",
content: "Investidores ajustam posições após novos dados econômicos.",
impact: () => (Math.random() - 0.5) * 0.1 // -5% a +5%
},
{
title: "Volatilidade Marca Sessão de Negociação",
content: "Traders aproveitam oportunidades em sessão movimentada.",
impact: () => (Math.random() - 0.5) * 0.15 // -7.5% a +7.5%
},
{
title: "Análise Técnica Aponta Tendência",
content: "Especialistas identificam padrões importantes no mercado.",
impact: () => (Math.random() - 0.5) * 0.08 // -4% a +4%
}
];
const randomTemplate = newsTemplates[Math.floor(Math.random() * newsTemplates.length)];
// Escolher ações aleatórias para serem afetadas (25% das ações)
const affectedCount = Math.max(1, Math.floor(stocks.length * 0.25));
const shuffledStocks = stocks.sort(() => 0.5 - Math.random());
const affectedStocks = shuffledStocks.slice(0, affectedCount);
const affectedStockIds = affectedStocks.map(s => s.id);
const impact = randomTemplate.impact();
// Criar notícia
await prisma.stockNews.create({
data: {
title: randomTemplate.title,
content: randomTemplate.content,
affectedStocks: JSON.stringify(affectedStockIds),
priceImpact: impact
}
});
// Aplicar impacto nas ações afetadas
for (const stock of affectedStocks) {
const stockImpact = impact * (0.8 + Math.random() * 0.4); // Variação individual
const priceChange = stock.currentPrice * stockImpact;
const newPrice = Math.max(
stock.basePrice * 0.1,
Math.min(stock.basePrice * 5.0, stock.currentPrice + priceChange)
);
await prisma.stock.update({
where: { id: stock.id },
data: {
currentPrice: newPrice,
lastUpdate: new Date()
}
});
// Registrar no histórico
await prisma.stockHistory.create({
data: {
stockId: stock.id,
price: newPrice,
change: ((newPrice - stock.currentPrice) / stock.currentPrice) * 100
}
});
}
}
// Graceful shutdown (KISS: limpeza essencial)
process.on('SIGTERM', async () => {
console.log('🔄 Desconectando bot...');
await prisma.$disconnect();
client.destroy();
process.exit(0);
});
// Graceful shutdown
process.on('SIGTERM', async () => {
console.log('🔄 Desconectando bot...');
if (bugHuntScheduler) {
bugHuntScheduler.stop();
}
await prisma.$disconnect();
client.destroy();
process.exit(0);
});
process.on('SIGINT', async () => {
console.log('🛑 Desligando Lucy Bot...');
if (bugHuntScheduler) {
bugHuntScheduler.stop();
}
await prisma.$disconnect();
client.destroy();
process.exit(0);
});