-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbot_source_old_no2fa.js
1139 lines (927 loc) · 59.5 KB
/
bot_source_old_no2fa.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* WARNING
If there is an active offer in the database AND the items in the offer aren't in the bot inventory, the bot won't try to send it and it will remain active until the items in the offer (queue table in db) are in the inventory.
Please don't empty the bot's inventory when there are active offers in the database to avoid this problem.
You can see the active offers and how long they have been active in the admin panel on the site.
IF THERE ARE ERRORS WITH THE BOT PLEASE FIRST CHECK HTTP://STEAMSTAT.US TO SEE IF THE STEAM SERVERS ARE DOWN (steamcommunity, steamstore and cs:go services such as player inventories should be up for this to work properly)
*/
var admin = '76561198065442530'; //the id of the person that can use /commands and empty the bots inventory via chat etc
var logOnOptions = { //the bot's steam info
accountName: '',
password: ''
};
// EDIT THESE VARIABLES IN include/config.php AS WELL ON THE SITE!
var GameTime = 80; //round time in seconds (recommended: 120) //should make this 3-5 seconds longer than the one in config.php
var maxitems=10; //max items a player can deposit PER ROUND (recommended: 10)
var maxitemsinpot=50; //max items in pot (recommended: 50)
var minbet=0.5; //min value PER BET an user can deposit
//if you chance one of these variables ^ and you get any kind of errors on the site you may also want to check app.js in static/js/app.js
var accesspassword='anythingyoudonthavetorememberthisshit'; //you can set this to whatever you want as long as its matching the same variable in include/config.php (this is used to safely access endgame.php and cost.php)
var gamedbprefix='z_round_';
var offerssent=[]; //as long as the bot is running it adds the game ids in this array and checks it before sending an offer (another thing to stop multiple offers...). if the bot is restarted this is emptied
var itemprices={}; //as long as the bot is running it adds the item prices in this array, whenever it gets an item from this array it doesnt try to get it from the site (saves time, resources)
var sitename = "needforskins.com"; //site url WITH NO http:// in front of it and NO forward slash ( / ) after it
var steamstatusurl = 'http://'+sitename+'/steamstatus.php';
var contentcreatorsurl = 'http://'+sitename+'/cc.php';
var gamestarted='no';
var apik = ''; //steam api key, you can get one at https://steamcommunity.com/dev
////
var prf=gamedbprefix;
//when first logging in the bot you will receive an authentication code via e-mail and then the bot won't be able to trade for 7 days
var authCode = '1234ZZZ'; //this is the code you'll receive via e-mail when first logging in the bot
var globalSessionID;
if (require('fs').existsSync('sentry_' + logOnOptions['accountName'] + '.hash')) {
logOnOptions['shaSentryfile'] = require('fs').readFileSync('sentry_' + logOnOptions['accountName'] + '.hash');
} else if (require('fs').existsSync('ssfn_' + logOnOptions['accountName'])) {
var sha = require('crypto').createHash('sha1');
sha.update(require('fs').readFileSync('ssfn_' + logOnOptions['accountName']));
var sentry = new Buffer(sha.digest(), 'binary');
logOnOptions['shaSentryfile'] = sentry;
require('fs').writeFileSync('sentry_' + logOnOptions['accountName'] + '.hash', sentry);
myconsolelog('Converting ssfn to sentry file!');
myconsolelog('Now you can remove ssfn_' + logOnOptions['accountName']);
} else if (authCode != '') {
logOnOptions['authCode'] = authCode;
}
var Steam = require('steam'); //use npm install [email protected] - this code isn't compatible with the latest version.
var SteamTradeOffers = require('steam-tradeoffers'); //use npm install [email protected] - this code isn't compatible with the latest version.
var mysql = require('mysql');
var request = require("request");
//socket
var connections=0;
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
connections=connections+1;
// myconsolelog('[socket] a user connected. total connections: '+connections);
//
socket.emit('handshake',1);
socket.emit('online',connections);
request(steamstatusurl+'?pw='+accesspassword, function(error, response, body) {
//myconsolelog('steamstatus: '+body);
io.emit('steamstatus',body);
});
request(contentcreatorsurl+'?pw='+accesspassword, function(error, response, body) {
//myconsolelog('steamstatus: '+body);
io.emit('cc',body);
});
socket.on('disconnect', function(){
connections=connections-1;
// myconsolelog('[socket] user disconnected total connections: '+connections);
socket.emit('online',connections);
});
});
//
var mysqlInfo; //ENABLE REMOTE MYSQL IF THE DATABASE IS HOSTED ON ANOTHER SERVER THAN THE BOT (usually the case)
mysqlInfo = {
host: 'localhost',
user: '',
password: '',
database: '',
charset: 'utf8_general_ci'
};
var mysqlConnection = mysql.createConnection(mysqlInfo);
mysqlConnection.connect(function(err) {
if (err) {
myconsolelog('MYSQL ERROR. err.code: '+err.code+' (err.fatal: '+err.fatal+')');
myconsolelog('MYSQL ERROR. err.stack: '+err.stack);
return;
}
myconsolelog('Connected to MySQL database "'+mysqlInfo['database']+'" on host "'+mysqlInfo['host']+'". Connection id: ' + mysqlConnection.threadId);
});
var steam = new Steam.SteamClient();
var offers = new SteamTradeOffers();
var recheck = true;
steam.logOn(logOnOptions);
steam.on('debug', function(text) {
console.log(text);
require('fs').appendFile('debug.log', text + "\r\n");
});
function myconsolelog(text){
console.log(text);
require('fs').appendFile('bot_debug.log', text + "\r\n");
}
function getUserName(steamid) {
getUserInfo(steamid, function(error, data) {
if (error) throw error;
var datadec = JSON.parse(JSON.stringify(data.response));
return (cleanString(datadec.players[0].personaname));
});
}
function proceedWinners() {
var url = 'http://' + sitename + '/endgame.php?pw='+accesspassword;
request(url, function(error, response, body) {
myconsolelog('proceedwinners() callback response: '+body);
gamestarted='no';
io.emit('roundend',body);
});
}
function getUserInfo(steamids, callback) {
var url = 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=' + apik + '&steamids=' + steamids + '&format=json';
request({
url: url,
json: true
}, function(error, response, body) {
if (!error && response.statusCode === 200) {
callback(null, body);
} else if (error) {
getUserInfo(steamids, callback);
}
});
}
function addslashes(str) {
str = str.replace(/\\/g, '\\\\');
str = str.replace(/\'/g, '\\\'');
str = str.replace(/\"/g, '\\"');
str = str.replace(/\0/g, '\\0');
return str;
}
var locked = false,
proceeded;
var itemscopy;
var detected = false;
var detected2 = false;
var endtimer = -1;
function weblogon() {
steam.webLogOn(function(newCookie) {
offers.setup({
sessionID: globalSessionID,
webCookie: newCookie
}, function(err) {
if (err) {}
});
});
}
function sendoffers() {
myconsolelog('........');
myconsolelog('sendoffers() was called.');
detected2 = false;
offers.loadMyInventory({
appId: 730,
contextId: 2
}, function(err, itemx) {
if (err) {
myconsolelog('Tried checking offers: ERROR 1! (error while loading own inventory). Check if steam servers are down at http://steamstat.us');
weblogon();
setTimeout(sendoffers, 2000);
return;
}
if (detected2 == true) {
myconsolelog('Tried checking offers: ERROR 2! (detected2==true) Maybe its sent already?');
return;
}
if(itemx.length>0){ //sendoffers() cant work if the bot's inventory isnt being loaded (servers down)
myconsolelog(itemx.length+' items in inventory.');
}else{
myconsolelog('WARNING! '+itemx.length+' items in inventory. The inventory may actually be empty OR steam servers are down. Check http://steamstat.us');
}
detected2 = true;
itemscopy = itemx;
detected = false;
mysqlConnection.query('SELECT * FROM `queue` WHERE `status`=\'active\' ORDER BY `gameid` DESC LIMIT 1', function(err, row, fields) {
if (err) {
myconsolelog('Tried checking offers: ERROR 3! (mysql query error: '+err.stack+')');
return;
}
if (detected == true) {
myconsolelog('Tried checking offers: ERROR 4! (detected==true)');
return;
}
detected = true;
///AUG | Chameleon (Field-Tested)/Dual Berettas | Moon in Libra (Factory New)/AK-47 | Safari Mesh (Field-Tested)/XM1014 | Blue Spruce (Field-Tested)/G3SG1 | Polar Camo (Minimal Wear)
for (var y = 0; y < row.length; y++) {
myconsolelog('Y: '+y+' Processing offer '+row[y].id+' for game '+row[y].gameid);
if(!in_array(row[y].gameid,offerssent)){
if(row[y].token.length<5){
myconsolelog('Token is: '+row[y].token+' which seems to be incorrect. Stopping the process...');
myconsolelog('The "token" is the last part in trade url and it is 6 characters long, maybe user hasn\'t set his trade url in the database. Check user with steam id '+row[y].userid);
}
var queueid = row[y].id;
var gameid = row[y].gameid;
var theuserid = row[y].userid;
var thetoken = row[y].token;
var theitems=row[y].items;
var sendItems = (row[y].items).split('/');
var item = [],
queries = [],
itemstobesent = '',
itemidsintheoffer = [],
num = 0;
for (var x = 0; x < itemscopy.length; x++) {
(function(z){ //fucking bullshit asynchronous crap
mysqlConnection.query('SELECT * FROM `sentitems` WHERE `itemid`=\''+itemscopy[z].id+'\'', function(errz, rowz, fieldsz) {
if (errz) {
myconsolelog('Q:'+queueid+'/G:'+gameid+'/ Error while trying to check for sent items (mysql query error: '+errz.stack+')');
return;
}
itemscopy[z].market_name=itemscopy[z].market_name.replace('★','★');
itemscopy[z].market_name=itemscopy[z].market_name.replace('龍王','??');
itemscopy[z].market_name=itemscopy[z].market_name.replace('壱','?');
var countitems=rowz.length;
for (var j = 0; j < sendItems.length; j++) {
if (itemscopy[z].tradable && (itemscopy[z].market_name).indexOf(sendItems[j]) == 0) {
if(!(countitems>0)){
item[num] = {
appid: 730,
contextid: 2,
amount: 1, //was itemscopy[z].amount ?
assetid: itemscopy[z].id
}
itemstobesent=itemstobesent+''+itemscopy[z].market_name+'/';
queries[num]='INSERT INTO `sentitems` (`itemid`,`name`,`gameid`,`queueid`,`userid`) VALUES ("'+itemscopy[z].id+'","'+itemscopy[z].market_name.replace('龍王','??')+'","'+gameid+'","'+queueid+'","'+theuserid+'")';
myconsolelog('Q:'+queueid+'/G:'+gameid+'/ '+'Added '+itemscopy[z].market_name+' in the list for sending ('+queueid+'/G:'+gameid+'/Z:'+z+')');
sendItems[j] = "empty";
itemscopy[z].market_name = "emptyagain";
num++;
}else{
myconsolelog('Q:'+queueid+'/G:'+gameid+'/Z:'+z+' '+itemscopy[z].market_name+' with id '+itemscopy[z].id+' was already sent in another offer. looking for another item...');
}
}
}
if(num==sendItems.length){
myconsolelog(num+'=='+sendItems.length);
//myconsolelog('Gone through all the items TRYING to send the offer now. Result: num: '+num+'; sendItems.length: '+sendItems.length);
offers.makeOffer({
partnerSteamId: theuserid,
itemsFromMe: item,
accessToken: thetoken,
itemsFromThem: [],
message: 'Congratulations! You won a round on '+sitename+'! These are the winnings from round #' + gameid
}, function(err, response) {
if (err) {
//myconsolelog('Q:'+queueid+'/G:'+gameid+'/ '+y+'(y) / '+z+'(z) / '+j+' (j) / '+x+' (x) / '+num+' (num) / '+sendItems.length+' (sendItems.length) / '+item+' (item)');
myconsolelog('Q:'+queueid+'/G:'+gameid+'/ '+'(ERROR) Tried sending offers: Token: '+thetoken+'; USERID: '+theuserid+'; items: '+itemstobesent+' (steam servers down? too many offers sent already? empty token (from trade link) in database? check pls). ' + err + '. https://github.com/SteamRE/SteamKit/blob/master/Resources/SteamLanguage/eresult.steamd');
//myconsolelog('Trying sendoffers again in 2 seconds...');
//setTimeout(sendoffers, 2000);
return;
}
offerssent[gameid]=gameid; //add it to the array
//myconsolelog('Q:'+queueid+'/G:'+gameid+'/ '+y+'(y) / '+z+'(z) / '+j+' (j) / '+x+' (x) / '+num+' (num) / '+sendItems.length+' (sendItems.length) / '+item+' (item)');
myconsolelog('Q:'+queueid+'/G:'+gameid+'/ '+'Trade offer ' + queueid + ' (game '+gameid+') sent! Marking items as sent in the database....');
var thetheitems=theitems.replace(/\/$/, '');
var theitemstobesent=itemstobesent.replace(/\/$/, '');
var numtheitems = (thetheitems).split('/').length;
var numitemstobesent = (theitemstobesent).split('/').length;
if(numtheitems!=numitemstobesent){
myconsolelog('Q:'+queueid+'/G:'+gameid+'/ '+'WARNING !!! Sent '+numtheitems+' items! Needed to send '+numitemstobesent+'!!!');
myconsolelog('Sent ('+numtheitems+'): '+thetheitems);
myconsolelog('Needed to send ('+numitemstobesent+'): '+theitemstobesent);
}else{
myconsolelog('Q:'+queueid+'/G:'+gameid+'/ '+'ALL IS GOOD! Sent '+numtheitems+' items! Needed to send '+numitemstobesent+'.');
}
//myconsolelog('Tried sending: '+thetheitems+'. Ended up sending: '+theitemstobesent);
for(bla=0;bla<queries.length;bla++){
mysqlConnection.query(queries[bla], function (blaerr, blarows, blafields){
if(blaerr) {
throw blaerr;
}
myconsolelog('Q:'+queueid+'/G:'+gameid+'/ '+'SUCCESS marking the item as sent in the database.');
});
}
myconsolelog('Q:'+queueid+'/G:'+gameid+'/ '+'Calling sendoffers again in 2 seconds...');
setTimeout(sendoffers, 2000);
mysqlConnection.query('UPDATE `queue` SET `status`=\'sent ' + response.tradeofferid + '\' WHERE `id`=\'' + queueid + '\'', function(err, row, fields) {
if (err) throw err;
});
});
num++; //avoid running this multiple times when the loop runs
}
});
})(x);
}
}else{
myconsolelog('Tried processing game '+row[y].gameid+' (queue '+row[y].id+') again? Check the queues in the database...');
}
}
});
})
}
function cleanString(input) {
var output = "";
for (var i=0; i<input.length; i++) {
if (input.charCodeAt(i) <= 127) {
output += input.charAt(i);
}
}
return output;
}
(function() {
/**
* Decimal adjustment of a number.
*
* @param {String} type The type of adjustment.
* @param {Number} value The number.
* @param {Integer} exp The exponent (the 10 logarithm of the adjustment base).
* @returns {Number} The adjusted value.
*/
function decimalAdjust(type, value, exp) {
// If the exp is undefined or zero...
if (typeof exp === 'undefined' || +exp === 0) {
return Math[type](value);
}
value = +value;
exp = +exp;
// If the value is not a number or the exp is not an integer...
if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
return NaN;
}
// Shift
value = value.toString().split('e');
value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
// Shift back
value = value.toString().split('e');
return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
}
// Decimal round
if (!Math.round10) {
Math.round10 = function(value, exp) {
return decimalAdjust('round', value, exp);
};
}
// Decimal floor
if (!Math.floor10) {
Math.floor10 = function(value, exp) {
return decimalAdjust('floor', value, exp);
};
}
// Decimal ceil
if (!Math.ceil10) {
Math.ceil10 = function(value, exp) {
return decimalAdjust('ceil', value, exp);
};
}
})();
function EndGame() {
endtimer = -1;
proceedWinners();
myconsolelog('EndGame was called... (EndGame ends the timer, proceedWinners(), sendoffers())');
setTimeout(sendoffers, 2000);
}
function loadinventory(){
offers.loadMyInventory({
appId: 730,
contextId: 2
}, function(err, itemx) {
if (err) {
myconsolelog('Error on loading inventory. '+err+'. Calling weblogon(). Calling loadinventory again after 2 seconds... (if this persists check the api key or check if steam servers are down at http://steamstat.us)');
weblogon();
setTimeout(loadinventory,3500);
return;
}
setTimeout(function(){ checkoffers(1); },3500);
myconsolelog('Own inventory loaded successfully. Items list in itemx var.');
if(itemx.length>0){
myconsolelog(itemx.length+' items in inventory.');
}else{
myconsolelog('WARNING! '+itemx.length+' items in inventory. The inventory may actually be empty OR steam servers are down. Check http://steamstat.us');
}
//myconsolelog(itemx);
});
}
steam.on('loggedOn', function(result) {
myconsolelog('Logged in on Steam!');
steam.setPersonaState(Steam.EPersonaState.LookingToTrade);
steam.addFriend(admin);
steam.sendMessage(admin, "I'm online now.");
loadinventory();
});
steam.on('webSessionID', function(sessionID) {
globalSessionID = sessionID;
weblogon();
setTimeout(function() {
mysqlConnection.query('SELECT `value` FROM `info` WHERE `name`=\'current_game\'', function(err, rows, fields) {
if (err) return;
mysqlConnection.query('SELECT `starttime` FROM `games` WHERE `id`=\'' + rows[0].value + '\'', function(errs, rowss, fieldss) {
if (errs) return;
var timeleft;
if (rowss[0].starttime == 2147483647) timeleft = GameTime;
else {
var unixtime = Math.round(new Date().getTime() / 1000.0);
timeleft = rowss[0].starttime + GameTime - unixtime;
if (timeleft < 0) timeleft = 0;
}
if (timeleft != GameTime) {
setTimeout(EndGame, timeleft * 1000);
io.emit('roundstart','1');
gamestarted='yes';
myconsolelog('Restoring game on ' + timeleft + 'second');
}
});
});
}, 1500);
});
steam.on('friendMsg', function(steamID, message, type) {
if (type != Steam.EChatEntryType.ChatMsg) return;
if (steamID == admin) {
if (message.indexOf("/sendallitems") == 0) {
offers.loadMyInventory({
appId: 730,
contextId: 2
}, function(err, items) {
if (err) {
steam.sendMessage(steamID, 'Error while trying to load invenotry to send items. Calling weblogon() - try again please.');
myconsolelog('Error while trying to load inventory to send items. Calling weblogon() - try again please.');
weblogon();
return;
}
var item = [],
num = 0;
for (var i = 0; i < items.length; i++) {
if (items[i].tradable) {
item[num] = {
appid: 730,
contextid: 2,
amount: items[i].amount,
assetid: items[i].id
}
num++;
}
}
if (num > 0) {
offers.makeOffer({
partnerSteamId: steamID,
itemsFromMe: item,
itemsFromThem: [],
message: 'You requested all the items with the /sendallitems command.'
}, function(err, response) {
if (err) {
steam.sendMessage(steamID, 'Error while trying to send offer with items. Calling weblogon() - try again please.');
myconsolelog('Error while trying to send offer with items. Calling weblogon() - try again please.');
weblogon();
return;
}
steam.sendMessage(steamID, 'Trade offer with all items from the inventory sent!');
myconsolelog('Offer from /sendallitems request sent to '+steamID);
});
}
});
} else if (message.indexOf("/send") == 0) {
var params = message.split(' ');
if (params.length == 1) return steam.sendMessage(steamID, 'Format: /send [item name]');
myconsolelog('Received /send request');
offers.loadMyInventory({
appId: 730,
contextId: 2
}, function(err, items) {
if (err) {
steam.sendMessage(steamID, 'Could not load the inventory. Calling weblogon() - try again please.');
myconsolelog('Could not load the inventory. Calling weblogon() - try again please.');
weblogon();
return;
}
var item = 0;
for (var i = 0; i < items.length; i++) {
if ((items[i].market_name).indexOf(params[1]) != -1) {
item = items[i].id;
break;
}
}
if (item != 0) {
offers.makeOffer({
partnerSteamId: steamID,
itemsFromMe: [{
appid: 730,
contextid: 2,
amount: 1,
assetid: item
}],
itemsFromThem: [],
message: 'You requested this item with the /send command.'
}, function(err, response) {
if (err) {
throw err;
}
steam.sendMessage(steamID, 'Trade offer with the requested item sent!');
myconsolelog('Offer from /send request sent to '+steamID);
});
}else{
steam.sendMessage(steamID, 'Couldn\'t match the item requested! /send is case sensitive!');
myconsolelog('Couldn\'t match the item selected by '+steamID);
}
});
} else if (message.indexOf("/show") == 0) {
var params = message.split(' ');
offers.loadMyInventory({
appId: 730,
contextId: 2
}, function(err, items) {
if (err) {
steam.sendMessage(steamID, '(2) Could not load the inventory. Calling weblogon() - try again please.');
myconsolelog('(2) Could not load the inventory. Calling weblogon() - try again please.');
weblogon();
return;
}
steam.sendMessage(steamID, 'Items list: ');
for (var i = 0; i < items.length; i++) {
steam.sendMessage(steamID, 'http://steamcommunity.com/id/tradecschance1/inventory/#' + items[i].appid + '_' + items[i].contextid + '_' + items[i].id);
}
});
} else if (message.indexOf("/end") == 0) {
steam.sendMessage(steamID, 'Got request to end the game (/end)');
if (endtimer != -1) clearTimeout(endtimer);
EndGame();
} else if (message.indexOf("/so") == 0) {
steam.sendMessage(steamID, 'Got request to send pending offers (/so)');
sendoffers();
} else if (message.indexOf("/co") == 0) {
steam.sendMessage(steamID, 'Got request to check incomming offers (/co)');
checkoffers(1);
} else {
steam.sendMessage(steamID, 'Available commands:\r\n/co - checks incomming offers\r\n/so - sends pending offers (calls sendoffers())\r\n/end - ends the game (clears timeout endtimer, calls EndGame())\r\n/show - displays all the items in the inventory\r\n/send [item] - sends trade offer with [item]\r\n/sendallitems - sends offer with all the items in the inventory (it breaks active offers, only use it when there are no active offers)');
myconsolelog('Displayed available commands to '+steamID);
}
}
getUserInfo(steamID, function(error, data) {
if (error) throw error;
var datadec = JSON.parse(JSON.stringify(data.response));
var name = datadec.players[0].personaname;
myconsolelog(name + ': ' + message); // Log it
});
//steam.sendMessage(steamID, 'I\'m a bot that accepts all your unwanted items. If you would like to grab a few crates from me, please request a trade.');
});
function in_array(needle, haystack, strict) {
var found = false,
key, strict = !!strict;
for (key in haystack) {
if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
found = true;
break;
}
}
return found;
}
var declinedoffer=false;
function checkoffers(thenumber) {
declinedoffer=false;
myconsolelog('Checking for offers...');
if (thenumber > 0) {
offers.getOffers({
get_received_offers: 1,
active_only: 1,
get_sent_offers: 0,
get_descriptions: 1,
language: "en_us"
}, function(error, body) {
myconsolelog('Trade offers not empty... '+thenumber);
if (error) {
myconsolelog('Error getting offers. Steam servers down? Error: '+error);
return;
}
if (body.response.trade_offers_received) {
body.response.trade_offers_received.forEach(function(offer) {
if (offer.trade_offer_state == 2) {
myconsolelog('Trade offer incomming...');
myconsolelog('Trade offer id '+offer.tradeofferid+' from '+offer.steamid_other);
if (offer.items_to_give) {
myconsolelog('Trade declined (items requested from the bot inventory)');
offers.declineOffer({
tradeOfferId: offer.tradeofferid
});
return;
}
myconsolelog('dbg 1');
if (offer.items_to_receive == undefined){
myconsolelog('Undefined items_to_receive. Retrying checkoffers...');
weblogon();
setTimeout(function(){ checkoffers(1) },3500);
return;
}
myconsolelog('dbg 2');
mysqlConnection.query('SELECT `value` FROM `info` WHERE `name`=\'current_game\'', function(err, row, fields) {
if(err) throw err;
myconsolelog('dbg 3');
var current_game = row[0].value;
mysqlConnection.query('SELECT COUNT(*) AS `totalitems` FROM `'+prf+current_game+'`', function(totalerr, totalres, totalfields){
if(totalerr) throw totalerr;
if(totalres.totalitems>maxitemsinpot){
myconsolelog('Trade declined (pot reached limit)');
offers.declineOffer({
tradeOfferId: offer.tradeofferid
});
offer.items_to_receive = [];
var unixtime = Math.round(new Date().getTime() / 1000.0);
//mysqlConnection.query('INSERT INTO `messages` (`userid`,`msg`,`from`, `win`, `system`, `time`) VALUES (\'' + offer.steamid_other + '\',\'too much items\',\'System\', \'0\', \'1\', \'' + unixtime + '\')', function(err, row, fields) {});
var messagedata={to:offer.steamid_other,msg:'Trade declined. The pot reached the maximum limit of '+maxitemsinpot+' items. Deposit again next round.',time:unixtime,type:'toomanyitems'};
io.emit('message',messagedata);
myconsolelog('[socket] too many items message sent to '+offer.steamid_other);
declinedoffer=true;
return;
}else{
mysqlConnection.query('SELECT COUNT(*) AS `usersitems` FROM `'+prf+current_game+'` WHERE `userid`=\''+offer.steamid_other+'\'', function(errs, rows, fieldss) {
if(errs) throw errs;
myconsolelog('dbg 4');
if (offer.items_to_receive.length > maxitems || offer.items_to_receive.length+rows[0].usersitems > maxitems) {
myconsolelog('Trade declined (too many items)');
offers.declineOffer({
tradeOfferId: offer.tradeofferid
});
offer.items_to_receive = [];
var unixtime = Math.round(new Date().getTime() / 1000.0);
//mysqlConnection.query('INSERT INTO `messages` (`userid`,`msg`,`from`, `win`, `system`, `time`) VALUES (\'' + offer.steamid_other + '\',\'too much items\',\'System\', \'0\', \'1\', \'' + unixtime + '\')', function(err, row, fields) {});
var messagedata={to:offer.steamid_other,msg:'Trade declined. You offered too many items. Max '+maxitems+' items per round!',time:unixtime,type:'toomanyitems'};
io.emit('message',messagedata);
myconsolelog('[socket] too many items message sent to '+offer.steamid_other);
declinedoffer=true;
return;
}
myconsolelog('dbg 5');
});
}
myconsolelog('dbg 5.5');
});
myconsolelog('dbg 6');
});
myconsolelog('dbg 7');
var delock = false;
offers.loadPartnerInventory({
partnerSteamId: offer.steamid_other,
appId: 730,
contextId: 2,
tradeOfferId: offer.tradeofferid,
language: "en"
}, function(err, hitems) {
myconsolelog('dbg 8');
if (err) {
myconsolelog('Error loading partnerinventory. Calling weblogon and trying again.');
setTimeout(function(){ checkoffers(1) },3500);
weblogon();
recheck = true;
return;
}
myconsolelog('dbg 9');
if (delock == true) return;
delock = true;
var items = offer.items_to_receive;
var wgg = [],
num = 0;
for (var i = 0; i < items.length; i++) {
for (var j = 0; j < hitems.length; j++) {
if (items[i].assetid == hitems[j].id) {
wgg[num] = hitems[j];
num++;
break;
}
}
}
myconsolelog('dbg 10');
var price = [];
for (var i = 0; i < num; i++) {
if (wgg[i].appid != 730 && !declinedoffer) { //got other items than cs items
myconsolelog('Trade declined (got other items than cs items)');
offers.declineOffer({
tradeOfferId: offer.tradeofferid
});
var unixtime = Math.round(new Date().getTime() / 1000.0);
//mysqlConnection.query('INSERT INTO `messages` (`userid`,`msg`,`from`, `win`, `system`, `time`) VALUES (\'' + offer.steamid_other + '\',\'only csgo items\',\'System\', \'0\', \'1\', \'' + unixtime + '\')', function(err, row, fields) {});
var messagedata={to:offer.steamid_other,msg:'Trade declined. You offered something else than CS:GO items!',time:unixtime,type:'otheritems'};
io.emit('message',messagedata);
myconsolelog('[socket] got other items than cs items message sent to '+offer.steamid_other);
declinedoffer=true;
return;
}
myconsolelog('dbg 11');
if (wgg[i].market_name.indexOf("Souvenir") != -1 && !declinedoffer) {
var unixtime = Math.round(new Date().getTime() / 1000.0);
myconsolelog('Trade declined (got souvenir items)');
offers.declineOffer({
tradeOfferId: offer.tradeofferid
});
//mysqlConnection.query('INSERT INTO `messages` (`userid`,`msg`,`from`, `win`, `system`, `time`) VALUES (\'' + offer.steamid_other + '\',\'You cant bet souvenir weapons\',\'System\', \'0\', \'1\', \'' + unixtime + '\')', function(err, row, fields) {});
var messagedata={to:offer.steamid_other,msg:'Trade declined. You cannot deposit souvenir items!',time:unixtime,type:'souvenir'};
io.emit('message',messagedata);
myconsolelog('[socket] got souvenir items message sent to '+offer.steamid_other);
declinedoffer=true;
return;
}
myconsolelog('dbg 12');
/*
if (!declinedoffer && wgg[i].market_name.indexOf("Weapon Case") != -1 || wgg[i].market_name == 'Chroma 2 Case' || wgg[i].market_name == 'Chroma Case' || wgg[i].market_name == 'eSports 2013 Winter Case' || wgg[i].market_name == 'Falchion Case' || wgg[i].market_name.indexOf("Sticker Capsule") != -1) {
var unixtime = Math.round(new Date().getTime() / 1000.0);
offers.declineOffer({
tradeOfferId: offer.tradeofferid
});
//mysqlConnection.query('INSERT INTO `messages` (`userid`,`msg`,`from`, `win`, `system`, `time`) VALUES (\'' + offer.steamid_other + '\',\'You cant bet weapon cases\',\'System\', \'0\', \'1\', \'' + unixtime + '\')', function(err, row, fields) {});
myconsolelog('Trade declined (received weapon case... ' + wgg[i].market_name+')');
var messagedata={to:offer.steamid_other,msg:'Trade declined. You cannot deposit weapon cases!',time:unixtime,type:'weaponcase'};
io.emit('message',messagedata);
myconsolelog('[socket] got weapon cases message sent to '+offer.steamid_other);
declinedoffer=true;
return;
}
*/
myconsolelog('dbg 13');
var itemname = wgg[i].market_name;
var url = 'http://' + sitename + '/cost.php?pw='+accesspassword+'&item=' + encodeURIComponent(itemname);
if(!declinedoffer){
myconsolelog('dbg 14');
(function(someshit) {
if(!(itemname in itemprices)){
request(url, function(error, response, body) {
if (!error && response.statusCode === 200) {
var unixtime = Math.round(new Date().getTime() / 1000.0);
if (body == "notfound") {
offers.declineOffer({
tradeOfferId: offer.tradeofferid
});
myconsolelog('Trade declined. Item not found (notfound response when trying to get item cost).');
//mysqlConnection.query('INSERT INTO `messages` (`userid`,`msg`,`from`, `win`, `system`, `time`) VALUES (\'' + offer.steamid_other + '\',\'Item not available \',\'System\', \'0\', \'1\', \'' + unixtime + '\')', function(err, row, fields) {});
var messagedata={to:offer.steamid_other,msg:'Trade declined. An item you sent is unavailable ('+wgg[someshit].market_name+')!',time:unixtime,type:'itemunavailable'};
io.emit('message',messagedata);
myconsolelog('[socket] item unavailable message sent to '+offer.steamid_other);
} else if (body == "unauthorized") {
offers.declineOffer({
tradeOfferId: offer.tradeofferid
});
myconsolelog('Trade declined. Could not get price for item (unauthorized acces when accessing cost.php on the server. Check if accesspassword variable is set accordingly in bot_source.js (see include/config.php on site)');
//mysqlConnection.query('INSERT INTO `messages` (`userid`,`msg`,`from`, `win`, `system`, `time`) VALUES (\'' + offer.steamid_other + '\',\'Item not available \',\'System\', \'0\', \'1\', \'' + unixtime + '\')', function(err, row, fields) {});
var messagedata={to:offer.steamid_other,msg:'Trade declined. Unknown error please try again or contact an administrator!',time:unixtime,type:'unauthorized'};
io.emit('message',messagedata);
myconsolelog('[socket] item cost unknown error message sent to '+offer.steamid_other);
} else {
wgg[someshit].cost = parseFloat(body);
itemprices[wgg[someshit].market_name]=wgg[someshit].cost;
myconsolelog('Got item price from site: ' + wgg[someshit].market_name + ' = ' + body);
}
} else {
offers.declineOffer({
tradeOfferId: offer.tradeofferid
});
myconsolelog('Declined offer (error on getting price on ' + wgg[someshit].market_name + ')');
var messagedata={to:offer.steamid_other,msg:'Trade declined. We could not get the price on one of your items ('+wgg[someshit].market_name+')!',time:unixtime,type:'priceerror'};
io.emit('message',messagedata);
myconsolelog('[socket] couldnt get price on item message sent to '+offer.steamid_other);
}
});
}else{
myconsolelog('Got item price from local array. '+wgg[someshit].market_name+' = '+itemprices[wgg[someshit].market_name]);
wgg[someshit].cost=parseFloat(itemprices[wgg[someshit].market_name]);
}
})(i)
}else{
myconsolelog('dbg 15');
myconsolelog('declinedoffer is true apparently? declinedoffer: '+declinedoffer)
return;
}
}
if(!declinedoffer)
setTimeout(function() { // UNDEFINED PRICES? LOOK AT THIS! ITS GLIZDA!
myconsolelog('Timeout step 1...');
var sum = 0;
for (var i = 0; i < num; i++) {
sum += wgg[i].cost;
}
myconsolelog('Timeout step 1.2...');
if (sum < minbet && !declinedoffer) {
num = 0;
var unixtime = Math.round(new Date().getTime() / 1000.0);
offers.declineOffer({
tradeOfferId: offer.tradeofferid
});
myconsolelog('Trade declined, value was too small.');
//mysqlConnection.query('INSERT INTO `messages` (`userid`,`msg`,`from`, `win`, `system`, `time`) VALUES (\'' + offer.steamid_other + '\',\'Value is too small. ' + sum + '<' + row[0].value + '\',\'System\', \'0\', \'1\', \'' + unixtime + '\')', function(err, row, fields) {});
var messagedata={to:offer.steamid_other,msg:'Trade declined. The value of your items was too small ($'+sum+')! Min $'+minbet+' per bet.',time:unixtime,type:'priceerror'};
io.emit('message',messagedata);
myconsolelog('[socket] value too small message sent to '+offer.steamid_other);
declinedoffer=true;
return;
}
myconsolelog('Timeout step 1.3... (next: getuserinfo) - if this hangs up too long then steam servers are probably fucking up: getUserInfo('+offer.steamid_other);
getUserInfo(offer.steamid_other, function(error, data) {
myconsolelog('Timeout step 1.4...');
if (error) throw error;
myconsolelog('Timeout step 2...');
var datadec = JSON.parse(JSON.stringify(data.response));
var name = addslashes(cleanString(datadec.players[0].personaname));
var avatar = (datadec.players[0].avatarfull);
if (num == 0) return;
offers.acceptOffer({
tradeOfferId: offer.tradeofferid
}, function(err, response) {
if (err != null){
myconsolelog('Erorr while accepting offer (?) Calling weblogon and checking offers again in 2 seconds...'+err);
weblogon();
setTimeout(function(){ checkoffers(1) },2000);
return;
}
myconsolelog('Accepted trade offer #' + offer.tradeofferid + ' by ' + name + ' (' + offer.steamid_other + ')');
mysqlConnection.query('SELECT `value` FROM `info` WHERE `name`=\'current_game\'', function(err, row, fields) {
if(err) throw err;
var restosocket={};
restosocket.newitems=[];
var current_game = row[0].value;
restosocket.current_game = current_game;
mysqlConnection.query('SELECT `totalvalue`,`itemsnum` FROM `games` WHERE `id`=\'' + current_game + '\'', function(err1, row1, fields1) {
var current_bank = parseFloat(row1[0].totalvalue);
var itemsnum = row1[0].itemsnum;
for (var j = 0; j < num; j++) {
restosocket.newitems[j]={};
var qualityclasssplit=wgg[j].type.split(' ');
var qc=qualityclasssplit[0].toLowerCase();
var qcdb;
/* consumer, industrial, mil-spec, restricted, classified, covert, knife, contraband */
if(qc=='consumer' || qc=='base'){
qcdb='1consumer';
}else if (qc=='industrial'){