How do I get these properties to not be undefined when they're in an embed - node.js

const Discord = require('discord.js')
const prefix1 = '*add'
const prefix2 = '*what'
const prefix3 = '*remove'
const prefix4 = '*search'
const bot4 = new Discord.Client();
let a = []
let fakea = []
bot4.on('message', msg => {
if(msg.member.hasPermission('ADMINISTRATOR')){
if(msg.content.startsWith(prefix1)){
let splited = msg.content.split(' ')
let unchanged = msg.content.split(' ')
splited.splice('*info', 1)
splited.splice(msg.content[1], 1)
splited.splice(msg.content[2], 1)
let c = splited.join(' ')
b = {
namer: unchanged[1],
imformation: unchanged[2],
description: c
}
if(fakea.includes(unchanged[1])){
msg.channel.send('It already exists')
} else {
a.push(b)
fakea.push(unchanged[1])
}
console.log(a)
}
if(msg.content.startsWith(prefix3)){
let armay = msg.content.split(' ')
console.log(a)
console.log(fakea)
if(armay.length != 2){
msg.channel.send(`You have either less or more than two words. That either means you wrote *add on it's own or you had more than one word that you put with the command`)
} else {
if(!fakea.includes(armay[1])){
msg.channel.send(`That doesn't exist. You can't delete something that doesn't exist.`)
} else {
let fakeafind = fakea.find(plot => plot === armay[1])
let afind = a.find(plote => plote.namer === armay[1])
fakea.splice(fakeafind, 1)
a.splice(afind, 1)
}
console.log(a)
console.log(fakea)
}
}
if(msg.content.startsWith(prefix2)){
let coolon = fakea.join('\n')
let don = `_________\n[\n${coolon}\n]\n_________`
const notbot3embed = new Discord.MessageEmbed()
.setTitle('Everything you can search')
.setColor('15DD7C')
.addField('The things you can search', don)
msg.channel.send(notbot3embed)
}
if(msg.content.startsWith(prefix4)){
let mayi = msg.content.split(' ')
if(mayi.length != 2){
msg.channel.send(`You have either less or more than two words. That either means you wrote *search on it's own or you had more than one word that you put with the command`)
} else {
if(fakea.includes(mayi[1])){
let ft = a.filter(thing => thing.namer === mayi[1])
console.log(ft)
let secot = ft.namer
let thirt = ft.imformation
let fort = ft.description
const someembed = new Discord.MessageEmbed()
.setTitle(secot)
.setColor('FF4200')
.addField(thirt, fort)
msg.channel.send(someembed)
} else {
msg.channel.send('This is not a searchable term. Use *what to see the terms that are there.')
}
}
}
}
})
bot4.login(process.env.token4)
I wrote all of it because you would be confused about the properties if I didn't. In the last part I try to get the properties of the object with the name after '*search'. Then I want to put it an embed. Here's the problem I get. On the embed all three of the things say undefined. How do I fix this
If you're confused what I'm trying to do here's what I'm trying to do. I'm trying to make a system that you can put search things(I don't know how to frase it), remove them, check which ones exist and search something. Most of it is working. But in the search part it says for all of them in the embed undefined.

I found out that you need to use find instead of filter. Find works.

Related

Svelte Store. Spread syntax is not merging - just adding

