Tobkubos commited on
Commit
0e51c08
·
1 Parent(s): 566faed

front update

Browse files
Files changed (1) hide show
  1. index.js +155 -55
index.js CHANGED
@@ -9,7 +9,11 @@ import {
9
  TextInputBuilder,
10
  TextInputStyle,
11
  ActionRowBuilder,
12
- MessageFlags
 
 
 
 
13
  } from "discord.js";
14
 
15
  const client = new Client({
@@ -30,11 +34,16 @@ client.once(Events.ClientReady, async () => {
30
  {
31
  name: "detect",
32
  description: "Otwiera okienko do wklejenia linku lub tekstu do analizy",
 
33
  },
 
 
 
 
34
  ]);
35
- console.log("Pomyślnie zarejestrowano komendę /detect");
36
  } catch (error) {
37
- console.error("Błąd podczas rejestracji komendy:", error);
38
  }
39
  });
40
 
@@ -66,7 +75,7 @@ function preparePayload(input) {
66
  type: "file",
67
  payload: {
68
  file_url: trimmed,
69
- content_type: "file"
70
  }
71
  };
72
  }
@@ -81,7 +90,108 @@ function preparePayload(input) {
81
  };
82
  }
83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  client.on(Events.InteractionCreate, async (interaction) => {
 
85
  if (interaction.isChatInputCommand()) {
86
  if (interaction.commandName === "detect") {
87
  const modal = new ModalBuilder()
@@ -102,65 +212,55 @@ client.on(Events.InteractionCreate, async (interaction) => {
102
  }
103
  }
104
 
105
- if (interaction.isModalSubmit()) {
106
- if (interaction.customId === "detectModal") {
107
- const userContent = interaction.fields.getTextInputValue("detectInput");
108
-
109
- await interaction.deferReply({ flags: [MessageFlags.Ephemeral] });
 
 
 
 
 
110
 
111
- try {
112
- const { type, payload } = preparePayload(userContent);
113
-
114
- console.log(`Wysyłanie zapytania typu: ${type} do API...`);
115
-
116
- const response = await fetch(`${API_URL}/analyze`, {
117
- method: "POST",
118
- headers: {
119
- "Content-Type": "application/json",
120
- },
121
- body: JSON.stringify(payload),
122
  });
 
123
 
124
- if (!response.ok) {
125
- const errorData = await response.json().catch(() => ({}));
126
- console.error("Szczegóły błędu z FastAPI:", JSON.stringify(errorData, null, 2));
127
-
128
- let errorMsg = `Błąd serwera API (Status ${response.status})`;
129
- if (errorData.detail) {
130
- if (Array.isArray(errorData.detail)) {
131
- errorMsg = errorData.detail
132
- .map(err => `• Pole \`${err.loc.join(".")}\`: ${err.msg}`)
133
- .join("\n");
134
- } else {
135
- errorMsg = errorData.detail;
136
- }
137
- }
138
- throw new Error(errorMsg);
139
- }
140
 
141
- const data = await response.json();
 
 
 
 
 
142
 
143
- const statusEmoji = data.is_deepfake ? "⚠️ **Wykryto potencjalny Deepfake!**" : "✅ **Zawartość wydaje się oryginalna**";
144
- const confidencePercent = (data.confidence * 100).toFixed(2);
145
- const timeSec = data.analysis_time.toFixed(3);
 
 
 
 
 
146
 
147
- const replyMessage =
148
- `### Wyniki Analizy (${data.content_type.toUpperCase()})\n` +
149
- `${statusEmoji}\n\n` +
150
- `* **Pewność modelu:** \`${confidencePercent}%\`\n` +
151
- `* **Użyty model:** \`${data.model_used}\`\n` +
152
- `* **Czas przetwarzania:** \`${timeSec} sekund\`\n`;
153
 
154
- await interaction.editReply({
155
- content: replyMessage,
156
- });
 
 
 
157
 
158
- } catch (error) {
159
- console.error("Błąd podczas analizy:", error);
160
- await interaction.editReply({
161
- content: `❌ Nie udało się przeprowadzić analizy.\n\n**Szczegóły błędu:**\n${error.message}`,
162
- });
163
- }
164
  }
165
  }
166
  });
 
9
  TextInputBuilder,
10
  TextInputStyle,
11
  ActionRowBuilder,
12
+ MessageFlags,
13
+ ApplicationCommandType,
14
+ EmbedBuilder,
15
+ ButtonBuilder,
16
+ ButtonStyle
17
  } from "discord.js";
18
 
19
  const client = new Client({
 
34
  {
35
  name: "detect",
36
  description: "Otwiera okienko do wklejenia linku lub tekstu do analizy",
37
+ type: ApplicationCommandType.ChatInput
38
  },
39
+ {
40
+ name: "Przeanalizuj tekst",
41
+ type: ApplicationCommandType.Message
42
+ }
43
  ]);
44
+ console.log("Pomyślnie zarejestrowano komendy (/detect oraz menu kontekstowe)");
45
  } catch (error) {
46
+ console.error("Błąd podczas rejestracji komend:", error);
47
  }
