Need Help Declining Steam Offers That Take Things From Me - javascript

Ok so I have a code from a steam bot the accepts and declines trades if the offer state is correct. But I would like it to accept trade offers that give me things but decline trade offers that are made by someone else asking for things.
if(body.response.trade_offers_received){
body.response.trade_offers_received.forEach(function(offer) {
if (offer.trade_offer_state == 2){
offers.acceptOffer({tradeOfferId: offer.tradeofferid});
}
else {
offers.declineOffer({tradeOfferId: offer.tradeofferid});
}
}
);
}

Not exactly sure what bot you're basing your code off, however after looking at the steam api for trade offers, there should be an array called "items_to_give" which you could check and see if it is empty before accepting.
if (offer.trade_offer_state === 2 && (!offer.hasOwnProperty("items_to_give") || offer.items_to_give.length === 0)){
So above we check if we do not have the "items_to_give" key, which doesn't exist if you are giving nothing. Then we check to make 100% sure that it has no items in it, just in case Steam decides to include empty keys with their API at a later date.
After looking at the steam api again, I believe your code could be improved if you also checked for TradeOfferStateCountered(4), which would let you accept counter offers as well. Here is the code for that
if ((offer.trade_offer_state === 2 || offer.trade_offer_state === 4) && (!offer.hasOwnProperty("items_to_give") || offer.items_to_give.length === 0)){

Related

Discord JS : How to "iterate" a stringified JSON?

I'm learning JS (And discord JS to be accurate) since a few days. All goes well but now I'm before an issue I don't really know how to wrap my head around.
I have a sequelize database, all working well, aka an "User Card Collection", filling up as intended.
Now, I want to ask for a showing up of all "user_id" card collection.
I used a JSON.stringify (is it already the right way to do it ?). I can call it in console.log easily, showing up as a JSON. But how could I insert the list into an embed to PM it to the user ?
I've try to iterate it, it says me that it's, of course, not iterable.
Here is my concerned code :
} else if (command === 'Collection' || command === 'collec' || command === 'col') {
const target = message.author.id;
const cards = await UserCollec.findAll({where: {user_id: target}, attributes: ['card_name', 'card_lvl', 'amount']});
console.log(cards.every(card => card instanceof UserCollec)); // true if ok. DEBUG : working as intended.
const JSONcardlist = console.log(`${message.author}, all your cards :`, JSON.stringify(cards, null, 2)) // returns the JSON list. DEBUG : Working as intended.
When I try to call ${JSONcardlist} in a message or embed, it returns undefined. What am I missing ?
Thx for your help :) Probably something easy but, you know... Beginner here, not found the answer on internet in a few hours so better to ask.
That's ok, thx for help.
I found my solution with this :
function GetCards(JSONcardlist) { return Object.values(cards).map(card => `• ${card.card_name} (lvl ${card.card_lvl}), ${card.amount} x`).join('\n')
}
message.channel.send(GetCards(JSONcardlist))

How to create a command that only who have one of the roles can use?

let staffrole = ['383874699941117952', '149622819158884353', '149622998180036608'];
How do you make a command that only people who have one of the roles can use it?
Thank you!
What you can do is that, on a message event, you run the command, and you can check the member's roles for one of the ones in the array.
Heres what that would look like:
client.on("message", msg => {
if(command === "whateverItIs") {
let staffrole = ['383874699941117952', '149622819158884353', '149622998180036608'];
for(i=0;i<staffrole.length;i++) {
if(msg.member.roles.filter((role) => role.id == staffrole[i]).size > 0) {
//run the code
return;
}
}
}
})
On a message event, with the determined command, the bot will check through each of the staff roles and if the message author 's roles includes one of the staffrole's then the command will run.
I would recommend doing something like this:
First, set your command name in the client's message listener:
// ... (in client message listener)
switch(command) {
case '<your command>':
runIfRoleIncluded(message);
break;
}
Next, get the role Id from the message that was sent and check if that message's role Id is in your staffrole array:
function runIfRoleIncluded(message) {
let rolesCollection = message.member.roles;
let staffrole = ['383874699941117952', '149622819158884353', '149622998180036608'];
// only 1 member can send a message, so get role collection's first key (id)
let messageRoleId = rolesCollection.firstKey();
// check if message's role id is in staff role array
if (staffrole.includes(messageRoleId)) {
// do stuff here
// ...
}
}
The .roles property of the .member object is a Collection, which is why you have to use the .firstKey() method. You can also turn the Collection into a normal js Array, but the way I outlined above is easier.
Started looking at this... Don't know the discord space very well but got an example bot and with a hello world ping, also found this pretty sweet Github gist that lays out fairly well how to build what amounts to a command switch statement. Making a lot of guesses here -- as a note for future questions it would be very helpful for you to add in some code on what you are trying to do -- a single variable set to an array isn't much to go on...
After Reading what #Raymond Zhang said, because, yeh that's what I was doing...
this is straight out of the Github gist I linked ->
...
if(command === "kick") {
if(!message.member.roles.some(r=>["Administrator","Moderator"].includes(r.name)) )
return message.reply("Sorry, you don't have permissions to use this!");
...
I have tested this and it works great, although it checks against the roles name not a number. It would help if you updated you answer to explain your process. More info = better answer. :)

What's wrong with this logic? Node JS

I built a mini cms app with Node JS. I allow users to edit their own profile and admins to edit all profiles. I have a weird problem with the logic - If I use this syntax, I get an error (401) when an admin tries to edit other user's profile:
if (!loggedUser.isAdmin || foundUser.id !== loggedUser.id) {
res.status(401).json();
} else {
// Save Updated User
foundUser.username = req.body.username;
foundUser.birthday = req.body.birthday;
foundUser.personalWeb = req.body.personalWeb;
foundUser.location = req.body.location;
foundUser.save().then(() => res.status(200).json(200));
}
But if I use this syntax, the permissions work just fine:
if (loggedUser.isAdmin || foundUser.id === loggedUser.id) {
// Save Updated User
foundUser.username = req.body.username;
foundUser.profileImg = req.body.profileImg;
foundUser.personalWeb = req.body.personalWeb;
foundUser.location = req.body.location;
foundUser.save().then(() => res.status(200).json(200));
} else {
res.status(401).json();
}
Can someone please explain what's the differnce between the two conditions?
!loggedUser.isAdmin || foundUser.id !== loggedUser.id and loggedUser.isAdmin || foundUser.id === loggedUser.id are not boolean inverses of each other.
The first is saying "if the user is not an admin or the found user's id does not match the logged in user's id." In the case of an admin you would expect their id to not match the found user's id.
I think that your second code block is easier to read and you should keep it, but if you wanted to do the negative condition first it would be:
!loggedUser.isAdmin && foundUser.id !== loggedUser.id
That is: "if the logged in user is not an admin and the found user's id does not match the logged in user's id."
This is also the boolean inverse:
!(loggedUser.isAdmin || foundUser.id === loggedUser.id)
// expands to
!loggedUser.isAdmin && foundUser.id !== loggedUser.id
It was surprisingly difficult for me to find good documentation or descriptions of boolean negation, but this article explains the concepts well I think: http://www.math.toronto.edu/preparing-for-calculus/3_logic/we_3_negation.html
Although you can simplify boolean expressions, I think it's best to write them in a way that makes the most sense to read back for you and your development team, so I suggest you use the first block since it's easy to read. Failing that, leave a comment about what the expression is trying to accomplish.
It's because your foundUser.id !== loggedUser.id is evaluating to true when editing any user that's not you.
To add to that, any non admin user will get a 401 due to the first condition evaluating to true.
With || as long as one condition is met, the body will execute and then it's done. It won't move on to the else body if only one condition is false. Both need to be false
Personally I would just use your second example. It's more readable.

Cannot get the full json with request json

When I am actually entering the XXXX YYYY, then I am getting the players json code in my html page (around 150 values).
But when I am trying to use a function on the players list it somewhy does not contain all the 150 values and the try throws me into the catch error part, where I can see that players json has only 100 players inside there.
Any idea what could be the problem?
if(yourID === "XXXX" && targetID === "YYYY"){
return players;
}
try{
if(isUserAlive(yourID)){
if(targetID === ""){
return userTargetInfo(yourID);
}
var checkForMatch = getUserTarget(yourID);
if(checkForMatch === targetID){
killTarget(targetID);
getUser(yourID).targetID = getTargetTarget(targetID);
addScore(yourID);
return userTargetInfo(yourID);
//return getTargetTargetStats(targetID);
}else{
return "INVALID";
}
}else{
return "DEAD"
}
}catch(err){
console.log("Error",console.log(players))
return "INVALID"
}
Edit: Since I had no time, I created 2 websites and divided the database into 2 different databases, so it would work under 100 people on each. Did not have time to fix the error at this point. So I won't be choosing the solution to that since I won't be trying that any time soon.
Thank you for all your help!
Check the link api that you are using , it might have pagination integrated with it . in that case i will return certain number of object 1st and then you can re-request to get next batch . Most likely they might have a option to change the no of object returned (sometimes with max value)
I'm pretty sure body is returned as a string. Try changing it to an object so you can work with it easier.
Change:
players = body;
to:
players = JSON.parse(body);
I'm not sure the rest of your code, but you may want to add var on your players variable declaration because this looks like the first time you are setting it.
Research: namespace collisions
If you are still having issues, edit your question to include the response you are getting from console.log(JSON.parse(body));. You will be able to get more helpful answers. Personally, I am curious to see the keys such as:
{ query:
{ count: 1,
created: '2017-04-23T22:03:31Z',
lang: 'en-US',
results: { channel: [Object] } } }
If it's paginated, you should see some kind of cursor key in there, or prev and next along with some kind of totalCount.
Hope this helps.

Implementing remove tweet and like/upvote functionality in Firebase

Continuing from this thread, on HN: https://news.ycombinator.com/item?id=5462769
Reading through the firefeed rules file answered a lot of questions for me, except for these two:
Editing an existing tweet isn't allowed (".write": "!data.exists()"). How can you make it not editable, but deletable by the author?
How would you securely handle liking/unliking or upvoting/downvoting? write if authenticated, validate for the increase/decrease by one, if the user hasn't modified this before? How would that work? Would there have to be a child list of people who edited this? I'm just really curious about this specific use case as it seems pretty common in many apps, yet seems to me, would be really complicated to implement in firebase?
1. Not editable but deletable by the author
".write": "!data.exists() || (!newData.exists() && data.child('author') === auth.id)"
2. Liking/Upvoting
On the client, use a transaction which allows you to increment the value safely:
ref.transaction(function(currentValue) {
return (currentValue||0)+1;
}, function(error) {
if( error ) /* failed too many times */
else /* it worked */
});
Security is also straightforward:
".validate": "newData.isNumber() && newData.val() === data.val()+1"
2.5 Ensuring Unique Votes
I'm not sure what this means; the records can't be edited and presumably if they could, only the author would be able to do so; so I don't really understand "modified" in this context: "if the user hasn't modified this before? How would that work?"
To ensure votes are unique, you just store them by user ID. The user can remove their vote by deleting the record.
I'd recommend storing these in a separate path than the sparks and still maintaining a simple increment (the messages that are getting voted up/down) as you don't want to have to retrieve the entire list of voters each time you fetch the spark.
The security rules would look like so:
"votes": {
"$spark_id": {
"$vote": {
".read": "$vote === auth.id",
".write": "$vote === auth.id",
// to allow downvoting in addition to up or delete, just add -1 here
".validate": "newData.val() === 1 || newData.val() === null"
}
}
}
And now add a check to the validate rule for the increment:
".validate": "!root.child('votes').child($spark_id).child(auth.id).exists() && newData.isNumber() && newData.val() === data.val()+1"
Now that Firebase Functions has been released (in beta) to the general public, it seems to be a good option: https://firebase.googleblog.com/2017/03/introducing-cloud-functions-for-firebase.html
The idea is to have each user be allowed to add their name, by key, to an "upvoters" collection for the tweet. They can create or delete their entry --
but there can only be one, since it's by-key and the security rule only allows control of their one key.
When finding of the "upvote count" is to take place, the client could get the full list of upvoters and tally the number. But instead, for performance's sake, we create a Firebase Function which is triggered whenever an upvote entry is added or removed.
All it does then is increase or decrease an "upvote count" property on the tweet. This is the same as before, except that we make a security rule that only lets the cloud-hosted Function modify this field. Thus, the modification is always trusted and safe, and removes the need for the client to receive the list of upvoters just to get the upvote-count.

Categories