-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathCasinoBot.java
591 lines (528 loc) · 20.9 KB
/
CasinoBot.java
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
/*
Copyright (C) 2013-2014 Yizhe Shen <[email protected]>
This file is part of irccasino.
irccasino is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
irccasino is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with irccasino. If not, see <http://www.gnu.org/licenses/>.
*/
package irccasino;
import irccasino.blackjack.Blackjack;
import irccasino.texaspoker.TexasPoker;
import irccasino.cardgame.CardGame;
import irccasino.texastourney.TexasTourney;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.StringTokenizer;
import org.pircbotx.Channel;
import org.pircbotx.Colors;
import org.pircbotx.PircBotX;
import org.pircbotx.User;
import org.pircbotx.cap.SASLCapHandler;
import org.pircbotx.exception.IrcException;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.*;
/**
* The default standalone bot that allows any number of games, each in their
* own channel. It also logs all activity to log.txt.
* @author Yizhe Shen
*/
public class CasinoBot extends PircBotX implements GameManager {
protected HashMap<String,String> configMap;
protected ArrayList<CardGame> gameList;
protected String logFile;
protected SimpleDateFormat timeFormat;
/**
* Listener for CasinoBot initialization commands.
*/
public static class InitListener extends ListenerAdapter<CasinoBot> {
protected CasinoBot bot;
protected char commandChar;
public InitListener(CasinoBot parent, char commChar) {
bot = parent;
commandChar = commChar;
}
/**
* Joins the channels in the config file upon successful connection.
* @param event Connect event
*/
@Override
public void onConnect(ConnectEvent<CasinoBot> event){
Channel chan;
StringTokenizer st;
// Auto-join channels from config
st = new StringTokenizer(bot.configMap.get("channel"), ", ");
while(st.hasMoreTokens()) {
bot.joinChannel(st.nextToken());
}
// Auto-start Blackjack
st = new StringTokenizer(bot.configMap.get("bjchannel"), ", ");
while(st.hasMoreTokens()) {
chan = bot.getChannel(st.nextToken());
blackjack(chan, null, new String[0], null);
}
// Auto-start TexasPoker
st = new StringTokenizer(bot.configMap.get("tpchannel"), ", ");
while(st.hasMoreTokens()) {
chan = bot.getChannel(st.nextToken());
texaspoker(chan, null, new String[0], null);
}
// Auto-start TexasTourney
st = new StringTokenizer(bot.configMap.get("ttchannel"), ", ");
while(st.hasMoreTokens()) {
chan = bot.getChannel(st.nextToken());
texastourney(chan, null, new String[0], null);
}
}
/**
* Parses channel messages for commands and parameters.
* @param event Message event
*/
@Override
public void onMessage(MessageEvent<CasinoBot> event){
String msg = event.getMessage();
// Parse the message if it is a command
if (msg.length() > 1 && msg.charAt(0) == commandChar && msg.charAt(1) != ' ') {
msg = msg.substring(1);
StringTokenizer st = new StringTokenizer(msg);
String command = st.nextToken();
String[] params = new String[st.countTokens()];
for (int ctr = 0; ctr < params.length; ctr++){
params[ctr] = st.nextToken();
}
processCommand(event.getChannel(), event.getUser(), command, params, msg);
}
}
/**
* Processes initialization commands for a CasinoBot.
* @param channel the originating channel of the command
* @param user the user who gave the command
* @param command the command
* @param params the parameters after the command
* @param msg
*/
public void processCommand(Channel channel, User user, String command, String[] params, String msg){
if (!channel.isOp(user)){
return; // Do nothing if not a channel Op
}
if (command.equalsIgnoreCase("games")) {
games(channel, user, params, msg);
} else if (command.equalsIgnoreCase("blackjack") || command.equalsIgnoreCase("bj")) {
blackjack(channel, user, params, msg);
} else if (command.equalsIgnoreCase("texaspoker") || command.equalsIgnoreCase("tp")) {
texaspoker(channel, user, params, msg);
} else if (command.equalsIgnoreCase("texastourney") || command.equalsIgnoreCase("tt")) {
texastourney(channel, user, params, msg);
} else if (command.equalsIgnoreCase("endgame")) {
endGame(channel, user, params, msg);
} else if (command.equalsIgnoreCase("botquit") || command.equalsIgnoreCase("shutdown")) {
botQuit(channel, user, params, msg);
} else if (command.equalsIgnoreCase("reboot") || command.equalsIgnoreCase("reconnect")) {
reboot(channel, user, params, msg);
}
}
/**
* Displays a list of games the bot is currently running.
* @param channel
* @param user
* @param params
* @param msg
*/
public void games(Channel channel, User user, String[] params, String msg) {
String str;
if (!bot.hasGames()) {
str = "No games are running.";
} else {
str = "Games: ";
for (CardGame game : bot.getGames()) {
str += game.getGameNameStr() + " in " + game.getChannel().getName() + ", ";
}
str = str.substring(0, str.length() - 2);
}
bot.sendMessage(channel, str);
}
/**
* Starts a new game of Blackjack.
* @param channel
* @param user
* @param params
* @param msg
*/
public void blackjack(Channel channel, User user, String[] params, String msg) {
if (bot.hasGame(channel)) {
bot.sendMessage(channel, bot.getGame(channel).getGameNameStr() + " is already running in this channel.");
} else if (params.length > 0) {
bot.startGame(new Blackjack(bot, commandChar, channel, params[0]));
} else {
bot.startGame(new Blackjack(bot, commandChar, channel));
}
}
/**
* Starts a new game of Texas Hold'em.
* @param channel
* @param user
* @param params
* @param msg
*/
public void texaspoker(Channel channel, User user, String[] params, String msg) {
if (bot.hasGame(channel)) {
bot.sendMessage(channel, bot.getGame(channel).getGameNameStr() + " is already running in this channel.");
} else if (params.length > 0) {
bot.startGame(new TexasPoker(bot, commandChar, channel, params[0]));
} else {
bot.startGame(new TexasPoker(bot, commandChar, channel));
}
}
/**
* Starts a new game of Texas Hold'em tournament.
* @param channel
* @param user
* @param params
* @param msg
*/
public void texastourney(Channel channel, User user, String[] params, String msg) {
if (bot.hasGame(channel)) {
bot.sendMessage(channel, bot.getGame(channel).getGameNameStr() + " is already running in this channel.");
} else if (params.length > 0) {
bot.startGame(new TexasTourney(bot, commandChar, channel, params[0]));
} else {
bot.startGame(new TexasTourney(bot, commandChar, channel));
}
}
/**
* Ends the game in the specified channel.
* @param channel
* @param user
* @param params
* @param msg
*/
public void endGame(Channel channel, User user, String[] params, String msg) {
if (!bot.hasGame(channel)) {
bot.sendMessage(channel, "No game is currently running.");
} else {
CardGame game = bot.getGame(channel);
if (game.isInProgress()){
bot.sendMessage(channel, "Please wait for the current round to finish.");
} else {
bot.endGame(game);
}
}
}
/**
* Disconnects the CasinoBot and ends all games.
* @param channel
* @param user
* @param params
* @param msg
*/
public void botQuit(Channel channel, User user, String[] params, String msg) {
if (bot.gamesInProgress()) {
bot.sendMessage(channel, "There is a game in progress. Please wait for it to finish.");
} else {
bot.endAllGames();
bot.setAutoReconnect(false);
bot.quitServer("Bye.");
}
}
/**
* Reconnects the CasinoBot to the IRC server.
* @param channel
* @param user
* @param params
* @param msg
*/
public void reboot(Channel channel, User user, String[] params, String msg) {
if (bot.gamesInProgress()) {
bot.sendMessage(channel, "There is a game in progress. Please wait for it to finish.");
} else {
bot.quitServer("Reconnecting...");
}
}
}
/**
* Initializes custom CasinoBot fields.
*/
public CasinoBot(){
super();
logFile = "";
gameList = new ArrayList<>();
configMap = new HashMap<>();
timeFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS");
}
/**
* Retains the original PircBotX.log() functionality, while adding the
* ability to output the log to a file.
* @param line the line to add to the log
*/
@Override
public void log(String line){
if (verbose) {
Date time = new Date(System.currentTimeMillis());
String output = Colors.removeFormattingAndColors(line);
System.out.println(timeFormat.format(time) + " " + output);
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(logFile,true)))) {
out.println(timeFormat.format(time) + " " + output);
} catch(IOException e) {
System.err.println("Error: unable to write to " + logFile);
}
}
}
/**
* Patch to eliminate exceptions during shutdown of the bot. All channel
* caching has been removed.
* @param noReconnect Toggle whether to reconnect if enabled. Set to true to
* 100% shutdown the bot
*/
@Override
public void shutdown(boolean noReconnect) {
try {
if (outputThread != null) outputThread.interrupt();
if (inputThread != null) inputThread.interrupt();
} catch (Exception e) {
logException(e);
}
//Close the socket from here and let the threads die
if (socket != null && !socket.isClosed())
try {
socket.shutdownInput();
socket.close();
} catch (IOException e) {
logException(e);
}
//Close the DCC Manager
try {
dccManager.close();
} catch (IOException ex) {
//Not much we can do with it here. And throwing it would not let other things shutdown
logException(ex);
}
//Clear relevant variables of information
userChanInfo.clear();
userNickMap.clear();
channelListBuilder.finish();
//Dispatch event
getListenerManager().dispatchEvent(new DisconnectEvent(this));
log("*** Disconnected.");
}
@Override
public boolean hasGame(Channel channel) {
return getGame(channel) != null;
}
@Override
public boolean hasGames() {
return !gameList.isEmpty();
}
@Override
public CardGame getGame(Channel channel) {
for (CardGame game : gameList) {
if (game.getChannel().equals(channel)){
return game;
}
}
return null;
}
@Override
public CardGame getGame(String nick) {
for (CardGame game : gameList) {
if (game.isJoined(nick) || game.isWaitlisted(nick)) {
return game;
}
}
return null;
}
@Override
public List<CardGame> getGames() {
return gameList;
}
@Override
public boolean isBlacklisted(String nick) {
for (CardGame game : gameList) {
if (game.isBlacklisted(nick)) {
return true;
}
}
return false;
}
@Override
public boolean gamesInProgress() {
for (CardGame game : gameList) {
if (game.isInProgress()){
return true;
}
}
return false;
}
@Override
public void startGame(CardGame game) {
gameList.add(game);
getListenerManager().addListener(game);
}
@Override
public void endGame(CardGame game) {
game.endGame();
getListenerManager().removeListener(game);
gameList.remove(game);
}
@Override
public void endAllGames() {
while(!gameList.isEmpty()){
endGame(gameList.get(0));
}
}
/**
* Loads configuration file for this bot.
* @param configFile the configuration file
*/
protected void loadConfig(String configFile){
try (BufferedReader in = new BufferedReader(new FileReader(configFile))) {
String str, key, value;
StringTokenizer st;
while (in.ready()) {
str = in.readLine();
if (!str.startsWith("#") && str.contains("=")) {
st = new StringTokenizer(str, "=");
key = st.nextToken();
value = "";
if (st.hasMoreTokens()){
value = st.nextToken();
}
configMap.put(key, value);
}
}
} catch (IOException e) {
/* load defaults if config file is not found */
log(configFile + " not found! Loading default values...");
configMap.put("nick", "CasinoBot");
configMap.put("network", "chat.freenode.net");
configMap.put("channel", "##CasinoBot");
configMap.put("password", "");
configMap.put("bjchannel", "");
configMap.put("tpchannel", "");
configMap.put("ttchannel", "");
saveConfig(configFile);
}
}
/**
* Saves configuration file for this bot.
* @param configFile
*/
protected void saveConfig(String configFile) {
/* Write these values to a new file */
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(configFile)))) {
out.println("#Bot nick");
out.println("nick=" + configMap.get("nick"));
out.println("#SASL password");
out.println("password=" + configMap.get("password"));
out.println("#IRC network");
out.println("network=" + configMap.get("network"));
out.println("#IRC channel");
out.println("channel=" + configMap.get("channel"));
out.println("#Blackjack channel");
out.println("bjchannel=" + configMap.get("bjchannel"));
out.println("#Texas Hold'em channel");
out.println("tpchannel=" + configMap.get("tpchannel"));
out.println("#Texas Hold'em Tournament channel");
out.println("ttchannel=" + configMap.get("ttchannel"));
} catch (IOException f) {
log("Error creating " + configFile + "!");
}
}
/**
* Initializes bot with custom parameters.
* @param config
* @param log
*/
protected void initBot(String config, String log) {
version = "CasinoBot using PircBotX";
logFile = log;
setMessageDelay(200);
loadConfig(config);
setVerbose(true);
setAutoNickChange(true);
setAutoReconnect(true);
setCapEnabled(true);
setName(configMap.get("nick"));
setLogin(configMap.get("nick"));
// Add listener for initialization commands
getListenerManager().addListener(new InitListener(this, '.'));
}
/**
* Attempts to connect the bot to an IRC server.
* Attempts to reconnect upon failure or disconnection.
* @throws Exception
*/
protected void runBot() throws Exception{
int timeInt = 30000; // milliseconds
int attempt = 0;
// Continue trying to connect to the server if not in a connected state
while (!isConnected()) {
try {
attempt++;
if (!configMap.get("password").equals("")){
getCapHandlers().clear();
getCapHandlers().add(new SASLCapHandler(configMap.get("nick"), configMap.get("password")));
}
// Reset IRC threads
inputThread = null;
outputThread = null;
// Attempt to connect
log("Connection attempt " + attempt + "...");
connect(configMap.get("network"));
} catch (IOException | IrcException e){
// Log the exception that caused connection failure
logException(e);
// Wait for IRC threads to die
if (inputThread != null) inputThread.join();
if (outputThread != null) outputThread.join();
// Set delay up to 600 seconds or 10 minutes
int delay = Math.min(attempt * timeInt, timeInt * 20);
log("Attempt to reconnect in " + (delay/1000) + " seconds...");
Thread.sleep(delay);
// Retry
continue;
}
// If we make it here that means we're connected, reset attempts
attempt = 0;
// Wait for any disconnections
inputThread.join();
outputThread.join();
// Terminate if no auto-reconnect is required
if (!autoReconnect) {
break;
}
// Otherwise wait the 10 seconds to reconnect
Thread.sleep(timeInt);
}
}
/**
* Creates and initializes a new CasinoBot and connects it to an IRC network.
* Also attempts reconnect on connection failure or disconnection.
* @param args alternate config file path
* @throws Exception
*/
public static void main(String[] args) throws Exception {
CasinoBot bot = new CasinoBot();
// Check for alternate config file
if (args.length > 0) {
bot.initBot(args[0], "log.txt");
} else {
bot.initBot("irccasino.conf", "log.txt");
}
bot.runBot();
}
}