if the command used does not contain a valid hex code - discord.js

if (command === "hex")
{ let hex = args[0]
if(!hex) return message.reply("Please specify a hex code!")
function hexToRgb(hex) {
if (hex.charAt(0) === '#') hex = hex.substring(1)
if(!hexToRgb(hex)) return message.reply("Not a valid hex.")
var bigint = parseInt(hex, 16);
var r = (bigint >> 16) & 255;
var g = (bigint >> 8) & 255;
var b = bigint & 255;
return r + "," + g + "," + b;
}
let embed = new Discord.MessageEmbed()
.setTitle("Hex Code")
.setColor(hex)
.addFields(
{
name: `RGB`,
value: hexToRgb(hex) + ``
}
)
message.channel.send({embeds: [embed]})
}
Here is my above code for the hex command. I would like the bot to send a message that it's unable to convert hex to color if the user is using an invalid hex code (e.g. #GGGGGG) or a non-hex code (e.g. "Hello"). How could I achieve that?

You can use regex. This simple function will return whether or not it is a valid hex code
String.prototype.isHex = function() {
return ( this.match(/#?[a-f0-9]+/i)?.[0] || false )
}
And run it like this
'#ffffff'.isHex() //'#ffffff'
'Hello'.isHex() //false
'#gggggg'.isHex() //false

You can use a RegExp (#[A-Za-z0-9_]{6}) to validate the string as a hexadecimal value preceded by a #
function isHex(str) {
return !!str.match(/#[A-Za-z0-9_]{6}/).length;
}
if (!isHex('some value')) return message.reply("Not a valid hex.")

Related

How to write Conditional regex?

I want to use Yup for validation. in a part of validation I have
const validationSchema = Yup.object({password: Yup.string().matches(passwordRegex, "passRegex")})
passWordRegex is a varibale that contains a regex :
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$!%*?&])[A-Za-z\d#$!%*?&]{4,32}$/;
I have some booleans that determine that if for example small letter or big letter or speciall character is needed in password or not:
smallLetter = false
capitalLetter = true
specialChar = true
now my regex ( passwordRegex variable) is not conditional . how can I write a regex (passwordRegex variable) conditional base on my Boolean variables
You could build the regex string you want and then create a proper RegExp object:
var input = "aB#3";
var smallLetter = false;
var capitalLetter = true;
var specialChar = true;
var number = true;
var regex = "";
if (smallLetter) regex += "(?=.*[a-z])";
if (capitalLetter) regex += "(?=.*[A-Z])";
if (specialChar) regex += "(?=.*[#$!%*?&])";
if (number) regex += "(?=.*[0-9])";
regex = "^" + regex + "[A-Za-z0-9#$!%*?&]{4,32}$";
var re = new RegExp(regex);
if (re.test(input)) {
console.log(input + " => valid");
}

How to read abc.txt.gz file in react js?

hi i am having problem to read a .gz file compressed by php code:
i am using following function in php for compressing in .gz in php i am able to uncompress,
$compressed = gzcompress('Compress me', 9);
but I dont know if there is any way to read .gz file in react
js*. I am new to this. Thanks in advance.
From this article:
const fs = require('fs');
const zlib = require('zlib');
const fileContents = fs.createReadStream('./abc.txt.gz');
const writeStream = fs.createWriteStream('./abc.txt');
const unzip = zlib.createGunzip();
fileContents.pipe(unzip).pipe(writeStream);
You have to install the zlib module.
This code is assuming that the file to be executed is located in the same directory as abc.txt.gz. It creates a file called abc.txt which is the unzipped version.
use zlib for compress and decompress buffer,
fetch your compressed string by your php and call my unzipMe function
base of this function on base64 string, if you fetch except base64 then change unzipMe.
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
var zlib = require("zlib");
function App() {
const [decodeStr, setDecodeStr] = React.useState("");
var utf8ArrayToStr = (function() {
var charCache = new Array(128); // Preallocate the cache for the common single byte chars
var charFromCodePt = String.fromCodePoint || String.fromCharCode;
var result = [];
return function(array) {
var codePt, byte1;
var buffLen = array.length;
result.length = 0;
for (var i = 0; i < buffLen; ) {
byte1 = array[i++];
if (byte1 <= 0x7f) {
codePt = byte1;
} else if (byte1 <= 0xdf) {
codePt = ((byte1 & 0x1f) << 6) | (array[i++] & 0x3f);
} else if (byte1 <= 0xef) {
codePt =
((byte1 & 0x0f) << 12) |
((array[i++] & 0x3f) << 6) |
(array[i++] & 0x3f);
} else if (String.fromCodePoint) {
codePt =
((byte1 & 0x07) << 18) |
((array[i++] & 0x3f) << 12) |
((array[i++] & 0x3f) << 6) |
(array[i++] & 0x3f);
} else {
codePt = 63; // Cannot convert four byte code points, so use "?" instead
i += 3;
}
result.push(
charCache[codePt] || (charCache[codePt] = charFromCodePt(codePt))
);
}
return result.join("");
};
})();
const unzipMe = base64gz => {
// if your data not a base64 then comment this line
let compressData = atob(base64gz);
compressData = compressData.split("").map(function(e) {
return e.charCodeAt(0);
});
let binData = new Uint8Array(compressData);
zlib.gunzip(binData, function(err, dezipped) {
const str = utf8ArrayToStr(dezipped);
setDecodeStr(str);
});
};
const gzStr = "H4sIAAAAAAAA//NIzcnJV3BKTErM1gEAVJXqUQwAAAA=";
unzipMe(gzStr);
return (
<div className="App">
<h1>Coded string : {gzStr}</h1>
<hr />
<h2>Decoded string : {decodeStr}</h2>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
I used this site for testing compress string : Compress Str to gz
Answer output: HERE

Convert objectGuid to UUID string using Javascript

I have been looking for a way to convert the ObjectGuid out of Active Directory is a special type that gets converted to a string, which is odd looking, using libraries such as ldapjs and or adding it as a claim using ping federate. An example of this is the following:
const ldapjs = require("ldapjs");
let _client = ldapjs.createClient({
"url": this._ldap_uri
});
_client.search(this._search_dn, opts, (error, res) => {
res.on("searchEntry", (entry) => {
console.log(entry.object.objectGUID)
}
Here is an example of the output that comes out of ldapjs. The same comes out of a ping federate when you add it as a claim.
H�Y��fB�_-_���
However, this is equivalent to a valid UUID.
b9****48-6***-42**-a**f-2d5f*****40b
What I am trying to do is convert this strange value to a the correct UUID. I have scoured and tested a few different postings and websites but I have not found a valid solution.
Here are a few I researched:
Read objectGUID from active directory
Javascript convert GUID in string format into Base64
http://www.tdi-users.org/foswiki/Integrator/UsingGUIDs
If anyone has a solution to this it would be appreciated.
experiment with this code (read GUID) :
String.prototype.padLeft = function( len, str ) {
//return Array( len - String(this).length + 1 ).join(str) + this;
var s = this;
str = str || '0';
if ( str.length > 0 ) {
while ( s.length < len ) {
s = ( str + s );
};
}
return s;
}
var destAD = GetObject("LDAP://dc.yourdomain.pl/cn=Administrator,cn=Users,dc=yourdomain,dc=pl");
var guidValueArr = destAD.Get("objectguid").toArray();
var guid = "", i;
for ( i = 0; i < guidValueArr.length; i ++ ) {
guid += guidValueArr[i].toString(16).padLeft(2,"0");
}
var guidFormated = guid.replace(/(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})(.{4})(.{12})/, "$4$3$2$1-$6$5-$8$7-$9-$10");
alert( guidFormated );
Universally unique identifier

Make a command that maps arguments in a message after certain words

I want to make it so that it would grab out certain information after certain words, and stop at certain words, for example
ss!submit | WIYISD: _____ | SHIWW: _____ | WDYWTA: _____ | SPN: _____
Collect arguements after the WIYISD:, SHIWW:, WDYWTA:, and SPN: and stop at the |'s after collecting each arguement.
I just don't know where to start.
I looked at what other people did, and I tried to pull it off myself but can't figure out how.
Edit: I'd like it based off of user input, and posts it in a channel, kind of similar to the bug-bot in discord testers.
Start by splitting at the vertical bars to get each portion of the string (String.split()). Then, iterate through the substrings ("Loops and iteration") and check the start of each (String.startsWith()), dealing with the resulting arguments however you want.
const str = 'ss!submit | WIYISD: hopefully | SHIWW: this code | WDYWTA: will | SPN: help you!';
const split = str.split(' | ').slice(1); // Also removing the command portion.
const args = {};
for (let i = 0; i < split.length; i++) {
const arg = split[i];
if (arg.startsWith('WIYISD: ')) args.WIYISD = arg.replace('WIYISD: ', '');
else if (arg.startsWith('SHIWW: ')) args.SHIWW = arg.replace('SHIWW: ', '');
else if (arg.startsWith('WDYWTA: ')) args.WDYWTA = arg.replace('WDYWTA: ', '');
else if (arg.startsWith('SPN: ')) args.SPN = arg.replace('SPN: ', '');
else {
console.error('Check your syntax.'); // Send an error message instead...
break; // ...and return (illegal in this context).
}
}
console.log(args); // The result in this example is an object, not an array.
Incorporating this into your message event...
// const bot = new Discord.Client();
const prefix = 'ss!';
bot.on('message', message => {
// Stop if the author is a bot or the message doesn't start with the prefix.
if (message.author.bot || !message.content.startsWith(prefix)) return;
// This is a very crude setup. Consider a command handler to keep the code organized.
if (message.content.startsWith(`${prefix}submit `)) {
const split = message.content.split(' | ').slice(1);
const args = {};
for (let i = 0; i < split.length; i++) {
const arg = split[i];
if (arg.startsWith('WIYISD: ')) args.WIYISD = arg.replace('WIYISD: ', '');
else if (arg.startsWith('SHIWW: ')) args.SHIWW = arg.replace('SHIWW: ', '');
else if (arg.startsWith('WDYWTA: ')) args.WDYWTA = arg.replace('WDYWTA: ', '');
else if (arg.startsWith('SPN: ')) args.SPN = arg.replace('SPN: ', '');
else {
return message.channel.send(':x: Invalid syntax.')
.catch(console.error); // Make sure the catch rejected promises.
}
}
// Use 'args' as you wish.
}
});

Read content from PDF using React Native

I am trying to read text from PDF file using expo and React Native. I used the below code to read but it's not working. On click of a button i use the DocumentPicker to select the PDF file and then i wanted to extract the text from the document alone. I am trying to create a app to read out the text for me.
But i am not able to do that. Thanks in advance.
loadText = async()=>{
//Alert.alert("load text triggered");
let result = await DocumentPicker.getDocumentAsync({});
if(result.type == 'success') {
// alert(result.uri);
let contents = await FileSystem.readAsStringAsync(result.uri);
//console.warn('content', contents);
if(contents.length > 0){
//let res = base64.fromByteArray(this.stringToUint8Array(contents));
//alert("t" + res);
this.setState({textToBeRead : this.atob(contents)});
alert("test" + this.state.textToBeRead);
}
}
};
atob = (input) => {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
let str = input.replace(/=+$/, '');
let output = '';
if (str.length % 4 == 1) {
throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");
}
for (let bc = 0, bs = 0, buffer, i = 0;
buffer = str.charAt(i++);
~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
) {
buffer = chars.indexOf(buffer);
}
return output;
}

Resources