So I'm working in a discord bot where I want to add different user Ids in a command but now it doesn't work. the code looks like this:
if (message.author.id !== '513773028606476308', '749446086493470751') return message.channel.send("no")
I'm assuming you want a command only to run ONLY for users with specific IDs. Therefore that if statement would be in some kind of function that handles that specific command.. your answer would be to change that if statement to
if (!['513773028606476308', '749446086493470751'].includes(message.author.id)){return message.channel.send("no")}
However, the best solution would be to have an array of these special IDs in the first place like
let allowed=['513773028606476308', '749446086493470751']
if (!allowed.includes(message.author.id)){return message.channel.send("no")}
There's a few things that are contributing to the problem you're seeing here.
The first is that your if statement isn't set up properly. To do what you're looking for, it'd have to look like if (message.author.id !== '513773028606476308' && message.author.id !== '749446086493470751'). While being able to just comma-seperate those values would be a nice feature, it's not currently something you can do in Javascript. You have to explicitly say "if the author ID is not equal to 513773028606476308 and the author ID is not equal to 749446086493470751" etc.
All that said, just continuously adding IDs on that if statement probably isn't a really good idea. Like commenters have pointed out, structuring this a bit differently would probably result in code that's both more readable and easier to change in the future. You'd do this by putting those user IDs in an array and then checking if the array doesn't contain those IDs, like so:
let admins = ['749446086493470751', '749446086493470751'];
if (!admins.includes(message.author.id)) {
return message.channel.send("no");
}
This makes your life a little easier down the line for a few reasons:
If you want to have other commands that only these two users can use, you don't have to copy-paste that big long if block elsewhere, it's fairly simple and easy.
If you do add another command like this, and then later want to add a third special user, you only have to change your code in one place (the admins array), rather than potentially missing a spot.
Related
I have this command in javascript that works, but can't seem to translate it into playwright. For my project, I have 10 item cards and I need to find if item description is missing inside each item card or not. (there should be 1 missing description in my case)
document.getElementsByClassName(itemCard)[i].querySelector(itemDescription)
I've tried
const rows = await this.page.locator(itemCard);
inside loop)
if (await rows.locator('has:itemDescription').nth(i) == null) {
console.log("No description") }
else { console.log("has description"}
but the above code seems to print out 10 "has descriptions" instead of 9. There should be one "No description".
To do an almost exact translation of what you seemed to be doing, your if condition could translate to this:
if (!(await rows.nth(i).locator(itemDescription).isVisible())) {
I don’t know the full context/goal or what your actual core requirement is, but if it satisfies it, you could also just get a count of how many exist, and assert or log how many there are. To get this count, you could do something like this:
await rows.filter({ has: this.page.locator(itemDescription) }).count();
Also just realized that you were doing get by class name before, so your rows locator also would need a tweak to specify css class, like so:
const rows = await this.page.locator(`.${itemCard}`);
Happy to provide more specifics if needed and given more context. Hope that helps!
Hello!
I will try to do my best as possible to explain this issue i have.
A bin with some of the code mentioned, with comments:
Codebin
I am currently working on a Discord bot, where there is data stored in a .json file (As string).
Maybe this should be converted to an array instead?
A user writes a command and the bot initializes a sequence where it will go through several options depending on whats found in the string.
I've been struggling with this far too long (atleast 10 hours now & i am severely out of ideas now) on getting a check in for user response, to see if the input he does is in the array.
If i write !color 76561197458345 - it starts the process as seen below:
As you see the Available Options for found Dino (Carnotaurus) is:
[Utah1, Utah2]
Which is correct since its listed as the detailcrest options for Carnotaurus below in my json
[
{
"name": "Acrocanthosaurus",
"detailcrest": "[Utah1, Utah2]",
"underbelly": "[Utah3, Utah4]",
"body1": "[Utah5, Utah6]",
"body2": "[Utah7, Utah8]",
"body3": "[Utah9, Utah10]"
},
{
"name": "Carnotaurus",
"detailcrest": "[Utah1, Utah2]",
"underbelly": "[Utah3, Utah4]",
"body1": "[Utah5, Utah6]",
"body2": "[Utah7, Utah8]",
"body3": "[Utah9, Utah10]"
}
]
What then happens is that the user is gonna give a input based on the options found (This case Utah1, Utah2).
I want the bot to check the response from user in chat, if his answer is existing in the json file.
If respond to the bot in chat with Utah1 - it would proceed to next question (Because it exists).
If respond to the bot in chat with Pizza2 - it would respond (Not found, please select available options)
TL;DR:
I simply need a way to check if user response (word) is existing in the string
If Yes: continue, If No: error
I hope someone can give tips, or atleast push in the right direction on how to procceed with this.
I found a simple, but obviously not the most smart answer to my own solution - however it works as expected.
I've changed my .json strings to simply not include any brackets
"detailcrest": "Utah1, Utah2",
To search through my string i applied a .split() function (to seperate words with ,)
const inputCheck = color.detailcrest.toLowerCase().split(',').includes(detailcrest);
If i then do a if else statement on it, it returns true or false - for the given input, if it exists in the json file.
if (inputCheck === true) {
console.log("found")
} else {
console.log("False")
}
Obviously this wouldn't be the smartest way to proceed in a professional
But in my little bot it should work out with what is expected.
Due to limits, i will accept my own answer as solution in two days.
I have an issue with JavaScript case sensitivity and I will need your valuable piece of advice here. I have the following object created:
var foo = function () {
this.myColor1 = '#000000';
this.MyColor2 = '#FF2000';
this.MyCOLOR3 = '#FFFFFF';
}
as you can see, each property may come in any case form, lowercase, uppcase, mixed, etc. These values are coming from a database and I don't have control onto them.
I want to be able to call them ignoring the case sensitivity. For example, I would like to be able to call them like this:
console.log(foo.mycolor1);
// or
console.log(foo.myColor1);
I guess my only approach to achieve this, would be to convert everything in, let's say, lowercase when I define those, and then, when I call them back to convert my request into lowercase again.
A little piece of background here; my aim is to provide an SDK to a few developers that they will write their own code for a platform I am working on. These values will be saved by the developers themselves into a database. For some reason, all those values are stored in lowercase. So, I either have to tell them 'no matter how you set them, you should request everything in lowercase', or, ideally, I should find a way to convert everything before their request is post.
An idea would be to write a method, and tell them to make the request like this
foo('mycolor1');
foo, is going to be a function that would handle the case sensitivity easily. But, I would prefer to use the foo.mycolor1 notation, so ... your help is needed :)
FYI, jQuery is available!
Thank you,
Giorgoc
when you render the javascript from DB use toLower() to set the variables names... and then reference them in lower case...
I'm doing some research for a project that I have going on the uses the document.createTreeWalker and I'm looking at a script that uses quite a few xpath's, but I'm curious as to where these come from. Some are obvious and I have been able to find answers to online, such as [#AttributeName] and [#TagName], but what is [#StoreName], [#AttributeValue1], [#AttributeValue2]...these I have not been able to look up online.
Particularly, I'm looking at these lines and not understanding:
thisURL = window.document.location.href.toString();
if(thisURL.search("[#StoreName]") != -1) { //do something }
Perhaps I'm misunderstanding your question, but there's nothing functionally or syntactically different between [#AttributeName] and [#StoreName]. They're both predicates that are looking for elements with particular attributes. The first one is looking for AttributeName attributes, while the second is looking for StoreName attributes.
That said, the code you're showing isn't actually doing any XPath work. It's just looking at whether the URL contains the character sequence [#StoreName] using JavaScript's string search function, and doing something if it does.
This has been a question I've had since I started doing serious ajax stuff. Let me just give an example.
Let's say you pull a regular HTML page of a customer from the server. The url can look like this:
/myapp/customer/54
After the page is rendered, you want to provide ajax functionality that acts on this customer. In order to do this, you need to send the id "54" back to the server in each request.
Which is the best/most common way to do this? I find myself putting this in hidden form forms. I find it easy to select, but it also feels a bit fragile. What if the document changes and the script doesn't work? What if that id gets duplicated for css purposes 3 months from now, and thus breaks the page since there are 2 ids with the same name?
I could parse the url to get the value "54". Is that approach better? It would work for simple cases repeatedly. It might not work so well for complex cases where you might want to pass multiple ids, or lists of ids.
I'd just like to know a best practice - something robust that is clean, elegant and is given 2-thumbs up.
I think the best way to do this is to think like you don't have Ajax.
Let's say you have a form which is submitted using Ajax. How do you know what URL to send it to?
The src attribute. Simply have your script send the form itself. All the data is in the form already.
Let's say you have a link which loads some new data. How do you know the URL and parameters?
The href attribute. Simply have the script read the URL.
So basically you would always read the URL/data from the element being acted upon, similar to what the browser does.
Since your server-side code knows the ID's etc. when the page is being loaded, you can easily generate these URLs there. The client-side code will only need to read the attributes.
This approach has more than just one benefit:
It makes it simpler where the URLs and data is stored, because they are put exactly in the attributes that you'd normally find then in HTML.
It makes it easier to make your code work without JavaScript if you want to, because the URLs and all are already in places where the browser can understand them without JS.
If you're doing something more complex than links/forms
In a case where you need to allow more complex interactions, you can store the IDs or other relevant data in attributes. HTML5 provides the data-* attributes for this purpose - I would suggest you use these even if you're not doing HTML5:
<div data-article-id="5">...</div>
If you have a more full-featured application on the page, you could also consider simply storing your ID in JS code. When you generate the markup in the PHP end, simply include a snippet in the markup which assigns the ID to a variable or calls a function or whatever you decide is best.
Ideally your form should work without javascript, so you probably have a hidden form input or something that contains the id value already. If not, you probably should.
It's all "fragile" in the sense that a small change will affect everything, not much you can do about that, but you don't always want to put it in the user's hands by reading the url or query string, which can be easily manipulated by the user. (this is fine for urls of course, but not for everything. Same rules that apply to trusting $_GET and query strings apply here).
Personally, I like to build all AJAX on top of existing, functional code and I've never had a problem "hooking" into what is already there.
Not everything is a form though. For
example, let's say you click a "title"
and it becomes editable. You edit it,
press enter, and then it becomes
uneditable and part of the page again.
You needed to send an ID as part of
this. Also, what about moving things
around and you want those positions
updated? Here's another case where
using the form doesn't work because it
doesn't exist.
All of that is still possible, and not entirely difficult to do without javascript, so a form could work in either case, but I do indeed see what you're saying. In almost every case, there is some sort of unique id, whether it's a database id or file name, that can be used as the "id" attribute of the html that represents it. * Or the data- attribute as Jani Hartikainen has mentioned.
For instance, I have a template system that allows drag/drop of blocks of content. Every block has an id and every area that it can get dropped has one as well. I will use prefixes on the containing div id like "template-area_35" or "content-block_264". In this case, I don't bother to fallback w/o javascript, but it could be done (dropdown-> move this to area for example). In any case, it's a good use of the id attribute.
What if that id gets duplicated for
css purposes 3 months from now, and
thus breaks the page since there are 2
ids with the same name?
If that happens (which it really shouldn't), someone is doing something wrong. It would be their fault if the code failed to work, and they would be responsible. Ids are by definition supposed to be unique.
IMHO putting is at a request parameter (i. e. ?customerId=54) would be good 'cos even if you can't handle AJAX (like in some old mobile browsers, command-line browsers and so) you can still have a reference to the link.
Apparently you have an application that is aware of the entity "Customer", you should reflect this in your Javascript (or PHP, but since you're doing ajax I would put it in Javascript).
Instead of handmaking each ajax call you could wrap it into more domain aware functions:
Old scenario:
var customer_id = fetch_from_url(); // or whatever
ajax("dosomething", { "customer": customer_id }, function () {
alert("did something!");
});
ajax("dosomethingelse", { "customer": customer_id }, function () {
alert("did something else!");
});
New scenario:
var create_customer = function (customer_id) {
return {
"dosomething" : function () {
ajax("dosomething", { "customer": customer_id }, function () {
alert("did something!");
});
},
"dosomethingelse": function () {
ajax("dosomethingelse", { "customer": customer_id }, function () {
alert("did something else!");
});
}
};
}
var customer_id = fetch_from_url(); // or whatever
var customer = create_customer(customer_id);
// now you have a reference to the customer, you are no longer working with ids
// but with actual entities (or classes or objects or whathaveyou)
customer.dosomething();
customer.dosomethingelse();
To round it up. Yes, you need to send the customer id for each request but I would wrap it in Javascript in proper objects.