-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathTwirk.java
More file actions
637 lines (569 loc) · 23.5 KB
/
Twirk.java
File metadata and controls
637 lines (569 loc) · 23.5 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
package com.gikk.twirk;
import com.gikk.twirk.events.TwirkListener;
import com.gikk.twirk.types.clearChat.ClearChat;
import com.gikk.twirk.types.clearChat.ClearChatBuilder;
import com.gikk.twirk.types.clearMsg.ClearMsg;
import com.gikk.twirk.types.clearMsg.ClearMsgBuilder;
import com.gikk.twirk.types.hostTarget.HostTarget;
import com.gikk.twirk.types.hostTarget.HostTargetBuilder;
import com.gikk.twirk.types.mode.Mode;
import com.gikk.twirk.types.mode.ModeBuilder;
import com.gikk.twirk.types.notice.Notice;
import com.gikk.twirk.types.notice.NoticeBuilder;
import com.gikk.twirk.types.roomstate.Roomstate;
import com.gikk.twirk.types.roomstate.RoomstateBuilder;
import com.gikk.twirk.types.twitchMessage.TwitchMessage;
import com.gikk.twirk.types.twitchMessage.TwitchMessageBuilder;
import com.gikk.twirk.types.usernotice.Usernotice;
import com.gikk.twirk.types.usernotice.UsernoticeBuilder;
import com.gikk.twirk.types.users.TwitchUser;
import com.gikk.twirk.types.users.TwitchUserBuilder;
import com.gikk.twirk.types.users.Userstate;
import com.gikk.twirk.types.users.UserstateBuilder;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**Class for communicating with the TwitchIrc chat.<br>
* To create instances of Twirk, see {@link TwirkBuilder}.<br><br>
*
* TwitchIrc behaves a bit different from regular IRC, in that it uses only a few types of message types
* and it has a few message types of its own. This class is intended to cover all of Twitch's special
* features, and thus making it easier to communicate with Twitch chat programmatically. <br><br>
*
* To connect to Twitch chat, you need to generate a Twitch account and you need to generate an IRC oAuth
* token for that account. To generate a oAuth token, visit <a href="https://twitchapps.com/tmi/">https://twitchapps.com/tmi/</a><br><br>
*
* This library is very basic, and only intended for simplistic bots. I would not recommend using this
* in a advanced, long term or commercial product. For those kinds of applications, consider looking
* into a more robust and well tested library, such as IrcAPI or PircBotX.<br><br>
*
* For documentation about how Twitch communicates via IRC,
* see <a href="https://github.com/justintv/Twitch-API/blob/master/IRC.md">
* https://github.com/justintv/Twitch-API/blob/master/IRC.md </a>
*
* Code inspired by <a href="http://archive.oreilly.com/pub/h/1966#code">http://archive.oreilly.com/pub/h/1966#code</a>
*
* @author Gikkman
*
*/
public final class Twirk {
//***********************************************************************************************
// VARIABLES
//***********************************************************************************************
private final String serverAddress;
private final int serverPort;
private final String nick;
private final String pass;
private final String channel;
final TwirkLogger logger;
private OutputThread outThread;
private InputThread inThread;
private final OutputQueue queue;
private boolean resourcesCreated = false;
private boolean isConnected = false;
private boolean isDisposed = false;
private Socket socket = null;
private BufferedWriter writer = null;
private BufferedReader reader = null;
private final ArrayList<TwirkListener> listeners = new ArrayList<>();
final Set<String> moderators = Collections.newSetFromMap( new ConcurrentHashMap<>() );
final Set<String> online = Collections.newSetFromMap( new ConcurrentHashMap<>() );
private final ClearChatBuilder clearChatBuilder;
private final ClearMsgBuilder clearMsgBuilder;
private final HostTargetBuilder hostTargetBuilder;
private final ModeBuilder modeBuilder;
private final NoticeBuilder noticeBuilder;
private final RoomstateBuilder roomstateBuilder;
private final TwitchMessageBuilder twitchMessageBuilder;
private final TwitchUserBuilder twitchUserBuilder;
private final UserstateBuilder userstateBuilder;
private final UsernoticeBuilder usernoticeBuilder;
private final SocketFactory socketFactory;
private final int pingIntervalSeconds;
//***********************************************************************************************
// CONSTRUCTOR
//***********************************************************************************************
Twirk(TwirkBuilder builder) {
this.serverAddress = builder.server;
this.serverPort = builder.port;
this.nick = builder.nick;
this.pass = builder.oauth;
this.channel = builder.channel;
this.logger = builder.getLogger();
this.clearChatBuilder = builder.getClearChatBuilder();
this.clearMsgBuilder = builder.getClearMsgBuilder();
this.hostTargetBuilder= builder.getHostTargetBuilder();
this.modeBuilder = builder.getModeBuilder();
this.noticeBuilder = builder.getNoticeBuilder();
this.roomstateBuilder = builder.getRoomstateBuilder();
this.twitchUserBuilder= builder.getTwitchUserBuilder();
this.userstateBuilder = builder.getUserstateBuilder();
this.twitchMessageBuilder = builder.getTwitchMessageBuilder();
this.usernoticeBuilder= builder.getUsernoticeBuilder();
this.socketFactory = builder.getSocketFactory();
this.pingIntervalSeconds = builder.getPingInterval();
this.queue = new OutputQueue();
addIrcListener( new TwirkMaintainanceListener(this) );
}
//***********************************************************************************************
// PUBLIC
//***********************************************************************************************
/**Sends a message directly to the server. The message will not be formatted in
* any way. <br>
* This method should be used very sparsely, as it sidesteps the messaging
* delay and can get your bot Irc-banned on Twitch's side (might happen if the bot sends
* more than 20 messages in 30 seconds).
*
* @param message The message that should be sent
*/
public void serverMessage(String message) {
outThread.quickSend(message);
}
/**Enqueues a whisper at the end of the message queue. The whisper will
* be sent when all messages enqueued before it has been sent.
* <br>
* Be aware that too frequent use of whispers might get your bot rate
* limited.
*
* @param receiver The user that should receive the message
* @param message The message to whisper
*/
public void whisper(TwitchUser receiver, String message){
whisper(receiver.getUserName(), message);
}
/**Enqueues a whisper at the end of the message queue. The whisper will
* be sent when all messages enqueued before it has been sent.
* <br>
* Be aware that too frequent use of whispers might get your bot rate
* limited.
*
* @param userName The name of the user that should receive the message.
* @param message The message to whisper
*/
public void whisper(String userName, String message){
queue.add("PRIVMSG " + channel + " :/w " + userName + " " + message);
}
/**Enqueues a message at the end of the message queue. The message will be
* sent to the channel when all messages enqueued before it has been sent.
*
* @param message The message that should be sent
*/
public void channelMessage(String message){
queue.add("PRIVMSG " + channel + " :" + message);
}
/**Enqueues a message at the end of the message queue. The message will be
* sent to the channel when all messages enqueued before it has been sent.
*
* @param message The message that should be sent
* @param messageId The message id to reply to
*/
public void channelMessage(String message, String replyTarget){
queue.add("@reply-parent-msg-id=" + replyTarget + " PRIVMSG " + channel + " :" + message);
}
/**Enqueues a message at the front of the message queue. The message will be sent as soon as possible.
*
* @param message The message that should be sent
* @param messageId The message id to reply to
*/
public void priorityChannelMessage(String message, String replyTarget){
queue.addFirst("@reply-parent-msg-id=" + replyTarget + " PRIVMSG " + channel + " :" + message);
}
/**Enqueues a message at the front of the message queue. The message will be sent as soon as possible.
*
* @param message The message that should be sent
*/
public void priorityChannelMessage(String message){
queue.addFirst("PRIVMSG " + channel + " :" + message);
}
/**Check if this Twirk instance is currently connected to Twitch. If we are not, and we are not
* {@link #isDisposed()}, then we may try to reconnect. See {@link #connect()}
*
* @return <code>True</code> if we are connected
*/
public boolean isConnected() {
return isConnected;
}
/**Check if this Twirk instance has been disposed. If it has, no further
* connect attempts will succeed.
*
* @return <code>True</code> if it is disposed
*/
public boolean isDisposed() {
return isDisposed;
}
/**Fetches a set of all the users that are <b>currently</b> online in the joined channel. Note that this set is
* <b>copy</b> of the underlying set of online users. Thus, changes to the original set will not be visible
* in the returned set, and changes to the returned set will not affect the original set.<br><br>
*
* For getting all users online as soon as we connect, and the server has told us who are online,
* see {@link TwirkListener#onNamesList(java.util.Collection)}
*
* Also worth noting is that the set only contains the users names in lower case letters.
*
* @return A copy of the Set of online users.
*/
public Set<String> getUsersOnline(){
synchronized (online) {
return new HashSet<>(online);
}
}
/** Fetches a set of all the moderators that are <b>currently</b> online in the joined channel. Note that this set is
* <b>copy</b> of the underlying set of online moderators. Thus, changes to the original set will not be visible
* in the returned set, and changes to the returned set will not affect the original set.<br><br>
*
* Also worth noting is that the set only contains the moderators names in lower case letters.
*
* @return A copy of the Set of online moderators.
* @deprecated A few years ago, twitch sent a list of what mods were online when you connected. From that, it was
* easy to maintain a set of whom where online and not. But they've removed that feature some time ago,
* so this feature is now very much unreliable. It might still be doable via their Websocket API, but
* that is outside of the scope of this library.
*/
public Set<String> getModsOnline(){
synchronized (moderators) {
return new HashSet<>(moderators);
}
}
/** Fetches the nick of the bot, which it will use to connect to an IRC server
*
* @return The bot nick
*/
public String getNick() {
return nick;
}
/**Adds a specific listener to the list of active listeners
*
* @param listener Listener to be added
*/
public void addIrcListener(TwirkListener listener){
synchronized (listeners) {
this.listeners.add(listener);
}
}
/**Removes a specific listener from the list of active listeners
*
* @param listener Listener to be removed
* @return <code>true</code> if the listener was removed
*/
public boolean removeIrcListener(TwirkListener listener){
synchronized (listeners) {
return this.listeners.remove(listener);
}
}
/**Connects to the Twitch server and joins the channel which was designated in the TwirkBuilder.
*
* @return {@code true} if connection was successful
* @throws IOException In case the BufferedReader or BufferedWriter throws an error during connection. Might be due to timeout, socket closing or something else
* @throws InterruptedException In case the Twirk process is interrupted while connecting
*/
public synchronized boolean connect() throws IOException, InterruptedException{
if( isDisposed ){
logger.error("\tError. Cannot connect. This Twirk instance has been disposed.");
return false;
}
if( isConnected ){
logger.error("\tError. Cannot connect. Already connected to Twitch server");
return false;
}
logger.debug("\n\tCreating Twirk resources (threads, sockets...)");
if( !resourcesCreated ) {
createResources(); //Creates a socket and our input/output threads
}
logger.debug("\tConnecting to Twitch\n");
int oldTimeout = socket.getSoTimeout();
socket.setSoTimeout(10 * 1000); //Set a timeout for connection to 10 seconds, during connection
isConnected = doConnect();
socket.setSoTimeout(oldTimeout); //Return timeout to what it was before connecting
if( isConnected ){
//Start the output thread
outThread.start();
//Add capacities to the bot and wait for them to take effect
addCapacities();
Thread.sleep(1000);
//Start the input thread
inThread.start();
//Join the channel
serverMessage("JOIN " + channel);
for( TwirkListener listener: listeners ) {
listener.onConnect();
}
return true;
}
else {
logger.error("Connection to Twitch failed permanently. Please consult the debug logs for information");
return false;
}
}
/**Closes the connection to the IrcServer, leaves all channels, terminates the input- and output thread and
* frees all resources. <br><br>
*
* It is safe to call this method even if connections are already closed.<br><br>
*
* This method is different from {@link #close()} in that it calls the {@link TwirkListener#onDisconnect()} method
* of all the listeners. A listener may thus attempt to reconnect
*/
public synchronized void disconnect() {
//Since several sources can call this method on program shutdown, we avoid entering it again if
//we've already disconnected
if( !isConnected || isDisposed ) {
return;
}
isConnected = false;
logger.info("\n\tDisconnecting from Twitch chat...");
releaseResources();
logger.info("\tDisconnected from Twitch chat\n");
for( TwirkListener l : listeners ) {
l.onDisconnect();
}
}
/**Closes the connection to the IrcServer, leaves all channels, terminates the input- and output thread and
* frees all resources. <br><br>
*
* It is safe to call this method even if connections are already closed.<br><br>
*
* This method is different from {@link Twirk#disconnect()} in that it <b>does not</b> call the
* {@link TwirkListener#onDisconnect()} method of any of the listeners. Thus, this method is intended to be
* called if you intend to end using the Twirk instance, and want to make sure no reconnect attempts are performed.
*/
public synchronized void close(){
if( isDisposed ) {
return;
}
isConnected = false;
isDisposed = true;
logger.info("\n\tDisposing of IRC...");
releaseResources();
logger.info("\tDisposing of IRC completed\n");
}
//***********************************************************************************************
// PRIVATE and PACKAGE
//***********************************************************************************************
private void createResources() throws IOException{
socket = socketFactory.createSocket(serverAddress, serverPort);
socket.setSoTimeout(this.pingIntervalSeconds * 1000);
writer = new BufferedWriter( new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));
reader = new BufferedReader( new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
this.outThread = new OutputThread(this, queue, reader, writer);
this.inThread = new InputThread(this, reader, writer);
resourcesCreated = true;
}
private void releaseResources(){
resourcesCreated = false;
outThread.end();
inThread.end();
try { socket.close(); }
catch (IOException ignored) { }
try { reader.close(); }
catch (IOException ignored) { }
try { writer.close(); }
catch (IOException ignored) { }
}
private boolean doConnect() throws IOException{
// Log on to the server.
writer.write("PASS " + pass + "\r\n");
writer.write("NICK " + nick + "\r\n");
writer.write("USER " + nick + " 8 * : GikkBot\r\n");
writer.flush( );
// Read lines from the server until it tells us we have connected.
String line;
while ((line = reader.readLine()) != null) {
logger.debug("IN " + line);
//When we get a message containing 004, we have successfully logged in
if (line.contains("004")) {
return true;
}
else if (line.contains("Error logging in")) {
return false;
}
}
//We hit this return if the reader timed out, or we reached the end of stream
return false;
}
/**Gives us the appropriate Twitch capacities, such as seeing JOIN/PART messages,
* to send Twitch commands (such as .timeout, .mod and so on) and to see
* users tags (such as display color)
*/
private void addCapacities(){
serverMessage("CAP REQ :twitch.tv/membership");
serverMessage("CAP REQ :twitch.tv/commands");
serverMessage("CAP REQ :twitch.tv/tags");
}
/**Tells the OutputThread how long we should wait, at minimum, in between
* each message sent to Twitch.
*
* @param millis the delay
*/
void setOutputMessageDelay(int millis){
this.outThread.setMessageDelay(millis);
}
void incommingMessage(String line){
//PING is a bit strange, so we need to handle it separately. And also, we want to respond to a ping
//before we do anything else.
if ( line.contains("PING") ) {
// A PING contains the message "PING MESSAGE", and we want to reply with MESSAGE as well
// Hence, we reply "PONG MESSAGE" . That's where the substring(5) comes from bellow, we strip
//out everything but the message
logger.debug("IN " + line);
serverMessage("PONG " + line.substring(5) ); //Remove the "PING " part, and send the rest back
return;
}
//Call all the appropriate listeners for the given message.
synchronized (listeners) {
//First, we call all onAnything messages
for(TwirkListener l : listeners ) {
l.onAnything( line );
}
TwitchMessage message = twitchMessageBuilder.build(line);
//This message is a reply for a capacity request. Just ignore it
String s = message.getCommand();
switch (s) {
case "JOIN":
{
String userName = parseUsername( message.getPrefix() );
for(TwirkListener l : listeners ) {
l.onJoin( userName );
}
break;
}
case "MODE":
{
Mode mode = modeBuilder.build(message);
for(TwirkListener l : listeners ) {
l.onMode( mode );
}
break;
}
case "PART":
{
String userName = parseUsername( message.getPrefix() );
for(TwirkListener l : listeners ) {
l.onPart( userName );
}
break;
}
case "CLEARCHAT":
{
ClearChat clearChat = clearChatBuilder.build(message);
for(TwirkListener l : listeners ) {
l.onClearChat(clearChat);
}
break;
}
case "CLEARMSG":
{
ClearMsg clearMsg = clearMsgBuilder.build(message);
for(TwirkListener l : listeners ) {
l.onClearMsg(clearMsg);
}
break;
}
case "PRIVMSG":
{
TwitchUser user = twitchUserBuilder.build(message);
for(TwirkListener l : listeners ) {
l.onPrivMsg(user, message);
}
break;
}
case "WHISPER":
{
TwitchUser user = twitchUserBuilder.build(message);
for(TwirkListener l : listeners ) {
l.onWhisper(user, message);
}
break;
}
case "NOTICE":
{
Notice notice = noticeBuilder.build(message);
for(TwirkListener l : listeners ) {
l.onNotice( notice );
}
break;
}
case "USERSTATE":
{
Userstate userstate = userstateBuilder.build(message);
for(TwirkListener l : listeners ) {
l.onUserstate( userstate );
}
break;
}
case "USERNOTICE":
{
TwitchUser user = twitchUserBuilder.build(message);
Usernotice usernotice = usernoticeBuilder.build(message);
for(TwirkListener l : listeners ) {
l.onUsernotice(user, usernotice );
}
break;
}
case "ROOMSTATE":
{
Roomstate roomstate = roomstateBuilder.build(message);
for(TwirkListener l : listeners ) {
l.onRoomstate(roomstate);
}
break;
}
case "HOSTTARGET":
{
HostTarget hostTarget = hostTargetBuilder.build(message);
for(TwirkListener l : listeners ) {
l.onHost(hostTarget);
}
break;
}
case "RECONNECT":
{
for(TwirkListener l : listeners ) {
l.onReconnect();
}
break;
}
case "353":
{
//Code 353 is USER LIST messages, which lists users online separated by a space
List<String> users = Arrays.asList( message.getContent().split(" ") );
online.addAll( users );
break;
}
case "366":
{
//Code 366 means the USER LIST has ended
Set<String> users = Collections.unmodifiableSet(online);
for(TwirkListener l : listeners ) {
l.onNamesList(users);
}
break;
}
default:
{
//If we've gotten all the way down here, we don't know this message's type
for(TwirkListener l : listeners ) {
l.onUnknown( line );
}
}
}
}
}
private String parseUsername(String prefix) {
/* The user name is extracted from the message's prefix.
* JOIN or PART messages are formatted like this:
*
* :twitch_username!twitch_username@twitch_username.tmi.twitch.tv JOIN #channel
*/
return prefix.substring( prefix.charAt(0) == ':' ? 1 : 0, prefix.indexOf('!'));
}
}