NoMoreAcronyms/commands/countChars.ts

52 lines
1.9 KiB
TypeScript

2023-04-04 16:16:24 +07:00
const { SlashCommandBuilder, Discord, codeBlock } = require('discord.js');
2023-04-04 16:12:56 +07:00
module.exports = {
data: new SlashCommandBuilder()
.setName('count_chars')
.setDescription('Counts the number of characters in a string')
2023-04-04 17:20:28 +07:00
.addStringOption(option =>
2023-04-04 16:12:56 +07:00
option.setName('string')
2023-04-04 17:20:28 +07:00
.setDescription("String to count characters in")
.setRequired(false)
)
.addStringOption(option =>
option.setName('messageid')
2023-04-04 17:15:56 +07:00
.setDescription("Message ID of message to count characters in")
.setRequired(false)
2023-04-04 17:20:28 +07:00
),
async execute(interaction, client) {
2023-04-04 17:15:56 +07:00
var inputString;
2023-04-04 17:20:28 +07:00
2023-04-04 17:15:56 +07:00
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;
}
2023-04-04 17:20:28 +07:00
2023-04-04 16:18:28 +07:00
await interaction.reply("Input: `" + inputString + "`\n" + "Output: " + codeBlock("", countChars(inputString)));
2023-04-04 17:20:28 +07:00
console.log("User " + interaction.user.tag + " ran /count_chars");
2023-04-04 16:12:56 +07:00
},
};
function countChars(string) {
var outputString = "";
string = string.toLowerCase();
2023-04-04 17:31:50 +07:00
var letterCount = Array(65535).fill(0); // Creates an array with 26 values, all equaling 0.
2023-04-04 16:12:56 +07:00
for (let i = 0; i < string.length; ++i) {
let currentChar = string.charAt(i);
2023-04-04 17:31:50 +07:00
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
2023-04-04 16:12:56 +07:00
}
2023-04-04 17:31:50 +07:00
letterCount[arrayIndex]++;
2023-04-04 16:12:56 +07:00
}
for (let i = 0; i < letterCount.length; ++i) {
if (letterCount[i] > 0) {
2023-04-04 17:31:50 +07:00
outputString += "Number of " + String.fromCharCode(i).toUpperCase() + "'s: " + letterCount[i] + "\n";
2023-04-04 16:12:56 +07:00
}
}
return outputString;
}
//console.log(countChars("test string"));