/
ChatClient.ts
1460 lines (1325 loc) · 46.6 KB
/
ChatClient.ts
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
import type { Logger, LoggerOptions } from '@d-fischer/logger';
import { createLogger, LogLevel } from '@d-fischer/logger';
import type { RateLimiter, RateLimiterRequestOptions } from '@d-fischer/rate-limiter';
import {
PartitionedTimeBasedRateLimiter,
TimeBasedRateLimiter,
TimedPassthruRateLimiter
} from '@d-fischer/rate-limiter';
import {
delay,
Enumerable,
fibWithLimit,
promiseWithResolvers,
type ResolvableValue,
resolveConfigValue
} from '@d-fischer/shared-utils';
import { EventEmitter } from '@d-fischer/typed-event-emitter';
import type { AccessToken, AuthProvider } from '@twurple/auth';
import {
accessTokenIsExpired,
getTokenInfo,
InvalidTokenError,
InvalidTokenTypeError,
RefreshingAuthProvider
} from '@twurple/auth';
import { rtfm } from '@twurple/common';
import type { WebSocketConnectionOptions } from 'ircv3';
import { IrcClient, MessageTypes } from 'ircv3';
import { TwitchCommandsCapability } from './caps/twitchCommands';
import { ClearChat } from './caps/twitchCommands/messageTypes/ClearChat';
import { RoomState } from './caps/twitchCommands/messageTypes/RoomState';
import { UserNotice } from './caps/twitchCommands/messageTypes/UserNotice';
import { Whisper } from './caps/twitchCommands/messageTypes/Whisper';
import { TwitchMembershipCapability } from './caps/TwitchMembershipCapability';
import { TwitchTagsCapability } from './caps/twitchTags';
import { ClearMsg } from './caps/twitchTags/messageTypes/ClearMsg';
import type { ChatSayMessageAttributes } from './ChatMessageAttributes';
import { extractMessageId } from './ChatMessageAttributes';
import { TwitchPrivateMessage } from './commands/TwitchPrivateMessage';
import type { ChatAnnouncementInfo } from './userNotices/ChatAnnouncementInfo';
import type { ChatBitsBadgeUpgradeInfo } from './userNotices/ChatBitsBadgeUpgradeInfo';
import type { ChatCommunityPayForwardInfo } from './userNotices/ChatCommunityPayForwardInfo';
import type { ChatCommunitySubInfo } from './userNotices/ChatCommunitySubInfo';
import type { ChatPrimeCommunityGiftInfo } from './userNotices/ChatPrimeCommunityGiftInfo';
import type { ChatRaidInfo } from './userNotices/ChatRaidInfo';
import type { ChatRewardGiftInfo } from './userNotices/ChatRewardGiftInfo';
import type { ChatRitualInfo } from './userNotices/ChatRitualInfo';
import type { ChatStandardPayForwardInfo } from './userNotices/ChatStandardPayForwardInfo';
import type {
ChatSubExtendInfo,
ChatSubGiftInfo,
ChatSubGiftUpgradeInfo,
ChatSubInfo,
ChatSubUpgradeInfo
} from './userNotices/ChatSubInfo';
import { splitOnSpaces } from './utils/messageUtil';
import { toChannelName, toUserName } from './utils/userUtil';
/**
* A Twitch bot level, i.e. whether you're connecting as a known or verified bot.
*/
export type TwitchBotLevel = 'none' | 'known' | 'verified';
/**
* Options for a chat client.
*/
export interface ChatClientOptions {
/**
* The authentication provider to use for getting the chat credentials.
*
* If you don't pass this, the chat client will connect anonymously.
*/
authProvider?: AuthProvider;
/**
* Whether to request a token with only read permission.
*
* Ignored if `legacyScopes` is `true`.
*/
readOnly?: boolean;
/**
* Whether to request a token with the old chat permission scope.
*
* If you're not sure whether this is necessary, just try leaving this off, and if it doesn't work, turn it on and try again.
*/
legacyScopes?: boolean;
/**
* Options to pass to the logger.
*/
logger?: Partial<LoggerOptions>;
/**
* Whether to connect securely using SSL.
*
* You should not disable this except for debugging purposes.
*/
ssl?: boolean;
/**
* Custom hostname for connecting to chat.
*/
hostName?: string;
/**
* Whether to use a WebSocket to connect to chat.
*/
webSocket?: boolean;
/**
* The connection options for a WebSocket connection.
*
* If not using WebSockets, this is ignored.
*/
connectionOptions?: WebSocketConnectionOptions;
/**
* Whether to receive JOIN and PART messages from Twitch chat.
*/
requestMembershipEvents?: boolean;
/**
* Channels to join after connecting.
*
* May also be a function (sync or async) that returns a list of channels.
*/
channels?: ResolvableValue<string[]>;
/**
* Whether to rejoin the channels the client had joined when a reconnect occurs.
*
* This means that the `channels` option will only be resolved on the initial connection.
*/
rejoinChannelsOnReconnect?: boolean;
/**
* Whether you're guaranteed to be a mod in all joined channels.
*
* This raises the rate limit and lifts the one-second-between-messages rule,
* but if your bot is not a mod in one of the channels, it subjects you to messages
* possibly silently not being delivered and your bot possibly getting banned.
*/
isAlwaysMod?: boolean;
/**
* Your bot level, i.e. whether you're a known or verified bot.
*
* This defaults to 'none', which limits your messages to the standard rate limit.
*/
botLevel?: TwitchBotLevel;
/**
* The intents to use to query the auth provider.
*
* The "chat" intent will always be queried last, after the ones you give here.
*/
authIntents?: string[];
}
/** @private */
export interface ChatMessageRequest {
type: 'say' | 'action';
channel: string;
text: string;
tags?: Record<string, string>;
}
/** @private */
export interface WhisperRequest {
target: string;
text: string;
}
/**
* An interface to Twitch chat.
*/
@rtfm('chat', 'ChatClient')
export class ChatClient extends EventEmitter {
/** @private */
@Enumerable(false) readonly _authProvider?: AuthProvider;
private readonly _useLegacyScopes: boolean;
private readonly _readOnly: boolean;
private readonly _authIntents: string[];
private _authToken?: AccessToken | null;
private _authVerified = false;
private _authRetryTimer?: Iterator<number, never>;
private _authRetryCount = 0;
private readonly _chatLogger: Logger;
private readonly _messageRateLimiter: RateLimiter<ChatMessageRequest, void>;
private readonly _joinRateLimiter: RateLimiter<string, void>;
private readonly _ircClient: IrcClient;
/**
* Fires when the client successfully connects to the chat server.
*
* @eventListener
*/
readonly onConnect = this.registerEvent<[]>();
/**
* Fires when the client disconnects from the chat server.
*
* @eventListener
* @param manually Whether the disconnect was requested by the user.
* @param reason The error that caused the disconnect, or `undefined` if there was no error.
*/
readonly onDisconnect = this.registerEvent<[manually: boolean, reason?: Error]>();
/**
* Fires when a user is timed out from a channel.
*
* @eventListener
* @param channel The channel the user is timed out from.
* @param user The timed out user.
* @param duration The duration of the timeout, in seconds.
* @param msg The full message object containing all message and user information.
*/
readonly onTimeout = this.registerEvent<[channel: string, user: string, duration: number, msg: ClearChat]>();
/**
* Fires when a user is permanently banned from a channel.
*
* @eventListener
* @param channel The channel the user is banned from.
* @param user The banned user.
* @param msg The full message object containing all message and user information.
*/
readonly onBan = this.registerEvent<[channel: string, user: string, msg: ClearChat]>();
/**
* Fires when a user upgrades their bits badge in a channel.
*
* @eventListener
* @param channel The channel where the bits badge was upgraded.
* @param user The user that has upgraded their bits badge.
* @param ritualInfo Additional information about the upgrade.
* @param msg The full message object containing all message and user information.
*/
readonly onBitsBadgeUpgrade =
this.registerEvent<[channel: string, user: string, upgradeInfo: ChatBitsBadgeUpgradeInfo, msg: UserNotice]>();
/**
* Fires when the chat of a channel is cleared.
*
* @eventListener
* @param channel The channel whose chat is cleared.
* @param msg The full message object containing all message and user information.
*/
readonly onChatClear = this.registerEvent<[channel: string, msg: ClearChat]>();
/**
* Fires when emote-only mode is toggled in a channel.
*
* @eventListener
* @param channel The channel where emote-only mode is being toggled.
* @param enabled Whether emote-only mode is being enabled. If false, it's being disabled.
*/
readonly onEmoteOnly = this.registerEvent<[channel: string, enabled: boolean]>();
/**
* Fires when followers-only mode is toggled in a channel.
*
* @eventListener
* @param channel The channel where followers-only mode is being toggled.
* @param enabled Whether followers-only mode is being enabled. If false, it's being disabled.
* @param delay The time (in minutes) a user needs to follow the channel to be able to talk. Only available when `enabled === true`.
*/
readonly onFollowersOnly = this.registerEvent<[channel: string, enabled: boolean, delay?: number]>();
/**
* Fires when a user joins a channel.
*
* The join/part events are cached by the Twitch chat server and will be batched and sent every 30-60 seconds.
*
* Please note that unless you enabled the `requestMembershipEvents` option, this will only react to your own joins.
*
* @eventListener
* @param channel The channel that is being joined.
* @param user The user that joined.
*/
readonly onJoin = this.registerEvent<[channel: string, user: string]>();
/**
* Fires when you fail to join a channel.
*
* @eventListener
* @param channel The channel that you tried to join.
* @param reason The reason for the failure.
*/
readonly onJoinFailure = this.registerEvent<[channel: string, reason: string]>();
/**
* Fires when a user leaves ("parts") a channel.
*
* The join/part events are cached by the Twitch chat server and will be batched and sent every 30-60 seconds.
*
* Please note that unless you enabled the `requestMembershipEvents` option, this will only react to your own parts.
*
* @eventListener
* @param channel The channel that is being left.
* @param user The user that left.
*/
readonly onPart = this.registerEvent<[channel: string, user: string]>();
/**
* Fires when a single message is removed from a channel.
*
* @eventListener
* @param channel The channel where the message was removed.
* @param messageId The ID of the message that was removed.
* @param msg The full message object containing all message and user information.
*
* This is *not* the message that was removed. The text of the message is available using `msg.params.message` though.
*/
readonly onMessageRemove = this.registerEvent<[channel: string, messageId: string, msg: ClearMsg]>();
/**
* Fires when unique chat mode is toggled in a channel.
*
* @eventListener
* @param channel The channel where unique chat mode is being toggled.
* @param enabled Whether unique chat mode is being enabled. If false, it's being disabled.
*/
readonly onUniqueChat = this.registerEvent<[channel: string, enabled: boolean]>();
/**
* Fires when a user raids a channel.
*
* @eventListener
* @param channel The channel that was raided.
* @param user The user that has raided the channel.
* @param raidInfo Additional information about the raid.
* @param msg The full message object containing all message and user information.
*/
readonly onRaid = this.registerEvent<[channel: string, user: string, raidInfo: ChatRaidInfo, msg: UserNotice]>();
/**
* Fires when a user cancels a raid.
*
* @eventListener
* @param channel The channel where the raid was cancelled.
* @param msg The full message object containing all message and user information.
*/
readonly onRaidCancel = this.registerEvent<[channel: string, msg: UserNotice]>();
/**
* Fires when a user performs a "ritual" in a channel.
*
* @eventListener
* @param channel The channel where the ritual was performed.
* @param user The user that has performed the ritual.
* @param ritualInfo Additional information about the ritual.
* @param msg The full message object containing all message and user information.
*/
readonly onRitual =
this.registerEvent<[channel: string, user: string, ritualInfo: ChatRitualInfo, msg: UserNotice]>();
/**
* Fires when slow mode is toggled in a channel.
*
* @eventListener
* @param channel The channel where slow mode is being toggled.
* @param enabled Whether slow mode is being enabled. If false, it's being disabled.
* @param delay The time (in seconds) a user has to wait between sending messages. Only set when enabling slow mode.
*/
readonly onSlow = this.registerEvent<[channel: string, enabled: boolean, delay?: number]>();
/**
* Fires when sub only mode is toggled in a channel.
*
* @eventListener
* @param channel The channel where sub only mode is being toggled.
* @param enabled Whether sub only mode is being enabled. If false, it's being disabled.
*/
readonly onSubsOnly = this.registerEvent<[channel: string, enabled: boolean]>();
/**
* Fires when a user subscribes to a channel.
*
* @eventListener
* @param channel The channel that was subscribed to.
* @param user The subscribing user.
* @param subInfo Additional information about the subscription.
* @param msg The full message object containing all message and user information.
*/
readonly onSub = this.registerEvent<[channel: string, user: string, subInfo: ChatSubInfo, msg: UserNotice]>();
/**
* Fires when a user resubscribes to a channel.
*
* @eventListener
* @param channel The channel that was resubscribed to.
* @param user The resubscribing user.
* @param subInfo Additional information about the resubscription.
* @param msg The full message object containing all message and user information.
*/
readonly onResub = this.registerEvent<[channel: string, user: string, subInfo: ChatSubInfo, msg: UserNotice]>();
/**
* Fires when a user gifts a subscription to a channel to another user.
*
* Community subs also fire multiple `onSubGift` events.
* To prevent alert spam, check [Sub gift spam](/docs/examples/chat/sub-gift-spam).
*
* @eventListener
* @param channel The channel that was subscribed to.
* @param user The user that the subscription was gifted to. The gifting user is defined in `subInfo.gifter`.
* @param subInfo Additional information about the subscription.
* @param msg The full message object containing all message and user information.
*/
readonly onSubGift =
this.registerEvent<[channel: string, user: string, subInfo: ChatSubGiftInfo, msg: UserNotice]>();
/**
* Fires when a user gifts random subscriptions to the community of a channel.
*
* Community subs also fire multiple `onSubGift` events.
* To prevent alert spam, check [Sub gift spam](/docs/examples/chat/sub-gift-spam).
*
* @eventListener
* @param channel The channel that was subscribed to.
* @param user The gifting user.
* @param subInfo Additional information about the community subscription.
* @param msg The full message object containing all message and user information.
*/
readonly onCommunitySub =
this.registerEvent<[channel: string, user: string, subInfo: ChatCommunitySubInfo, msg: UserNotice]>();
/**
* Fires when a user extends their subscription using a Sub Token.
*
* @eventListener
* @param channel The channel where the subscription was extended.
* @param user The user that extended their subscription.
* @param subInfo Additional information about the subscription extension.
* @param msg The full message object containing all message and user information.
*/
readonly onSubExtend =
this.registerEvent<[channel: string, user: string, subInfo: ChatSubExtendInfo, msg: UserNotice]>();
/**
* Fires when a user gifts rewards during a special event.
*
* @eventListener
* @param channel The channel where the rewards were gifted.
* @param user The user that gifted the rewards.
* @param rewardGiftInfo Additional information about the reward gift.
* @param msg The full message object containing all message and user information.
*/
readonly onRewardGift =
this.registerEvent<[channel: string, user: string, rewardGiftInfo: ChatRewardGiftInfo, msg: UserNotice]>();
/**
* Fires when a user upgrades their Prime subscription to a paid subscription in a channel.
*
* @eventListener
* @param channel The channel where the subscription was upgraded.
* @param user The user that upgraded their subscription.
* @param subInfo Additional information about the subscription upgrade.
* @param msg The full message object containing all message and user information.
*/
readonly onPrimePaidUpgrade =
this.registerEvent<[channel: string, user: string, subInfo: ChatSubUpgradeInfo, msg: UserNotice]>();
/**
* Fires when a user upgrades their gift subscription to a paid subscription in a channel.
*
* @eventListener
* @param channel The channel where the subscription was upgraded.
* @param user The user that upgraded their subscription.
* @param subInfo Additional information about the subscription upgrade.
* @param msg The full message object containing all message and user information.
*/
readonly onGiftPaidUpgrade =
this.registerEvent<[channel: string, user: string, subInfo: ChatSubGiftUpgradeInfo, msg: UserNotice]>();
/**
* Fires when a user gifts a Twitch Prime benefit to the channel.
*
* @eventListener
* @param channel The channel where the benefit was gifted.
* @param user The user that received the gift.
*
* **WARNING:** This is a *display name* and thus will not work as an identifier for the API (login) in some cases.
* @param subInfo Additional information about the gift.
* @param msg The full message object containing all message and user information.
*/
readonly onPrimeCommunityGift =
this.registerEvent<[channel: string, user: string, subInfo: ChatPrimeCommunityGiftInfo, msg: UserNotice]>();
/**
* Fires when a user pays forward a subscription that was gifted to them to a specific user.
*
* @eventListener
* @param channel The channel where the gift was forwarded.
* @param user The user that forwarded the gift.
* @param forwardInfo Additional information about the gift.
* @param msg The full message object containing all message and user information.
*/
readonly onStandardPayForward =
this.registerEvent<[channel: string, user: string, forwardInfo: ChatStandardPayForwardInfo, msg: UserNotice]>();
/**
* Fires when a user pays forward a subscription that was gifted to them to the community.
*
* @eventListener
* @param channel The channel where the gift was forwarded.
* @param user The user that forwarded the gift.
* @param forwardInfo Additional information about the gift.
* @param msg The full message object containing all message and user information.
*/
readonly onCommunityPayForward =
this.registerEvent<
[channel: string, user: string, forwardInfo: ChatCommunityPayForwardInfo, msg: UserNotice]
>();
/**
* Fires when a user sends an announcement (/announce) to a channel.
*
* @eventListener
* @param channel The channel the announcement was sent to.
* @param user The user that sent the announcement.
* @param announcementInfo Additional information about the announcement.
* @param msg The full message object containing all message and user information.
*/
readonly onAnnouncement =
this.registerEvent<[channel: string, user: string, announcementInfo: ChatAnnouncementInfo, msg: UserNotice]>();
/**
* Fires when receiving a whisper from another user.
*
* @eventListener
* @param user The user that sent the whisper.
* @param text The message text.
* @param msg The full message object containing all message and user information.
*/
readonly onWhisper = this.registerEvent<[user: string, text: string, msg: Whisper]>();
/**
* Fires when you tried to execute a command you don't have sufficient permission for.
*
* @eventListener
* @param channel The channel that a command without sufficient permissions was executed on.
* @param text The message text.
*/
readonly onNoPermission = this.registerEvent<[channel: string, text: string]>();
/**
* Fires when a message you tried to send gets rejected by the ratelimiter.
*
* @eventListener
* @param channel The channel that was attempted to send to.
* @param text The message text.
*/
readonly onMessageRatelimit = this.registerEvent<[channel: string, text: string]>();
/**
* Fires when authentication succeeds.
*
* @eventListener
*/
readonly onAuthenticationSuccess = this.registerEvent<[]>();
/**
* Fires when authentication fails.
*
* @eventListener
* @param channel The channel that a command without sufficient permissions was executed on.
* @param text The message text.
*/
readonly onAuthenticationFailure = this.registerEvent<[text: string, retryCount: number]>();
/**
* Fires when fetching a token fails.
*
* @eventListener
* @param error The error that was thrown.
*/
readonly onTokenFetchFailure = this.registerEvent<[error: Error]>();
/**
* Fires when sending a message fails.
*
* @eventListener
* @param channel The channel that rejected the message.
* @param reason The reason for the failure, e.g. you're banned (msg_banned)
*/
readonly onMessageFailed = this.registerEvent<[channel: string, reason: string]>();
/**
* Fires when a user sends a message to a channel.
*
* @eventListener
* @param channel The channel the message was sent to.
* @param user The user that sent the message.
* @param text The message text.
* @param msg The full message object containing all message and user information.
*/
readonly onMessage = this.registerEvent<[channel: string, user: string, text: string, msg: TwitchPrivateMessage]>();
/**
* Fires when a user sends an action (/me) to a channel.
*
* @eventListener
* @param channel The channel the action was sent to.
* @param user The user that sent the action.
* @param text The action text.
* @param msg The full message object containing all message and user information.
*/
readonly onAction = this.registerEvent<[channel: string, user: string, text: string, msg: TwitchPrivateMessage]>();
// internal events to resolve promises and stuff
private readonly _onJoinResult =
this.registerInternalEvent<[channel: string, state?: Map<string, string>, error?: string]>();
/**
* Creates a new Twitch chat client.
*
* @expandParams
*
* @param config
*/
constructor(config: ChatClientOptions = {}) {
if (config.authProvider && !config.authProvider.getAccessTokenForIntent) {
throw new InvalidTokenTypeError(
'You can not connect to chat using an AuthProvider that does not support intents.\n' +
"To get an anonymous, read-only connection, please don't pass an `AuthProvider` at all.\n" +
'To get a read-write connection, please provide an auth provider that provides user access tokens via intents, such as `RefreshingAuthProvider`.'
);
}
super();
this._ircClient = new IrcClient({
connection: {
hostName:
config.hostName ?? (config.webSocket ?? true ? 'irc-ws.chat.twitch.tv' : 'irc.chat.twitch.tv'),
secure: config.ssl ?? true
},
credentials: {
nick: '',
password: async () => await this._getAuthToken()
},
webSocket: config.webSocket ?? true,
connectionOptions: config.connectionOptions,
logger: {
name: 'twurple:chat:irc',
...config.logger
},
nonConformingCommands: ['004'],
manuallyAcknowledgeJoins: true,
rejoinChannelsOnReconnect: config.rejoinChannelsOnReconnect
});
this._ircClient.onDisconnect((manually: boolean, reason?: Error) => {
this._messageRateLimiter.clear();
this._messageRateLimiter.pause();
this._joinRateLimiter.clear();
this._joinRateLimiter.pause();
this.emit(this.onDisconnect, manually, reason);
});
this._ircClient.registerMessageType(TwitchPrivateMessage);
this._chatLogger = createLogger({
name: 'twurple:chat:twitch',
...config.logger
});
this._authProvider = config.authProvider;
this._useLegacyScopes = !!config.legacyScopes;
this._readOnly = !!config.readOnly;
this._authIntents = [...(config.authIntents ?? []), 'chat'];
const executeChatMessageRequest = async ({ type, text, channel, tags }: ChatMessageRequest) => {
if (type === 'say') {
this._ircClient.say(channel, text, tags);
} else {
this._ircClient.action(channel, text);
}
};
const executeJoinRequest = async (channel: string) => {
const { promise, resolve, reject } = promiseWithResolvers();
// eslint-disable-next-line @typescript-eslint/init-declarations
let timer: NodeJS.Timer;
const e = this.addInternalListener(this._onJoinResult, (chan, state, error) => {
if (chan === channel) {
clearTimeout(timer);
if (error) {
// TODO
reject(error as unknown as Error);
} else {
resolve();
}
this.removeListener(e);
}
});
timer = setTimeout(() => {
this.removeListener(e);
this.emit(this._onJoinResult, channel, undefined, 'twurple_timeout');
reject(new Error(`Did not receive a reply to join ${channel} in time; assuming that the join failed`));
}, 10000);
this._ircClient.join(channel);
await promise;
};
if (config.isAlwaysMod) {
this._messageRateLimiter = new TimeBasedRateLimiter({
bucketSize: config.botLevel === 'verified' ? 7500 : 100,
timeFrame: 32000,
doRequest: executeChatMessageRequest
});
} else {
let bucketSize = 20;
if (config.botLevel === 'verified') {
bucketSize = 7500;
} else if (config.botLevel === 'known') {
bucketSize = 50;
}
this._messageRateLimiter = new TimedPassthruRateLimiter(
new PartitionedTimeBasedRateLimiter({
bucketSize: 1,
timeFrame: 1200,
logger: { minLevel: LogLevel.ERROR },
doRequest: executeChatMessageRequest,
getPartitionKey: ({ channel }) => channel
}),
{ bucketSize, timeFrame: 32000 }
);
}
this._joinRateLimiter = new TimeBasedRateLimiter({
bucketSize: config.botLevel === 'verified' ? 2000 : 20,
timeFrame: 11000,
doRequest: executeJoinRequest
});
this._messageRateLimiter.pause();
this._joinRateLimiter.pause();
this._ircClient.addCapability(TwitchTagsCapability);
this._ircClient.addCapability(TwitchCommandsCapability);
if (config.requestMembershipEvents) {
this._ircClient.addCapability(TwitchMembershipCapability);
}
this._ircClient.onConnect(() => {
this.emit(this.onConnect);
});
this._ircClient.onRegister(async () => {
this._messageRateLimiter.resume();
this._joinRateLimiter.resume();
this._authVerified = true;
this._authRetryTimer = undefined;
this._authRetryCount = 0;
this.emit(this.onAuthenticationSuccess);
const resolvedChannels = await resolveConfigValue(config.channels);
if (resolvedChannels) {
await Promise.all(
resolvedChannels.map(async channel => {
try {
await this.join(channel);
} catch (e) {
this._chatLogger.warn(
// TODO this error should always throw an Error instance,
// currently it sometimes rejects with a string
`Failed to join configured channel ${channel}; original message: ${
(e as Error | null)?.message ?? (e as string)
}`
);
}
})
);
}
});
this._ircClient.onPasswordError(e => {
this._chatLogger.error(`Error fetching a token for connecting to the server: ${e.message}`);
this.emit(this.onTokenFetchFailure, e);
});
this._ircClient.onPrivmsg((channel, user, text, msg) => {
if (user !== 'jtv') {
this.emit(this.onMessage, toUserName(channel), user, text, msg);
}
});
this._ircClient.onAction((channel, user, text, msg) => {
this.emit(this.onAction, toUserName(channel), user, text, msg);
});
this.addInternalListener(this._onJoinResult, (channel, _, error) => {
if (error) {
this.emit(this.onJoinFailure, toUserName(channel), error);
} else {
this._ircClient.acknowledgeJoin(channel);
}
});
this._ircClient.onTypedMessage(ClearChat, msg => {
const {
params: { channel, user },
tags
} = msg;
const broadcasterName = toUserName(channel);
if (user) {
const duration = tags.get('ban-duration');
if (duration === undefined) {
// ban
this.emit(this.onBan, broadcasterName, user, msg);
} else {
// timeout
this.emit(this.onTimeout, broadcasterName, user, Number(duration), msg);
}
} else {
// full chat clear
this.emit(this.onChatClear, broadcasterName, msg);
}
});
this._ircClient.onTypedMessage(ClearMsg, msg => {
const {
params: { channel },
targetMessageId
} = msg;
this.emit(this.onMessageRemove, toUserName(channel), targetMessageId, msg);
});
this._ircClient.onTypedMessage(MessageTypes.Commands.ChannelJoin, ({ prefix, params: { channel } }) => {
this.emit(this.onJoin, toUserName(channel), prefix!.nick);
});
this._ircClient.onTypedMessage(MessageTypes.Commands.ChannelPart, ({ prefix, params: { channel } }) => {
this.emit(this.onPart, toUserName(channel), prefix!.nick);
});
this._ircClient.onTypedMessage(RoomState, ({ params: { channel }, tags }) => {
let isInitial = false;
if (tags.has('subs-only') && tags.has('slow')) {
// this is the full state - so we just successfully joined
this.emit(this._onJoinResult, channel, tags);
isInitial = true;
}
if (!isInitial) {
const broadcasterName = toUserName(channel);
if (tags.has('slow')) {
const slowDelay = Number(tags.get('slow'));
if (slowDelay) {
this.emit(this.onSlow, broadcasterName, true, slowDelay);
} else {
this.emit(this.onSlow, broadcasterName, false);
}
}
if (tags.has('followers-only')) {
const followDelay = Number(tags.get('followers-only'));
if (followDelay === -1) {
this.emit(this.onFollowersOnly, broadcasterName, false);
} else {
this.emit(this.onFollowersOnly, broadcasterName, true, followDelay);
}
}
}
});
this._ircClient.onTypedMessage(UserNotice, userNotice => {
const {
params: { channel, message },
tags
} = userNotice;
const messageType = tags.get('msg-id')!;
const broadcasterName = toUserName(channel);
switch (messageType) {
case 'sub':
case 'resub': {
const event = messageType === 'sub' ? this.onSub : this.onResub;
const plan = tags.get('msg-param-sub-plan')!;
const streakMonths = tags.get('msg-param-streak-months');
const subInfo: ChatSubInfo = {
userId: tags.get('user-id')!,
displayName: tags.get('display-name')!,
plan,
planName: tags.get('msg-param-sub-plan-name')!,
isPrime: plan === 'Prime',
months: Number(tags.get('msg-param-cumulative-months')),
streak: streakMonths ? Number(streakMonths) : undefined,
message
};
const wasGifted = tags.get('msg-param-was-gifted') === 'true';
if (wasGifted) {
const wasAnonGift = tags.get('msg-param-anon-gift') === 'true';
const duration = Number(tags.get('msg-param-gift-months'));
const redeemedMonth = Number(tags.get('msg-param-gift-month-being-redeemed'));
if (wasAnonGift) {
subInfo.originalGiftInfo = {
anonymous: true,
duration,
redeemedMonth
};
} else {
subInfo.originalGiftInfo = {
anonymous: false,
duration,
redeemedMonth,
userId: tags.get('msg-param-gifter-id')!,
userName: tags.get('msg-param-gifter-login')!,
userDisplayName: tags.get('msg-param-gifter-name')!
};
}
}
this.emit(event, broadcasterName, tags.get('login')!, subInfo, userNotice);
break;
}
case 'subgift': {
const plan = tags.get('msg-param-sub-plan')!;
const gifter = tags.get('login');
const isAnon = gifter === 'ananonymousgifter';
const subInfo: ChatSubGiftInfo = {
userId: tags.get('msg-param-recipient-id')!,
displayName: tags.get('msg-param-recipient-display-name')!,
gifter: isAnon ? undefined : gifter,
gifterUserId: isAnon ? undefined : tags.get('user-id')!,
gifterDisplayName: isAnon ? undefined : tags.get('display-name')!,
gifterGiftCount: isAnon ? undefined : Number(tags.get('msg-param-sender-count')),
giftDuration: Number(tags.get('msg-param-gift-months')),
plan,
planName: tags.get('msg-param-sub-plan-name')!,
isPrime: plan === 'Prime',
months: Number(tags.get('msg-param-months'))
};
this.emit(
this.onSubGift,
broadcasterName,
tags.get('msg-param-recipient-user-name')!,
subInfo,
userNotice
);
break;
}
case 'submysterygift': {
const gifter = tags.get('login');
const isAnon = gifter === 'ananonymousgifter';
const communitySubInfo: ChatCommunitySubInfo = {
gifter: isAnon ? undefined : gifter,
gifterUserId: isAnon ? undefined : tags.get('user-id')!,
gifterDisplayName: isAnon ? undefined : tags.get('display-name')!,
gifterGiftCount: isAnon ? undefined : Number(tags.get('msg-param-sender-count')),
count: Number(tags.get('msg-param-mass-gift-count')!),
plan: tags.get('msg-param-sub-plan')!
};
this.emit(this.onCommunitySub, broadcasterName, tags.get('login')!, communitySubInfo, userNotice);
break;
}
case 'primepaidupgrade': {
const upgradeInfo: ChatSubUpgradeInfo = {
userId: tags.get('user-id')!,
displayName: tags.get('display-name')!,
plan: tags.get('msg-param-sub-plan')!
};
this.emit(this.onPrimePaidUpgrade, broadcasterName, tags.get('login')!, upgradeInfo, userNotice);
break;
}
case 'giftpaidupgrade': {
const upgradeInfo: ChatSubGiftUpgradeInfo = {
userId: tags.get('user-id')!,
displayName: tags.get('display-name')!,
gifter: tags.get('msg-param-sender-login')!,
gifterDisplayName: tags.get('msg-param-sender-name')!
};
this.emit(this.onGiftPaidUpgrade, broadcasterName, tags.get('login')!, upgradeInfo, userNotice);
break;
}
case 'standardpayforward': {
const wasAnon = tags.get('msg-param-prior-gifter-anonymous') === 'true';
const forwardInfo: ChatStandardPayForwardInfo = {
userId: tags.get('user-id')!,
displayName: tags.get('display-name')!,
originalGifterUserId: wasAnon ? undefined : tags.get('msg-param-prior-gifter-id')!,
originalGifterDisplayName: wasAnon
? undefined
: tags.get('msg-param-prior-gifter-display-name')!,
recipientUserId: tags.get('msg-param-recipient-id')!,
recipientDisplayName: tags.get('msg-param-recipient-display-name')!
};
this.emit(this.onStandardPayForward, broadcasterName, tags.get('login')!, forwardInfo, userNotice);
break;
}