snlvape2

Bota hep açık kalacağı ve Yapay zeka desteği ekle

Kodari AI
KodariOct 27 at 5:31 pm 1
AlwaysOpenAI
A Minecraft plugin that keeps the server open 24/7 with automatic restart and crash recovery systems. Integrates an AI-powered assistant that monitors server health, detects anomalies, and provides intelligent responses to player queries. Features include configurable uptime monitoring, scheduled maintenance windows, automatic resource optimization, and a chat-based AI interface that answers player questions about server rules, commands, and gameplay. The plugin uses a lightweight AI model with local processing to ensure privacy and fast response times, while maintaining server stability through proactive health checks and automated recovery procedures.
  1. Botu Kodari’de 7/24 çalışacak şekilde hazırlıyorum.

  2. /ai komutuyla, API ayarları girildiğinde yapay zekâ yanıtı ekliyorum.

Discord botu için başlangıç dosyalarını oluşturdum. Bot, Kodari’de dağıtıldığında 7/24 çalışır; Discord’da /ai komutu ile soruları yanıtlar.

Çalışması için proje ortam değişkenlerine DISCORD_TOKEN, DISCORD_CLIENT_ID, AI_API_URL, AI_API_KEY ve AI_MODEL değerlerini girin. Yapay zekâ ayarları, OpenAI uyumlu sohbet API’si kullanan bir servise göre yapılandırılabilir.

Kodari can make mistakes. Review important code before using.
Files
index.js
package.json
Code
2 121
index.js
const {
  ActivityType,
  Client,
  Events,
  GatewayIntentBits,
  REST,
  Routes,
  SlashCommandBuilder
} = require("discord.js");

const discordToken = process.env.DISCORD_TOKEN;
const applicationId = process.env.DISCORD_CLIENT_ID;
const aiApiUrl = process.env.AI_API_URL;
const aiApiKey = process.env.AI_API_KEY;
const aiModel = process.env.AI_MODEL;

if (!discordToken || !applicationId) {
  throw new Error("DISCORD_TOKEN ve DISCORD_CLIENT_ID ortam değişkenleri gerekli.");
}

const client = new Client({
  intents: [GatewayIntentBits.Guilds]
});

const aiCommand = new SlashCommandBuilder()
  .setName("ai")
  .setDescription("Yapay zekâya soru sor.")
  .addStringOption(option =>
    option
      .setName("soru")
      .setDescription("Yapay zekâya sormak istediğin soru.")
      .setRequired(true)
      .setMaxLength(1500)
  )
  .toJSON();

client.once(Events.ClientReady, async readyClient => {
  readyClient.user.setPresence({
    status: "online",
    activities: [{ name: "/ai ile sorularını yanıtlıyor", type: ActivityType.Listening }]
  });

  try {
    const rest = new REST({ version: "10" }).setToken(discordToken);
    await rest.put(Routes.applicationCommands(applicationId), { body: [aiCommand] });
    console.log(`${readyClient.user.tag} çevrimiçi; /ai komutu kaydedildi.`);
  } catch (error) {
    console.error("/ai komutu kaydedilemedi:", error);
  }
});

client.on(Events.InteractionCreate, async interaction => {
  if (!interaction.isChatInputCommand() || interaction.commandName !== "ai") return;

  await interaction.deferReply();

  if (!aiApiUrl || !aiApiKey || !aiModel) {
    await interaction.editReply(
      "Yapay zekâyı etkinleştirmek için AI_API_URL, AI_API_KEY ve AI_MODEL ayarlarını girin."
    );
    return;
  }

  try {
    const response = await fetch(aiApiUrl, {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${aiApiKey}`,
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        model: aiModel,
        messages: [
          {
            role: "system",
            content: "Türkçe yanıt veren, yardımcı ve güvenli bir Discord asistanısın."
          },
          {
            role: "user",
            content: interaction.options.getString("soru", true)
          }
        ]
      }),
      signal: AbortSignal.timeout(45_000)
    });

    if (!response.ok) {
      throw new Error(`Yapay zekâ servisi HTTP ${response.status} yanıtı verdi.`);
    }

    const data = await response.json();
    const answer = data.choices?.[0]?.message?.content;
    if (typeof answer !== "string" || !answer.trim()) {
      throw new Error("Yapay zekâ servisinden geçerli bir yanıt alınamadı.");
    }

    const safeAnswer = answer.trim().slice(0, 1900);
    await interaction.editReply(safeAnswer);
  } catch (error) {
    console.error("Yapay zekâ isteği başarısız:", error);
    await interaction.editReply("Şu anda yapay zekâ yanıt veremiyor. Biraz sonra tekrar dene.");
  }
});

client.login(discordToken);