Spaces:
Runtime error
Runtime error
File size: 23,122 Bytes
e4b505c 87bf5cb fc6d61f e4b505c b171365 f19cc50 fc6d61f e4b505c fc6d61f b171365 87bf5cb fc6d61f f19cc50 87bf5cb f19cc50 0e51c08 b13ede6 87bf5cb c56dba2 87bf5cb fc6d61f 87bf5cb fc6d61f 0e51c08 fc6d61f 480a4f9 f19cc50 480a4f9 f19cc50 480a4f9 f19cc50 480a4f9 f19cc50 db0fed3 da164cc db0fed3 87bf5cb db0fed3 87bf5cb db0fed3 da164cc db0fed3 b13ede6 b171365 b13ede6 87bf5cb b13ede6 87bf5cb b13ede6 87bf5cb b13ede6 b171365 87bf5cb b13ede6 87bf5cb b13ede6 87bf5cb b171365 87bf5cb b171365 87bf5cb b171365 0e51c08 87bf5cb 0e51c08 480a4f9 f19cc50 87bf5cb f19cc50 87bf5cb 480a4f9 da164cc 480a4f9 da164cc 480a4f9 87bf5cb 480a4f9 f19cc50 87bf5cb 480a4f9 da164cc 480a4f9 87bf5cb 480a4f9 87bf5cb 480a4f9 da164cc 480a4f9 f19cc50 da164cc f19cc50 87bf5cb f19cc50 480a4f9 f19cc50 87bf5cb f19cc50 db0fed3 f19cc50 87bf5cb d95e4bb 87bf5cb d95e4bb 87bf5cb f19cc50 87bf5cb 0e51c08 b13ede6 db0fed3 e8d43fa f19cc50 87bf5cb 0e51c08 87bf5cb 0e51c08 87bf5cb 0e51c08 87bf5cb 0e51c08 87bf5cb 0e51c08 87bf5cb 0e51c08 87bf5cb 0e51c08 da164cc 092a7c8 da164cc 092a7c8 da164cc 0e51c08 87bf5cb 0e51c08 87bf5cb 0e51c08 c56dba2 fc6d61f b171365 fc6d61f b171365 fc6d61f b171365 fc6d61f f19cc50 87bf5cb f19cc50 db0fed3 f19cc50 480a4f9 87bf5cb 480a4f9 da164cc 480a4f9 87bf5cb f19cc50 87bf5cb f19cc50 480a4f9 f19cc50 87bf5cb f19cc50 480a4f9 87bf5cb f19cc50 fc6d61f 0e51c08 b13ede6 0e51c08 87bf5cb 0e51c08 b13ede6 0e51c08 87bf5cb 0e51c08 b13ede6 0e51c08 b171365 0e51c08 87bf5cb b171365 0e51c08 b171365 87bf5cb 0e51c08 87bf5cb c56dba2 b171365 c56dba2 87bf5cb c56dba2 0e51c08 c56dba2 b171365 0e51c08 b171365 0e51c08 f19cc50 7365bef 0ca9fa7 7365bef 87bf5cb 7365bef db0fed3 da164cc 7365bef 87bf5cb 7365bef 87bf5cb 7365bef 87bf5cb 7365bef f19cc50 87bf5cb f19cc50 0e51c08 90c3e03 87bf5cb 90c3e03 87bf5cb 90c3e03 87bf5cb 0e51c08 b171365 87bf5cb f19cc50 87bf5cb f19cc50 87bf5cb f19cc50 0e51c08 b171365 90c3e03 0e51c08 90c3e03 87bf5cb 90c3e03 87bf5cb 90c3e03 87bf5cb 0e51c08 fc6d61f 87bf5cb f19cc50 87bf5cb f19cc50 87bf5cb f19cc50 fc6d61f da164cc fc6d61f e4b505c 87bf5cb | 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 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 | import dotenv from "dotenv";
dotenv.config();
import {
Client,
GatewayIntentBits,
Events,
ModalBuilder,
TextInputBuilder,
TextInputStyle,
ActionRowBuilder,
MessageFlags,
ApplicationCommandType,
EmbedBuilder,
ButtonBuilder,
ButtonStyle,
PermissionFlagsBits,
ChannelSelectMenuBuilder,
StringSelectMenuBuilder,
ChannelType,
} from "discord.js";
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
});
const API_URL = process.env.API_URL || "http://127.0.0.1:8000";
const activeSetupSessions = new Map();
client.once(Events.ClientReady, async () => {
console.log(`Bot ready: ${client.user.tag}`);
try {
await client.application.commands.set([
{
name: "detect",
description: "Otwiera okienko do wklejenia linku lub tekstu do analizy",
type: ApplicationCommandType.ChatInput,
},
{
name: "setup",
description:
"Ustawienia kanału logów i modeli analizy (Wymaga Administratora)",
default_member_permissions:
PermissionFlagsBits.Administrator.toString(),
type: ApplicationCommandType.ChatInput,
},
{
name: "Wykryj deepfake",
type: ApplicationCommandType.Message,
},
{
name: "Weryfikacja faktów", // <--- TA LINIA
type: ApplicationCommandType.Message,
},
]);
console.log(
"Pomyślnie zarejestrowano komendy (/detect, /setup oraz menu kontekstowe)",
);
} catch (error) {
console.error("Błąd podczas rejestracji komend:", error);
}
});
// Pobieranie modeli bezpośrednio z FastAPI
async function fetchAvailableModels() {
try {
const response = await fetch(API_URL);
if (response.ok) {
const data = await response.json();
if (data.available_models) {
return data.available_models;
}
}
} catch (err) {
console.error("Błąd połączenia z FastAPI:", err.message);
}
return null;
}
async function fetchGuildConfig(guildId) {
try {
const response = await fetch(`${API_URL}/guilds/${guildId}/config`);
if (response.ok) {
const data = await response.json();
return {
logChannelId: data.log_channel_id,
multiModelWorkflow: data.multi_model_workflow || false,
models: {
text: data.active_text_model || "none",
image: data.active_image_model || "none",
},
};
}
} catch (err) {
console.error(
`[CONFIG ERROR] Błąd pobierania konfiguracji dla gildii ${guildId}:`,
err.message,
);
}
return {
logChannelId: null,
multiModelWorkflow: false,
models: {}
};
}
function preparePayload(input, explicitContentType = null) {
const trimmed = input.trim();
if (explicitContentType) {
if (explicitContentType.startsWith("image/")) {
return {
type: "image",
payload: { image_url: trimmed, content_type: "image" },
};
} else if (explicitContentType.startsWith("video/")) {
return {
type: "video",
payload: { video_url: trimmed, content_type: "video" },
};
} else {
return {
type: "file",
payload: { file_url: trimmed, content_type: "file" },
};
}
}
const isUrl = trimmed.startsWith("http://") || trimmed.startsWith("https://");
if (isUrl) {
const cleanUrl = trimmed.toLowerCase().split("?")[0];
if (cleanUrl.match(/\.(png|jpg|jpeg|webp|gif)$/)) {
return {
type: "image",
payload: { image_url: trimmed, content_type: "image" },
};
} else if (cleanUrl.match(/\.(mp4|webm|mov|avi)$/)) {
return {
type: "video",
payload: { video_url: trimmed, content_type: "video" },
};
} else {
return {
type: "file",
payload: { file_url: trimmed, content_type: "file" },
};
}
}
return {
type: "text",
payload: { text: trimmed, content_type: "text" },
};
}
function getProgressBar(confidence, isDeepfake) {
const totalBlocks = 10;
const filledBlocks = Math.min(
totalBlocks,
Math.max(0, Math.round(confidence * totalBlocks)),
);
const emptyBlocks = totalBlocks - filledBlocks;
const blockEmoji = isDeepfake ? "🟥" : "🟩";
return blockEmoji.repeat(filledBlocks) + "⬛".repeat(emptyBlocks);
}
// CAŁKOWICIE DYNAMICZNY GENERATOR WIDOKU SETUPU
function generateSetupView(tempConfig, availableModels) {
const embed = new EmbedBuilder()
.setColor(0x5865f2)
.setTitle("⚙️ Konfiguracja Systemu Detekcji")
.setDescription(
"Wybierz kanał do wysyłania logów oraz aktywne modele dla poszczególnych formatów danych.",
)
.setTimestamp()
.setFooter({ text: "Wybierz opcje i kliknij Zapisz ustawienia" });
embed.addFields({
name: "🔗 Tryb wielomodelowy (Multi-Model Workflow)",
value: tempConfig.multiModelWorkflow
? "🟢 **Włączony** (zostaną użyte wszystkie dostępne modele, indywidualny wybór jest zablokowany)"
: "🔴 **Wyłączony** (będzie używany tylko model wybrany poniżej)",
inline: false
});
for (const [contentType, models] of Object.entries(availableModels)) {
const currentSelected = tempConfig.multiModelWorkflow
? "Wszystkie (Multi-Model Workflow)"
: (tempConfig.models[contentType] || models[0] || "Brak");
embed.addFields({
name: `⚙️ Model dla formatu: ${contentType.toUpperCase()}`,
value: `\`${currentSelected}\``,
inline: true,
});
}
const channelSelect = new ChannelSelectMenuBuilder()
.setCustomId("setup_log_channel")
.setPlaceholder("Wybierz kanał dla raportów")
.addChannelTypes(ChannelType.GuildText);
const components = [new ActionRowBuilder().addComponents(channelSelect)];
for (const [contentType, models] of Object.entries(availableModels)) {
if (components.length >= 4) break;
const currentSelected = tempConfig.models[contentType] || models[0];
const selectOptions = models.map((model) => ({
label: model,
value: model,
default: currentSelected === model,
}));
const modelSelect = new StringSelectMenuBuilder()
.setCustomId(`setup_model_${contentType}`)
.setPlaceholder(`Wybierz model dla ${contentType}`)
.addOptions(selectOptions)
// WYszarzenie i zablokowanie wyboru, gdy włączony jest Multi-Model Workflow
.setDisabled(tempConfig.multiModelWorkflow);
components.push(new ActionRowBuilder().addComponents(modelSelect));
}
const buttonsRow = new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setCustomId("setup_toggle_multimodel")
.setLabel(tempConfig.multiModelWorkflow ? "Tryb Wielomodelowy: WŁ" : "Tryb Wielomodelowy: WYŁ")
.setStyle(tempConfig.multiModelWorkflow ? ButtonStyle.Primary : ButtonStyle.Secondary)
.setEmoji(tempConfig.multiModelWorkflow ? "🟢" : "⚫"),
new ButtonBuilder()
.setCustomId("setup_save")
.setLabel("Zapisz ustawienia")
.setStyle(ButtonStyle.Success)
.setEmoji("💾"),
new ButtonBuilder()
.setCustomId("setup_cancel")
.setLabel("Anuluj")
.setStyle(ButtonStyle.Danger)
.setEmoji("❌"),
);
components.push(buttonsRow);
return {
embeds: [embed],
components: components,
};
}
async function sendLogToDiscord(guild, embedToSend) {
const config = await fetchGuildConfig(guild.id);
if (!config.logChannelId) return;
try {
const channel = await guild.channels.fetch(config.logChannelId);
if (channel) {
await channel.send({ embeds: [embedToSend] });
}
} catch (err) {
console.warn(
`Nie można wysłać logu na kanał ${config.logChannelId}:`,
err.message,
);
}
}
async function handleFactCheck(interaction, statement) {
await interaction.deferReply({ flags: [MessageFlags.Ephemeral] });
try {
console.log(`Wysyłanie zapytania do weryfikacji faktów: "${statement.slice(0, 30)}..."`);
const response = await fetch(`${API_URL}/factcheck`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ statement: statement }),
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.detail || `Błąd API (Status ${response.status})`);
}
const data = await response.json();
let embedColor = 0xFFAA00; // Żółty domyślnie (SPORNE)
let verdictEmoji = "⚖️";
if (data.verdict === "PRAWDA") {
embedColor = 0x00FF00; // Zielony
verdictEmoji = "✅";
} else if (data.verdict === "FAŁSZ") {
embedColor = 0xFF0000; // Czerwony
verdictEmoji = "❌";
}
const embed = new EmbedBuilder()
.setColor(embedColor)
.setTitle(`${verdictEmoji} Wynik Weryfikacji Faktów`)
.setDescription(`**Badane stwierdzenie:**\n*"${statement}"*\n\n**Werdykt:** \`${data.verdict}\``)
.addFields(
{ name: "📝 Analiza merytoryczna", value: data.explanation },
{ name: "🎯 Pewność analizy", value: `\`${(data.confidence * 100).toFixed(0)}%\``, inline: true }
)
.setTimestamp()
.setFooter({ text: "System Fact-checkingowy", iconURL: client.user.displayAvatarURL() });
// Formatowanie źródeł
/*
if (data.sources && data.sources.length > 0) {
const sourcesText = data.sources
.map((src, idx) => `**[${idx + 1}]** [${src.title}](${src.url})\n*${src.snippet.slice(0, 150)}...*`)
.join("\n\n");
// Discord ma limit 1024 znaków na jedno pole w Embedzie, zabezpieczamy się przed jego przekroczeniem
const truncatedSources = sourcesText.length > 1024 ? sourcesText.slice(0, 1000) + "..." : sourcesText;
embed.addFields({ name: "🔗 Wykorzystane źródła internetowe", value: truncatedSources });
} else {
embed.addFields({ name: "🔗 Wykorzystane źródła internetowe", value: "Brak bezpośrednich źródeł." });
}
*/
await interaction.editReply({
embeds: [embed]
});
} catch (error) {
console.error("Błąd podczas weryfikacji faktów:", error);
await interaction.editReply({
content: `❌ Nie udało się przeprowadzić weryfikacji faktów.\n\n**Szczegóły błędu:**\n${error.message}`,
});
}
}
async function handleAnalysis(
interaction,
userContent,
targetMessage = null,
explicitContentType = null,
) {
await interaction.deferReply({ flags: [MessageFlags.Ephemeral] });
try {
const { type, payload } = preparePayload(userContent, explicitContentType);
payload.guild_id = interaction.guildId;
payload.user_id = interaction.user.id;
console.log(
`Wysyłanie zapytania typu: ${type} do API z modelem: ${payload.model || "domyślny"}...`,
);
const response = await fetch(`${API_URL}/analyze`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
console.error(
"Szczegóły błędu z FastAPI:",
JSON.stringify(errorData, null, 2),
);
let errorMsg = `Błąd serwera API (Status ${response.status})`;
if (errorData.detail) {
if (Array.isArray(errorData.detail)) {
errorMsg = errorData.detail
.map((err) => `• Pole \`${err.loc.join(".")}\`: ${err.msg}`)
.join("\n");
} else {
errorMsg = errorData.detail;
}
}
throw new Error(errorMsg);
}
const data = await response.json();
if (targetMessage) {
try {
if (data.is_deepfake) {
await targetMessage.react("⚠️");
} else {
await targetMessage.react("✅");
}
} catch (reactError) {
console.warn(
"Nie udało się dodać reakcji do wiadomości:",
reactError.message,
);
}
}
const embedColor = data.is_deepfake ? 0xFF0000 : 0x00FF00;
const verdictText = data.is_deepfake ? "⚠️ Wykryto potencjalny Deepfake!" : "✅ Zawartość wydaje się oryginalna";
const confidencePercent = (data.confidence * 100).toFixed(2);
const embed = new EmbedBuilder()
.setColor(embedColor)
.setTitle("🛡️ Wynik Analizy Treści")
.setDescription(`**Werdykt:** ${verdictText}`)
.setTimestamp()
.setFooter({
text: "Deepfake Detection Service",
iconURL: client.user.displayAvatarURL(),
});
if (data.details && data.details.length > 0) {
// Widok dla Multi-Modelu: ładnie listujemy każdy model
embed.addFields({ name: "📊 Średnia pewność systemu", value: `\`${confidencePercent}%\``, inline: false });
for (const detail of data.details) {
const detailBar = getProgressBar(detail.confidence, detail.is_deepfake);
const statusText = detail.is_deepfake ? "🟥 FAKE" : "🟩 REAL";
const pct = (detail.confidence * 100).toFixed(1);
embed.addFields({
name: `🤖 Model: ${detail.model.split("/").pop()}`, // skracamy ścieżkę modelu
value: `Werdykt: **${statusText}** (Pewność: \`${pct}%\`)\n${detailBar}`,
inline: false
});
}
} else {
// Standardowy widok dla pojedynczego modelu (progressBar jest bezpiecznie zdefiniowany tutaj)
const progressBar = getProgressBar(data.confidence, data.is_deepfake);
embed.addFields(
{ name: "Pewność modelu", value: `\`${confidencePercent}%\` \n${progressBar}` },
{ name: "Użyty model", value: `\`${data.used_model}\``, inline: true }
);
}
// 3. Dodatkowe pola wspólne (dodawane tylko raz na samym końcu)
embed.addFields(
{ name: "Czas przetwarzania", value: `\`${data.analysis_time.toFixed(3)}s\``, inline: true },
{ name: "Format danych", value: `\`${data.content_type.toUpperCase()}\``, inline: true }
);
const buttonRow = new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setCustomId("modelCorrect")
.setLabel("Model odpowiedział poprawnie")
.setStyle(ButtonStyle.Success)
.setEmoji("✅"),
new ButtonBuilder()
.setCustomId("reportError")
.setLabel("Zgłoś błąd analizy")
.setStyle(ButtonStyle.Danger)
.setEmoji("⚠️"),
);
await interaction.editReply({
embeds: [embed],
components: [buttonRow],
});
} catch (error) {
console.error("Błąd podczas analizy:", error);
await interaction.editReply({
content: `❌ Nie udało się przeprowadzić analizy.\n\n**Szczegóły błędu:**\n${error.message}`,
});
}
}
//funkcja kupczaka
client.on(Events.InteractionCreate, async (interaction) => {
if (interaction.isChatInputCommand()) {
if (interaction.commandName === "detect") {
const modal = new ModalBuilder()
.setCustomId("detectModal")
.setTitle("Detektor Deepfake");
const textInput = new TextInputBuilder()
.setCustomId("detectInput")
.setLabel("Wklej tutaj tekst lub link (obraz/wideo):")
.setStyle(TextInputStyle.Paragraph)
.setPlaceholder("Wklej zawartość...")
.setRequired(true);
const actionRow = new ActionRowBuilder().addComponents(textInput);
modal.addComponents(actionRow);
await interaction.showModal(modal);
}
if (interaction.commandName === "setup") {
const guildId = interaction.guildId;
await interaction.deferReply({ flags: [MessageFlags.Ephemeral] });
// Pobieramy konfigurację bezpośrednio z FastAPI
const currentConfig = await fetchGuildConfig(guildId);
const availableModels = await fetchAvailableModels();
if (!availableModels || Object.keys(availableModels).length === 0) {
return interaction.editReply({
content:
"❌ **Błąd konfiguracji:** Nie udało się nawiązać połączenia z backendem (FastAPI). Uruchom swój backend w Pythonie i spróbuj ponownie!",
});
}
if (currentConfig.multiModelWorkflow === undefined) {
currentConfig.multiModelWorkflow = false;
}
for (const [contentType, models] of Object.entries(availableModels)) {
if (!currentConfig.models[contentType] && models.length > 0) {
currentConfig.models[contentType] = models[0];
}
}
activeSetupSessions.set(guildId, {
config: { ...currentConfig },
availableModels,
});
const setupView = generateSetupView(currentConfig, availableModels);
await interaction.editReply(setupView);
}
}
if (interaction.isChannelSelectMenu()) {
if (interaction.customId === "setup_log_channel") {
const guildId = interaction.guildId;
const tempSession = activeSetupSessions.get(guildId);
if (tempSession) {
tempSession.config.logChannelId = interaction.values[0];
await interaction.update(
generateSetupView(tempSession.config, tempSession.availableModels),
);
}
}
}
// OBSŁUGA DYNAMICZNYCH MENU ROZWIJANYCH DLA MODELI
if (interaction.isStringSelectMenu()) {
const guildId = interaction.guildId;
const tempSession = activeSetupSessions.get(guildId);
if (tempSession) {
// Sprawdzamy czy zmieniany jest model (szukamy przedrostka setup_model_)
if (interaction.customId.startsWith("setup_model_")) {
const contentType = interaction.customId.replace("setup_model_", "");
tempSession.config.models[contentType] = interaction.values[0];
await interaction.update(
generateSetupView(tempSession.config, tempSession.availableModels),
);
}
}
}
if (interaction.isMessageContextMenuCommand()) {
if (interaction.commandName === "Wykryj deepfake") {
const targetMessage = interaction.targetMessage;
let contentToAnalyze = targetMessage.content;
let explicitContentType = null;
const attachment = targetMessage.attachments.first();
if (attachment) {
contentToAnalyze = attachment.url;
explicitContentType = attachment.contentType;
}
if (!contentToAnalyze || contentToAnalyze.trim().length === 0) {
return interaction.reply({
content:
"❌ Ta wiadomość nie zawiera tekstu ani załączników do analizy.",
flags: [MessageFlags.Ephemeral],
});
}
await handleAnalysis(
interaction,
contentToAnalyze,
targetMessage,
explicitContentType,
);
}
if (interaction.commandName === "Weryfikacja faktów") {
const targetMessage = interaction.targetMessage;
const contentToVerify = targetMessage.content;
if (!contentToVerify || contentToVerify.trim().length < 10) {
return interaction.reply({
content:
"❌ Wiadomość musi mieć przynajmniej 10 znaków tekstu, aby można było ją zweryfikować.",
flags: [MessageFlags.Ephemeral],
});
}
await handleFactCheck(interaction, contentToVerify);
}
}
//koniec funkcji kupczaka
if (interaction.isModalSubmit()) {
if (interaction.customId === "detectModal") {
const userContent = interaction.fields.getTextInputValue("detectInput");
await handleAnalysis(interaction, userContent);
}
}
if (interaction.isButton()) {
const guildId = interaction.guildId;
if (interaction.customId === "setup_save") {
const tempSession = activeSetupSessions.get(guildId);
if (tempSession) {
try {
const response = await fetch(`${API_URL}/guilds/${guildId}/setup`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
active_text_model: tempSession.config.models?.text || "none",
active_image_model: tempSession.config.models?.image || "none",
log_channel_id: tempSession.config.logChannelId || null,
multi_model_workflow: tempSession.config.multiModelWorkflow || false
})
});
if (!response.ok) {
const errData = await response.json();
throw new Error(errData.detail || "Błąd zapisu na backendzie");
}
activeSetupSessions.delete(guildId);
await interaction.update({
content:
"✅ **Ustawienia zostały pomyślnie zapisane na backendzie!**",
embeds: [],
components: [],
});
} catch (error) {
console.error("[SETUP ERROR]", error);
await interaction.update({
content: `❌ **Wystąpił błąd podczas zapisywania konfiguracji:** ${error.message}`,
embeds: [],
components: [],
});
}
}
}
if (interaction.customId === "setup_cancel") {
activeSetupSessions.delete(guildId);
await interaction.update({
content: "❌ **Konfiguracja została anulowana.**",
embeds: [],
components: [],
});
}
if (interaction.customId === "reportError") {
const disabledRow = new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setCustomId("modelCorrect")
.setLabel("Model odpowiedział poprawnie")
.setStyle(ButtonStyle.Success)
.setEmoji("✅")
.setDisabled(true),
new ButtonBuilder()
.setCustomId("reportError")
.setLabel("Zgłoś błąd analizy")
.setStyle(ButtonStyle.Danger)
.setEmoji("⚠️")
.setDisabled(true),
);
// 2 UPDATE BUTTONS
await interaction.update({
embeds: [interaction.message.embeds[0]],
components: [disabledRow],
});
// 3 CONFIRMATION
await interaction.followUp({
content:
"✅ **Dziękujemy!** Twoje zgłoszenie błędu zostało zarejestrowane.",
flags: [MessageFlags.Ephemeral],
});
console.log(
`[RAPORT BŁĘDU] Użytkownik ${interaction.user.tag} (ID: ${interaction.user.id}) zgłosił błąd klasyfikacji.`,
);
const originalEmbed = interaction.message.embeds[0];
if (originalEmbed) {
const logEmbed = EmbedBuilder.from(originalEmbed)
.setColor(0xffaa00)
.setTitle("⚠️ Zgłoszenie błędu analizy")
.setDescription(
`Użytkownik **${interaction.user.tag}** (ID: \`${interaction.user.id}\`) zgłosił błąd analizy w poniższym raporcie.`,
);
await sendLogToDiscord(interaction.guild, logEmbed);
}
}
// CORRECT CLICK
if (interaction.customId === "modelCorrect") {
const disabledRow = new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setCustomId("modelCorrect")
.setLabel("Model odpowiedział poprawnie")
.setStyle(ButtonStyle.Success)
.setEmoji("✅")
.setDisabled(true),
new ButtonBuilder()
.setCustomId("reportError")
.setLabel("Zgłoś błąd analizy")
.setStyle(ButtonStyle.Danger)
.setEmoji("⚠️")
.setDisabled(true),
);
// 2 DISABLE BUTTONS
await interaction.update({
embeds: [interaction.message.embeds[0]],
components: [disabledRow],
});
// 3 CONFIRMATION
await interaction.followUp({
content:
"✅ **Dziękujemy!** Twoje potwierdzenie zostało pomyślnie zapisane.",
flags: [MessageFlags.Ephemeral],
});
console.log(
`[POTWIERDZENIE] Użytkownik ${interaction.user.tag} (ID: ${interaction.user.id}) potwierdził poprawną klasyfikację.`,
);
const originalEmbed = interaction.message.embeds[0];
if (originalEmbed) {
const logEmbed = EmbedBuilder.from(originalEmbed)
.setColor(0x00aaff)
.setTitle("✅ Potwierdzona poprawność analizy")
.setDescription(
`Użytkownik **${interaction.user.tag}** (ID: \`${interaction.user.id}\`) potwierdził poprawność raportu.`,
);
await sendLogToDiscord(interaction.guild, logEmbed);
}
}
if (interaction.customId === "setup_toggle_multimodel") {
const tempSession = activeSetupSessions.get(guildId);
if (tempSession) {
tempSession.config.multiModelWorkflow = !tempSession.config.multiModelWorkflow;
await interaction.update(generateSetupView(tempSession.config, tempSession.availableModels));
}
}
}
});
client.on(Events.MessageCreate, (message) => {
if (message.author.bot) return;
console.log(`Message from ${message.author.tag}: ${message.content}`);
});
client.login(process.env.DISCORD_TOKEN);
|