Having a bot send an embed using a player command - node.js

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.

Related

How to extract text from element having text in brackets in cypress i.e. test(5)

Can someone pls help in extracting text from element. Let us say we have element shown in page having text 'Test(10).
How we can get text as o/p Test and 10 separately.
Thanks in advance!
You can use regex with name capture group.
// example for 'Test(10)'
cy.get('.element-selector')
.invoke('text')
.then(elText => {
const matcher = /(?<text>test)\((?<number>\d+)\)/
// extracts 'Test'
const text = elText.match(matcher)?.groups?.text
// extracts '10'
const num = elText.match(matcher)?.groups?.num
})

How would I isolate a string between two strings in DiscordJS?

I've currently been using this script:
var portion = body.substring(
str.lastIndexOf('ID Background',") + 1,
str.lastIndexOf('ID Theme',")
);
"Body" is the input, "Portion" being the output.
I'm trying to isolate text between the words strings "ID Background" and "ID Theme"
Example:
ID Background
Background information Background information Background information Background information
ID Theme
Theme information Theme information Theme information Theme information Theme information
...Et Cetera.
Expected Output:
Background information Background information Background information
Current Output:
undefined
I cannot figure out why this script is not working. I'm using this for a Discord bot (Discord.JS)
You should use RegExp capturing groups ()
// objective: get everything in between 'start' and 'end'
const str = 'start hello how was your day end';
// capture everything in between the two words in parentheses
console.log(str.match(/start (.*) end/)[1]);
Since you're example uses line breaks, which the special character . doesn't cover, you should use [\s\S] (\s is whitespace, and \S is anything but whitespace. Together, they cover everything. Also, use optional chaining ? so that your code doesn't throw a TypeError if no match is found.
var portion = body.match(/ID Background *([\s\S]*) *ID Theme/)?.[1];
if (!portion)
// no match found...

How to remove string after and before specific chars

I have this string: https://2352353252142dsbxcs35#github.com/happy.git
I want to get result: https://github.com/happy.git (without random string after second / and after # but without #).
Now I have something like this:
var s = 'https://2352353252142dsbxcs35#github.com/happy.git';
var d = s.substring(s.indexOf('/')+2, s.indexOf('#')+1;
s = s.replace(d, "");
it works, but I know it's an ugly solution.
What is the most efficient and more universal solution?
Try this:
const indexOfAtSign: number = receivedMessage.indexOf('#')+1
const httpsString: string = 'https://'
const trimmedString: string = s.slice(indexOfAtSign)
const requiredURL: string = httpsString.concat(trimmedString)
// Print this value of requiredURL wherever you want.
So here what my code does is, it gets position of # and removes everything before it along with the sign itself. Then using the slice() function, we are left with the remaining part which I named as trimmedString. Now I have pre-defined the `https string, anf we just need to merge them now. Done :-)
I had tried this out in my telegram bot and here's how it works:

Find and replace text and wrap in "href"

I am trying to find specific word in a div (id="Test") that starts with "a04" (no case). I can find and replace the words found. But I am unable to correctly use the word found in a "href" link.
I am trying the following working code that correctly identifies my search criteria. My current code is working as expected but I would like help as i do not know how to used the found work as the url id?
var test = document.getElementById("test").innerHTML
function replacetxt(){
var str_rep = document.getElementById("test").innerHTML.replace(/a04(\w)+/g,'TEST');
var temp = str_rep;
//alert(temp);
document.getElementById("test").innerHTML = temp;
}
I would like to wrap the found word in an href but i do not know how to use the found word as the url id (url.com?id=found word).
Can someone help point out how to reference the found work please?
Thanks
If you want to use your pattern with the capturing group, you could move the quantifier + inside the group or else you would only get the value of the last iteration.
\ba04(\w+)
\b word boundary to prevent the match being part of a longer word
a04 Match literally
(\w+) Capture group 1, match 1+ times a word character
Regex demo
Then you could use the first capturing group in the replacement by referring to it with $1
If the string is a04word, you would capture word in group 1.
Your code might look like:
function replacetxt(){
var elm = document.getElementById("test");
if (elm) {
elm.innerHTML = elm.innerHTML.replace(/\ba04(\w+)/g,'TEST');
}
}
replacetxt();
<div id="test">This is text a04word more text here</div>
Note that you don't have to create extra variables like var temp = str_rep;

"RichEmbed descriptions may not exceed 2048 characters"

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)

Resources