-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathBot.java
More file actions
1315 lines (1121 loc) · 38.4 KB
/
Bot.java
File metadata and controls
1315 lines (1121 loc) · 38.4 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
package oakbot.bot;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import org.jsoup.Jsoup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.mangstadt.sochat4j.ChatMessage;
import com.github.mangstadt.sochat4j.IChatClient;
import com.github.mangstadt.sochat4j.IRoom;
import com.github.mangstadt.sochat4j.PrivateRoomException;
import com.github.mangstadt.sochat4j.RoomNotFoundException;
import com.github.mangstadt.sochat4j.RoomPermissionException;
import com.github.mangstadt.sochat4j.event.Event;
import com.github.mangstadt.sochat4j.event.InvitationEvent;
import com.github.mangstadt.sochat4j.event.MessageEditedEvent;
import com.github.mangstadt.sochat4j.event.MessagePostedEvent;
import com.github.mangstadt.sochat4j.util.Sleeper;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import oakbot.Database;
import oakbot.MemoryDatabase;
import oakbot.Rooms;
import oakbot.Statistics;
import oakbot.filter.ChatResponseFilter;
import oakbot.inactivity.InactivityTask;
import oakbot.listener.Listener;
import oakbot.task.ScheduledTask;
import oakbot.util.ChatBuilder;
/**
* A Stackoverflow chat bot.
* @author Michael Angstadt
*/
public class Bot implements IBot {
private static final Logger logger = LoggerFactory.getLogger(Bot.class);
static final int BOTLER_ID = 13750349;
private static final Duration ROOM_JOIN_DELAY = Duration.ofSeconds(2);
private final BotConfiguration config;
private final SecurityConfiguration security;
private final IChatClient connection;
private final AtomicLong choreIdCounter = new AtomicLong();
private final BlockingQueue<Chore> choreQueue = new PriorityBlockingQueue<>();
private final Rooms rooms;
private final Integer maxRooms;
private final List<Listener> listeners;
private final List<ChatResponseFilter> responseFilters;
private final List<ScheduledTask> scheduledTasks;
private final List<InactivityTask> inactivityTasks;
private final Map<Integer, LocalDateTime> timeOfLastMessageByRoom = new HashMap<>();
private final Multimap<Integer, TimerTask> inactivityTimerTasksByRoom = ArrayListMultimap.create();
private final Statistics stats;
private final Database database;
private final Timer timer = new Timer();
private TimerTask timeoutTask;
private volatile boolean timeout = false;
/**
* <p>
* A collection of messages that the bot posted, but have not been "echoed"
* back yet in the chat room. When a message is echoed back, it is removed
* from this map.
* </p>
* <p>
* This is used to determine whether something the bot posted was converted
* to a onebox. It is then used to edit the message in order to hide the
* onebox.
* </p>
* <ul>
* <li>Key = The message ID.</li>
* <li>Value = The raw message content that was sent to the chat room by the
* bot (which can be different from what was echoed back).</li>
* </ul>
*/
private final Map<Long, PostedMessage> postedMessages = new HashMap<>();
private Bot(Builder builder) {
connection = Objects.requireNonNull(builder.connection);
var userName = (connection.getUsername() == null) ? builder.userName : connection.getUsername();
var userId = (connection.getUserId() == null) ? builder.userId : connection.getUserId();
config = new BotConfiguration(userName, userId, builder.trigger, builder.greeting, builder.hideOneboxesAfter);
security = new SecurityConfiguration(builder.admins, builder.bannedUsers, builder.allowedUsers);
maxRooms = builder.maxRooms;
stats = builder.stats;
database = (builder.database == null) ? new MemoryDatabase() : builder.database;
rooms = new Rooms(database, builder.roomsHome, builder.roomsQuiet);
listeners = builder.listeners;
scheduledTasks = builder.tasks;
inactivityTasks = builder.inactivityTasks;
responseFilters = builder.responseFilters;
}
private void scheduleTask(ScheduledTask task) {
var nextRun = task.nextRun();
if (nextRun <= 0) {
return;
}
scheduleChore(nextRun, new ScheduledTaskChore(task));
}
private void scheduleTask(InactivityTask task, IRoom room, Duration nextRun) {
var timerTask = scheduleChore(nextRun, new InactivityTaskChore(task, room));
inactivityTimerTasksByRoom.put(room.getRoomId(), timerTask);
}
/**
* Starts the chat bot. The bot will join the rooms in the current thread
* before launching its own thread.
* @param quiet true to start the bot without broadcasting the greeting
* message, false to broadcast the greeting message
* @return the thread that the bot is running in. This thread will terminate
* when the bot terminates
* @throws IOException if there's a network problem
*/
public Thread connect(boolean quiet) throws IOException {
joinRoomsOnStart(quiet);
var thread = new ChoreThread();
thread.start();
return thread;
}
private void joinRoomsOnStart(boolean quiet) {
var first = true;
var roomsCopy = new ArrayList<>(rooms.getRooms());
for (var room : roomsCopy) {
if (!first) {
/*
* Insert a pause between joining each room in an attempt to
* resolve an issue where the bot chooses to ignore all messages
* in certain rooms.
*/
Sleeper.sleep(ROOM_JOIN_DELAY);
}
try {
joinRoom(room, quiet);
} catch (Exception e) {
logger.atError().setCause(e).log(() -> "Could not join room " + room + ". Removing from rooms list.");
rooms.remove(room);
}
first = false;
}
}
private class ChoreThread extends Thread {
@Override
public void run() {
try {
scheduledTasks.forEach(Bot.this::scheduleTask);
while (true) {
Chore chore;
try {
chore = choreQueue.take();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
logger.atError().setCause(e).log(() -> "Thread interrupted while waiting for new chores.");
break;
}
if (chore instanceof StopChore || chore instanceof FinishChore) {
break;
}
chore.complete();
database.commit();
}
} catch (Exception e) {
logger.atError().setCause(e).log(() -> "Bot terminated due to unexpected exception.");
} finally {
try {
connection.close();
} catch (IOException e) {
logger.atError().setCause(e).log(() -> "Problem closing ChatClient connection.");
}
database.commit();
timer.cancel();
}
}
}
@Override
public List<ChatMessage> getLatestMessages(int roomId, int count) throws IOException {
var room = connection.getRoom(roomId);
var notInRoom = (room == null);
if (notInRoom) {
return List.of();
}
//@formatter:off
return room.getMessages(count).stream()
.map(this::convertFromBotlerRelayMessage)
.toList();
//@formatter:on
}
@Override
public String getOriginalMessageContent(long messageId) throws IOException {
return connection.getOriginalMessageContent(messageId);
}
@Override
public String uploadImage(String url) throws IOException {
return connection.uploadImage(url);
}
@Override
public String uploadImage(byte[] data) throws IOException {
return connection.uploadImage(data);
}
@Override
public void sendMessage(int roomId, PostMessage message) throws IOException {
var room = connection.getRoom(roomId);
if (room != null) {
sendMessage(room, message);
}
}
private void sendMessage(IRoom room, String message) throws IOException {
sendMessage(room, new PostMessage(message));
}
private void sendMessage(IRoom room, PostMessage message) throws IOException {
final String filteredMessage;
if (message.bypassFilters()) {
filteredMessage = message.message();
} else {
var messageText = message.message();
for (var filter : responseFilters) {
if (filter.isEnabled(room.getRoomId())) {
messageText = filter.filter(messageText);
}
}
filteredMessage = messageText;
}
logger.atInfo().log(() -> "Sending message [room=" + room.getRoomId() + "]: " + filteredMessage);
synchronized (postedMessages) {
var messageIds = room.sendMessage(filteredMessage, message.parentId(), message.splitStrategy());
var condensedMessage = message.condensedMessage();
var ephemeral = message.ephemeral();
var postedMessage = new PostedMessage(Instant.now(), filteredMessage, condensedMessage, ephemeral, room.getRoomId(), message.parentId(), messageIds);
postedMessages.put(messageIds.get(0), postedMessage);
}
}
@Override
public void join(int roomId) throws IOException {
joinRoom(roomId);
}
/**
* Joins a room.
* @param roomId the room ID
* @return the connection to the room
* @throws RoomNotFoundException if the room does not exist
* @throws PrivateRoomException if the room can't be joined because it is
* private
* @throws IOException if there's a problem connecting to the room
*/
private IRoom joinRoom(int roomId) throws RoomNotFoundException, PrivateRoomException, IOException {
return joinRoom(roomId, false);
}
/**
* Joins a room.
* @param roomId the room ID
* @param quiet true to not post an announcement message, false to post one
* @return the connection to the room
* @throws RoomNotFoundException if the room does not exist
* @throws PrivateRoomException if the room can't be joined because it is
* private
* @throws IOException if there's a problem connecting to the room
*/
private IRoom joinRoom(int roomId, boolean quiet) throws RoomNotFoundException, PrivateRoomException, IOException {
var room = connection.getRoom(roomId);
if (room != null) {
return room;
}
logger.atInfo().log(() -> "Joining room " + roomId + "...");
room = connection.joinRoom(roomId);
room.addEventListener(MessagePostedEvent.class, event -> choreQueue.add(new ChatEventChore(event)));
room.addEventListener(MessageEditedEvent.class, event -> choreQueue.add(new ChatEventChore(event)));
room.addEventListener(InvitationEvent.class, event -> choreQueue.add(new ChatEventChore(event)));
if (!quiet && config.greeting() != null) {
try {
sendMessage(room, config.greeting());
} catch (RoomPermissionException e) {
logger.atWarn().setCause(e).log(() -> "Unable to post greeting when joining room " + roomId + ".");
}
}
rooms.add(roomId);
for (var task : inactivityTasks) {
var nextRun = task.getInactivityTime(room, this);
if (nextRun == null) {
continue;
}
scheduleTask(task, room, nextRun);
}
return room;
}
@Override
public void leave(int roomId) throws IOException {
logger.atInfo().log(() -> "Leaving room " + roomId + "...");
inactivityTimerTasksByRoom.removeAll(roomId).forEach(TimerTask::cancel);
timeOfLastMessageByRoom.remove(roomId);
rooms.remove(roomId);
var room = connection.getRoom(roomId);
if (room != null) {
room.leave();
}
}
@Override
public String getUsername() {
return config.userName();
}
@Override
public Integer getUserId() {
return config.userId();
}
@Override
public List<Integer> getAdminUsers() {
return security.getAdmins();
}
private boolean isAdminUser(Integer userId) {
return security.isAdmin(userId);
}
@Override
public boolean isRoomOwner(int roomId, int userId) throws IOException {
var userInfo = connection.getUserInfo(roomId, userId);
return (userInfo == null) ? false : userInfo.isOwner();
}
@Override
public String getTrigger() {
return config.trigger();
}
@Override
public List<Integer> getRooms() {
return rooms.getRooms();
}
@Override
public IRoom getRoom(int roomId) {
return connection.getRoom(roomId);
}
@Override
public List<Integer> getHomeRooms() {
return rooms.getHomeRooms();
}
@Override
public List<Integer> getQuietRooms() {
return rooms.getQuietRooms();
}
@Override
public Integer getMaxRooms() {
return maxRooms;
}
@Override
public void broadcastMessage(PostMessage message) throws IOException {
for (var room : connection.getRooms()) {
if (!rooms.isQuietRoom(room.getRoomId())) {
sendMessage(room, message);
}
}
}
@Override
public synchronized void timeout(Duration duration) {
if (timeout) {
timeoutTask.cancel();
} else {
timeout = true;
}
timeoutTask = new TimerTask() {
@Override
public void run() {
timeout = false;
}
};
timer.schedule(timeoutTask, duration.toMillis());
}
@Override
public synchronized void cancelTimeout() {
timeout = false;
if (timeoutTask != null) {
timeoutTask.cancel();
}
}
/**
* Sends a signal to immediately stop processing tasks. The bot thread will
* stop running once it is done processing the current task.
*/
public void stop() {
choreQueue.add(new StopChore());
}
/**
* Sends a signal to finish processing the tasks in the queue, and then
* terminate.
*/
public void finish() {
choreQueue.add(new FinishChore());
}
private TimerTask scheduleChore(long delay, Chore chore) {
var timerTask = new TimerTask() {
@Override
public void run() {
choreQueue.add(chore);
}
};
timer.schedule(timerTask, delay);
return timerTask;
}
private TimerTask scheduleChore(Duration delay, Chore chore) {
return scheduleChore(delay.toMillis(), chore);
}
/**
* Represents a message that was posted to the chat room.
* @author Michael Angstadt
*/
private static class PostedMessage {
private final Instant timePosted;
private final String originalContent;
private final String condensedContent;
private final boolean ephemeral;
private final int roomId;
private final long parentId;
private final List<Long> messageIds;
/**
* @param timePosted the time the message was posted
* @param originalContent the original message that the bot sent to the
* chat room
* @param condensedContent the text that the message should be changed
* to after the amount of time specified in the "hideOneboxesAfter"
* setting
* @param ephemeral true to delete the message after the amount of time
* specified in the "hideOneboxesAfter" setting, false not to
* @param roomId the ID of the room the message was posted in
* @param parentId the ID of the message that this was a reply to
* @param messageIds the ID of each message that was actually posted to
* the room (the chat client may split up the original message due to
* length limitations)
*/
public PostedMessage(Instant timePosted, String originalContent, String condensedContent, boolean ephemeral, int roomId, long parentId, List<Long> messageIds) {
this.timePosted = timePosted;
this.originalContent = originalContent;
this.condensedContent = condensedContent;
this.ephemeral = ephemeral;
this.roomId = roomId;
this.parentId = parentId;
this.messageIds = messageIds;
}
/**
* Gets the time the message was posted.
* @return the time the message was posted
*/
public Instant getTimePosted() {
return timePosted;
}
/**
* Gets the content of the original message that the bot sent to the
* chat room. This is used for when a message was converted to a onebox.
* @return the original content
*/
public String getOriginalContent() {
return originalContent;
}
/**
* Gets the text that the message should be changed to after the amount
* of time specified in the "hideOneboxesAfter" setting.
* @return the new content or null to leave the message alone
*/
public String getCondensedContent() {
return condensedContent;
}
/**
* Gets the ID of each message that was actually posted to the room. The
* chat client may split up the original message due to length
* limitations.
* @return the message IDs
*/
public List<Long> getMessageIds() {
return messageIds;
}
/**
* Gets the ID of the room the message was posted in.
* @return the room ID
*/
public int getRoomId() {
return roomId;
}
/**
* Determines if the message has requested that it be condensed or
* deleted after the amount of time specified in the "hideOneboxesAfter"
* setting. Does not include messages that were converted to oneboxes.
* @return true to condense or delete the message, false to leave it
* alone
*/
public boolean isCondensableOrEphemeral() {
return condensedContent != null || isEphemeral();
}
/**
* Determines if the message has requested that it be deleted after the
* amount of time specified in the "hideOneboxesAfter"
* setting. Does not include messages that were converted to oneboxes.
* @return true to delete the message, false not to
*/
public boolean isEphemeral() {
return ephemeral;
}
/**
* Gets the ID of the message that this was a reply to.
* @return the parent ID or 0 if it's not a reply
*/
public long getParentId() {
return parentId;
}
}
private abstract class Chore implements Comparable<Chore> {
private final long choreId;
public Chore() {
choreId = choreIdCounter.getAndIncrement();
}
public abstract void complete();
@Override
public int compareTo(Chore that) {
/*
* The "lowest" value will be popped off the queue first.
*/
if (isBothStopChore(that)) {
return 0;
}
if (isThisStopChore()) {
return -1;
}
if (isThatStopChore(that)) {
return 1;
}
if (isBothCondenseMessageChore(that)) {
return Long.compare(this.choreId, that.choreId);
}
if (isThisCondenseMessageChore()) {
return -1;
}
if (isThatCondenseMessageChore(that)) {
return 1;
}
return Long.compare(this.choreId, that.choreId);
}
private boolean isBothStopChore(Chore that) {
return this instanceof StopChore && that instanceof StopChore;
}
private boolean isThisStopChore() {
return this instanceof StopChore;
}
private boolean isThatStopChore(Chore that) {
return that instanceof StopChore;
}
private boolean isBothCondenseMessageChore(Chore that) {
return this instanceof CondenseMessageChore && that instanceof CondenseMessageChore;
}
private boolean isThisCondenseMessageChore() {
return this instanceof CondenseMessageChore;
}
private boolean isThatCondenseMessageChore(Chore that) {
return that instanceof CondenseMessageChore;
}
}
private class StopChore extends Chore {
@Override
public void complete() {
//empty
}
}
private class FinishChore extends Chore {
@Override
public void complete() {
//empty
}
}
private class ChatEventChore extends Chore {
private final Event event;
public ChatEventChore(Event event) {
this.event = event;
}
@Override
public void complete() {
if (event instanceof MessagePostedEvent mpe) {
handleMessage(mpe.getMessage());
return;
}
if (event instanceof MessageEditedEvent mee) {
handleMessage(mee.getMessage());
return;
}
if (event instanceof InvitationEvent ie) {
var roomId = ie.getRoomId();
var userId = ie.getUserId();
var inviterIsAdmin = isAdminUser(userId);
boolean acceptInvitation;
if (inviterIsAdmin) {
acceptInvitation = true;
} else {
try {
acceptInvitation = isRoomOwner(roomId, userId);
} catch (IOException e) {
logger.atError().setCause(e).log(() -> "Unable to handle room invite. Error determining whether user is room owner.");
acceptInvitation = false;
}
}
if (acceptInvitation) {
handleInvitation(ie);
}
return;
}
logger.atError().log(() -> "Ignoring event: " + event.getClass().getName());
}
private void handleMessage(ChatMessage message) {
var userId = message.getUserId();
var isAdminUser = isAdminUser(userId);
var isBotInTimeout = timeout && !isAdminUser;
if (isBotInTimeout) {
//bot is in timeout, ignore
return;
}
var messageWasDeleted = message.getContent() == null;
if (messageWasDeleted) {
//user deleted their message, ignore
return;
}
var hasAllowedUsersList = !security.getAllowedUsers().isEmpty();
var userIsAllowed = security.isAllowed(userId);
if (hasAllowedUsersList && !userIsAllowed) {
//message was posted by a user who is not in the green list, ignore
return;
}
var userIsBanned = security.isBanned(userId);
if (userIsBanned) {
//message was posted by a banned user, ignore
return;
}
var room = connection.getRoom(message.getRoomId());
if (room == null) {
//the bot is no longer in the room
return;
}
if (message.getUserId() == config.userId()) {
//message was posted by this bot
handleBotMessage(message);
return;
}
message = convertFromBotlerRelayMessage(message);
timeOfLastMessageByRoom.put(message.getRoomId(), message.getTimestamp());
var actions = handleListeners(message);
handleActions(message, actions);
}
private void handleBotMessage(ChatMessage message) {
PostedMessage postedMessage;
synchronized (postedMessages) {
postedMessage = postedMessages.remove(message.getMessageId());
}
/*
* Check to see if the message should be edited for brevity
* after a short time so it doesn't spam the chat history.
*
* This could happen if (1) the bot posted something that Stack
* Overflow Chat converted to a onebox (e.g. an image) or (2)
* the message itself has asked to be edited (e.g. a javadoc
* description).
*
* ===What is a onebox?===
*
* Stack Overflow Chat converts certain URLs to "oneboxes".
* Oneboxes can be fairly large and can spam the chat. For
* example, if the message is a URL to an image, the image
* itself will be displayed in the chat room. This is nice, but
* gets annoying if the image is large or if it's an animated
* GIF.
*
* After giving people some time to see the onebox, the bot will
* edit the message so that the onebox no longer displays, but
* the URL is still preserved.
*/
var messageIsOnebox = message.getContent().isOnebox();
if (postedMessage != null && config.hideOneboxesAfter() != null && (messageIsOnebox || postedMessage.isCondensableOrEphemeral())) {
var postedMessageAge = Duration.between(postedMessage.getTimePosted(), Instant.now());
var hideIn = config.hideOneboxesAfter().minus(postedMessageAge);
logger.atInfo().log(() -> {
var action = messageIsOnebox ? "Hiding onebox" : "Condensing message";
return action + " in " + hideIn.toMillis() + "ms [room=" + message.getRoomId() + ", id=" + message.getMessageId() + "]: " + message.getContent();
});
scheduleChore(hideIn, new CondenseMessageChore(postedMessage));
}
}
private ChatActions handleListeners(ChatMessage message) {
var actions = new ChatActions();
for (var listener : listeners) {
try {
actions.addAll(listener.onMessage(message, Bot.this));
} catch (Exception e) {
logger.atError().setCause(e).log(() -> "Problem running listener.");
}
}
return actions;
}
private void handleActions(ChatMessage message, ChatActions actions) {
if (actions.isEmpty()) {
return;
}
logger.atInfo().log(() -> "Responding to message [room=" + message.getRoomId() + ", user=" + message.getUsername() + ", id=" + message.getMessageId() + "]: " + message.getContent());
if (stats != null) {
stats.incMessagesRespondedTo();
}
var queue = new LinkedList<>(actions.getActions());
while (!queue.isEmpty()) {
var action = queue.removeFirst();
processAction(action, message, queue);
}
}
private void processAction(ChatAction action, ChatMessage message, LinkedList<ChatAction> queue) {
// Conditional dispatch based on action type (replaces polymorphism)
if (action instanceof PostMessage pm) {
handlePostMessageAction(pm, message);
} else if (action instanceof DeleteMessage dm) {
var response = handleDeleteMessageAction(dm, message);
queue.addAll(response.getActions());
} else if (action instanceof JoinRoom jr) {
var response = handleJoinRoomAction(jr);
queue.addAll(response.getActions());
} else if (action instanceof LeaveRoom lr) {
handleLeaveRoomAction(lr);
} else if (action instanceof Shutdown) {
stop();
} else {
logger.atWarn().log(() -> "Unknown action type: " + action.getClass().getName());
}
}
private void handlePostMessageAction(PostMessage action, ChatMessage message) {
try {
if (action.delay() != null) {
scheduleChore(action.delay(), new DelayedMessageChore(message.getRoomId(), action));
} else {
if (action.broadcast()) {
broadcastMessage(action);
} else {
sendMessage(message.getRoomId(), action);
}
}
} catch (Exception e) {
logger.atError().setCause(e).log(() -> "Problem posting message [room=" + message.getRoomId() + "]: " + action.message());
}
}
private ChatActions handleDeleteMessageAction(DeleteMessage action, ChatMessage message) {
try {
var room = connection.getRoom(message.getRoomId());
room.deleteMessage(action.messageId());
return action.onSuccess().get();
} catch (Exception e) {
logger.atError().setCause(e).log(() -> "Problem deleting message [room=" + message.getRoomId() + ", messageId=" + action.messageId() + "]");
return action.onError().apply(e);
}
}
private ChatActions handleJoinRoomAction(JoinRoom action) {
if (maxRooms != null && connection.getRooms().size() >= maxRooms) {
return action.onError().apply(new IOException("Cannot join room. Max rooms reached."));
}
try {
var joinedRoom = joinRoom(action.roomId());
if (joinedRoom.canPost()) {
return action.onSuccess().get();
}
leaveRoomSafely(action.roomId(), () -> "Problem leaving room " + action.roomId() + " after it was found that the bot can't post messages to it.");
return action.ifLackingPermissionToPost().get();
} catch (PrivateRoomException | RoomPermissionException e) {
leaveRoomSafely(action.roomId(), () -> "Problem leaving room " + action.roomId() + " after it was found that the bot can't join or post messages to it.");
return action.ifLackingPermissionToPost().get();
} catch (RoomNotFoundException e) {
return action.ifRoomDoesNotExist().get();
} catch (Exception e) {
return action.onError().apply(e);
}
}
/**
* Attempts to leave a room and logs any errors that occur.
* @param roomId the room ID to leave
* @param logMessage supplier for the complete log message (evaluated only if an error occurs)
**/
private void leaveRoomSafely(int roomId, Supplier<String> logMessage) {
try {
leave(roomId);
}
catch (Exception e) {
logger.atError().setCause(e).log(logMessage);
}
}
private void handleLeaveRoomAction(LeaveRoom action) {
try {
leave(action.roomId());
} catch (Exception e) {
logger.atError().setCause(e).log(() -> "Problem leaving room " + action.roomId() + ".");
}
}
private void handleInvitation(InvitationEvent event) {
/*
* If the bot is currently connected to multiple rooms, the
* invitation event will be sent to each room and this method will
* be called multiple times. Check to see if the bot has already
* joined the room it was invited to.
*/
var roomId = event.getRoomId();
if (connection.isInRoom(roomId)) {
return;
}
/*
* Ignore the invitation if the bot is connected to the maximum
* number of rooms allowed. We can't really post an error message
* because the invitation event is not linked to a specific chat
* room.
*/
var maxRoomsExceeded = (maxRooms != null && connection.getRooms().size() >= maxRooms);
if (maxRoomsExceeded) {
return;
}
try {
joinRoom(roomId);
} catch (Exception e) {
logger.atError().setCause(e).log(() -> "Bot was invited to join room " + roomId + ", but couldn't join it.");
}
}
}
private class CondenseMessageChore extends Chore {
private final Pattern replyRegex = Pattern.compile("^:(\\d+) (.*)", Pattern.DOTALL);
private final PostedMessage postedMessage;
public CondenseMessageChore(PostedMessage postedMessage) {
this.postedMessage = postedMessage;
}
@Override
public void complete() {
var roomId = postedMessage.getRoomId();
var room = connection.getRoom(roomId);
var botIsNoLongerInTheRoom = (room == null);
if (botIsNoLongerInTheRoom) {
return;
}
try {
List<Long> messagesToDelete;
if (postedMessage.isEphemeral()) {
messagesToDelete = postedMessage.getMessageIds();
} else {
var condensedContent = postedMessage.getCondensedContent();
var isAOneBox = (condensedContent == null);
if (isAOneBox) {
condensedContent = postedMessage.getOriginalContent();
}
var messageIds = postedMessage.getMessageIds();
var quotedContent = quote(condensedContent);
room.editMessage(messageIds.get(0), postedMessage.getParentId(), quotedContent);
/*
* If the original content was split up into
* multiple messages due to length constraints,
* delete the additional messages.
*/
messagesToDelete = messageIds.subList(1, messageIds.size());
}
for (var id : messagesToDelete) {
room.deleteMessage(id);
}
} catch (Exception e) {
logger.atError().setCause(e).log(() -> "Problem editing chat message [room=" + roomId + ", id=" + postedMessage.getMessageIds().get(0) + "]");