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);