-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
621 lines (534 loc) · 17.6 KB
/
index.js
File metadata and controls
621 lines (534 loc) · 17.6 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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
require('dotenv').config()
const { Client, GatewayIntentBits, EmbedBuilder } = require('discord.js')
const { Pool } = require('pg')
if (!process.env.DISCORD_BOT_TOKEN) {
console.error(
'❌ DISCORD_BOT_TOKEN tanimli degil. .env dosyasini kontrol edin.'
)
process.exit(1)
}
if (!process.env.DATABASE_URL) {
console.error('❌ DATABASE_URL tanimli degil. .env dosyasini kontrol edin.')
process.exit(1)
}
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
],
})
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
})
const BASLANGIC_BAKIYESI = 0
const PREFIX = '!'
const MAX_TRANSFER_AMOUNT = 1_000_000_000
const FOOTER_TEXT = 'AYS Balance Bot'
const AUTHORIZED_ROLES = [
'Guild Master',
'Right Hand',
'Moderator',
'Police',
'Officer',
'Shotcaller',
'Diplomat',
]
function getFooter(client) {
return { text: FOOTER_TEXT, iconURL: client.user.displayAvatarURL() }
}
function isPositiveIntString(value) {
return typeof value === 'string' && /^\d+$/.test(value)
}
async function safeReply(message, payload) {
try {
return await message.reply(payload)
} catch (err) {
console.error('❌ Mesaj yanitlanamadi:', err)
}
}
async function veritabaniBaslat() {
try {
await pool.query(`
CREATE TABLE IF NOT EXISTS users (
user_id VARCHAR(255) PRIMARY KEY,
balance INTEGER DEFAULT ${BASLANGIC_BAKIYESI}
)
`)
await pool.query(`
ALTER TABLE users
ADD COLUMN IF NOT EXISTS username VARCHAR(255),
ADD COLUMN IF NOT EXISTS global_name VARCHAR(255),
ADD COLUMN IF NOT EXISTS roles JSONB
`)
await pool.query(`
CREATE TABLE IF NOT EXISTS balance_logs (
id SERIAL PRIMARY KEY,
executor_id VARCHAR(255) NOT NULL,
executor_name TEXT,
target_id VARCHAR(255) NOT NULL,
target_name TEXT,
action_type VARCHAR(50) NOT NULL,
amount INTEGER NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);`)
console.log('✅ Veritabanı başarıyla başlatıldı!')
} catch (error) {
console.error('❌ Veritabanı başlatma hatası:', error)
}
}
async function kullaniciProfiliniGuncelle(member) {
try {
if (!member) return
if (member.partial || !member.user || !member.user.username) {
member = await member.fetch().catch(() => member)
}
if (!member.roles?.cache?.size && member.guild) {
await member.guild.members.fetch(member.id).catch(() => {})
}
const userId = member.user?.id || member.id
const username = member.user?.username || null
const globalName =
member.user?.globalName || member.user?.global_name || null
const roles = member.roles?.cache
? Array.from(member.roles.cache.values()).map((r) => r.name)
: []
await pool.query(
`INSERT INTO users (user_id, username, global_name, roles, balance)
VALUES ($1, $2, $3, $4, COALESCE((SELECT balance FROM users WHERE user_id = $1::VARCHAR), $5))
ON CONFLICT (user_id) DO UPDATE SET
username = EXCLUDED.username,
global_name = EXCLUDED.global_name,
roles = EXCLUDED.roles`,
[userId, username, globalName, JSON.stringify(roles), BASLANGIC_BAKIYESI]
)
} catch (error) {
console.error('❌ Kullanıcı profili güncellenemedi:', error)
}
}
async function bakiyeGetir(userId) {
try {
const result = await pool.query('SELECT * FROM users WHERE user_id = $1', [
userId,
])
if (result.rows.length === 0) {
await pool.query(
'INSERT INTO users (user_id, balance) VALUES ($1, $2) ON CONFLICT (user_id) DO NOTHING',
[userId, BASLANGIC_BAKIYESI]
)
return { balance: BASLANGIC_BAKIYESI, error: null }
}
return { balance: result.rows[0].balance, error: null }
} catch (error) {
console.error('❌ Bakiye alınamadı:', error)
return { balance: null, error: 'Veritabanı hatası' }
}
}
async function silverGonder(gonderenId, aliciId, miktar) {
const dbClient = await pool.connect()
try {
await dbClient.query('BEGIN')
const gonderenSonuc = await dbClient.query(
'SELECT balance FROM users WHERE user_id = $1 FOR UPDATE',
[gonderenId]
)
if (gonderenSonuc.rows.length === 0) {
await dbClient.query(
'INSERT INTO users (user_id, balance) VALUES ($1, $2) ON CONFLICT (user_id) DO NOTHING',
[gonderenId, BASLANGIC_BAKIYESI]
)
}
const mevcutBakiye =
gonderenSonuc.rows.length > 0
? gonderenSonuc.rows[0].balance
: BASLANGIC_BAKIYESI
if (mevcutBakiye < miktar) {
await dbClient.query('ROLLBACK')
return { error: 'yetersiz_bakiye', balance: mevcutBakiye }
}
const aliciSonuc = await dbClient.query(
'SELECT balance FROM users WHERE user_id = $1',
[aliciId]
)
if (aliciSonuc.rows.length === 0) {
await dbClient.query(
'INSERT INTO users (user_id, balance) VALUES ($1, $2) ON CONFLICT (user_id) DO NOTHING',
[aliciId, BASLANGIC_BAKIYESI]
)
}
const cekSonuc = await dbClient.query(
'UPDATE users SET balance = balance - $1 WHERE user_id = $2 AND balance >= $1',
[miktar, gonderenId]
)
if (cekSonuc.rowCount === 0) {
await dbClient.query('ROLLBACK')
return { error: 'yetersiz_bakiye', balance: mevcutBakiye }
}
await dbClient.query(
'UPDATE users SET balance = balance + $1 WHERE user_id = $2',
[miktar, aliciId]
)
await dbClient.query('COMMIT')
return { error: null }
} catch (error) {
await dbClient.query('ROLLBACK')
console.error('❌ Silver transfer hatası:', error)
return { error: 'Transfer başarısız. Lütfen tekrar deneyin.' }
} finally {
dbClient.release()
}
}
client.on('ready', async () => {
console.log(`🤖 ${client.user.tag} olarak giriş yapıldı!`)
console.log(`Bot aktif! Sunucu sayısı: ${client.guilds.cache.size}`)
await veritabaniBaslat()
})
client.on('messageCreate', async (message) => {
if (message.author.bot) return
if (!message.content.startsWith(PREFIX)) return
const args = message.content.slice(PREFIX.length).trim().split(/ +/)
const komut = args.shift().toLowerCase()
try {
if (message.member) {
await kullaniciProfiliniGuncelle(message.member)
}
} catch (_) {}
if (komut === 'balance' || komut === 'bal') {
const userData = await bakiyeGetir(message.author.id)
if (userData.error) {
return message.reply('❌ Bakiye alınamadı. Lütfen tekrar deneyin.')
}
const embed = new EmbedBuilder()
.setColor('#00b4d8')
.setTitle('💰 Cüzdan Bilgisi')
.setDescription(
`🪙 **${
message.author.username
}**'in bakiyesi: **${userData.balance.toLocaleString('tr-TR')} Silver**`
)
.setFooter(getFooter(client))
.setTimestamp()
await safeReply(message, { embeds: [embed] })
} else if (komut === 'gonder' || komut === 'transfer') {
const alici = message.mentions.users.first()
const miktarStr = args[1]
if (!isPositiveIntString(miktarStr)) {
return await safeReply(message, '❌ Geçerli bir miktar girin.')
}
const miktar = Number(miktarStr)
if (!alici) {
return await safeReply(message, '❌ Lütfen bir kullanıcı etiketleyin.')
}
if (alici.bot) {
return await safeReply(message, '🤖 Botlara silver gönderemezsin.')
}
if (alici.id === message.author.id) {
return await safeReply(message, '❌ Kendine silver gönderemezsin.')
}
if (miktar <= 0 || miktar > MAX_TRANSFER_AMOUNT) {
return await safeReply(message, '❌ Geçerli bir miktar girin.')
}
const gonderenData = await bakiyeGetir(message.author.id)
if (gonderenData.balance < miktar) {
return await safeReply(
message,
`❌ Yetersiz bakiye! Mevcut bakiyen: **${gonderenData.balance} Silver**`
)
}
const transferSonuc = await silverGonder(
message.author.id,
alici.id,
miktar
)
if (transferSonuc.error) {
if (transferSonuc.error === 'yetersiz_bakiye') {
return await safeReply(
message,
`❌ Yetersiz bakiye! Mevcut bakiyen: **${transferSonuc.balance} Silver**`
)
}
return await safeReply(message, `❌ ${transferSonuc.error}`)
}
const embed = new EmbedBuilder()
.setColor('#00ff88')
.setTitle('💸 Silver Transferi Başarılı!')
.setDescription(
`✨ **${message.author.username}** ➜ **${alici.username}**'e **${miktar} Silver** gönderdi!`
)
.addFields(
{
name: 'Gönderen',
value: message.author.username,
inline: true,
},
{ name: 'Alıcı', value: alici.username, inline: true },
{ name: 'Miktar', value: `${miktar} 🪙 Silver`, inline: true }
)
.setFooter(getFooter(client))
.setTimestamp()
await safeReply(message, { embeds: [embed] })
await pool.query(
`INSERT INTO balance_logs (executor_id, executor_name, target_id, target_name, action_type, amount)
VALUES ($1, $2, $3, $4, 'transfer', $5)`,
[
message.author.id,
message.author.username,
alici.id,
alici.username,
miktar,
]
)
} else if (komut === 'yardim' || komut === 'help') {
const embed = new EmbedBuilder()
.setColor('#1d3557')
.setTitle('📜 Komut Listesi')
.setDescription('Aşağıda mevcut komutlar listelenmiştir:')
.addFields(
{
name: '💰 /balance - !balance veya !bal ',
value: 'Bakiyeni görüntüle',
inline: false,
},
{
name: '💰 /balance kullanici ',
value: 'Yetkili kişilerin başka bakiyeleri görüntülemesini sağlar',
inline: false,
},
{
name: '💸 /transfer kullanici miktar veya !gonder @kullanici miktar',
value: 'Belirtilen kullanıcıya silver gönder',
inline: false,
},
{
name: '🍷 /yukle kullanici miktar veya !yukle @kullanici miktar',
value: 'Bu yetkili personelin yükleme yapmasını sağlar',
inline: false,
},
{
name: 'ℹ️ !yardim veya !help',
value: 'Bu yardım menüsünü gösterir',
inline: false,
}
)
.setFooter(getFooter(client))
.setTimestamp()
await safeReply(message, { embeds: [embed] })
} else if (komut === 'yukle' || komut === 'addbal') {
const alici = message.mentions.users.first()
const miktarStr = args[1]
if (!isPositiveIntString(miktarStr)) {
return await safeReply(message, '❌ Geçerli bir miktar girin.')
}
const miktar = Number(miktarStr)
if (!alici) {
return await safeReply(message, '❌ Lütfen bir kullanıcı etiketleyin.')
}
if (alici.bot) {
return await safeReply(message, '🤖 Botlara silver yüklenemez.')
}
const memberRoles = message.member.roles.cache.map((r) => r.name)
const yetkili = AUTHORIZED_ROLES.some((role) => memberRoles.includes(role))
if (!yetkili) {
return await safeReply(message, '⛔ Bu komutu kullanma yetkiniz yok.')
}
const aliciData = await bakiyeGetir(alici.id)
const yeniBakiye = aliciData.balance + miktar
await pool.query('UPDATE users SET balance = $1 WHERE user_id = $2', [
yeniBakiye,
alici.id,
])
const embed = new EmbedBuilder()
.setColor('#ffd700')
.setTitle('💵 Bakiye Yükleme Başarılı')
.setDescription(
`🪙 **${miktar.toLocaleString('tr-TR')} Silver**, **${
alici.username
}** kullanıcısına yüklendi.`
)
.addFields(
{ name: 'Yükleyen', value: message.author.username, inline: true },
{ name: 'Alıcı', value: alici.username, inline: true },
{
name: 'Yeni Bakiye',
value: `${yeniBakiye.toLocaleString('tr-TR')} 🪙`,
inline: true,
}
)
.setFooter(getFooter(client))
.setTimestamp()
await safeReply(message, { embeds: [embed] })
await pool.query(
`INSERT INTO balance_logs (executor_id, executor_name, target_id, target_name, action_type, amount)
VALUES ($1, $2, $3, $4, 'load', $5)`,
[
message.author.id,
message.author.username,
alici.id,
alici.username,
miktar,
]
)
}
})
client.login(process.env.DISCORD_BOT_TOKEN)
async function shutdown(signal) {
try {
console.log(`\n${signal} alindi, kapatiliyor...`)
await client.destroy()
await pool.end()
} catch (err) {
console.error('❌ Kapanis hatasi:', err)
} finally {
process.exit(0)
}
}
process.on('SIGINT', () => shutdown('SIGINT'))
process.on('SIGTERM', () => shutdown('SIGTERM'))
module.exports = { client, pool }
// Slash komutlarını yakalama
client.on('interactionCreate', async (interaction) => {
if (!interaction.isCommand()) return
const { commandName } = interaction
// balance komutu
if (commandName === 'balance') {
const targetUser =
interaction.options.getUser('kullanici') || interaction.user
const guildMember = await interaction.guild.members.fetch(
interaction.user.id
)
const memberRoles = guildMember.roles.cache.map((r) => r.name)
const yetkili = AUTHORIZED_ROLES.some((r) => memberRoles.includes(r))
// Başkalarının bakiyesini sorgulama kontrolü
if (targetUser.id !== interaction.user.id && !yetkili) {
return await interaction.reply({
content:
'⛔ Başka bir kullanıcının bakiyesini görüntüleme yetkiniz yok.',
ephemeral: true,
})
}
const userData = await bakiyeGetir(targetUser.id)
if (!userData) {
return await interaction.reply({
content: '❌ Kullanıcının bakiyesi alınamadı.',
ephemeral: true,
})
}
const embed = new EmbedBuilder()
.setColor('#00b4d8')
.setTitle('💰 Cüzdan Bilgisi')
.setDescription(
`🪙 **${
targetUser.username
}**'in bakiyesi: **${userData.balance.toLocaleString('tr-TR')} Silver**`
)
.setFooter(getFooter(client))
.setTimestamp()
await interaction.reply({ embeds: [embed] })
}
// transfer komutu
else if (commandName === 'transfer') {
const alici = interaction.options.getUser('kullanici')
const miktar = interaction.options.getInteger('miktar')
if (!alici || alici.bot || alici.id === interaction.user.id) {
return await interaction.reply({
content: '❌ Geçerli bir kullanıcı seçin.',
ephemeral: true,
})
}
if (miktar <= 0 || miktar > MAX_TRANSFER_AMOUNT) {
return await interaction.reply({
content: '❌ Geçerli bir miktar girin.',
ephemeral: true,
})
}
const gonderenData = await bakiyeGetir(interaction.user.id)
if (gonderenData.balance < miktar) {
return await interaction.reply({
content: `❌ Yetersiz bakiye! Mevcut bakiyen: ${gonderenData.balance} Silver`,
ephemeral: true,
})
}
const transferSonuc = await silverGonder(
interaction.user.id,
alici.id,
miktar
)
if (transferSonuc.error) {
return await interaction.reply({
content: `❌ ${transferSonuc.error}`,
ephemeral: true,
})
}
const embed = new EmbedBuilder()
.setColor('#00ff88')
.setTitle('💸 Silver Transferi Başarılı!')
.setDescription(
`✨ **${interaction.user.username}** ➜ **${alici.username}**'e **${miktar} Silver** gönderdi!`
)
.setFooter(getFooter(client))
.setTimestamp()
await interaction.reply({ embeds: [embed] })
await pool.query(
`INSERT INTO balance_logs (executor_id, executor_name, target_id, target_name, action_type, amount)
VALUES ($1, $2, $3, $4, 'transfer', $5)`,
[
interaction.user.id,
interaction.user.username,
alici.id,
alici.username,
miktar,
]
)
}
// yukle komutu
else if (commandName === 'yukle') {
const alici = interaction.options.getUser('kullanici')
const miktar = interaction.options.getInteger('miktar')
if (!alici || alici.bot) {
return await interaction.reply({
content: '❌ Geçerli bir kullanıcı seçin.',
ephemeral: true,
})
}
const guildMember = await interaction.guild.members.fetch(
interaction.user.id
)
const memberRoles = guildMember.roles.cache.map((r) => r.name)
const yetkili = AUTHORIZED_ROLES.some((r) => memberRoles.includes(r))
if (!yetkili) {
return await interaction.reply({
content: '⛔ Bu komutu kullanma yetkiniz yok.',
ephemeral: true,
})
}
const aliciData = await bakiyeGetir(alici.id)
const yeniBakiye = aliciData.balance + miktar
await pool.query('UPDATE users SET balance = $1 WHERE user_id = $2', [
yeniBakiye,
alici.id,
])
const embed = new EmbedBuilder()
.setColor('#ffd700')
.setTitle('💵 Bakiye Yükleme Başarılı')
.setDescription(
`🪙 **${miktar.toLocaleString('tr-TR')} Silver**, **${
alici.username
}** kullanıcısına yüklendi.`
)
.setFooter(getFooter(client))
.setTimestamp()
await interaction.reply({ embeds: [embed] })
await pool.query(
`INSERT INTO balance_logs (executor_id, executor_name, target_id, target_name, action_type, amount)
VALUES ($1, $2, $3, $4, 'load', $5)`,
[
interaction.user.id,
interaction.user.username,
alici.id,
alici.username,
miktar,
]
)
}
})