perk wok

make a username checker and so that it sends untaken usersnames ina chaneel

Kodari AI
KodariOct 27 at 6:17 am 1
UsernameChecker
A Minecraft plugin that checks username availability in real-time. When a player types a command, the plugin validates if the username is taken or available, then sends the result to a designated Discord channel via webhook. Features include command-based checking, automatic response formatting, configurable channel webhook URL, rate limiting to prevent spam, and logging of all checks. The plugin integrates seamlessly with existing server infrastructure, providing instant feedback on username availability without requiring external database lookups. It supports multiple server instances and handles special characters in usernames correctly. The system includes a cooldown system to prevent abuse and an admin command to configure the webhook endpoint dynamically.

I’ll create a Discord bot with /check for one Minecraft username and /scan to post available names in the channel where it’s run.

Created a Discord bot that checks Minecraft usernames against Mojang:

  • /check username checks one name.

  • /scan usernames checks up to 20 comma-, space-, or line-separated names and posts available ones in the channel where you ran it.

Set DISCORD_TOKEN and DISCORD_CLIENT_ID in the bot’s environment, then invite it with the bot and applications.commands scopes. Availability is reported as “appears to be available” because Mojang’s lookup only confirms whether a profile currently exists.

Kodari can make mistakes. Review important code before using.
Files
src
package.json
username checker
Code
3 164
src/index.js
import {
  Client,
  Events,
  GatewayIntentBits,
  REST,
  Routes,
  SlashCommandBuilder
} from 'discord.js';

const token = process.env.DISCORD_TOKEN;
const clientId = process.env.DISCORD_CLIENT_ID;

if (!token || !clientId) {
  throw new Error('Set the DISCORD_TOKEN and DISCORD_CLIENT_ID environment variables.');
}

const commands = [
  new SlashCommandBuilder()
    .setName('check')
    .setDescription('Check whether a Minecraft username appears to be available.')
    .addStringOption(option =>
      option
        .setName('username')
        .setDescription('Minecraft username to check')
        .setRequired(true)
        .setMinLength(3)
        .setMaxLength(16)
    ),
  new SlashCommandBuilder()
    .setName('scan')
    .setDescription('Post available Minecraft usernames in this channel.')
    .addStringOption(option =>
      option
        .setName('usernames')
        .setDescription('Up to 20 usernames separated by spaces, commas, or new lines')
        .setRequired(true)
        .setMaxLength(1000)
    )
];

const rest = new REST({ version: '10' }).setToken(token);
const client = new Client({ intents: [GatewayIntentBits.Guilds] });

function isValidUsername(username) {
  return /^[a-zA-Z0-9_]{3,16}$/.test(username);
}

async function checkUsername(username) {
  const response = await fetch(
    `https://api.mojang.com/users/profiles/minecraft/${encodeURIComponent(username)}`,
    { signal: AbortSignal.timeout(10000) }
  );

  if (response.status === 200) return false;
  if (response.status === 204) return true;
  if (response.status === 429) {
    throw new Error('Mojang is rate-limiting checks. Please try again later.');
  }
  throw new Error(`Mojang username lookup failed (HTTP ${response.status}).`);
}

function delay(milliseconds) {
  return new Promise(resolve => setTimeout(resolve, milliseconds));
}

client.once(Events.ClientReady, readyClient => {
  console.log(`Logged in as ${readyClient.user.tag}`);
});

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

  if (interaction.commandName === 'check') {
    const username = interaction.options.getString('username', true).trim();
    if (!isValidUsername(username)) {
      await interaction.reply({
        content: 'Minecraft usernames must be 3–16 characters and contain only letters, numbers, or underscores.',
        ephemeral: true
      });
      return;
    }

    await interaction.deferReply();
    try {
      const available = await checkUsername(username);
      await interaction.editReply(
        available
          ? `**${username}** appears to be available.`
          : `**${username}** is already taken.`
      );
    } catch (error) {
      await interaction.editReply(error.message || 'The username check failed. Please try again later.');
    }
    return;
  }

  if (interaction.commandName === 'scan') {
    const usernames = interaction.options
      .getString('usernames', true)
      .split(/[\s,]+/)
      .filter(Boolean);
    const uniqueUsernames = [...new Map(usernames.map(name => [name.toLowerCase(), name])).values()];

    if (uniqueUsernames.length === 0 || uniqueUsernames.length > 20) {
      await interaction.reply({
        content: 'Provide between 1 and 20 usernames, separated by spaces, commas, or new lines.',
        ephemeral: true
      });
      return;
    }

    const invalidUsernames = uniqueUsernames.filter(username => !isValidUsername(username));
    if (invalidUsernames.length > 0) {
      await interaction.reply({
        content: `Invalid Minecraft username${invalidUsernames.length === 1 ? '' : 's'}: ${invalidUsernames.join(', ')}. Names must be 3–16 letters, numbers, or underscores.`,
        ephemeral: true
      });
      return;
    }

    await interaction.deferReply();
    try {
      const availableUsernames = [];
      for (let index = 0; index < uniqueUsernames.length; index++) {
        const username = uniqueUsernames[index];
        if (await checkUsername(username)) availableUsernames.push(username);
        if (index < uniqueUsernames.length - 1) await delay(1100);
      }

      await interaction.editReply(
        availableUsernames.length > 0
          ? `Available usernames:\n${availableUsernames.map(name => `• ${name}`).join('\n')}`
          : 'None of those usernames appear to be available.'
      );
    } catch (error) {
      await interaction.editReply(error.message || 'The username scan failed. Please try again later.');
    }
  }
});

try {
  await rest.put(Routes.applicationCommands(clientId), {
    body: commands.map(command => command.toJSON())
  });
  await client.login(token);
} catch (error) {
  console.error('Could not start the username checker:', error);
  process.exitCode = 1;
}