This repository was archived by the owner on Aug 10, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathchatBot.js
More file actions
1139 lines (1015 loc) · 42.9 KB
/
chatBot.js
File metadata and controls
1139 lines (1015 loc) · 42.9 KB
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
var ver = "2.4.0-beta"; //update this before pushing to master.
var fs = require("fs");
var steam = require("steam");
var winston = require("winston");
var _ = require("lodash");
var SteamTrade = require('steam-trade');
var http = require("http");
var Express = require('express');
var expressWinston = require('express-winston');
var TriggerFactory = require("./triggerFactory.js").TriggerFactory;
var qs = require('qs');
var crypto = require('crypto');
var SteamWebLogon = require('steam-weblogon');
var GetSteamApiKey = require('steam-web-api-key');
var GetInterface = require('steam-web-api');
//keep track of crap that's loaded later
//var colors=require('colors/safe'); //colors is used by winston anyways, iirc, so this shouldn't be an extra dependency
//var io = require('socket.io');
var serversFile = "servers";
// Load latest servers from file
if (fs.existsSync(serversFile)) {
try {
winston.silly("Init: Attempting to read servers file");
steam.servers = JSON.parse(fs.readFileSync(serversFile));
} catch(err) {
winston.error("Init: Error reading serversFile:",err.stack);
}
} else {
winston.warn("Init: No servers file found, using defaults");
}
var wcfg = { //define some extra logLevels for winston, also colors
levels: {
spam: 0,
protocol: 1,
silly: 2,
verbose: 3,
info: 4,
data: 5,
warn: 6,
debug: 7,
error: 8,
failure: 9
},
colors: {
spam:'bold',
protocol:'grey',
silly:'magenta',
verbose:'cyan',
info:'green',
data:'gray',
warn:'yellow',
debug:'blue',
error:'red',
failure:'rainbow'
}
}
// Bot should be usually created without options, it is a parameter mainly for testing
var ChatBot = function(username, password, options) {
var that = this;
this._gitVersionString();
if(username instanceof Object) {
options = username;
if(options.username) username = options.username;
if(options.password) password = options.password;
}
this.options = options || {};
this.winston = new (winston.Logger)({
levels:wcfg.levels,
colors: options.winstonColors||wcfg.colors
});
this.steamClient = options.client || new steam.SteamClient();
this.steamUser = options.user || new steam.SteamUser(this.steamClient);
this.steamFriends = options.friends || new steam.SteamFriends(this.steamClient);
this.steamTrading = options.trading || new steam.SteamTrading(this.steamClient);
this.steamWebLogon = new SteamWebLogon(this.steamClient, this.steamUser);
this.steamTrade = new SteamTrade();
this.name = options.name || username;
this.username = username;
this.password = password;
if(options.guardCode) {
this.guardCode = options.guardCode;
} else {
this.guardCode = undefined;
}
if(options.twoFactorAuth instanceof Function) {
this.twoFactorAuth = options.twoFactorAuth;
} else if (options.twoFactorAuth) {
this.twoFactorAuth = function(){ return options.twoFactorAuth };
} else {
this.twoFactorAuth = function(){ return undefined; };
}
this.apikey = options.steamapikey || undefined;
this.games = [];
this.logFile = undefined;
this.cookie = undefined;
this.ignores = options.ignores || [];
this.startTime = process.hrtime();
this.logoffTime = process.hrtime();
this.autojoinRooms = undefined;
if(!fs.existsSync(this.name)) { fs.mkdirSync(this.name); }
this.sentryFile = options.sentryFile || this.name+"/bot."+this.name+".sentry";
this.autojoinFile = options.autojoinFile || this.name+"/bot." + this.name+".autojoin";
this.logFile = options.hasOwnProperty('logFile') ? options.logFile : this.name+"/bot."+this.name+".log";
if (this.logFile===undefined||this.logFile===true) { this.logFile = this.name+"/bot."+this.name+".log"; }
this.winston.add(winston.transports.Console,{
handleExceptions: false,
colorize: options.consoleColors||true,
timestamp: options.consoleTime||true,
level: options.consoleLogLevel||"info",
json: false
});
if(!fs.existsSync(this.name+"/firstRun")) {
var c = require('colors/safe');
console.error(c.white.bgBlack('=================='));
console.error(c.bgBlack.cyan("The location and names of default files has been changed."));
console.error(c.bgBlack.cyan("All files (including sentries) should now either be located in the default bot folder with the default name, or should be specified in the config. Sentry location logic has been removed. You can continue to store the config file wherever you like."));
console.error(c.bgBlack.cyan("The default folder is the bot's `name`, which defaults to the username but can be changed in the constructor. \n"));
console.error(c.bgBlack.cyan("Default filenames for this bot are as follows:"));
var t = function(a,b){
console.error(" "+c.bgBlack.magenta(a)+c.bgBlack.cyan(" : ")+c.bgBlack.green(b));
}
t("sentryFile ",this.name+"/bot."+this.name+".autojoin");
t("autojoinFile",this.name+"/bot."+this.name+".sentry");
t("logFile ",this.name+"/bot."+this.name+".log");
t("servers* ","servers");
console.error();
console.error(c.bgBlack.cyan("*The servers file is an exception, as it is not specific to any one bot."));
console.error(c.bgBlack.cyan("Individual triggers that have not yet moved their default storage location will have it moved in a coming release."));
console.error(c.bgBlack.cyan("This message will not appear again."));
console.error(c.white.bgBlack('=================='));
fs.writeFileSync(this.name+"/firstRun","The presence of this file indicates that you received a message regarding the new default location of bot files.");
process.exit();
}
if(!this.logFile===false) {
this.winston.info(this.name+"/chatBot.js: logging output to: " + this.logFile);
this.winston.add(
winston.transports.File, {
level: options.logLevel || "info",
colorize:false,
timestamp:true,
filename: that.logFile,
json:false
}
);
}
if(fs.existsSync(this.sentryFile)) {
this.winston.info(this.name+"/chatBot.js: using sentryFile "+this.sentryFile);
} else {
this.winston.warn(this.name+"/chatBot.js: sentryFile does not exist. "+this.sentryFile+" will be created on successful login");
}
this.connected = false; // Bot is connected to the steam network
this.muted = false; // Should not send any messages to a chat room when muted
this.winston.silly(this.name+"/chatBot.js: Starting webserver");
if(!options.disableWebserver) {
this._startWebServer(options.webServerPort||8080);
}
this.winston.silly(this.name+"/chatBot.js: Starting triggerFactory");
this.triggers = {};
if (options.triggerFactory) {
this.triggerFactory = options.triggerFactory;
} else {
this.triggerFactory = new TriggerFactory();
}
this.unmutedState = steam.EPersonaState.Online;
this.mutedState = steam.EPersonaState.Snooze;
if(options.onLogon instanceof Function) {
this.onLogon = options.onLogon;
}
//Steam-client events
this.steamClient.on("error", function() { that._onError(); });
this.steamClient.on("logOnResponse", function(res) { that._onLogOnResponse(res); that.onLogon(that); that.triggerLoggedOn(); });
this.steamClient.on("loggedOff", function(eresult) { that._onDisconnected(eresult); that.triggerLoggedOff(); });
this.steamClient.on('connected', function() { that._onConnected(); });
this.steamClient.on('message', function(header, body, cb) { that._onMessage(header, body, cb) });
//Steam-user events
this.steamUser.on("updateMachineAuth", function(sentry, cb) { that._onUpdateMachineAuth(sentry, cb); });
this.steamUser.on('tradeOffers', function(number) { that._onTradeOffers(number); });
//Steam-friends events
this.steamFriends.on("chatInvite", function(roomId, roomName, inviterId) { that._onChatInvite(roomId, roomName, inviterId); });
this.steamFriends.on("friend", function(userId, relationship) { that._onRelationship(userId, relationship); });
this.steamFriends.on("friendMsg", function(userId, message, type) { that._onFriendMsg(userId, message, type); });
this.steamFriends.on("chatMsg", function(roomId, message, type, chatterId) { that._onChatMsg(roomId, message, type, chatterId); });
this.steamFriends.on("chatStateChange", function(stateChange, chatterActedOn, steamChatId, actedOnBy) { that._onChatStateChange(stateChange, chatterActedOn, steamChatId, actedOnBy); });
//this.steamFriends.on('clanState', function(res) { that._onClanState(res); });
//Steam-trading events
this.steamTrading.on('tradeProposed', function(tradeID, steamID) { that._onTradeProposed(tradeID, steamID, that.acceptTrade); });
this.steamTrading.on('tradeResult', function(tradeID, result, steamID) { that._onTradeResult(tradeID, result, steamID) });
this.steamTrading.on('sessionStart', function(steamID) { that._onSessionStart(steamID) });
//This was removed in node-steam 1.0.0, using module node-steam-weblogon by Alex7Kom instead
//this.steamClient.on('webSessionID', function(sessionID) { that._onWebSessionID(sessionID); });
//This was replaced in node-steam 1.0.0 with 'clanState', which is handled above in steam-friends
//this.steamClient.on('announcement', function(groupID, headline) { that._onAnnouncement(groupID, headline); });
/*
// These events exist in node-steam, but are only half-implemented in this file...
this.steamClient.on("user", function(obscureData) {that._onUser(obscureData); });
this.steamClient.on("group", function(group, clanRelationship) {that._onGroup(group, clanRelationship); });
this.steamClient.on("richPresence", function(steamId,status,obscureData) {that._onRichPresence(steamId,status,obscureData); });
*/
// Store latest servers
this.steamClient.on("servers", function(servers) {
try{
that.winston.silly(that.name+"/chatBot.js: Attempting to write servers file");
fs.writeFileSync(serversFile, JSON.stringify(servers));
} catch(err) {
that.winston.error(that.name+"/chatBot.js: Error writing servers file:",err.stack);
}
});
if (options.autoConnect) {
this.connect();
}
};
// Public interface
ChatBot.prototype.onLogon = function(bot) {
return;
}
ChatBot.prototype.logOn = function() {
// Continuously try to reconnect if started but not connected
// If someone logs in as the bot it will be disconnected, so this allows the bot to recover automatically when it can
var that = this;
if (this.options.autoReconnect && !this.babysitInterval) {
var babysitTimer = this.options.babysitTimer || 5*60*1000;
this.babysitInterval = setInterval(function() { that.logOn(); }, babysitTimer);
}
if (!this.connected) {
this.winston.info(this.name+"/chatBot.js: Trying to connect");
try {
var sha = '';
if(fs.existsSync(this.sentryFile)) {
var file = fs.readFileSync(this.sentryFile);
sha = crypto.createHash('sha1').update(file).digest();
}
this.steamUser.logOn({
account_name: that.username,
password: that.password,
auth_code: that.guardCode,
two_factor_code: that.twoFactorAuth(),
sha_sentryfile: sha
});
} catch (err) {
this.winston.error(this.name+"/chatBot.js: Exception trying to connect", err);
}
}
}
ChatBot.prototype.connect = function() {
this.steamClient.connect();
this.winston.debug(this.name+'/chatBot.js: Connecting to Steam network...');
}
ChatBot.prototype.log = function(){};
ChatBot.prototype.mute = function() {
this.muted = true;
this._updatePersonaState();
}
ChatBot.prototype.unmute = function() {
this.muted = false;
this._updatePersonaState();
}
// Run the .onLoggedOff function for each trigger
ChatBot.prototype.triggerLoggedOff = function() {
if(!this.triggers || this.triggers.length === 0) {
return;
}
var that = this;
this.logoffTime = process.hrtime();
_.each(this.triggers, function(trigger) {
try {
that.winston.debug(that.name+"/chatBot.js: Running onLoggedOff for " + trigger.type + " trigger " + trigger.name);
trigger.onLoggedOff();
return null;
} catch(err) {
that.winston.error(that.name+"/chatBot.js: Error running onLoggedOff for " + trigger.type + " trigger " + trigger.name,err.stack);
}
});
return null;
}
// Run the .onLoggedOn function for each trigger
ChatBot.prototype.triggerLoggedOn = function() {
if(!this.triggers || this.triggers.length === 0) {
return;
}
this.logonTime = process.hrtime();
var that = this;
_.each(this.triggers, function(trigger) {
try {
that.winston.debug(that.name+"/chatBot.js: Running onLoggedOn for " + trigger.type + " trigger " + trigger.name);
trigger.onLoggedOn();
return null;
} catch(err) {
that.winston.error(that.name+"/chatBot.js: Error running onLoggedOn for " + trigger.type + " trigger " + trigger.name,err.stack);
}
});
return null;
}
// Add or replace a trigger - return the trigger or null
ChatBot.prototype.addTrigger = function(name, type, options) {
if (!name || !type) {
this.winston.error(this.name+"/chatBot.js ("+(name||type||"unknown trigger")+"): Trigger not correctly defined. Not loading. Name and type are both required.");
return false;
}
this.removeTrigger(name);
var trigger = this.triggerFactory.createTrigger(type, name, this, options || {}, true);
try {
this.winston.debug(this.name+"/chatBot.js: Testing onLoad for " + type + " trigger " + name);
if (trigger && trigger.onLoad()) {
this.winston.silly(this.name+"/chatBot.js: onLoad success for " + type + " trigger " + name);
this.triggers[name] = trigger;
return trigger;
} else if (trigger) {
this.winston.error(this.name+"/chatBot.js: Error loading " + type + " trigger " + name);
return null;
}
} catch(err) {
this.winston.error(this.name+"/chatBot.js: Error loading " + type + " trigger " + name + ":",err.stack);
}
return null;
}
// Any duplicate names will be replaced
// triggers is of the form [{name:"",type:"",options:{}}, {name:"",type:"",options:{}}, etc]
// Returns true if all were added, false if any couldn't be added
ChatBot.prototype.addTriggers = function(triggers) {
var ok = true;
var that = this;
_.each(triggers, function(trigger) {
ok = ok && (that.addTrigger(trigger.name, trigger.type, trigger.options) != null);
if(!ok) {
that.winston.error(that.name+"/chatBot.js: trigger not loaded because it or a previous trigger failed to load:",trigger);
}
});
return ok;
}
// Returns true if the trigger was removed
ChatBot.prototype.removeTrigger = function(name) {
if (name in this.triggers) {
this.winston.debug(this.name+"/chatBot.js: Deleting trigger: "+name);
delete this.triggers[name];
return true;
}
return false;
}
ChatBot.prototype.clearTriggers = function(callback) {
var that = this;
if(!this.options.disableWebserver) {
//First, deinitialize the webserver
this.server.close();
delete this.io;
delete this.server;
delete this.express;
}
this.winston.debug(this.name+"/chatBot.js: Clearing triggers");
this.triggers = {};
if(!this.options.disableWebserver) {
//now reinitialize it.
this._startWebServer(that.options.webServerPort||8080);
}
//allow users to redo their own webserver functions afterwards
if(callback && callback instanceof Function) {
callback();
}
}
// Returns triggers in the same form that can be used for addTriggers
// [{name:"",type:"",options:{}}, {name:"",type:"",options:{}}, etc]
ChatBot.prototype.getTriggerDetails = function() {
var triggerDetails = [];
_.each(this.triggers, function(trigger, name) {
triggerDetails.push({ name: name, type: trigger.type, options: trigger.getOptions() });
});
return triggerDetails;
}
ChatBot.prototype.sendMessage = function(steamId, message) {
this.steamFriends.sendMessage(steamId, message);
var haveSeenMessage = false;
_.each(this.triggers, function(trigger) {
var seenMessageThisTrigger = trigger.onSentMessage(steamId, message, haveSeenMessage);
haveSeenMessage = haveSeenMessage || seenMessageThisTrigger;
});
}
//left this here because some configs might still be using it?
ChatBot.prototype.joinGame = function(appId) {
this.games=[appId]; //update this.games
this.steamUser.gamesPlayed({ 'games_played': [{ 'game_id': parseInt(appId) }] });
}
//this function will play all the games it's told to. This doesn't always show
//the first game as the one being played, so there's another function that
//plays the first game, then waits a fraction of a second to play the others
ChatBot.prototype.setGames = function(appIdArray) {
var that = this;
this.games=appIdArray; //update this.games
if(this.games) this.winston.info(this.name+"/chatBot.js: Playing gameIDs " + this.games.toString());
else this.winston.info(this.name+"/chatBot.js: Playing nothing");
this.steamUser.gamesPlayed({ 'games_played': [{ 'game_id': parseInt(that.games.toString()) }] }); //play them!
}
ChatBot.prototype.setPrimaryGame = function(appId,delay) {
this.winston.info(this.name+"/chatBot.js: Setting " + appId + " as primary game.");
if(!this.games || this.games === undefined){
this.games=[appId];
} else {
this.games.unshift(appId); //update this.games
}
this.winston.info(this.name+"/chatBot.js: Playing gameID " + appId);
this.steamUser.gamesPlayed({ 'games_played': [{ 'game_id': parseInt(appId) }] }); //first, play only this game, so it shows up
var that = this;
setTimeout(function(){
that.winston.info(that.name+"/chatBot.js: Playing gameIDs " + that.games.toString());
that.steamUser.gamesPlayed({ 'games_played': [{ 'game_id': parseInt(that.games.toString()) }] }); //play them!
},(delay||1000)); //play all the games in 1 second.
}
ChatBot.prototype.send = function(header, body, callback) {
this.winston.protocol(this.name+'/chatBot.js: sending ProtoBuf message: ' + header.msg + (header.proto ? ', ' + JSON.stringify(header.proto) : ''));
this.steamClient.send(header, body, callback);
}
ChatBot.prototype.joinChat = function(roomId, autoJoinAfterDisconnect) {
this.winston.info("Chat bot " + this.name + " joining room " + roomId + " with autoJoinAfterDisconnect " + autoJoinAfterDisconnect);
this.steamFriends.joinChat(roomId);
if (autoJoinAfterDisconnect) {
this._addChatToAutojoin(roomId);
}
}
ChatBot.prototype.leaveChat = function(roomId) {
this.winston.info("Chat bot " + this.name + " leaving room " + roomId);
this._removeChatFromAutojoin(roomId);
this.steamFriends.leaveChat(roomId);
}
ChatBot.prototype.addFriend = function(userId) {
this.winston.info("Chat bot " + this.name + " adding friend " + this._userString(userId));
this.steamFriends.addFriend(userId);
}
ChatBot.prototype.removeFriend = function(userId) {
this.winston.info("Chat bot " + this.name + " removing friend " + this._userString(userId));
this.steamFriends.removeFriend(userId);
}
ChatBot.prototype.setPersonaName = function(name) {
this.winston.info("Chat bot " + this.name + " changing name to " + name);
this.steamFriends.setPersonaName(name);
}
ChatBot.prototype.setPersonaState = function(state) {
this.winston.info("Chat bot " + this.name + " changing state to " + state);
this.steamFriends.setPersonaState(state);
}
ChatBot.prototype.lockChat = function(roomId) {
this.winston.info("Chat bot " + this.name + " locking chat " + roomId);
this.steamFriends.lockChat(roomId);
}
ChatBot.prototype.unlockChat = function(roomId) {
this.winston.info("Chat bot " + this.name + " unlocking chat " + roomId);
this.steamFriends.unlockChat(roomId);
}
ChatBot.prototype.setModerated = function(roomId) {
this.winston.info("Chat bot " + this.name + " moderating chat " + roomId);
this.steamFriends.setModerated(roomId);
}
ChatBot.prototype.setUnmoderated = function(roomId) {
this.winston.info("Chat bot " + this.name + " unmoderating chat " + roomId);
this.steamFriends.setUnmoderated(roomId);
}
ChatBot.prototype.kick = function(roomId, userId) {
this.winston.info("Chat bot " + this.name + " kicking " + this._userString(userId) + " from " + roomId);
this.steamFriends.kick(roomId, userId);
}
ChatBot.prototype.ban = function(roomId, userId) {
this.winston.info("Chat bot " + this.name + " banning " + this._userString(userId) + " from " + roomId);
this.steamFriends.ban(roomId, userId);
}
ChatBot.prototype.unban = function(roomId, userId) {
this.winston.info("Chat bot " + this.name + " unbanning " + this._userString(userId) + " from " + roomId);
this.steamFriends.unban(roomId, userId);
}
ChatBot.prototype.users = function() {
return this.steamFriends.personaStates;
}
ChatBot.prototype.rooms = function() {
return this.steamFriends.chatRooms;
}
ChatBot.prototype.friends = function() {
return this.steamFriends.friends;
}
ChatBot.prototype.groups = function() {
return this.steamFriends.groups;
}
ChatBot.prototype.logOff = function() {
this.winston.info('Chat bot ' + this.name + ' logging off');
this.steamClient.disconnect();
}
ChatBot.prototype.chatInvite = function(chatSteamID, invitedSteamID) {
this.winston.info("Chat bot " + this.name+': Inviting ' + invitedSteamID + ' to chat ' + chatSteamID);
this.steamFriends.chatInvite(chatSteamID, invitedSteamID);
}
ChatBot.prototype.getSteamLevel = function(steamids) {
this.winston.info(this.name+'/chatBot.js: Getting steam level for ' + steamids.toString());
return this.steamFriends.getSteamLevel(steamids, function(levels) {
return levels;
});
}
ChatBot.prototype.setIgnoreFriend = function(steamID, setIgnore) {
this.winston.info(this.name+'/chatBot.js: Setting ' + steamID + ' block to ' + setIgnore);
var that = this.
this.steamFriends.setIgnoreFriend(steamID, setIgnore, function(callback) {
// that.winston.info(callback); //i don't know what this callback does
// ^ so you decided to log a function?
});
}
ChatBot.prototype.trade = function(steamID) {
this.winston.info(this.name+'/chatBot.js: Sending trade request to ' + steamID);
this.steamTrading.trade(steamID);
}
ChatBot.prototype.respondToTrade = function(tradeID, bool) {
if(bool === true) {
this.steamTrading.respondToTrade(tradeID, true);
this.winston.info(this.name+'/chatBot.js: Accepting trade');
} else {
this.steamTrading.respondToTrade(tradeID, false);
this.winston.info(this.name+'/chatBot.js: Denying trade');
}
}
ChatBot.prototype.cancelTrade = function(steamID) {
this.winston.info(this.name+'/chatBot.js: Cancelling trade to ' + steamID);
this.steamTrading.cancelTrade(steamID);
}
ChatBot.prototype.steamApi = function(interface, method, version, request, key, options) {
var that = this;
if(!key) {
that.winston.error(that.name+'/chatBot.js: Usage of Steam API requires an API key');
}
else {
return new Promise(function(resolve, reject) {
var endpoint = GetInterface(interface, key);
if(request === 'get') {
endpoint.get(method, parseInt(version), options, function(code, response) {
if(code !== 200) {
reject(code);
}
else {
resolve(response);
}
});
}
else if(request === 'post') {
endpoint.post(method, parseInt(version), options, function(code, response) {
if(code !== 200) {
reject(code);
}
else {
resolve(response);
}
});
}
});
}
}
// "Private" functions
ChatBot.prototype._updatePersonaState = function() {
this.steamFriends.setPersonaState(this.muted ? this.mutedState : this.unmutedState);
}
ChatBot.prototype._userString = function(id) {
var result = (this.steamFriends.personaStates && id in this.steamFriends.personaStates) ? (this.steamFriends.personaStates[id].player_name + "/") : "";
result += id;
return result;
};
//same as _userString, but only the name without the steamID
ChatBot.prototype._userName = function(id) {
var result = (this.steamFriends.personaStates && id in this.steamFriends.personaStates) ? (this.steamFriends.personaStates[id].player_name) : "";
return result;
};
////
ChatBot.prototype._autojoinChatrooms = function() {
// Auto-join chat rooms that the bot was previously invited to (and not removed from)
if (fs.existsSync(this.autojoinFile)) {
this.autojoinRooms = JSON.parse(fs.readFileSync(this.autojoinFile));
var that = this;
_.each(that.autojoinRooms, function(value, roomId) {
that.winston.info("Chat bot " + that.name + " auto-joining room " + roomId);
that.steamFriends.joinChat(roomId);
});
}
}
ChatBot.prototype._addChatToAutojoin = function(roomId) {
if (fs.existsSync(this.autojoinFile)) {
this.autojoinRooms = JSON.parse(fs.readFileSync(this.autojoinFile));
}
else {
this.autojoinRooms = {};
}
this.autojoinRooms[roomId] = true;
fs.writeFileSync(this.autojoinFile, JSON.stringify(this.autojoinRooms));
}
ChatBot.prototype._removeChatFromAutojoin = function(roomId) {
if (fs.existsSync(this.autojoinFile)) {
this.autojoinRooms = JSON.parse(fs.readFileSync(this.autojoinFile));
if (this.autojoinRooms[roomId]) {
delete this.autojoinRooms[roomId];
fs.writeFileSync(this.autojoinFile, JSON.stringify(this.autojoinRooms));
}
}
}
// Steam Events
ChatBot.prototype._onConnected = function() {
this.winston.debug(this.name+'/chatBot.js: Connected to steam, logging in');
this.logOn();
}
ChatBot.prototype._onMessage = function(header, body, callback) {
this.winston.protocol(this.name+'/chatBot.js: new ProtoBuf message: ' + header.msg + (header.proto ? ', ' + JSON.stringify(header.proto) : ''));
}
ChatBot.prototype._onError = function() {
this.winston.error(this.name+"/chatBot.js: disconnected");
this.connected = false;
this.connect();
};
var evilEResults = {
5: "Incorrect password",
7: "Please update steam-chat-bot and/or node-steam",
18:"Your account doesn't exist",
25:"Try again later",
43:true,
56:"Reset your password through support",
63:"Login denied due to steamguard, provide guard code sent to email",
65:"Wrong guard code",
66:"Check your guardCode",
71:"Guard code is expired",
73:"Your account is locked",
74:"Your account is locked. Please verify through email"
}
//Try again how much faster than babysitInterval? (don't get locked out, but don't wait 30min because steam is down...)
//Never tries more often than 5s anyways.
var badEResults = {
2: 0.5, 3: 0.1, 4: 0.1, 20: 0.5, 35: 0.3,
36: 0.3, 37: 0.3, 38: 0.3, 48: 0.1, 79: 0.5
}
ChatBot.prototype._onLogOnResponse = function(res) {
var that = this;
if(res.eresult === steam.EResult.OK) {
this.winston.info(this.name + "/chatBot.js: logged on");
this.connected = true;
this._updatePersonaState();
this._autojoinChatrooms();
this.steamUser.gamesPlayed({ 'games_played': [{ 'game_id': parseInt(that.games.toString()) }] });
this.steamWebLogon.webLogOn(function(sessionid, cookies) {
that.steamTrade.sessionID = sessionid;
that.winston.debug(that.name+'/chatBot.js: New cookie');
that.winston.debug(that.name+'/chatBot.js: New sessionid');
that.cookie = cookies;
that.winston.silly(that.name+'/chatBot.js: New sessionid: ' + sessionid);
that.winston.silly(that.name+'/chatBot.js: New cookie: ' + cookies);
cookies.forEach(function(cookie) {
that.steamTrade.setCookie(cookie.trim());
});
if(!that.apikey) {
GetSteamApiKey({
sessionID: sessionid,
webCookie: cookies
}, function(e, api) {
if(e) { that.winston.error(that.name + '/chatBot.js: error getting API key: ' + e); }
else { that.apikey = api; }
});
that.winston.info(that.name + '/chatBot.js: logged into Steam web');
}
});
} else if(res.eresult === 63) {
this.winston.warn(this.name + '/chatBot.js: EResult for logon response: 63 (AccountLogonDenied). Please provide the guardCode sent to your email at ' + res.email_domain);
//I'm not sure if we might want to use exit codes in the future? Just set exit codes to eresult num plus 100, leaving 1-100 open.
process.exit(163);
} else { //if any other eresults need extra data, we should separate them as well.
var reason = res.eresult+" ("+this._getEResult(res.eresult)+"). "+(evilEResults[res.eresult] || "Please fix the issue and try again.");
this.winston.warn(this.name + '/chatBot.js: EResult for logon response: ' +reason);
//open steamworks has comment explanations of many eresults.
this.winston.verbose("You can find more information on some EResults in Open Steamworks header comments at https://github.com/SteamRE/open-steamworks/blob/master/Open%20Steamworks/EResult.h");
if(res.eresult in evilEResults) {
process.exit(res.eresult+100); //evilEResults are things that won't be fixed by waiting (bad login, etc)
}
if(res.eresult in badEResults) { //not as bad as evilEResults; steam is down, or sth, so connect faster than usual.
if(this.eresultReconnect) { //only try once, though. Don't want to get rate limited. After that, let babysitter take over.
return;
}
var timer = (this.options.babysitTimer||5*60*1000)*badEResults[res.eresult];
if(timer <5000) { timer=5000; }
setTimeout(function() { that.logOn(); }, timer);
this.eresultReconnect = true;
}
}
}
ChatBot.prototype._getEResult = function(num) {
for (var result in steam.EResult) {
if(steam.EResult[result]===num) {
return result;
}
}
return false;
}
ChatBot.prototype._onDisconnected = function() {
this.winston.warn(this.name + "/chatBot.js: disconnected");
this.logOn();
}
ChatBot.prototype._onChatInvite = function(roomId, roomName, inviterId) {
this.winston.info(this.name + "/chatBot.js: was invited to chat in " + roomName + " (" + roomId + ")" + " by " + this._userString(inviterId));
_.each(this.triggers, function(trigger) {
trigger.onChatInvite(roomId, roomName, inviterId);
});
};
ChatBot.prototype._onRelationship = function(userId, relationship) {
this.winston.info(this.name + "/chatBot.js: relationship event for " + this._userString(userId) + " type " + relationship);
if (relationship === 2) {
_.each(this.triggers, function(trigger) {
trigger.onFriendRequest(userId);
});
}
};
ChatBot.prototype._onFriendMsg = function(userId, message, type) {
this.winston.info(this.name + "/chatBot.js: friendMsg " + type + " <" + this._userString(userId) + ">: " + message);
if (type === steam.EChatEntryType.ChatMsg) {
var haveSentMessage = false;
_.each(this.triggers, function(trigger) {
var sentMessageThisTrigger = trigger.onFriendMessage(userId, message, haveSentMessage);
haveSentMessage = haveSentMessage || sentMessageThisTrigger;
});
}
};
ChatBot.prototype._onChatMsg = function(roomId, message, type, chatterId) {
this.winston.info(this.name + "/chatBot.js: chatMsg " + type + " in " + roomId + " <" + this._userString(chatterId) + ">: " + message);
if (type === steam.EChatEntryType.ChatMsg) {
var that = this;
var haveSentMessage = false;
_.each(this.triggers, function(trigger) {
var sentMessageThisTrigger = trigger.onChatMessage(roomId, chatterId, message, haveSentMessage, that.muted);
haveSentMessage = haveSentMessage || sentMessageThisTrigger;
});
}
};
ChatBot.prototype._onChatStateChange = function(stateChange, chatterActedOn, steamChatId, chatterActedBy) {
this.winston.info(this.name + "/chatBot.js: chatStateChange " + stateChange + " in " + steamChatId + " " + chatterActedOn + " acted on by " + chatterActedBy);
var muted = this.muted;
var haveSentMessage = false;
var sentMessageThisTrigger = false;
if ((stateChange & steam.EChatMemberStateChange.Kicked) > 0) {
this.winston.info(this.name+"/chatBot.js:"+this._userString(chatterActedOn) + " was kicked from " + steamChatId + " by " + this._userString(chatterActedBy));
// Kicked from chat - don't autojoin
if(chatterActedOn === this.steamClient.steamID) {
this._removeChatFromAutojoin(steamChatId);
}
haveSentMessage = false;
_.each(this.triggers, function(trigger) {
sentMessageThisTrigger = trigger.onKickedChat(steamChatId, chatterActedOn, chatterActedBy, haveSentMessage, muted);
haveSentMessage = haveSentMessage || sentMessageThisTrigger;
});
}
else if ((stateChange & steam.EChatMemberStateChange.Entered) > 0) {
this.winston.info(this.name+"/chatBot.js:"+this._userString(chatterActedOn) + " joined " + steamChatId);
haveSentMessage = false;
_.each(this.triggers, function(trigger) {
sentMessageThisTrigger = trigger.onEnteredChat(steamChatId, chatterActedOn, haveSentMessage, muted);
haveSentMessage = haveSentMessage || sentMessageThisTrigger;
});
}
else if ((stateChange & steam.EChatMemberStateChange.Left) > 0) {
this.winston.info(this.name+"/chatBot.js:"+this._userString(chatterActedOn) + " left " + steamChatId);
haveSentMessage = false;
_.each(this.triggers, function(trigger) {
sentMessageThisTrigger = trigger.onLeftChat(steamChatId, chatterActedOn, haveSentMessage, muted);
haveSentMessage = haveSentMessage || sentMessageThisTrigger;
});
}
else if ((stateChange & steam.EChatMemberStateChange.Disconnected) > 0) {
this.winston.info(this.name+"/chatBot.js:"+this._userString(chatterActedOn) + " was disconnected from " + steamChatId);
haveSentMessage = false;
_.each(this.triggers, function(trigger) {
sentMessageThisTrigger = trigger.onDisconnected(steamChatId, chatterActedOn, haveSentMessage, muted);
haveSentMessage = haveSentMessage || sentMessageThisTrigger;
});
}
else if ((stateChange & steam.EChatMemberStateChange.Banned) > 0) {
this.winston.info(this.name+"/chatBot.js:"+this._userString(chatterActedOn) + " was banned from " + steamChatId);
haveSentMessage = false;
_.each(this.triggers, function(trigger) {
sentMessageThisTrigger = trigger.onBannedChat(steamChatId, chatterActedOn, chatterActedBy, haveSentMessage, muted);
haveSentMessage = haveSentMessage || sentMessageThisTrigger;
});
}
};
ChatBot.prototype._onUpdateMachineAuth = function(sentry, cb) {
this.winston.info(this.name+"/chatBot.js: Obtained sentry " + sentry.filename + ". Writing to " + this.sentryFile);
fs.writeFileSync(this.sentryFile, sentry.bytes);
cb({
sha_file: crypto.createHash('sha1').update(sentry.bytes).digest()
});
}
/*
ChatBot.prototype._onWebSessionID = function(sessionid) {
this.steamTrade.sessionID = sessionid;
this.winston.debug(this.name+'/chatBot.js: New sessionID');
this.winston.silly(this.name+'/chatBot.js: New sessionID: ', sessionid);
var that = this;
this.steamClient.webLogOn(function(cookie) {
that.winston.debug(that.name+'/chatBot.js: New cookie');
that.winston.silly(that.name+'/chatBot.js: New cookie: ', cookie);
that.cookie = cookie;
cookie.forEach(function(part) {
that.steamTrade.setCookie(part.trim());
});
console.log(cookie);
that.winston.info(this.name+'/chatBot.js: Logged into Steam Web API at ' + new Date().toString());
});
}
*/
ChatBot.prototype._onTradeOffers = function(number) { //this function gets called when someone sends a non-interactive trade offer. There are no built-in functions for dealing with this.
this.winston.info(this.name+'/chatBot.js: New trade offer count: ' + number);
var haveEatenEvent = false;
_.each(this.triggers, function(trigger) {
var eatenEventThisTrigger = trigger.onTradeOffer(number,haveEatenEvent);
haveEatenEvent = haveEatenEvent || eatenEventThisTrigger;
});
}
ChatBot.prototype._onTradeProposed = function(tradeID, steamID) { //interactive trading session.
this.winston.info(this.name+'/chatBot.js: Received trade request from ' + steamID);
var haveEatenEvent = false;
_.each(this.triggers, function(trigger) {
var eatenEventThisTrigger = trigger.onTradeProposed(tradeID,steamID,haveEatenEvent);
haveEatenEvent = haveEatenEvent || eatenEventThisTrigger;
});
}
ChatBot.prototype._onTradeResult = function(tradeID, result, steamID) {
this.winston.info(this.name+"/chatBot.js: " + result + ' from trade with ' + steamID);
}
ChatBot.prototype._onSessionStart = function(steamID) {
this.winston.info(this.name+'/chatBot.js: Trade with ' + steamID + ' initialized');
var haveEatenEvent = false;
_.each(this.triggers, function(trigger) {
var eatenEventThisTrigger = trigger.onTradeSession(steamID,haveEatenEvent);
haveEatenEvent = haveEatenEvent || eatenEventThisTrigger;
});
}
/* //i don't know how to do announcements, it isn't the same as before. now it uses protobufs from steamkit
ChatBot.prototype._onClanState = function(res) {
if(res === 'announcements') { //no idea if this works, https://github.com/SteamRE/SteamKit/blob/master/Resources/Protobufs/steamclient/steammessages_clientserver.proto#L1341
this.winston.info(this.name+"/chatBot.js:"+groupID + ' posted announcement with title ' + '"' + headline + '"');
var haveEatenEvent = false;
_.each(this.triggers, function(trigger) {
var eatenEventThisTrigger = trigger.onAnnouncement(groupID,headline,haveEatenEvent);
haveEatenEvent = haveEatenEvent || eatenEventThisTrigger;
});
}
*/
/*
* This crap is possibly not implemented correctly/fully. Don't expect it to work right without testing it. For info, see https://github.com/seishun/node-steam
ChatBot.prototype._onLoggedOff = function() {
this.winston.warning(this.name + "/chatBot.js: logged off!");
_.each(this.triggers, function(trigger) {
trigger.onLoggedOff();
});
}
ChatBot.prototype._onUser = function(obscureData) {
this.winston.info(this.name + "/chatBot.js: - User event detected");
_.each(this.triggers, function(trigger) {
trigger.onUserEvent(obscureData);
});
}
ChatBot.prototype._onFriend = function(steamId,friendRelationship) {
this.winston.info(this.name + "/chatBot.js: - Friend relationship event detected");
_.each(this.triggers, function(trigger) {
trigger.onFriendEvent(steamId,friendRelationship);
});
}
ChatBot.prototype._onGroup = function(steamId,clanRelationship) {
this.winston.info(this.name + "/chatBot.js: - Group relationship event detected");
_.each(this.triggers, function(trigger) {
trigger.onGroupEvent(steamId,clanRelationship);
});
}
ChatBot.prototype._onRichPresence = function(steamId,status,obscureData) {
this.winston.info(this.name + "/chatBot.js: - Rich presence event detected for user " + this._userString(steamId) + " - Status: " + status);
_.each(this.triggers, function(trigger) {
trigger.onRichPresence(steamId,status,obscureData);
});
}
*/
ChatBot.prototype.makeAnnouncement = function(target, head, body, source) {
var that = this;
var post_data = qs.stringify({
"sessionID" : that.steamTrade.sessionID,
"action" : "post",
"headline" : head,
"body" : body
});