Can't React with Unicode Emojis discord.js - javascript

I'm throwing together a poll command for my discord bot, and need emojis as options. However, when I try to react with default emojis I got from the message, it fails. I won't get into too many specifics, but here is almost all the relevant code:
// This just takes the <prefix> poll off then splits it by newlines
const args = message.content.slice(message.content.indexOf("poll")+"poll ".length).split("\n");
const fields = [];
const reactions = [];
// First arg is title
for(let i = 1; i < args.length; i++){
const splits = args[i].split("-"); // Split each arg by -
fields.push(splits[0] + ": " + splits[1]); // Field title
fields.push(splits[2]); // Field description
reactions.push(splits[0]); // This should be an emoji
}
// This function takes in message, embed title, [field title, field description, ...]
const msg = await embedGenerator.sendNormalEmbed(message, args[0], "", fields);
// React
for(let i = 0; i < reactions.length; i++){
await msg.react(reactions[i])
}
This works perfectly fine with custom emojis, however, it fails with default Unicode emojis:
The second poll gives me this error:
After some looking the put request makes a call that should react, however, the ID of the emoji is the Unicode code for šŸš. Is there any way to get a normal emoji instead of this Unicode code from the text, and if not is there a way to force discord to react with the Unicode code?

I was bit confused in your question, So maybe I am not correct. if it is, so please comment and ping me. You can also ask me for other help.
Reason:-
So discord does not use id for reacting of default emojis which are already in discord. If you want to implement ":helicopter:" as reaction, You need to replace it with this "šŸš".
Solution:-
You can still solve it by telling user to insert "\" before ":helicopter:" so that emoji becomes unicode or there's an npm package for that, this.
Also you can refer to this site to copy and paste them or this for help on emojis.

Related

Discord.js not capturing name after !register command

if (message.content === '!registrar') {
// pegue o nome do usuĆ”rio digitado apĆ³s o comando "!registrar"
var newName = message.content.split(' ')[1];
console.log(newName);
}
The idea is to capture what the user types after the !register and store it in the newName variable and display it in the console for testing, but it is not storing it and it also does not print any results in the console, nor does it print the message "undefined", it seems to me that the split is not working, however when I put only message.content without the split also it does not store what was typed by the user.
I tried to store in the variable only what the user typed without using split and it still didn't store it, I also tried to just show that the command is working after trying to store the information in the variable but it also doesn't go to the next line, it doesn't display no errors in the console, it just doesn't display what the user typed after the "!register"
In your if condition you check if the message equals '!registrar'. It won't work with a command like '!registrar Name'.
You need to check if the entered String starts with the given command prefix.
So you have to change it like that:
const registerCmd = '!registrar';
// check if message starts with register command
if(message.content.startsWith(registerCmd)) {
// get name from message
let args = message.content.slice(registerCmd.length).trim().split(/ +/g);
let newName = args.shift().toLowerCase();
// print name
console.log(newName);
}
For more information check the docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith?retiredLocale=en

Restrictring user To Enter some Prohibited words in the Address input field, if he enters we have to throw an Error, here i am using react.JS

