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.
Related
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.
So im creating a discord bot for fun on my server, and one of the things im trying to do is send a DM to the sender of the Msg if the msg contains my name. However, i've tried various approaches, using various commands but nothing seems to work. Ive looked on the internet for the answer but I havent seen anyone using eclipse to make the bot, so their Code doesnt always work for me (Unless im just doing something wrong). Could anyone help me out?
You can use some regex to search for your name being present in the message.
client.on("message", message => {
let text = message;
const containsName = text.search(/name/i);
/* search method returns the index of the first letter of the
string you're searching for if it is found, else returns -1.
Here we are using regex to search for the name, and the 'i' makes
it case insensitive.
*/
if(!(containsName === -1)) message.author.send("whatever you want to DM");
});
Your name goes in place of the name in the regex.
More about regex, here.
So I was pretty sure that this code worked correctly at one point, but recently it was brought to my attention that it sometimes works but not always (read: It will always purge my messages by n amount, but it might not purge another members).
Because I was teaching myself how to use multiple files on this project, the code is actually split between two files. I'm not sure if that has anything to do with the issue or not. Given the size of the two files, I've uploaded them both to pastebin.
The command code.
The Function code.
It purges just fine when I try and purge n where n is any number within the acceptable range, but when I try and purge n by username I get an error message stating
DiscordAPIError: Invalid Form Body
limit: Value "" is not int.
(note that is two double quotes, the formatting is a little unclear)
I'm confused as to where it is getting a value that is not an int, as I'm running the amount through praseInt. I've snipped out the code segment that checks if a user is defined and posted it below as I believe it to be the problem:
if (user) { // If User is Provided
debug.run(`Filtering messages by ${user.username}`);
const filterBy = user ? user.id : client.user.id;
messages = messages.filter(m => m.author.id === filterBy).array().slice(0, amount);
}
Any assistance would be greatly appreciated. I'm more or less about to scrap the user feature if I can't figure it out.
Also I apologize for the formatting. I can never get the hang of this sites formatting.
Try getting rid of
.array().slice(0, amount).
The array of fetched messages doesn't need to be cut by the amount variable if the message.channel.fetchMessages({ limit: amount }).then((messages) => { line already limits it.
Here is an example of what I am referring to: Facebook Example
I don't understand how this is coded. Is it simply some code that states if your name begins with the letter "A" then you are this person, "B" then this person, etc... or is it more complex then that. I have seen people whose names both begin with "A" get different results, so could it be just a random result? And how would this all be coded on the website's end, since Facebook just pulls up an image/text preview of the site (which is also another question, how could so many "sites/name" exist for every name possible)
Any insight would be greatly appreciated!
There is many different ways this could be achieved but if you were speaking generally I would assume they where chosen at random for either an object, array, database etc. An example of this would be the following using a JavaScript array
const la = ["Goofy", "Bugs Bunny", "Yosemite Sam", "Porky Pig"]
const generateRandomCharacter = () => {
return `Your character is: ${la[Math.floor((Math.random() * la.length} + 0)]}`)
}
alert(generateRandomCharacter) /* would return your random character */
running the generateRandomCharacter would return your random character.
Again this could be achieved many other ways this is just an example.
For your question about 'how that many sites could exist' well from my very minimal experience with php I create a site that would write a new file each time a user loaded. I speculate that whenever you were to click the button to generate your character it was writing a file with your randomly chosen character and your facebook name as the filename but again my php knowledge is very minimal.
Hope this helped somehow.
I would like to find out how to do the below, without actually doing the DB Query.. i.e. I would like to know if "someData" would pass "whereClause" without putting it in a table and asking for it back again. I.e. Run the logic inside findOne without the overhead of insert and select. Just to make it more fun, please consider that I need to have it thread safe, thats why im messing with a Guid kinda thing below.. Also please note the where clause is probably gonna be more complex than the below, like { a : { $ne : 1 } }
Given Source:
someData = { a: 1, b: 2 };
whereClause = { b: 2 };
My code that needs fixing:
someData.GUID = ObjectId();
// DB QUERY - insert
db.workspace.insert(someData);
whereClause.GUID = inputsValues.GUID;
// Check if the data passes the whereClause
// DB QUERY - findOne
var whereResult = db.workspace.findOne(whereClause);
// DB QUERY - remove
db.workspace.remove({ "GUID": whereClause.GUID });
if (whereResult == null)
alert("Fail");
else
alert("Pass");
In SQL what I want can be expressed kinda like this: (pseudo syntax)
if (
Select Count(*) from ((Select 1 as A, 2 as B) Data where B = 2) Result
) = 1 then 'pass' else 'fail'
The above query never actually touches a table - that is my main goal.
Ok so I took this question to MongoDB support (10gen) and asked them for advice. It seems there is no syntactic way of saying what I want to say. Their suggestion is to use a separate mongodb instance as close to the application as possible, and to use that for only this purpose avoiding any potential slowing down due to locking etc.
So the solution is: Make a new MongoDB instance local to the app, and run thses queries in there. That would be the only way to do this.
I'll leave the question open to anyone that can provide a better solution.
Ok, so Stennie (in a comment) above has provided clues to what I think is the best answer for this situation.
He provided the link below:
what Javascript library can evaluate MongoDB-like query predicates against an object?
This has led me to 2 javascript libraries:
1) Mingo - https://github.com/kofrasa/mingo
2) Sift - https://github.com/crcn/sift.js
Mingo has the advantage of being able to evaluate MongoDB syntax, where Sift seems to be more complete. For my situation Mingo is perfect and exactly what I was looking for.
(I don't know how to give Stennie credit for this answer, but it really belongs to him)