I am trying to add some brocolli to my basket in the svelte store I have created. My code adds the brocooli to the basket but then duplicates the baskets and adds a whole new basket to my store. Not sure if the problem is caused by my lack of understanding of javascript or svelte.
Desired result
Basket 1 OrangePineapple Basket 2 BananaApplePlumwalnuthazelnutnutmegbroccoli
ACTUAL RESULT
Basket 1 OrangePineapple Basket 2 BananaApplePlumwalnuthazelnutnutmeg Basket 2 BananaApplePlumwalnuthazelnutnutmegbroccoli
Link to svelte codebox where you can view and run code
https://svelte.dev/repl/80d428000a3f425da798cec3450a59d4?version=3.46.2
if you click the button you see that my basket is duplicating. I am just trying to add the brocooli to the basket.
code below
import { writable } from 'svelte/store';
export const storeBaskets = writable([
{
"name": "Basket 1",
"items": ["Orange", "Pineapple"]
},
{
"name": "Basket 2",
"items": ["Banana", "Apple","Plum","walnut","hazelnut","nutmeg"]
}
])
//Local functions
export const add = (item,basketIndex) => {
storeBaskets.update(val => {
const newItems = [...val[basketIndex].items, item]
const newBasket = {'name':val[basketIndex].name,'items':newItems}
val = [...val,newBasket]
return val
})
val = [...val,newBasket]
With this line you're copying the previous store value and adding the newBasket "on top". That's how the spread operator works with arrays
let arr = [1,2,3]
let n = 4
let arr2 = [...arr, n]
console.log(arr2) // [ 1 , 2 , 3 , 4 ]
I wonder if you might have thought of the different behaviour when spreading an object, where an already existing entry might be overriden if the key already exists
let obj = {key: 'value'}
let key = 'newValue'
let obj2 = {...obj, key}
console.log(obj2) // { key: "newValue" }
To make your code working you could replace the line by val[basketIndex] = newBasket
export const add = (item,basketIndex) => {
storeBaskets.update(val => {
const newItems = [...val[basketIndex].items, item]
const newBasket = {'name':val[basketIndex].name,'items':newItems}
val[basketIndex] = newBasket
return val
})
}
Or, instead of spreading, simply push the new value directly to the according nested array in just one line
export const add = (item,basketIndex) => {
storeBaskets.update(val => {
val[basketIndex].items.push(item)
return val
})
}
You might not need to spread, because it's an array, you'r spreading the existing items of the array and then adding the new basket to it. You can map and replace by basketIndex, like:
export const add = (item,basketIndex) => {
storeBaskets.update(val => {
const newItems = [...val[basketIndex].items, item]
const newBasket = {'name':val[basketIndex].name,'items':newItems}
return val.map((basket, i) => i === basketIndex ? newBasket : basket)
})
}
(Working example)

NodeJS TypeError: Cannot read properties of undefined (reading '0')

I get the enemyCards from the frontend and it is an array, with 990 x 7 poker cards.
The sortCardOrder function just take the cards in order so i can search in my datas.
This is my NodeJS code:
import fs from 'fs';
import G from 'generatorics';
export default function findEnemyStrongest(enemyCards) {
let eCombination = enemyCards.enemyCards;
let result = [];
for(const comb of eCombination){
result.push(findStrongest(comb));
}
console.log(result);
}
function createCombinations(enemyC){
let combine = enemyC;
let onlyName = [];
let allCombinations = [];
for (let card of combine){
onlyName.push(card.name);
}
for (let comb of G.combination(onlyName, 5)){
allCombinations.push(comb.slice());
}
return allCombinations;
}
function findStrongest(combi){
let rawdata = fs.readFileSync('data.json');
let strenghtOrder = JSON.parse(rawdata);
let combinations = createCombinations(combi);
let combinationsName = [];
let ordered = "";
let result = [];
for(let combination of combinations){
let nameString = "";
let colors = {'C': 0, 'S': 0, 'H':0, 'D':0};
for(let card of combination){
nameString += card[0];
colors[card[1]]+=1
}
ordered = sortCardOrder(nameString, colors);
combinationsName.push(ordered);
console.log(combinationsName)
result.push(strenghtOrder.cardStrenght[ordered]);
}
return Math.min(...result);
}
function sortCardOrder(string, colors){
}
Can anyone know what is the problem?
We can infer this line is causing the error:
nameString += card[0];
It is requesting the 0 property of the card variable, but card is undefined. Card gets its value from combination. Print out combination to see if it has undefined values.
...
for(let combination of combinations){
console.log(combination)
...
Combination gets it value from combinations, which comes from comb. Print out the values of comb.
...
for (let comb of G.combination(onlyName, 5)){
console.log(comb)
...
Keep going backwards until you find the source of the 'undefined' value. Without seeing the original source data (from G), stepping through the code is the only way to find the error source.

Is there a way to check if a message contains a Unicode emoji

So im trying to make a poll command it works but there is just one problem it does not support normal emojis just custom emojis this is my code
const Discord = require("discord.js")
const { Permissions , MessageEmbed } = require("discord.js")
let wrong = "#F04A47"
module.exports = {
name: "poll",
usage: "poll <message>",
description: "poll idk",
category: "other",
run: async (client, message, args) => {
try {
if(!message.member.permissions.has(Permissions.FLAGS.KICK_MEMBERS)) {
let embed = new MessageEmbed()
.setDescription("**You do not have permissions to send polls/kick members**")
.setColor(wrong)
return message.channel.send({embeds:[embed]})
}
if(!args[0]) return message.channel.send("please type the first option example => $poll <pizza> <sushi> <🍕> <🍣>")
if(!args[1]) return message.channel.send("please type the second option example => $poll <pizza> <sushi> <🍕> <🍣>")
if(!args[2]) return message.channel.send("please type the first emoji example => $poll <pizza> <sushi> <🍕> <🍣>")
if(!args[3]) return message.channel.send("please type the second emoji example => $poll <pizza> <sushi> <🍕> <🍣>")
const hasEmoteRegex = /<a?:.+:\d+>/gm
const emoteRegex = /<:.+:(\d+)>/gm
const animatedEmoteRegex = /<a:.+:(\d+)>/gm
const normalemoji = /<::>/gm
if(args[3] && args[2].match(/<:\w+:[0-9]+>/)) {
const reportlog = new MessageEmbed()
.setTitle('Poll Time 🥳')
.setColor('RANDOM')
.setDescription(`${args[0]}${args[2]} or ${args[1]}${args[3]}`)
.setFooter(`Poll by ${message.author.tag}`)
.setTimestamp()
message.channel.send({embeds: [reportlog]}).then(sentMessage => {
sentMessage.react(args[2])
sentMessage.react(args[3])
})
}
else{
message.channel.send("you can only use custom emojis for now ")
}
message.delete()
} catch(e) {
message.channel.send(`an error occcured ${e}`)
}
}
}
When i try to use a normal emoji it just return you can only use custom emojis blah blah blah how can i filter custom animated and normal emojis and i made this im not really good with matching and Unicode emojis
If you would like to only match moving emojis:
const animated = /<a:.+:(\d+)>/gm
if(message.match(animated)) {
// do something...
}
Matching non-moving custom emojis
const animated = /<a:.+:(\d+)>/gm
const normal = /<::>/gm
if(message.match(normal) && !message.match(animated)) {
// do something...
}

Discord content must be 2000 or fewer in length in a roles list

i know this error is already solved but in another form i could't solve my error:
if(msg.content.startsWith(`${prefix}roles`)) {
const spaces = ' ';
const roles = [];
msg.guild.roles.filter(r => r.name !== '#everyone').forEach(c => {
let list = roles.push(`${c.name} ${spaces.substring(c.name.length)} ${c.members.size} member`);
if(c.members.size < 2) roles.push(`${c.name} ${spaces.substring(c.name.length)} ${c.members.size} member`);
if(c.members.size >= 2) roles.push(`${c.name} ${spaces.substring(c.name.length)} ${c.members.size} members`);
});
msg.channel.send(`\`\`\` ${roles.join('\n')} \`\`\``);
}
});
Thanks.
Well that's probably because you are pushing to the array 2 times for each role
Once here:
let list = roles.push(${c.name} ${spaces.substring(c.name.length)} ${c.members.size} member);
And another time after that with the if statements,
After you change it to one time, it should fix it unless you have like 100 roles, and in which case you can just add the option split: true inside of message.channel.send
https://discord.js.org/#/docs/main/stable/typedef/MessageOptions
https://discord.js.org/#/docs/main/stable/typedef/SplitOptions
if (msg.content.startsWith(`${prefix}roles`)) {
const spaces = ' ';
const roles = [];
msg.guild.roles.filter(r => r.name !== '#everyone').forEach(role => {
let string = `${c.name} ${spaces.substring(c.name.length)} ${c.members.size} member`;
if (role.members.size >= 2) {
string += "s";
}
roles.push(string);
});
//all those escape characters look bad, just concat strings
msg.channel.send("```\n" + roles.join('\n') + "\n```", { split: true });
}

Parse string (node js ) .Find array of numbers into string

\n54766392632990,178.32.243.13,wfsdsfsdfs23432,\n54766393632990,178.32.243.13,
Above u can see example of string which I want to parse.. I want to get array if numbers which exist between (\n....,178.32.243.13) .. In this example it will be smth like :
[54766392632990,54766393632990] - how to make it
Please run this script it full file your requirement
var ss = "\n54766392632990,178.32.243.13,wfsdsfsdfs23432,\n54766393632990,178.32.243.13,"
var ddd = ss.split(",")
console.log(ddd)
var dfd = []
ddd.forEach(function(res){
if(res.startsWith("\n"))
{
dfd.push(res.replace("\n",""))
}
})
console.log(dfd)
Result [ '54766392632990', '54766393632990' ]
"\n54766392632990,178.32.243.13,wfsdsfsdfs23432,\n54766393632990,178.32.243.13,"
.split("\n")
.filter((n)=> n!== "")
.map(n=> parseInt(n.split(",")[0]))
You can do something like this to parse this string
let s = "\n54766392632990,178.32.243.13,wfsdsfsdfs23432,\n54766393632990,178.32.243.13,"
s = s.split("\n");
let array = [];
for(let i=0;i<s.length;i++) {
let v = s[i].split(",178.32.243.13,");
for(let j=0;j<v.length;j++) {
if(!isNaN(parseInt(v[j]))) {
array.push(v[j]);
}
}
}
console.log(array);

Resources