I have tried this approach to solve this problem,
in this approach, I can validate with the strings present in the Constant object,
if the user entered text will consists those words, the function will return true, with which I can update the error state in react
const constants = {
ADDRESS_PROHIBITED_WORDS:'POBOX|POSTBOX|POSTBUS|P.O.B.O.X|PO BOX|POST BOX'
}
//here we are assuming that user entered below text
const userInput = 'pobox 27 gujarat inida'
const checkForProhibitedWords = userInput => {
const addProhibitedWords = constants.ADDRESS_PROHIBITED_WORDS.split('|')
const prohibitedWordsCheck = userInput.split(' ').some(eachWord => !addProhibitedWords.every(prohibWord => eachWord.toLowerCase() !== prohibWord.toLowerCase()))
console.log('---->> checking',prohibitedWordsCheck );
if (prohibitedWordsCheck) {
console.log('Eror triggered' );
}else{
console.log('Eror removed' );
}
return prohibitedWordsCheck
}
checkForProhibitedWords(userInput);
But the actual problem is
I want to validate with space words also like PO BOX, POST BOX, POST BUS,
but while using split(' ') method on the userInput, it's extracting that word as a seperate one(i.e, for example POBOX it will become two strings as PO and BOX)..
note :
you may tell that, simply add those also in the Constants object as
const constants = {
ADDRESS_PROHIBITED_WORDS:'POBOX|POSTBOX|POSTBUS|P.O.B.O.X|PO BOX|POST BOX|**PO**|**BOX**'
}
but here according to my requirement, I can't use those strings(it's client requirement)
here I can only able to deal with user Input, not the Strings given by client,
did anyone have any idea ??
So when user enters POST BOX or similar words with space, I wanted them to be extracted as same (not only POST BOX, I have a ~100 similar words in my requirement),
What if after you split it, merge it without spaces?
userInput.split(' ').join('').... // logic goes

How to get my program to read an input escape sequence

I am making a discord bot and one of the commands allows the user to send and embed to any channel with whatever text they want, but I want them to be able to start a new line in the body of the embed too. Simply having them type "\n" in their message in the command does, not work, the bot will output that \n in the embed instead of making a new line. Is there an easy way to do this?
Embed:
const sayEmbed = new Discord.MessageEmbed()
.setColor('#4d4d4d')
.setTitle(header.join(' '))
.setDescription(args.join(' '))
The description field is where this is occurring when there is a "\n" in the args array it will not make a new line it will simply send.
You don't actually need to use \n, you can just create a new line when sending the message, and discord.js will do all the parsing work for you. I tested this out with my bot:
So I made a kind of simple DIY sort of thing. (LOL, actually I made this as I saw the question, took like 5 mins.)
It allows you to disect a message using the operator | (The one below BackSpace).
I tried using this in an eval command, so I'm sure it works.
The codes are:
// Creating array variables so it doesn't return undefined when we try to `.concat()` it.
let sentences = [];
let temp = [];
// Loops every args
for(l=0;l<args.length;l++) {
// Adding the args as an array to the `temp` variable.
temp = temp.concat(argss[l])
// If we meet `|` which is a sentence separator.
if (args[l] === "|") {
// Join the `temp` array, making it a sentence while removing the `|` operator.
sentences = sentences.concat(temp.join(' ').slice(0, -2));
// Resetting `temp` to reset the saved sentence and start a new one.
temp = [];
}
}
Using .join(' ') will not work since it returns a string from an array, and therefore joining \n cannot be used.
The above method may be more efficient. They use a command such as:
// Say prefix is `.` and the command is `embed`
.embed <header> | <content> | <title1> | <sentence1> | <title2> | <sentence2> |
and you will get sentences[0], sentences[1], sentences[2], sentences[3], sentences[4], sentences[5] respectively. You can then add this to your embed.
This will also allow multi string input, instead of a single args. Don't forget the | at the end since without it, it will ignore the whole last sentence.
const sayEmbed = new Discord.MessageEmbed()
.setColor('#4d4d4d')
.setTitle(sentences[0]) // <header>
.setDescription(sentences[1]) // <content>
.addField(sentences[2], sentences[3]) // <title1> <sentence1>
.addField(sentences[4], sentences[5]) // <title2> <sentence2>
// The more you add, the more it'll allow, you'll have to set it yourself.
TL;DR: A simpler answer:
sentences = args.join(" ").split(" | ");
Sorry, I tend to do things the hard way a lot.

Pick out words in a string that are in array