48
  });
49
 
 
75
  type: "file",
76
  payload: {
77
  file_url: trimmed,
78
+ content_type: "file"
79
  }
80
  };
81
  }
 
90
  };
91
  }
92
 
93
+ function getProgressBar(confidence, isDeepfake) {
94
+ const totalBlocks = 10;
95
+ const filledBlocks = Math.min(totalBlocks, Math.max(0, Math.round(confidence * totalBlocks)));
96
+ const emptyBlocks = totalBlocks - filledBlocks;
97
+ const blockEmoji = isDeepfake ? "🟥" : "🟩";
98
+ return blockEmoji.repeat(filledBlocks) + "⬛".repeat(emptyBlocks);
99
+ }
100
+
101
+ async function handleAnalysis(interaction, userContent, targetMessage = null) {
102
+ await interaction.deferReply({ flags: [MessageFlags.Ephemeral] });
103
+
104
+ try {
105
+ const { type, payload } = preparePayload(userContent);
106
+
107
+ console.log(`Wysyłanie zapytania typu: ${type} do API...`);
108
+
109
+ const response = await fetch(`${API_URL}/analyze`, {
110
+ method: "POST",
111
+ headers: {
112
+ "Content-Type": "application/json",
113
+ },
114
+ body: JSON.stringify(payload),
115
+ });
116
+
117
+ if (!response.ok) {
118
+ const errorData = await response.json().catch(() => ({}));
119
+ console.error("Szczegóły błędu z FastAPI:", JSON.stringify(errorData, null, 2));
120
+
121
+ let errorMsg = `Błąd serwera API (Status ${response.status})`;
122
+ if (errorData.detail) {
123
+ if (Array.isArray(errorData.detail)) {
124
+ errorMsg = errorData.detail
125
+ .map(err => `• Pole \`${err.loc.join(".")}\`: ${err.msg}`)
126
+ .join("\n");
127
+ } else {
128
+ errorMsg = errorData.detail;
129
+ }
130
+ }
131
+ throw new Error(errorMsg);
132
+ }
133
+
134
+ const data = await response.json();
135
+
136
+ if (targetMessage) {
137
+ try {
138
+ if (data.is_deepfake) {
139
+ await targetMessage.react('⚠️');
140
+ } else {
141
+ await targetMessage.react('✅');
142
+ }
143
+ } catch (reactError) {
144
+ console.warn("Nie udało się dodać reakcji do wiadomości:", reactError.message);
145
+ }
146
+ }
147
+
148
+ const embedColor = data.is_deepfake ? 0xFF0000 : 0x00FF00;
149
+ const verdictText = data.is_deepfake ? "⚠️ Wykryto potencjalny Deepfake!" : "✅ Zawartość wydaje się oryginalna";
150
+ const progressBar = getProgressBar(data.confidence, data.is_deepfake);
151
+ const confidencePercent = (data.confidence * 100).toFixed(2);
152
+
153
+ const embed = new EmbedBuilder()
154
+ .setColor(embedColor)
155
+ .setTitle("🛡️ Wynik Analizy Treści")
156
+ .setDescription(`**Werdykt:** ${verdictText}`)
157
+ .addFields(
158
+ { name: "Pewność modelu", value: `\`${confidencePercent}%\` \n${progressBar}` },
159
+ { name: "Czas przetwarzania", value: `\`${data.analysis_time.toFixed(3)}s\``, inline: true },
160
+ { name: "Użyty model", value: `\`${data.model_used}\``, inline: true },
161
+ { name: "Format danych", value: `\`${data.content_type.toUpperCase()}\``, inline: true }
162
+ )
163
+ .setTimestamp()
164
+ .setFooter({ text: "Deepfake Detection Service", iconURL: client.user.displayAvatarURL() });
165
+
166
+ // TWORZENIE PRZYCISKÓW
167
+ const buttonRow = new ActionRowBuilder().addComponents(
168
+ new ButtonBuilder()
169
+ .setCustomId("modelCorrect")
170
+ .setLabel("Model odpowiedział poprawnie")
171
+ .setStyle(ButtonStyle.Success)
172
+ .setEmoji("✅"),
173
+ new ButtonBuilder()
174
+ .setCustomId("reportError")
175
+ .setLabel("Zgłoś błąd analizy")
176
+ .setStyle(ButtonStyle.Danger)
177
+ .setEmoji("⚠️")
178
+ );
179
+
180
+ await interaction.editReply({
181
+ embeds: [embed],
182
+ components: [buttonRow]
183
+ });
184
+
185
+ } catch (error) {
186
+ console.error("Błąd podczas analizy:", error);
187
+ await interaction.editReply({
188
+ content: `❌ Nie udało się przeprowadzić analizy.\n\n**Szczegóły błędu:**\n${error.message}`,
189
+ });
190
+ }
191
+ }
192
+
193
  client.on(Events.InteractionCreate, async (interaction) => {
194
+
195
  if (interaction.isChatInputCommand()) {
196
  if (interaction.commandName === "detect") {
197
  const modal = new ModalBuilder()
 
212
  }
213
  }
214
 
215
+ if (interaction.isMessageContextMenuCommand()) {
216
+ if (interaction.commandName === "Przeanalizuj tekst") {
217
+ const targetMessage = interaction.targetMessage;
218
+
219
+ let contentToAnalyze = targetMessage.content;
220
+ const attachment = targetMessage.attachments.first();
221
+
222
+ if (attachment) {
223
+ contentToAnalyze = attachment.url;
224
+ }
225
 
226
+ if (!contentToAnalyze || contentToAnalyze.trim().length === 0) {
227
+ return interaction.reply({
228
+ content: "❌ Ta wiadomość nie zawiera tekstu ani załączników do analizy.",
229
+ flags: [MessageFlags.Ephemeral]
 
 
 
 
 
 
 
230
  });
231
+ }
232
 
233
+ await handleAnalysis(interaction, contentToAnalyze, targetMessage);
234
+ }
235
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
236
 
237
+ if (interaction.isModalSubmit()) {
238
+ if (interaction.customId === "detectModal") {
239
+ const userContent = interaction.fields.getTextInputValue("detectInput");
240
+ await handleAnalysis(interaction, userContent);
241
+ }
242
+ }
243
 
244
+ // GUZIKI
245
+ if (interaction.isButton()) {
246
+ // ZGŁOSZENIE BŁĘDU
247
+ if (interaction.customId === "reportError") {
248
+ await interaction.reply({
249
+ content: "✅ **Dziękujemy!** Twoje zgłoszenie błędu zostało zarejestrowane. Pomoże nam ono udoskonalić algorytmy detekcji.",
250
+ flags: [MessageFlags.Ephemeral]
251
+ });
252
 
253
+ console.log(`[RAPORT BŁĘDU] Użytkownik ${interaction.user.tag} (ID: ${interaction.user.id}) zgłosił błędną klasyfikację bota.`);
254
+ }
 
 
 
 
255
 
256
+ // POTWIERDZENIE POPRAWNOŚCI
257
+ if (interaction.customId === "modelCorrect") {
258
+ await interaction.reply({
259
+ content: "✅ **Dziękujemy!** Twoje potwierdzenie zostało pomyślnie zapisane. Cieszymy się, że model zadziałał prawidłowo.",
260
+ flags: [MessageFlags.Ephemeral]
261
+ });
262
 
263
+ console.log(`[POTWIERDZENIE] Użytkownik ${interaction.user.tag} (ID: ${interaction.user.id}) potwierdził poprawną klasyfikację bota.`);
 
 
 
 
 
264
  }
265
  }
266
  });