"RichEmbed descriptions may not exceed 2048 characters" - node.js

Basically if a user types more than 2048 characters in the description embed the embed would get split in 2 embeds and will send it in the guild. The part i dont understand how to fix, is splitting the embed in 2 messages. So first embed untill the end so 2048 then it will send another embed with the rest of the message.
You can see in the code below.
If this ${test} contains more than 2048
then split that in 2 embeds
message.author.send(new Discord.RichEmbed().setColor("00FFFF").setDescription(👉 **Here is what you typed:** 👈 \n \n **Test:** \n ${test}))

To split the string you can use the method provided in this answer: if you match the string with this RegExp /.{1,2048}/g you'll get an Array with all the substrings you need. You can use that array to build every embed.
Here's a function you can use to do that:
async function sendEmbeds(text, channel) {
const arr = text.match(/.{1,2048}/g); // Build the array
for (let chunk of arr) { // Loop through every element
let embed = new Discord.RichEmbed()
.setColor("00FFFF")
.setDescription(chunk);
await channel.send({ embed }); // Wait for the embed to be sent
}
}
To implement it, simply call it providing the text and the channel. In you case:
sendEmbeds(`👉 **Here is what you typed:** 👈 \n \n **Test:** \n ${test})`, message.author)

Related

PayPal IPN Validation Not Working Only for recurring_payment txn_type

My PayPal IPNs are validating fine, except for those with a txn_type of recurring_payment. When I pass the message to the validation endpoint, I'm converting the body into a query string using
var verificationString = '?cmd=_notify-validate';
Object.keys(body).map((key) => {
verificationString = verificationString + '&' + key + '=' + body[key];
return key;
});
My best guess is that this is messing with the order of the properties. PayPal's documentation states:
Your listener HTTPS POSTs the complete, unaltered message back to PayPal; the message must contain the same fields (in the same order) as the original message and be encoded in the same way as the original message.
But I didn't think Object.keys(body).map would rearrange anything in Nodejs. Any suggestions?
Found the solution. Turns out that PayPal allows user fields to contain things like backslash, newline characters, etc. This specific IPN had an address field with a \r\n newline between the street and apartment number. Using my original code, this was somehow being encoded different.
Instead of assembling the query string like in my original question, I now assemble it like this, since it preserves all characters and encoding:
var verificationString = '?cmd=_notify-validate&' + request.rawBody.toString();
And that solved the problem!

Convert string to BSTR

From the following function, I use the path. Now I generate some lets say list of names separated by newline
func(BSTR * path)
{
// From path paramter client sent, I use the path.
//Now I generate some lets say list of names separated by newline
string output = "Bob\n Rob \n Lilly \n";
// Now client wants the path to be modified with the output
// So i did the following
SysFreeString(*path);
*path= SysAllocStringByteLen(output.c_str(), output.size());
}
Is the last two lines correct. Somehow testing doesnot seems ok !

I need to read a string while ignoring any spaces or capital letters

I'm trying to read any message sent on a discord server and send a reply if a certain string is within the message ignoring all spaces and capitals. I'm very new to javascript and this is the first code I'm making just for fun.
This is the current main part of the code.
if(msg.content.toLowerCase().includes('string'))
{
msg.channel.send(emoji("480351478930866179"));
}
You can remove whitespace with replace() and shift the string to lowercase using toLowerCase() to achieve the desired result.
const original = 'Hello there.';
const str = original.replace(/\s/g, '').toLowerCase();
if (str.includes('hello')) console.log('Hi.');
You could use the string.replace method or you could use split then join. To ignore case just use toLowerCase();
Thank's, that solved my problem.
const original = 'Hello there.';
const str = original.replace(/\s/g, '').toLowerCase();
if (str.includes('hello')) console.log('Hi.');

Having a bot send an embed using a player command

I once again need help with creating my discord bot. I am trying to have a bot send an embed using a command. My code is too complex to send through this message because of all of the extra functions that i have in that effect the command, so I'm just going to say what the command should look like;
/embed [title]; [description]
and before the title and description would be would be
setAuthor(`${message.author.username}`, message.author.displayAvatarURL)
so the author of the embed would show up. Any idea on how to do this?
First, here is how you can use regex to parse text in a command:
case /^\/embed \[[\w ]+\]; \[[\w ]+\]$/.test(command):
sendEmbed(message);
break;
This Regular Expression (/^\/embed \[[\w ]+\]; \[[\w ]+\]$/) can be broken down as follows:
the beginning /^ and end $/ pieces mean we're trying to match an entire string / command.
/embed matches the exact text "embed"
\[[\w ]+\] is used for the title and for the description, and matches text within square brackets "[]", where the text is letters (uppercase or lowercase), numbers, underscore, or a space. If you need more characters like "!" or "-", I can show you how to add those.
.test(command) is testing that the Regular Expression matches the text from the command, and returns a boolean (true / false).
So now you put that regex checking code in your message / command listener and then call your send embed function (I named it sendEmbed) like this:
// set message listener
client.on('message', message => {
let command = message.content;
// match commands like /embed [title]; [description]
// first \w+ is for the title, 2nd is for description
if ( /^\/embed \[[\w ]+\]; \[[\w ]+\]$/.test(command) )
sendEmbed(message);
});
function sendEmbed(message) {
let command = message.content;
let channel = message.channel;
let author = message.author;
// get title string coordinates in command
let titleStart = command.indexOf('[');
let titleEnd = command.indexOf(']');
let title = command.substr(titleStart + 1, titleEnd - titleStart - 1);
// get description string coordinates in command
// -> (start after +1 so we don't count '[' or ']' twice)
let descStart = command.indexOf('[', titleStart + 1);
let descEnd = command.indexOf(']', titleEnd + 1);
let description = command.substr(descStart + 1, descEnd - descStart - 1);
// next create rich embed
let embed = new Discord.RichEmbed({
title: title,
description: description
});
// set author based of passed-in message
embed.setAuthor(author.username, author.displayAvatarURL);
// send embed to channel
channel.send(embed);
}
Let me know if you have questions!
Update Jan 2021
In the latest version of Discord js (as of Jan 2021), you'll have to create an embed like this:
const embed = new MessageEmbed()
.setTitle(title)
.setDescription(description)
.setAuthor(author.username, author.displayAvatarURL);
See example Embed in docs here. Everything else should be the same.

How to get first word from sentence in Swift

I am trying to get first word from String sentence as variable. How to do that? I have Local notification and I need to use it's message first word as variable, is it possible? For LocalNotifications I use LocalNotificationHelper library for easier handling. Maybe there is logic problem but I do not think so. More like I do not know enough options in Swift language.
Edit: I also have the nameField.text! in NSUserDefaults as an array. I need to delete the message first word from that array. Right now I remove only the first object from that array but that is not solution for me because I need to delete the nameField.text! from that array when LocalNotification pops out and user click on button.
Here I create notification message:
LocalNotificationHelper.sharedInstance().scheduleNotificationWithKey("text", title: "see options(left)", message: nameField.text!+"some text", date: deadlinePicker.date, userInfo: userInfo)
Now I need the message:nameField.text! to be variable at app launch.
This is how I trigger notification button actions:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "someFunction:", name: IDENTIFIER, object: nil)
Swift 3
let sentence = "First word needed"
let word = sentence.components(separatedBy: " ").first
print(word) // First
You can split your sentence using the white space char and then extracting the first element.
let sentence = "What a wonderful world"
if let firstWord = sentence.characters.split(" ").first.map(String.init) {
print(firstWord) // "What"
}

Resources