I have spent hours, close to 8 hours none stop on this, I am trying to use jQuery/JS to create two arrays, one which is dynamic as it is loading a chat script and will be split by whitespace in to an array, for example:
String: Hello my name is Peter
Converted to (message) array: ['hello','my','name','is','peter'];
I have a set array to look out for specific words, in this example let us use:
(find array) ['hello','peter'] however, this array is going to contain up to 20 elements and I need to ensure it searches the message array efficiently, please help.
I can help you with that.
var arrayOfWords = $(".echat-shared-chat-message-body").last().text().split(" ");
That code is actually working! i went to an open chat in this website so I can tested.
So just replace the word REPLACE with your DOM object :)
var arrayOfWords = $("REPLACE").last().text().split(" ");
If I understood well, you're asking to filter an array of string (from an incoming string) given a second array.
In your described case you'll certainly not have to worry about efficiency, really. Unless your incoming message is allowed to be very very big.
Given that, there is a dozen of options, I think this is the most succinct:
const whitelist = [
'hello',
'peter'
]
const message = 'hello my name is Peter'.split(' ')
const found = message.filter(function(word) {
return whitelist.indexOf(word) > -1
}
You can treat invariant case:
const whitelistLower = whitelist.toLowerCase()
const foundInvariantCase = message.filter(function(word) {
return whitelist.indexOf(word.toLowerCase()) > -1
}
Or use ESS Set:
const whitelistSet = new Set(whitelist)
const found = message.filter(function(word) {
return whitelistSet.has(word)
}

Line-oriented streams in Node.js

I'm developing a multi-process application using Node.js. In this application, a parent process will spawn a child process and communicate with it using a JSON-based messaging protocol over a pipe. I've found that large JSON messages may get "cut off", such that a single "chunk" emitted to the data listener on the pipe does not contain the full JSON message. Furthermore, small JSON messages may be grouped in the same chunk. Each JSON message will be delimited by a newline character, and so I'm wondering if there is already a utility that will buffer the pipe read stream such that it emits one line at a time (and hence, for my application, one JSON document at a time). This seems like it would be a pretty common use case, so I'm wondering if it has already been done.
I'd appreciate any guidance anyone can offer. Thanks.
Maybe Pedro's carrier can help you?
Carrier helps you implement new-line
terminated protocols over node.js.
The client can send you chunks of
lines and carrier will only notify you
on each completed line.
My solution to this problem is to send JSON messages each terminated with some special unicode character. A character that you would never normally get in the JSON string. Call it TERM.
So the sender just does "JSON.stringify(message) + TERM;" and writes it.
The reciever then splits incomming data on the TERM and parses the parts with JSON.parse() which is pretty quick.
The trick is that the last message may not parse, so we simply save that fragment and add it to the beginning of the next message when it comes. Recieving code goes like this:
s.on("data", function (data) {
var info = data.toString().split(TERM);
info[0] = fragment + info[0];
fragment = '';
for ( var index = 0; index < info.length; index++) {
if (info[index]) {
try {
var message = JSON.parse(info[index]);
self.emit('message', message);
} catch (error) {
fragment = info[index];
continue;
}
}
}
});
Where "fragment" is defined somwhere where it will persist between data chunks.
But what is TERM? I have used the unicode replacement character '\uFFFD'. One could also use the technique used by twitter where messages are separated by '\r\n' and tweets use '\n' for new lines and never contain '\r\n'
I find this to be a lot simpler than messing with including lengths and such like.
Simplest solution is to send length of json data before each message as fixed-length prefix (4 bytes?) and have a simple un-framing parser which buffers small chunks or splits bigger ones.
You can try node-binary to avoid writing parser manually. Look at scan(key, buffer) documentation example - it does exactly line-by line reading.
As long as newlines (or whatever delimiter you use) will only delimit the JSON messages and not be embedded in them, you can use the following pattern:
let buf = ''
s.on('data', data => {
buf += data.toString()
const idx = buf.indexOf('\n')
if (idx < 0) { return } // No '\n', no full message
let lines = buf.split('\n')
buf = lines.pop() // if ends in '\n' then buf will be empty
for (let line of lines) {
// Handle the line
}
})

Categories