i work on a comunautary bot for discord and i have a probleme in my code
this is my code :
for (let i = 0; i < body.players.length; i++) {
if ((body.players[i].votes >= myToken[0]['palier1'] ) && (body.players[i].votes < myToken[0]['palier2'] )) {
embed50.addFields(
{
name: body.players[i].playername + ' : ',
value: body.players[i].votes + ' votes ! ',
inline: true,
})
}else if((body.players[i].votes >= myToken[0]['palier2'] )) {
embed100.addFields(
{
name: body.players[i].playername + ' : ',
value: body.players[i].votes + ' votes ! ',
inline: true,
})
}
}
and this is my error :
return comparator(input, number) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, "Invalid number value", input, expected));
^
ExpectedConstraintError: Invalid number value
at Object.run (/root/bot/node_modules/#sapphire/shapeshift/dist/index.js:727:72)
at /root/bot/node_modules/#sapphire/shapeshift/dist/index.js:113:66
at Array.reduce (<anonymous>)
at NumberValidator.parse (/root/bot/node_modules/#sapphire/shapeshift/dist/index.js:113:29)
at validateFieldLength (/root/bot/node_modules/#discordjs/builders/dist/index.js:146:24)
at EmbedBuilder.addFields (/root/bot/node_modules/#discordjs/builders/dist/index.js:190:5)
at Object.run (/root/bot/commands/topvote.js:111:18)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
constraint: 's.number.lessThanOrEqual',
given: 26,
expected: 'expected <= 25'
}
my first if is okay but the second block my code .....
The stacktrace you posted suggests that the error is coming from a function in the Discord.js library called validateFieldLength.
Looking at the source code for this function in Discord.js it appears the name of this function might be a bit confusing; at first, I thought it was saying the name or value of a field was too long, but it appears that it's actually saying that you're adding too many fields to a single embed, you've added 26 and you're only allowed to add <= 25.
Here is a link to the documentation that goes over the limits for embeds: https://discordjs.guide/popular-topics/embeds.html#embed-limits
I would suggest you track how many fields you've added so far and when you've hit 25 go ahead and create a new embed (keep an array of these) and attach the next batch to that one. Just note that you can only have up to 10 embeds in a single message so you'll have to stop at 250.
Related
I've got the following module:
module.exports = {
name: "reputation",
aliases: ['rep','vouch'],
category: "misc",
/**
* #param {Discord.Message} message
* #param {Array} args
*/
async execute(message, args) {
if (args.length >= 2) {
args.shift();
reason = args.join(' ');
}else reason = 'No reason provided';
let member = message.mentions.members.first();
const repmessage = new Discord.MessageEmbed()
.setTitle("Reputation Given!")
.setDescription(`<a:peachverify:853511481747046420> You gave a reputation to ${member} for: \`${reason}\``)
.setFooter(`Rep ID: ${1++}`)
.setColor("#02b2f7")
message.channel.send(repmessage)
},
};
But whenever I try to run it I got an error:
Invalid left-hand side expression in postfix operation
How do I fix this?
In JavaScript, numbers are fixed. You cannot increment a number, but you can increment a variable.
let i = 1;
console.log(i++) //shouldn’t throw
Doing 1++ is just like doing the following:
1 = 1+1
Which is a clear error.
It's because you're trying to increment a number. Try to run the following snippet:
console.log(1++)
If you want to increase the reputation of the member, you must have some variable that you can increase. I can see none in your code, so you'll need to fix that.
Anyway, once you store the reputation somewhere, you can use the ++ like you wanted:
let rep = 0
console.log({ rep })
rep++
console.log({ rep })
rep++
console.log({ rep })
I'm trying to make a Discord bot and will apply commands from JSON file (for ex. if command is "abc", find "abc" in commands' array (list) and reply with abc's data). Here an element from my JSON file (file is long, because of this, haven't put full file):
[
{"howareyou": {
"Reply": "**Uh, oh... A few minutes ago lost my diamond banana from Middle Ages. But expect this, I'm OK.",
"NoArguments": true
}}
]
But the problem is: I get error "Cannot read property "Reply" of undefined" at this JS code:
const CMDFile = JSON.parse (FS.readFileSync ('./Commands.json', 'utf8', Error_ => { if (Error_) throw Error_ }))
if (Message.content.startsWith ('\\')) { // My prefix is '\'
if (Used_CMD == '' /* Used CMD is msg content without prefix */ || (Message.mentions.users.first () && Message.mentions.users.first ().id == '123456789012345678')) {
Cevapla ('Yes, I'm! For more, just use command `\\help`.')
} else {
const CMD = CMDFile [Used_CMD],
Reply = CMD.Reply, NoArg = CMD.NoArguments
My code runs correctly when I use '\' command btw, but when I type '\howareyou', it errors TypeError: Cannot read property 'Reply' of undefined. How can I fix this? Thanks.
The problem is either the format of your input file, or the code to get the proper command from the JSON.
either change your input file to :
{
"howareyou": {
"Reply": "**Uh, oh... A few minutes ago lost my diamond banana from Middle Ages. But expect this, I'm OK.",
"NoArguments": true
},
"other_cmd": {
"Reply": "xx",
"NoArguments": true
}
}
or find the command from the current structure :
var CMD = null
CMDFile.forEach((cmd) => { if(cmd.hasOwnProperty(Used_CMD)) CMD = cmd; });
or (as per comment)
const CMD = CMDFile.find(cmd => cmd.hasOwnProperty(Used_CMD));
I am using Cypress cy.get to grab elements, but if there are none, my test is failing.
I do not want it to fail. I want it to continue. The test is simply to list the items that are there, if any.
const listItemTitle = '[data-cy-component=list-item-title]';
cy.get(listItemTitle).each(($el, index, $list) => {
cy.wrap($el).then(($span) => {
const spanText = $span.text();
cy.log(`index: ` + index + ' ' + spanText);
});
});
I would have thought, if there are no elements there - that this code would still be ok, but not so. When I run it, I get this error: CypressError: Timed out retrying: Expected to find element: '[data-cy-component=list-item-title]', but never found it.
It works fine where elements are present. If no elements are found, I want to go on & do a different test.
Here is an experiment I tried:
let count: number = Cypress.$(listItemTitle).length;
cy.log('before:' + count);
cy.get(actionsBarActionsAdd).click();
cy.get(singlePickerSearch).type('Assets' + '{enter}');
cy.get(listItemCheckboxTitle)
.first()
.click();
cy.toast({
type: 'Success',
});
count = Cypress.$(listItemTitle).length;
cy.log('after:' + count);
cy.get(listItemTitle).each(($li, index, $lis) => {
cy.log('interface no. ' + (index + 1) + ' of ' + $lis.length);
cy.wrap($li).click();
});
This was the outcome:
18 LOG before:0
19 GET [data-cy-component-key="actions-add"] input
20 CLICK
21 GET [data-cy-component=single-picker-search] input
22 TYPE Assets{enter}
23 GET [data-cy-component="list-item-checkbox-title"]
24 FIRST
25 CLICK
26 GET .iziToast toast2
27 ASSERT expected [ <div.iziToast.iziToast-opening.fadeInUp.iziToast-theme-
alloy.iziToast-color-green.iziToast-animateInside>, 1 more... ] to have class iziToast-color-green
28 LOG after:0
29 GET [data-cy-component=list-item-title]
30 LOG interface no. 1 of 1
Conclusively shows that Cypress.$(listItemTitle).length does not count number of elements with selector: listItemTitle.
Update:
By putting a cy.wait(1000); after the Add had been executed (in my experiment) - giving the DOM time to update - the new element was found. With more specific selectors, the wait is not required
You can use jquery via Cypress.$ to check if any exist.
const listItemTitle = '[data-cy-component=list-item-title]';
if (Cypress.$(listItemTitle).length > 0) {
cy.get(listItemTitle).each(($el, index, $list) => {
cy.wrap($el).then(($span) => {
const spanText = $span.text();
cy.log(`index: ` + index + ' ' + spanText);
});
});
}
Update for Cypress 12
The ideal way to do this is with Gleb Bahmutov's cypress-if, but it's blocked at the moment due to changes in version 12 of Cypress.
The issue is being worked on, but in the meantime here is a hack on .should() that performs the check with retry, but does not fail when no elements turn up - based on #M.Justin's method.
let start = Date.now()
const commandRetry = ($subject, {assert, timeout}) => {
const elapsed = Date.now() - start
console.log(elapsed, assert($subject))
if (elapsed < timeout && !assert($subject)) {
const err = new Error('Retry')
err.isDefaultAssertionErr = true
throw err
}
}
cy.get('li')
.should($subject => commandRetry($subject, {
assert: ($subject) => $subject.length > 0,
timeout: 3000
}))
.should("have.length.gte", 0)
.then($subject => cy.log(`Found ${$subject.length} items`))
Below is the web page I used to test it. It initially has no <li> elements, and after two seconds adds one.
You can see the test retrying the assertion in the console, and passing after 2 seconds.
If you comment out the script on the page, so no <li> are added, you see the test run for 4 seconds but does not fail.
If both cases the correct element count is logged.
<ul></ul>
<script>
setTimeout(() => {
const ul = document.querySelector('ul')
const li = document.createElement('li')
li.innerText = 'A list item'
ul.appendChild(li)
}, 2000)
</script>
You can use cy.get(".field").should("have.length", 0)
The following retrieves the items, even if there are none:
cy.get(listItemTitle).should("have.length.gte", 0)
Note that this won't wait for the items to exist if the page is still loading them, and therefore might return before the elements are present. It should be safe to use when you know those items will have already been loaded.
This pattern can easily lead to problematic tests, so be careful about when and how it's used.
I have a similar case: I want the test to succeed if there is no element found, but if there are elements, I need that elements to be further tested with should. I came across this question, and based on the answer of M. Justin, I came up with the following:
cy.get('td:eq(0) i').should("have.length.gte", 0).then (($hits) => {
cy.log ('number of hits: ' + $hits.length)
if ($hits.length == 0) {
cy.log ('no hits OK');
cy.wrap (true);
}
else {
cy.log ('hits. test hits....');
// this is only an example
cy.wrap($hits).should('have.css',
'color').and('equal', 'rgb(170, 181, 0)');
}
});
I'm working on a CLI program, based on nodejs and the npm package "prompt".
Let say I want to have this prompt, putting the input in a variable pet:
Choose a pet:
(1) - Cat
(2) - Dog
(3) - Fish
(4) - Rabbit
(5) - Rat
: >
Basically I did the functionality, but I'm having the following problems:
If I use the conform function for custom validation - then my custom message - the multiline text - never appears. The name of the variable - pet - only appears. But I want to have validation, cause I want to make sure the user won't enter 333 for example.
If I remove the conform custom validation - I can have multiline text, but then something else happens: the blinking rectangle, where the entering happens, overlaps with the multiline text. And I can't make it blink after the last line of the multiline message.
(In the above example the blinking happens over the digit 5.)
Any idea how to resolve the two issues I have ? ... :)
================== EDIT: Added code samples ===================
This is how I generate the multiline text:
// generate the multiline text ..
var petsMessage = 'Choose a pet: \n';
var pets = [...];
for(var i = 0, l = pets.length; i < l; i++) {
petsMessage += ' (' + (i+1) + ') - ' + pets[i] + "\n";
}
This is how I generate the prompt with multiline text, but no validation:
// define the prompt stuff ..
var promptInfo = {
properties: {
Pet: {
message: petsMessage,
required: true
},
}
};
And this is with validation, but multiline message not working:
// define the prompt stuff ..
var promptInfo = [
{
name: 'Pet',
message: petsMessage,
required: true,
conform: function(value) {
value = parseInt(value);
if(value > 0 && value < pets.length) {
return true;
} else {
return false;
}
}
}
];
I believe the problem was that in the second snippet with the validation you assign the actual question in the message property, you should assign it in the description. The message property refers to error message. Try this please:
var petsMessage = 'Choose a pet: \n';
var pets = ["dog","cat","frog"];
for(var i = 0, l = pets.length; i < l; i++) {
petsMessage += '\t (' + (i+1) + ') - ' + pets[i] + "\n";
}
var prompt = require('prompt');
var promptInfo = [
{
name: 'Pet',
description: petsMessage,
required: true,
message: 'Options allowed:: 1'+'-'+pets.length,
conform: function(value) {
value = parseInt(value);
return value > 0 && value <= pets.length
}
}
];
prompt.start();
prompt.get(promptInfo, function (err, result) {
console.log('you Choose',result,'::::',pets[result.Pet-1])
});
Actually, the solution from "alex-rokabills" is not perfect too :( ... It's definitely better, but I still see issues.
If I use small amount of items then it's OK:
But if the number grows a little bit:
And for big prompts:
Also - can I get rid of the "prompt:" at the begining ? ...
Situation - looping over array of events and assigning properties from JSON parsed
Expected outcome - upload to Parse cloud storage
APIs that I'm using -
https://www.eventbrite.com/developer/v3/formats/event/#ebapi-std:format-event
https://www.parse.com/docs/js/guide
I'm new to Javascript (there actually might be more than one syntax error)
I don't know why I get this error on line 83 when trying to deploy to Parse Cloud Code
What I'm passing in -
var cities = ["San Francisco", "London"];
eventsArray = JSON.parse(httpResponse.text)["events"];
loopEvents(eventsArray);
the whole function as screenshot (syntax highlighting for readability) --> code
the function as text -->
function loopEvents(events) {
if (j == cities.length) {j=0};
for (var i = 0; i < events.length; i++) {
//Parse.Cloud.useMasterKey(); is not needed ATM I think
console.log("assigning properties for " + cities[j] + ".");
list.save({ // saving properties
number: String(i); // ****THIS IS THE LINE 83****
uri: events[i]["resource_uri"];
url: events[i]["url"];
id: events[i]["id"];
name: events[i]["name"]["text"];
description: events[i]["description"]["text"] || "None provided.";
status: events[i]["status"];
capacity: String(events[i]["capacity"]);
logo: events[i]["logo_id"]["logo"] || "http://www.ecolabelindex.com/files/ecolabel-logos-sized/no-logo-provided.png";
start: moment(events[i]["start"]["utc"]);
end: moment(events[i]["end"]["utc"]);
online: events[i]["online_event"];
currency: events[i]["currency"];
ticketClasses: events[i]["ticket_classes"] || "It's freeee!";
ticketClassesNames: events[i]["ticket_classes"]["name"] || "None provided.";
ticketClassesCost: events[i]["ticket_classes"]["cost"] || "It's freeee!";
ticketClassesDescription: events[i]["ticket_classes"]["description"] || "None provided.";
}, {
success: function(list) {
console.log("RIP CloudCode, we had good times!");
},
error: function(list, error) {
console.log("u fuc*ed up, with error: " + error.text + ", son.");
}
});
}
j++;
}
maybe it's all wrong, appreciate the effort and constructive answers ;))) if you need any other info just comment bellow and I'll edit.
EDIT.1 - after replacing ; for , I get the following error
As you're using object, semi-colon ; is not valid syntax.
Remove ; from all the lines inside the object.
number: String(i);
// ^
Use , comma instead.
number: String(i),
// ^
Code
// Notice the comma at the end of each element
list.save({ // saving properties
number: String(i),
uri: events[i]["resource_uri"],
url: events[i]["url"],
id: events[i]["id"],
name: events[i]["name"]["text"],
description: events[i]["description"]["text"] || "None provided.",
status: events[i]["status"],
capacity: String(events[i]["capacity"]),
logo: events[i]["logo_id"]["logo"] || "http://www.ecolabelindex.com/files/ecolabel-logos-sized/no-logo-provided.png",
start: moment(events[i]["start"]["utc"]),
end: moment(events[i]["end"]["utc"]),
online: events[i]["online_event"],
currency: events[i]["currency"],
ticketClasses: events[i]["ticket_classes"] || "It's freeee!",
ticketClassesNames: events[i]["ticket_classes"]["name"] || "None provided.",
ticketClassesCost: events[i]["ticket_classes"]["cost"] || "It's freeee!",
ticketClassesDescription: events[i]["ticket_classes"]["description"] || "None provided."
}, {
See Object creation
ticket classes is actually an array and to access it I had to add a expand parameter to the httpRequest, other than that the code itself was fine, thx Tushar for the syntax correction.