To add forceaddkos and forceremovekos commands to your Discord bot, you'll need to modify your existing code to:
-
Persistently store tracked users: Instead of hardcoding the TRACKED_USERS array, load it from a JSON file (tracked_users.json) when the bot starts and update this file when users are added or removed.
-
Handle Discord Commands: Listen for messages and process forceaddkos and forceremovekos commands to add or remove users from the tracked list.
-
Ensure Command Security: Restrict these commands to authorized users (e.g., bot administrators) to prevent unauthorized modifications.
Below is the updated code with these functionalities implemented:
const axios = require('axios');
const fs = require('fs');
const { Client, GatewayIntentBits, Permissions } = require('discord.js');
const PING_INTERVAL = 60 * 60 * 1000;
const PLACE_ID = '2202352383';
const TRACKED_USERS_FILE = 'tracked_users.json';
const MESSAGE_ID_FILE = 'message_id.json';
// Replace these with your actual Discord configurations
const DISCORD_TOKEN = 'YOUR_DISCORD_BOT_TOKEN';
const DISCORD_CHANNEL_ID = 'YOUR_DISCORD_CHANNEL_ID';
const COMMAND_PREFIX = '!';
const AUTHORIZED_USER_IDS = ['YOUR_DISCORD_USER_ID']; // Replace with IDs of users allowed to use admin commands
let TRACKED_USERS = [
'1mac1cam1',
'xKellus',
'Lucky_25713',
'Avenger_25713',
'XLucky_25713X',
'xNotLucky',
'santinoesmagico',
'kayaltaccountEz',
'bonk426',
'kay_shadow0101',
'Ghost_eLoex',
];
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
});
const userStatus = {};
let statusMessageId = null;
// Function to load tracked users from file
const loadTrackedUsers = () => {
try {
if (fs.existsSync(TRACKED_USERS_FILE)) {
const data = fs.readFileSync(TRACKED_USERS_FILE, 'utf8');
TRACKED_USERS = JSON.parse(data);
console.log(`Loaded ${TRACKED_USERS.length} tracked users from ${TRACKED_USERS_FILE}`);
} else {
// If file doesn't exist, initialize with default TRACKED_USERS and save
fs.writeFileSync(TRACKED_USERS_FILE, JSON.stringify(TRACKED_USERS, null, 4));
console.log(`Initialized ${TRACKED_USERS.length} tracked users and created ${TRACKED_USERS_FILE}`);
}
} catch (error) {
console.error('Error loading tracked users:', error);
}
};
// Function to save tracked users to file
const saveTrackedUsers = () => {
try {
fs.writeFileSync(TRACKED_USERS_FILE, JSON.stringify(TRACKED_USERS, null, 4));
console.log(`Saved ${TRACKED_USERS.length} tracked users to ${TRACKED_USERS_FILE}`);
} catch (error) {
console.error('Error saving tracked users:', error);
}
};
// Load tracked users on startup
loadTrackedUsers();
// Event listener for when the bot is ready
client.once('ready', () => {
console.log('Bot is ready!');
loadMessageId();
trackUsers();
});
// Function to load status message ID from file
const loadMessageId = () => {
try {
if (fs.existsSync(MESSAGE_ID_FILE)) {
const data = fs.readFileSync(MESSAGE_ID_FILE, 'utf8');
const json = JSON.parse(data);
statusMessageId = json.messageId;
console.log(`Loaded status message ID: ${statusMessageId}`);
} else {
console.log(`${MESSAGE_ID_FILE} does not exist. A new status message will be created.`);
}
} catch (error) {
console.error('Error loading message ID:', error);
}
};
// Function to save status message ID to file
const saveMessageId = (messageId) => {
try {
const data = JSON.stringify({ messageId }, null, 4);
fs.writeFileSync(MESSAGE_ID_FILE, data);
console.log(`Saved status message ID: ${messageId}`);
} catch (error) {
console.error('Error saving message ID:', error);
}
};
// Command handling
client.on('messageCreate', async (message) => {
// Ignore messages from bots or without the correct prefix
if (message.author.bot || !message.content.startsWith(COMMAND_PREFIX)) return;
const args = message.content.slice(COMMAND_PREFIX.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
// Check if the user is authorized to use admin commands
const isAuthorized = AUTHORIZED_USER_IDS.includes(message.author.id);
if (!isAuthorized) {
if (command === 'forceaddkos' || command === 'forceremovekos') {
return message.reply("You don't have permission to use this command.");
}
}
switch (command) {
case 'forceaddkos':
await handleForceAddKos(message, args);
break;
case 'forceremovekos':
await handleForceRemoveKos(message, args);
break;
case 'listkos':
await handleListKos(message);
break;
default:
// You can handle other commands here
break;
}
});
// Handler for forceaddkos command
const handleForceAddKos = async (message, args) => {
if (args.length !== 1) {
return message.reply('Usage: !forceaddkos <username>');
}
const username = args[0];
if (TRACKED_USERS.includes(username)) {
return message.reply(`User \`${username}\` is already being tracked.`);
}
// Optionally, verify if the username exists on Roblox
const userId = await getUserId(username);
if (!userId) {
return message.reply(`User \`${username}\` not found on Roblox.`);
}
TRACKED_USERS.push(username);
saveTrackedUsers();
message.reply(`User \`${username}\` has been added to the tracked list.`);
console.log(`Added user \`${username}\` to TRACKED_USERS via forceaddkos command.`);
};
// Handler for forceremovekos command
const handleForceRemoveKos = async (message, args) => {
if (args.length !== 1) {
return message.reply('Usage: !forceremovekos <username>');
}
const username = args[0];
const index = TRACKED_USERS.indexOf(username);
if (index === -1) {
return message.reply(`User \`${username}\` is not in the tracked list.`);
}
TRACKED_USERS.splice(index, 1);
saveTrackedUsers();
message.reply(`User \`${username}\` has been removed from the tracked list.`);
console.log(`Removed user \`${username}\` from TRACKED_USERS via forceremovekos command.`);
};
// Handler for listing all tracked KOS users
const handleListKos = async (message) => {
if (TRACKED_USERS.length === 0) {
return message.reply('No users are currently being tracked.');
}
const userList = TRACKED_USERS.map((user, index) => `${index + 1}. ${user}`).join('\n');
const embed = {
color: 0x0099ff,
title: 'Tracked KOS Users',
description: userList,
};
message.reply({ embeds: [embed] });
};
// Existing functions...
const trackUsers = async () => {
try {
const allServers = await fetchAllPublicServers(PLACE_ID);
const allPlayerTokens = allServers.flatMap(server =>
server.playerTokens.map(token => ({ token, serverId: server.id }))
);
let statusChanged = false;
let messageContent = "```diff\n";
let usersToPing = [];
for (let username of TRACKED_USERS) {
const userId = await getUserId(username);
if (!userId) {
console.warn(`User ID not found for username: ${username}`);
continue;
}
const isOnline = await checkOnlineStatus(userId);
let isInPublicServer = false;
let serverId = null;
if (isOnline) {
const thumbnailUrl = await getThumb(userId);
if (thumbnailUrl) {
const thumbnailIdMatch = thumbnailUrl.match(/([A-F0-9]{32})/i);
if (thumbnailIdMatch) {
const thumbnailId = thumbnailIdMatch[0].toUpperCase();
const result = await findUserInPublicServers(allPlayerTokens, thumbnailId);
if (result.found) {
isInPublicServer = true;
serverId = result.serverId;
}
}
}
}
const currentTime = Date.now();
if (
!userStatus[username] ||
userStatus[username].isOnline !== isOnline ||
userStatus[username].isInPublicServer !== isInPublicServer
) {
statusChanged = true;
if (isOnline && isInPublicServer) {
if (!userStatus[username] || !userStatus[username].lastPingTime ||
(currentTime - userStatus[username].lastPingTime >= PING_INTERVAL)) {
usersToPing.push(username);
userStatus[username] = {
...userStatus[username],
lastPingTime: currentTime
};
}
}
}
userStatus[username] = {
...userStatus[username],
isOnline,
isInPublicServer,
serverId
};
if (isOnline && isInPublicServer) {
messageContent += `+ ${username} (Online) - Server: roblox.com/games/${PLACE_ID}/SPTS-Classic#jobid=${serverId}\n\n`;
} else {
messageContent += `- ${username} (Offline)\n\n`;
}
}
messageContent += "```";
if (statusChanged) {
const channel = await client.channels.fetch(DISCORD_CHANNEL_ID);
if (!channel) {
console.error(`Channel with ID ${DISCORD_CHANNEL_ID} not found.`);
return;
}
if (statusMessageId) {
try {
const oldMessage = await channel.messages.fetch(statusMessageId);
await oldMessage.edit(messageContent);
} catch (error) {
console.error('Failed to edit existing message:', error);
statusMessageId = null;
}
}
if (!statusMessageId) {
const newMessage = await channel.send(messageContent);
statusMessageId = newMessage.id;
saveMessageId(statusMessageId);
}
// Ping for users who came online and meet the rate limit criteria
if (usersToPing.length > 0) {
const channel2 = await client.channels.fetch('1295508784592064583');
if (channel2) {
const pingMessage = `@everyone - the following KOS users are now online: ${usersToPing.join(', ')}`;
await channel2.send(pingMessage);
} else {
console.error('Ping channel not found.');
}
}
}
} catch (error) {
console.error('Error in trackUsers:', error);
} finally {
// Schedule the next tracking run
setTimeout(trackUsers, 60 * 1000); // Run every minute
}
};
// Existing helper functions...
const getUserId = async (username) => {
try {
const response = await axios.post(
'https://users.roblox.com/v1/usernames/users',
{
usernames: [username],
excludeBannedUsers: false,
},
{
headers: {
'Content-Type': 'application/json',
},
}
);
if (response.data && response.data.data && response.data.data.length > 0) {
return response.data.data[0].id.toString();
} else {
console.warn(`No data returned for username: ${username}`);
return null;
}
} catch (error) {
console.error(`Error fetching user ID for ${username}:`, error);
return null;
}
};
const getThumb = async (userId) => {
try {
const response = await axios.get(
`https://thumbnails.roblox.com/v1/users/avatar-headshot?userIds=${userId}&size=150x150&format=Png&isCircular=false`
);
if (response.data && response.data.data && response.data.data[0].imageUrl) {
return response.data.data[0].imageUrl;
} else {
console.warn(`No thumbnail URL found for user ID: ${userId}`);
return null;
}
} catch (error) {
console.error(`Error fetching thumbnail for user ID ${userId}:`, error);
return null;
}
};
const checkOnlineStatus = async (userId) => {
try {
const response = await axios.post(
'https://presence.roblox.com/v1/presence/users',
{
userIds: [parseInt(userId)],
},
{
headers: {
'Content-Type': 'application/json',
},
}
);
const userPresence = response.data.userPresences[0];
return userPresence && userPresence.userPresenceType === 2;
} catch (error) {
console.error(`Error checking online status for user ID ${userId}:`, error);
return false;
}
};
const fetchAllPublicServers = async (placeId) => {
let cursor = null;
let allServers = [];
try {
while (true) {
const response = await getPublicServers(placeId, cursor);
if (!response || !response.data) {
break;
}
allServers.push(...response.data);
if (!response.nextPageCursor) {
break;
}
cursor = response.nextPageCursor;
}
} catch (error) {
console.error('Error fetching public servers:', error);
}
return allServers;
};
const getPublicServers = async (placeId, cursor) => {
try {
let url = `https://games.roblox.com/v1/games/${placeId}/servers/Public?limit=100`;
if (cursor) {
url += `&cursor=${cursor}`;
}
const response = await axios.get(url);
return response.data;
} catch (error) {
console.error(`Error fetching public servers for place ID ${placeId}:`, error);
return null;
}
};
const findUserInPublicServers = async (allPlayerTokens, thumbnailId) => {
try {
const chunkSize = 100;
for (let i = 0; i < allPlayerTokens.length; i += chunkSize) {
const chunk = allPlayerTokens.slice(i, i + chunkSize);
const body = chunk.map((item) => ({
requestId: `${item.token}:${item.serverId}`,
type: 'AvatarHeadShot',
targetId: 0,
token: item.token,
format: 'png',
size: '150x150',
}));
const response = await axios.post('https://thumbnails.roblox.com/v1/batch', body, {
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
});
if (response.data && response.data.data) {
for (let thumbnail of response.data.data) {
if (thumbnail && thumbnail.imageUrl) {
const imageIdMatch = thumbnail.imageUrl.match(/([A-F0-9]{32})/i);
if (
imageIdMatch &&
imageIdMatch[0].toUpperCase() === thumbnailId.toUpperCase()
) {
const [token, serverId] = thumbnail.requestId.split(':');
return { found: true, serverId };
}
}
}
}
}
} catch (error) {
console.error('Error in findUserInPublicServers:', error);
}
return { found: false };
};
client.login(DISCORD_TOKEN);
Explanation of Changes
-
Persistent Storage of Tracked Users
- File Handling: Introduced
tracked_users.json to persist the list of tracked users.
- Loading Tracked Users: Added
loadTrackedUsers function to load the tracked users from the JSON file during startup. If the file doesn't exist, it initializes the file with the default TRACKED_USERS.
- Saving Tracked Users: Added
saveTrackedUsers function to write the current state of TRACKED_USERS to the JSON file whenever modifications occur.
-
Discord Command Handling
- Command Prefix and Authorization: Defined a command prefix (
!) and an array of authorized user IDs (AUTHORIZED_USER_IDS) who can use the administrative commands.
- Listening to Messages: Added an event listener for
messageCreate to handle incoming messages and parse commands.
- Commands Implemented:
!forceaddkos <username>: Adds a user to the tracked list after verifying their existence on Roblox.
!forceremovekos <username>: Removes a user from the tracked list.
!listkos: Lists all currently tracked users.
-
Security Measures
- Authorization Check: Only users whose IDs are in
AUTHORIZED_USER_IDS can execute forceaddkos and forceremovekos commands. Unauthorized users receive a permission denial message.
-
Additional Enhancements
- List Command: Included a
!listkos command to allow administrators to view all currently tracked users.
- Error Handling and Logging: Enhanced logging for better traceability when users are added or removed and when saving/loading files.
- User Existence Verification: When adding a user, the bot verifies if the username exists on Roblox before adding it to the tracked list.
Setting Up the Bot
-
Install Dependencies: Ensure you have the required packages installed. Run the following command in your project directory:
npm install discord.js axios
-
Configure the Bot:
- Replace
'YOUR_DISCORD_BOT_TOKEN' with your actual Discord bot token.
- Replace
'YOUR_DISCORD_CHANNEL_ID' with the ID of the Discord channel where the status messages should be posted.
- Replace
'YOUR_DISCORD_USER_ID' in AUTHORIZED_USER_IDS with the Discord user IDs that should have permission to use the administrative commands.
-
Run the Bot:
node your_bot_file.js
Replace your_bot_file.js with the name of your JavaScript file containing the bot code.
Usage
Notes
-
Permissions: Ensure that the bot has the necessary permissions to read and send messages in the specified channels.
-
Error Handling: The bot includes basic error handling, but you might want to enhance it further based on your use case.
-
Scalability: For larger projects or more complex command handling, consider implementing a command handler or using a framework like discord.js-commando or discord.js builders.
This implementation ensures that tracked users are managed dynamically through Discord commands and that the list persists across bot restarts by leveraging a JSON file for storage.