-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
216 lines (188 loc) · 8.97 KB
/
index.js
File metadata and controls
216 lines (188 loc) · 8.97 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
require("dotenv").config();
const {
Client,
GatewayIntentBits,
Collection,
EmbedBuilder,
Events,
MessageFlags,
PermissionFlagsBits,
} = require("discord.js");
const fs = require("fs");
const path = require("path");
const { detectProfanity } = require("./profanityList");
const { addFine, findFineByMessageId, getFineAmount, approveReport, rejectReport, getFineById, getReporterRejectedCount, getFalseReportThreshold } = require("./database");
// ── 클라이언트 설정 ──────────────────────────────────────────────────────────
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
});
// ── 슬래시 커맨드 로드 ───────────────────────────────────────────────────────
client.commands = new Collection();
const commandsPath = path.join(__dirname, "commands");
const commandFiles = fs.readdirSync(commandsPath).filter((f) => f.endsWith(".js"));
for (const file of commandFiles) {
const command = require(path.join(commandsPath, file));
client.commands.set(command.data.name, command);
console.log(`📌 커맨드 로드: /${command.data.name}`);
}
// ── 봇 준비 ─────────────────────────────────────────────────────────────────
client.once(Events.ClientReady, (c) => {
console.log(`✅ 봇 로그인: ${c.user.tag}`);
console.log(`📡 ${c.guilds.cache.size}개 서버에 연결됨`);
console.log(`💰 벌금 설정: 길드별 설정`);
c.user.setActivity("욕설 감시 중 👀", { type: 3 }); // WATCHING
});
// ── 메시지 감지 (욕설 탐지) ──────────────────────────────────────────────────
client.on(Events.MessageCreate, async (message) => {
// 봇 메시지, DM 무시
if (message.author.bot || !message.guild) return;
const { detected, words } = detectProfanity(message.content);
if (!detected) return;
// 이미 처리된 메시지면 중복 감지 방지
if (findFineByMessageId(message.guild.id, message.id)) return;
const userId = message.author.id;
const username = message.author.username;
const fineAmount = getFineAmount(message.guild.id); // 실시간으로 DB에서 읽어 최신 금액 반영
const totalFine = words.length * fineAmount;
const { lastInsertRowid: fineId } = addFine({ guildId: message.guild.id, userId, username, wordUsed: message.content, amount: totalFine, messageContent: message.content, messageId: message.id });
const embed = new EmbedBuilder()
.setTitle("🚨 욕설 감지!")
.setColor(0xe74c3c)
.setDescription(
`<@${userId}>님, 욕설을 사용하셨습니다.\n` +
`**${fineAmount.toLocaleString()}원**이 벌금으로 부과됩니다!`
)
.addFields(
{
name: "💬 원본 메시지",
value: `\`\`\`${message.content}\`\`\``,
inline: false,
},
{
name: "🤬 감지된 욕설",
value: words.map((w) => `\`${w}\``).join(", "),
inline: true,
},
{
name: "💸 이번 벌금",
value: `**${totalFine.toLocaleString()}원**`,
inline: true,
}
)
.setFooter({ text: `벌금 ID: #${fineId} | 욕설 1회 = ${fineAmount.toLocaleString()}원 | /순위 로 현황 확인` })
.setTimestamp();
try {
await message.reply({ embeds: [embed] });
} catch {
await message.channel.send({ embeds: [embed] });
}
});
// ── 버튼 처리 (신고 승인/기각) ───────────────────────────────────────────────
client.on(Events.InteractionCreate, async (interaction) => {
if (!interaction.isButton()) return;
const [, action, id] = interaction.customId.split("_"); // report_approve_123
if (action !== "approve" && action !== "reject") return;
// 관리자 권한 확인
const member = interaction.member;
const isAdmin = member.permissions.has(PermissionFlagsBits.Administrator);
if (!isAdmin) {
return interaction.reply({ content: "❌ 관리자만 처리할 수 있습니다.", flags: MessageFlags.Ephemeral });
}
if (action === "approve") {
const changed = approveReport(Number(id));
if (!changed) {
return interaction.update({ content: `⚠️ 신고 #${id}는 이미 처리되었습니다.`, components: [], embeds: [] });
}
await interaction.update({
content: `✅ 신고 #${id} **승인** — 벌금이 확정되었습니다.`,
components: [],
embeds: [],
});
} else {
const fine = getFineById(Number(id));
const changed = rejectReport(Number(id));
if (!changed) {
return interaction.update({ content: `⚠️ 신고 #${id}는 이미 처리되었습니다.`, components: [], embeds: [] });
}
await interaction.update({
content: `❌ 신고 #${id} **기각** — 벌금이 취소되었습니다.`,
components: [],
embeds: [],
});
// 허위 신고 벌금 처리
if (fine?.reporter_id) {
const rejectedCount = getReporterRejectedCount(interaction.guild.id, fine.reporter_id);
const threshold = getFalseReportThreshold(interaction.guild.id);
if (rejectedCount % threshold === 0) {
const fineAmount = getFineAmount(interaction.guild.id);
const reporter = await interaction.guild.members.fetch(fine.reporter_id).catch(() => null);
const reporterUsername = reporter?.user.username ?? "unknown";
const { lastInsertRowid: falseFineId } = addFine({
guildId: interaction.guild.id,
userId: fine.reporter_id,
username: reporterUsername,
wordUsed: "[허위 신고]",
amount: fineAmount,
status: "auto",
});
const falseReportEmbed = new EmbedBuilder()
.setTitle("⚠️ 허위 신고 벌금 부과")
.setColor(0xe67e22)
.setDescription(
`<@${fine.reporter_id}>님의 허위 신고가 **${rejectedCount}회** 누적되었습니다.\n` +
`벌금 **${fineAmount.toLocaleString()}원**이 부과됩니다! (기준: ${threshold}회마다)`
)
.setFooter({ text: `벌금 ID: #${falseFineId} | 💰 수금봇` })
.setTimestamp();
await interaction.channel.send({ embeds: [falseReportEmbed] });
}
}
}
});
// ── 슬래시 커맨드 처리 ───────────────────────────────────────────────────────
client.on(Events.InteractionCreate, async (interaction) => {
if (!interaction.isChatInputCommand() && !interaction.isMessageContextMenuCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
// 관리자 전용 커맨드 권한 확인
if (command.adminOnly) {
const member = interaction.member;
if (!member.permissions.has(PermissionFlagsBits.Administrator)) {
return interaction.reply({
content: "❌ 이 커맨드는 관리자 전용입니다.",
flags: MessageFlags.Ephemeral,
});
}
}
try {
await command.execute(interaction);
} catch (error) {
console.error(`❌ /${interaction.commandName} 오류:`, error);
const errorMsg = { content: "❌ 커맨드 실행 중 오류가 발생했습니다.", flags: MessageFlags.Ephemeral };
if (interaction.replied || interaction.deferred) {
await interaction.followUp(errorMsg);
} else {
await interaction.reply(errorMsg);
}
}
});
// ── 봇 시작 ─────────────────────────────────────────────────────────────────
const token = process.env.DISCORD_TOKEN;
console.log(`🔑 DISCORD_TOKEN 상태: ${token === undefined ? "undefined (미설정)" : token === "" ? "빈 문자열" : `설정됨 (앞 10자: ${token.slice(0, 10)}...)`}`);
client.login(token).catch((err) => {
console.error("❌ 봇 로그인 실패");
console.error(` message : ${err.message}`);
console.error(` code : ${err.code ?? "없음"}`);
console.error(` status : ${err.status ?? err.httpStatus ?? "없음"}`);
console.error(` type : ${err.constructor?.name ?? typeof err}`);
if (!token) {
console.error(" 원인 : DISCORD_TOKEN 환경변수가 설정되지 않았습니다. Railway Variables에서 추가하세요.");
} else if (/invalid token/i.test(err.message)) {
console.error(" 원인 : 토큰 값이 유효하지 않습니다. Discord Developer Portal에서 토큰을 재발급하고 Railway Variables를 업데이트하세요.");
}
process.exit(1);
});