0% found this document useful (0 votes)
1 views

orignal index.js

This document contains a Discord bot implementation using the discord.js library. It initializes the bot, sets up command handling, and fetches player statistics from a backend API. Additionally, it includes error handling for various events such as guild bans and API errors.

Uploaded by

alisaeed055148
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

orignal index.js

This document contains a Discord bot implementation using the discord.js library. It initializes the bot, sets up command handling, and fetches player statistics from a backend API. Additionally, it includes error handling for various events such as guild bans and API errors.

Uploaded by

alisaeed055148
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

const { Client, Intents, MessageEmbed } = require("discord.

js");
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MEMBERS, Intents.FLAGS.GUILD_BANS]
});
const fs = require("fs");
const path = require("path");
const fetch = require("node-fetch");
const config = JSON.parse(fs.readFileSync("./Config/config.json").toString());
const log = require("../structs/log.js");
const Users = require("../model/user.js");

client.once("ready", async () => {


log.bot("Bot is up and running!");

if (config.bEnableBackendStatus) {
if (!config.bBackendStatusChannelId ||
config.bBackendStatusChannelId.trim() === "") {
log.error("The channel ID has not been set in config.json for
bEnableBackendStatus.");
} else {
const channel =
client.channels.cache.get(config.bBackendStatusChannelId);
if (!channel) {
log.error(`Cannot find the channel with ID $
{config.bBackendStatusChannelId}`);
} else {
const embed = new MessageEmbed()
.setTitle("**Backend Online**")
.setDescription("🚀 **Reload Backend is now online!**")
.setColor("#4CAF50")

.setThumbnail("https://download944.mediafire.com/ot5medab9vwgxjpu9niNEXHl7v_RPoIoma
QoS2UF4TqsjilCUo-CUxH_LcaH5MzMm9UZuk27YyL54eOOGDoIzw1EEU-
Mjksdmw8JfRIA3P2rmxGNDdMiK2vveuWFhSXUsAmC_QA6eqQA5oG4J9g_Hi0WfuhqWeBgWMRbRWypvtA/
bhtpzucgz0gnizl/3z+png+%281%29_prev_ui.png")
.setFooter({
text: "🚀 **Reload Backend** is now live!",
iconURL:
"https://download944.mediafire.com/ot5medab9vwgxjpu9niNEXHl7v_RPoIomaQoS2UF4TqsjilC
Uo-CUxH_LcaH5MzMm9UZuk27YyL54eOOGDoIzw1EEU-
Mjksdmw8JfRIA3P2rmxGNDdMiK2vveuWFhSXUsAmC_QA6eqQA5oG4J9g_Hi0WfuhqWeBgWMRbRWypvtA/
bhtpzucgz0gnizl/3z+png+%281%29_prev_ui.png",
})
.setTimestamp()
.setFooter('Status updated on:');

channel.send({ embeds: [embed] }).catch(err => {


log.error(err);
});
}
}
}

let commands = client.application.commands;

// ✅ ‫ إضافة أمر‬vbuckskw
await commands.create({
name: "vbuckskw",
description: "Displays your current stats (V-Bucks, Kills, Wins)."
});

// ✅ ‫تحميل جميع الأوامر من المجلد‬


const loadCommands = (dir) => {
fs.readdirSync(dir).forEach(file => {
const filePath = path.join(dir, file);
if (fs.lstatSync(filePath).isDirectory()) {
loadCommands(filePath);
} else if (file.endsWith(".js")) {
const command = require(filePath);
commands.create(command.commandInfo);
}
});
};

loadCommands(path.join(__dirname, "commands"));
});

client.on("interactionCreate", async interaction => {


if (!interaction.isApplicationCommand()) return;

// ✅ ‫ التعامل مع أمر‬vbuckskw
if (interaction.commandName === "vbuckskw") {
await interaction.deferReply({ ephemeral: true });

const discordId = interaction.user.id;


const API_URL = `http://127.0.0.1:3551/player/${discordId}`;
const API_KEY = "1ba5acff-48c2-4014-81a3-13b2c1b100e9";

try {
const response = await fetch(API_URL, {
headers: { "x-api-key": API_KEY }
});

const data = await response.json();

if (!data.success) {
return interaction.editReply({ content: "❌ Player data not found!",
ephemeral: true });
}

const vbucks = data.data.vbucks || 0;


const kills = data.data.kills || 0;
const wins = data.data.wins || 0;
const totalVbucks = vbucks + (kills * config.Api.reasons.Kill) + (wins
* config.Api.reasons.Win);

const embed = new MessageEmbed()


.setTitle("Player Stats")
.setDescription(`⚔️
**V-Bucks:** ${vbucks}\n **Kills:** ${kills}\n🏆
**Wins:** ${wins}\n🔹 **Total V-Bucks:** ${totalVbucks}`)
.setTimestamp()
.setThumbnail('https://i.imgur.com/yLbihQa.png')
.setFooter({
text: "3z backend changer",
iconURL:
"https://download1076.mediafire.com/lx9li5d5v3ygZqwR3jI6jOpaV6nRSG041HMV0GPT-
YYeirjL6poGS3k5DJe_-9-Lol-3U8k3m-
Oe7OilLWAkYfIw2T5aa5y7AUnkfy22i6XY_gIM2eI0gnmkNi9N8LU2TnA00_HjtteY2zGbGftmgCIQCEq01
bQ_F2D2qdUnBeQ/e0yn9btih2a494y/3z+png.png"
})
.setColor("WHITE");

await interaction.editReply({ embeds: [embed], ephemeral: true });

} catch (error) {
console.error("❌ Error fetching player stats:", error);
return interaction.editReply({ content: "❌ An error occurred while
fetching data!", ephemeral: true });
}
}

// ✅ ‫تنفيذ الأوامر الأخرى‬


const executeCommand = (dir, commandName) => {
const commandPath = path.join(dir, commandName + ".js");
if (fs.existsSync(commandPath)) {
require(commandPath).execute(interaction);
return true;
}
const subdirectories = fs.readdirSync(dir).filter(subdir =>
fs.lstatSync(path.join(dir, subdir)).isDirectory());
for (const subdir of subdirectories) {
if (executeCommand(path.join(dir, subdir), commandName)) {
return true;
}
}
return false;
};

executeCommand(path.join(__dirname, "commands"), interaction.commandName);


});

// ✅ ‫بقية الأحداث ونظام البان‬

client.on("guildBanAdd", async (ban) => {


// ‫بقية الكود هنا‬...
});

client.on("guildBanRemove", async (ban) => {


// ‫بقية الكود هنا‬...
});

client.on("error", (err) => console.log("Discord API Error:", err));


process.on("unhandledRejection", (reason, p) => console.log("Unhandled promise
rejection:", reason, p));
process.on("uncaughtException", (err, origin) => console.log("Uncaught Exception:",
err, origin));
process.on("uncaughtExceptionMonitor", (err, origin) => console.log("Uncaught
Exception Monitor:", err, origin));

client.login(config.discord.bot_token);

You might also like