const { SlashCommandBuilder, Discord, codeBlock } = require('discord.js'); module.exports = { data: new SlashCommandBuilder() .setName('count_chars') .setDescription('Counts the number of characters in a string') .addStringOption(option => option.setName('string') .setDescription("String to count characters in") .setRequired(false) ) .addStringOption(option => option.setName('messageid') .setDescription("Message ID of message to count characters in") .setRequired(false) ), async execute(interaction, client) { var inputString; if (interaction.options.getString('string') !== null) { inputString = interaction.options.getString('string'); } else if (interaction.options.getString('messageid') !== null) { var messageId = interaction.options.getString('messageid'); const messagefromId = await client.channels.cache.get(interaction.channel.id).messages.fetch(messageId); inputString = messagefromId.content; } let inputStringPrint; if (inputString.length > 1000) { inputStringPrint = "too long to copy"; } else { inputStringPrint = inputString; } await interaction.reply("Input: `" + inputStringPrint + "`\n" + "input length: " + inputString.length + " characters long" + "\n Output: " + codeBlock("", countChars(inputString))); console.log("User " + interaction.user.tag + " ran /count_chars"); }, }; function countChars(string) { var outputString = ""; string = string.toLowerCase(); var letterCount = Array(65535).fill(0); // Creates an array with 26 values, all equaling 0. for (let i = 0; i < string.length; ++i) { let currentChar = string.charAt(i); let arrayIndex = currentChar.charCodeAt(0); if (string.charAt(i).search(/^[A-Z]+$/) === 0) { arrayIndex += 32; //This should make it cast any uppercase characters to lowercase } letterCount[arrayIndex]++; } for (let i = 0; i < letterCount.length; ++i) { let currentChar = String.fromCharCode(i).toUpperCase();; if (currentChar.charCodeAt(0) == 10 || currentChar.charCodeAt(0) == 13 || currentChar.charCodeAt(0) == 30 || currentChar.charCodeAt(0) == 115 || currentChar.charCodeAt(0) == 21 || currentChar.charCodeAt(0) == 118) { currentChar = "newline"; } if (currentChar.charCodeAt(0) == 32) { currentChar = "whitespace" } if (letterCount[i] > 0) { outputString += "Number of " + currentChar + "'s: " + letterCount[i] + "\n"; } } return outputString; } //console.log(countChars("test string"));