/
Bot.ts
1252 lines (1120 loc) · 39.8 KB
/
Bot.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 { LogLevel } from '@d-fischer/logger';
import { Enumerable, type ResolvableValue } from '@d-fischer/shared-utils';
import { EventEmitter } from '@d-fischer/typed-event-emitter';
import {
ApiClient,
type HelixChatAnnouncementColor,
type HelixChatUserColor,
type HelixModerator,
type HelixUpdateChatSettingsParams,
type HelixUserRelation
} from '@twurple/api';
import { type AuthProvider } from '@twurple/auth';
import {
ChatClient,
type ChatSayMessageAttributes,
extractMessageId,
type PrivateMessage,
toUserName
} from '@twurple/chat';
import { type CommercialLength, HellFreezesOverError, type UserIdResolvable } from '@twurple/common';
import { type BotCommand, type BotCommandMatch } from './BotCommand';
import { BotCommandContext } from './BotCommandContext';
import { AnnouncementEvent } from './events/AnnouncementEvent';
import { BanEvent } from './events/BanEvent';
import { BitsBadgeUpgradeEvent } from './events/BitsBadgeUpgradeEvent';
import { ChatClearEvent } from './events/ChatClearEvent';
import { CommunityPayForwardEvent } from './events/CommunityPayForwardEvent';
import { CommunitySubEvent } from './events/CommunitySubEvent';
import { EmoteOnlyToggleEvent } from './events/EmoteOnlyToggleEvent';
import { FollowersOnlyToggleEvent } from './events/FollowersOnlyToggleEvent';
import { GiftPaidUpgradeEvent } from './events/GiftPaidUpgradeEvent';
import { JoinEvent } from './events/JoinEvent';
import { JoinFailureEvent } from './events/JoinFailureEvent';
import { LeaveEvent } from './events/LeaveEvent';
import { MessageEvent } from './events/MessageEvent';
import { MessageRemoveEvent } from './events/MessageRemoveEvent';
import { PrimePaidUpgradeEvent } from './events/PrimePaidUpgradeEvent';
import { RaidCancelEvent } from './events/RaidCancelEvent';
import { RaidEvent } from './events/RaidEvent';
import { SlowModeToggleEvent } from './events/SlowModeToggleEvent';
import { StandardPayForwardEvent } from './events/StandardPayForwardEvent';
import { SubEvent } from './events/SubEvent';
import { SubGiftEvent } from './events/SubGiftEvent';
import { SubsOnlyToggleEvent } from './events/SubsOnlyToggleEvent';
import { UniqueChatToggleEvent } from './events/UniqueChatToggleEvent';
import { WhisperEvent } from './events/WhisperEvent';
export type BotAuthMethod = 'bot' | 'broadcaster';
/**
* The bot configuration.
*/
export interface BotConfig {
/**
* The {@link AuthProvider} instance to use for authenticating the bot and its users.
*/
authProvider: AuthProvider;
/**
* Whether to enable debug logs.
*/
debug?: boolean;
/**
* The channel to join.
*
* Takes priority over `channels`.
*/
channel?: string;
/**
* The channels to join.
*
* Is ignored when `channel` is set.
*/
channels?: ResolvableValue<string[]>;
/**
* The commands to register.
*/
commands?: BotCommand[];
/**
* Whether to receive `onMessage` events for message that were already handled as a command.
*/
emitCommandMessageEvents?: boolean;
/**
* The prefix for all commands.
*
* Defaults to `!`.
*/
prefix?: string;
/**
* The preferred authentication method for authorized actions such as moderation.
*
* Defaults to bot authentication.
*
* Some methods can only use broadcaster authentication - they will be marked as such.
*/
authMethod?: BotAuthMethod;
}
export type ChatAnnouncementColor = HelixChatAnnouncementColor;
export type ChatUserColor = HelixChatUserColor;
/**
* Twitch chatbots made easy.
*
* @meta category main
*/
export class Bot extends EventEmitter {
/**
* Direct access to the underlying API client. Use at your own risk.
*/
readonly api: ApiClient;
/**
* Direct access to the underlying chat client. Use at your own risk.
*/
readonly chat: ChatClient;
@Enumerable(false) private readonly _authProvider: AuthProvider;
private readonly _prefix: string;
private readonly _authMethod: BotAuthMethod;
private readonly _commands = new Map<string, BotCommand>();
private _botUserIdPromise: Promise<string> | null = null;
// region events
/**
* 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 event The event object.
*/
readonly onTimeout = this.registerEvent<[event: BanEvent]>();
/**
* Fires when a user is permanently banned from a channel.
*
* @eventListener
* @param event The event object.
*/
readonly onBan = this.registerEvent<[event: BanEvent]>();
/**
* Fires when a user upgrades their bits badge in a channel.
*
* @eventListener
* @param event The event object.
*/
readonly onBitsBadgeUpgrade = this.registerEvent<[event: BitsBadgeUpgradeEvent]>();
/**
* Fires when the chat of a channel is cleared.
*
* @eventListener
* @param event The event object.
*/
readonly onChatClear = this.registerEvent<[event: ChatClearEvent]>();
/**
* Fires when emote-only mode is toggled in a channel.
*
* @eventListener
* @param event The event object.
*/
readonly onEmoteOnlyToggle = this.registerEvent<[event: EmoteOnlyToggleEvent]>();
/**
* Fires when followers-only mode is toggled in a channel.
*
* @eventListener
* @param event The event object.
*/
readonly onFollowersOnlyToggle = this.registerEvent<[event: FollowersOnlyToggleEvent]>();
/**
* Fires when a user joins a channel.
*
* The join/leave events are cached by the Twitch chat server and will be batched and sent every 30-60 seconds.
*
* Please note that if you have not enabled the `requestMembershipEvents` option
* or the channel has more than 1000 connected chatters, this will only react to your own joins.
*
* @eventListener
* @param event The event object.
*/
readonly onJoin = this.registerEvent<[event: JoinEvent]>();
/**
* Fires when you fail to join a channel.
*
* @eventListener
* @param event The event object.
*/
readonly onJoinFailure = this.registerEvent<[event: JoinFailureEvent]>();
/**
* Fires when a user leaves ("parts") a channel.
*
* The join/leave events are cached by the Twitch chat server and will be batched and sent every 30-60 seconds.
*
* Please note that if you have not enabled the `requestMembershipEvents` option
* or the channel has more than 1000 connected chatters, this will only react to your own leaves.
*
* @eventListener
* @param event The event object.
*/
readonly onLeave = this.registerEvent<[event: LeaveEvent]>();
/**
* Fires when a single message is removed from a channel.
*
* @eventListener
* @param event The event object.
*/
readonly onMessageRemove = this.registerEvent<[event: MessageRemoveEvent]>();
/**
* Fires when unique chat mode is toggled in a channel.
*
* @eventListener
* @param event The event object.
*/
readonly onUniqueChatToggle = this.registerEvent<[event: UniqueChatToggleEvent]>();
/**
* Fires when a user raids a channel.
*
* @eventListener
* @param event The event object.
*/
readonly onRaid = this.registerEvent<[event: RaidEvent]>();
/**
* Fires when a user cancels a raid.
*
* @eventListener
* @param event The event object.
*/
readonly onRaidCancel = this.registerEvent<[event: RaidCancelEvent]>();
/**
* Fires when slow mode is toggled in a channel.
*
* @eventListener
* @param event The event object.
*/
readonly onSlowModeToggle = this.registerEvent<[event: SlowModeToggleEvent]>();
/**
* Fires when sub only mode is toggled in a channel.
*
* @eventListener
* @param event The event object.
*/
readonly onSubsOnlyToggle = this.registerEvent<[event: SubsOnlyToggleEvent]>();
/**
* Fires when a user subscribes to a channel.
*
* @eventListener
* @param event The event object.
*/
readonly onSub = this.registerEvent<[event: SubEvent]>();
/**
* Fires when a user resubscribes to a channel.
*
* @eventListener
* @param event The event object.
*/
readonly onResub = this.registerEvent<[event: SubEvent]>();
/**
* 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 the [example on how to handle sub gift spam](/docs/examples/chat/sub-gift-spam).
*
* @eventListener
* @param event The event object.
*/
readonly onSubGift = this.registerEvent<[event: SubGiftEvent]>();
/**
* 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 the [example on how to handle sub gift spam](/docs/examples/chat/sub-gift-spam).
*
* @eventListener
* @param event The event object.
*/
readonly onCommunitySub = this.registerEvent<[event: CommunitySubEvent]>();
/**
* Fires when a user upgrades their Prime subscription to a paid subscription in a channel.
*
* @eventListener
* @param event The event object.
*/
readonly onPrimePaidUpgrade = this.registerEvent<[event: PrimePaidUpgradeEvent]>();
/**
* Fires when a user upgrades their gift subscription to a paid subscription in a channel.
*
* @eventListener
* @param event The event object.
*/
readonly onGiftPaidUpgrade = this.registerEvent<[event: GiftPaidUpgradeEvent]>();
/**
* Fires when a user pays forward a subscription that was gifted to them to a specific user.
*
* @eventListener
* @param event The event object.
*/
readonly onStandardPayForward = this.registerEvent<[event: StandardPayForwardEvent]>();
/**
* Fires when a user pays forward a subscription that was gifted to them to the community.
*
* @eventListener
* @param event The event object.
*/
readonly onCommunityPayForward = this.registerEvent<[event: CommunityPayForwardEvent]>();
/**
* Fires when a user sends an announcement (/announce) to a channel.
*
* @eventListener
* @param event The event object.
*/
readonly onAnnouncement = this.registerEvent<[event: AnnouncementEvent]>();
/**
* Fires when receiving a whisper from another user.
*
* @eventListener
* @param event The event object.
*/
readonly onWhisper = this.registerEvent<[event: WhisperEvent]>();
/**
* 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 event The event object.
*/
readonly onMessage = this.registerEvent<[event: MessageEvent]>();
/**
* Fires when a user sends an action (/me) to a channel.
*
* @eventListener
* @param event The event object.
*/
readonly onAction = this.registerEvent<[event: MessageEvent]>();
// endregion
/**
* Creates a new bot.
*
* @param config The configuration for the bot.
*/
constructor(config: BotConfig) {
const {
authProvider,
authMethod,
channel: configChannel,
channels,
debug,
commands,
emitCommandMessageEvents,
prefix
} = config;
super();
const resolvableChannels = configChannel ? [configChannel] : channels;
if (!resolvableChannels) {
throw new Error("didn't pass channel nor channels option, exiting");
}
this._authProvider = authProvider;
this._prefix = prefix ?? '!';
this._authMethod = authMethod ?? 'bot';
this._commands = new Map<string, BotCommand>(commands?.map(cmd => [cmd.name, cmd]));
const minLevel = debug ? LogLevel.DEBUG : LogLevel.ERROR;
this.api = new ApiClient({
authProvider: this._authProvider,
logger: { minLevel }
});
this.chat = new ChatClient({
authProvider: this._authProvider,
logger: { minLevel },
channels: resolvableChannels
});
this.chat.onMessage(async (channel, user, text, msg) => {
const match = this._findMatch(msg);
if (match?.command.canExecute(msg.channelId!, msg.userInfo.userId)) {
await match.command.execute(match.params, new BotCommandContext(this, msg));
}
if (match === null || emitCommandMessageEvents) {
this.emit(this.onMessage, new MessageEvent(channel, user, text, false, msg, this));
}
});
// region event redirection
this.chat.onConnect(() => this.emit(this.onConnect));
this.chat.onDisconnect((manually, reason) => this.emit(this.onDisconnect, manually, reason));
this.chat.onAuthenticationSuccess(() => this.emit(this.onAuthenticationSuccess));
this.chat.onAuthenticationFailure((text, retryCount) =>
this.emit(this.onAuthenticationFailure, text, retryCount)
);
this.chat.onTokenFetchFailure(error => this.emit(this.onTokenFetchFailure, error));
this.chat.onMessageFailed((channel, text) => this.emit(this.onMessageFailed, channel, text));
this.chat.onTimeout((channel, user, duration, msg) =>
this.emit(this.onTimeout, new BanEvent(channel, user, duration, msg, this))
);
this.chat.onBan((channel, user, msg) => this.emit(this.onBan, new BanEvent(channel, user, null, msg, this)));
this.chat.onBitsBadgeUpgrade((channel, user, upgradeInfo, msg) =>
this.emit(this.onBitsBadgeUpgrade, new BitsBadgeUpgradeEvent(channel, user, upgradeInfo, msg, this))
);
this.chat.onChatClear((channel, msg) => this.emit(this.onChatClear, new ChatClearEvent(channel, msg, this)));
this.chat.onEmoteOnly((channel, enabled) =>
this.emit(this.onEmoteOnlyToggle, new EmoteOnlyToggleEvent(channel, enabled, this))
);
this.chat.onFollowersOnly((channel, enabled, delay) =>
this.emit(this.onFollowersOnlyToggle, new FollowersOnlyToggleEvent(channel, enabled, delay, this))
);
this.chat.onJoin((channel, user) => this.emit(this.onJoin, new JoinEvent(channel, user, this)));
this.chat.onJoinFailure((channel, reason) =>
this.emit(this.onJoinFailure, new JoinFailureEvent(channel, reason, this))
);
this.chat.onPart((channel, user) => this.emit(this.onLeave, new LeaveEvent(channel, user, this)));
this.chat.onMessageRemove((channel, messageId, msg) =>
this.emit(this.onMessageRemove, new MessageRemoveEvent(channel, messageId, msg, this))
);
this.chat.onUniqueChat((channel, enabled) =>
this.emit(this.onUniqueChatToggle, new UniqueChatToggleEvent(channel, enabled, this))
);
this.chat.onRaid((channel, user, raidInfo, msg) =>
this.emit(this.onRaid, new RaidEvent(channel, user, raidInfo, msg, this))
);
this.chat.onRaidCancel((channel, msg) => this.emit(this.onRaidCancel, new RaidCancelEvent(channel, msg, this)));
this.chat.onSlow((channel, enabled, delay) =>
this.emit(this.onSlowModeToggle, new SlowModeToggleEvent(channel, enabled, delay, this))
);
this.chat.onSubsOnly((channel, enabled) =>
this.emit(this.onSubsOnlyToggle, new SubsOnlyToggleEvent(channel, enabled, this))
);
this.chat.onSub((channel, user, subInfo, msg) =>
this.emit(this.onSub, new SubEvent(channel, user, subInfo, msg, this))
);
this.chat.onResub((channel, user, subInfo, msg) =>
this.emit(this.onResub, new SubEvent(channel, user, subInfo, msg, this))
);
this.chat.onSubGift((channel, user, subInfo, msg) =>
this.emit(this.onSubGift, new SubGiftEvent(channel, user, subInfo, msg, this))
);
this.chat.onCommunitySub((channel, user, subInfo, msg) =>
this.emit(this.onCommunitySub, new CommunitySubEvent(channel, subInfo, msg, this))
);
this.chat.onPrimePaidUpgrade((channel, user, subInfo, msg) =>
this.emit(this.onPrimePaidUpgrade, new PrimePaidUpgradeEvent(channel, user, subInfo, msg, this))
);
this.chat.onGiftPaidUpgrade((channel, user, subInfo, msg) =>
this.emit(this.onGiftPaidUpgrade, new GiftPaidUpgradeEvent(channel, user, subInfo, msg, this))
);
this.chat.onStandardPayForward((channel, user, forwardInfo, msg) =>
this.emit(this.onStandardPayForward, new StandardPayForwardEvent(channel, user, forwardInfo, msg, this))
);
this.chat.onCommunityPayForward((channel, user, forwardInfo, msg) =>
this.emit(this.onCommunityPayForward, new CommunityPayForwardEvent(channel, user, forwardInfo, msg, this))
);
this.chat.onAnnouncement((channel, user, announcementInfo, msg) =>
this.emit(this.onAnnouncement, new AnnouncementEvent(channel, user, announcementInfo, msg, this))
);
this.chat.onWhisper((user, text, msg) => this.emit(this.onWhisper, new WhisperEvent(user, text, msg, this)));
this.chat.onAction((channel, user, text, msg) =>
this.emit(this.onAction, new MessageEvent(channel, user, text, true, msg, this))
);
// endregion
this.chat.connect();
}
// region chat management commands
/**
* Sends an announcement to the given channel.
*
* @param channelName The name of the channel to send the announcement to.
* @param text The text to send.
* @param color The color to send the announcement in. If not passed, uses the default channel color.
*/
async announce(channelName: string, text: string, color?: ChatAnnouncementColor): Promise<void> {
await this.announceById(await this._resolveUserId(channelName), text, color);
}
/**
* Sends an announcement to the given channel using its ID.
*
* @param channel The channel to send the announcement to.
* @param text The text to send.
* @param color The color to send the announcement in. If not passed, uses the default channel color.
*/
async announceById(channel: UserIdResolvable, text: string, color?: ChatAnnouncementColor): Promise<void> {
await this.api.chat.sendAnnouncement(channel, await this._getPreferredUserIdForModAction(channel), {
message: text,
color
});
}
/**
* Bans a user from the given channel.
*
* @param channelName The name of the channel to ban the user from.
* @param userName The name of the user to ban.
* @param reason The reason for the ban.
*/
async ban(channelName: string, userName: string, reason: string): Promise<void> {
const channelId = await this._resolveUserId(channelName);
const userId = await this._resolveUserId(userName);
await this.banByIds(channelId, userId, reason);
}
/**
* Bans a user from the given channel using the channel and user IDs.
*
* @param channel The channel to ban the user from.
* @param user The user to ban.
* @param reason The reason for the ban.
*/
async banByIds(channel: UserIdResolvable, user: UserIdResolvable, reason: string): Promise<void> {
await this.api.moderation.banUser(channel, await this._getPreferredUserIdForModAction(channel), {
user,
reason
});
}
/**
* Unban a user from the given channel.
*
* @param channelName The name of the channel to unban the user from.
* @param userName The name of the user to unban.
*/
async unban(channelName: string, userName: string): Promise<void> {
const channelId = await this._resolveUserId(channelName);
const userId = await this._resolveUserId(userName);
await this.unbanByIds(channelId, userId);
}
/**
* Unbans a user from the given channel using the channel and user IDs.
*
* @param channel The channel to unban the user from.
* @param user The user to unban.
*/
async unbanByIds(channel: UserIdResolvable, user: UserIdResolvable): Promise<void> {
await this.api.moderation.unbanUser(channel, await this._getPreferredUserIdForModAction(channel), user);
}
/**
* Removes all messages from the given channel.
*
* @param channelName The name of the channel to remove all messages from.
*/
async clear(channelName: string): Promise<void> {
const channelId = await this._resolveUserId(channelName);
await this.clearById(channelId);
}
/**
* Removes all messages from the given channel using its ID.
*
* @param channel The channel to remove all messages from.
*/
async clearById(channel: UserIdResolvable): Promise<void> {
await this.api.moderation.deleteChatMessages(channel, await this._getPreferredUserIdForModAction(channel));
}
/**
* Changes the bot's username color.
*
* @param color The hexadecimal code (prefixed with #) or color name to use for your username.
*
* Please note that only Twitch Turbo or Prime users can use hexadecimal codes for arbitrary colors.
*
* If you have neither of those, you can only choose from the following color names:
*
* blue, blue_violet, cadet_blue, chocolate, coral, dodger_blue, firebrick, golden_rod, green, hot_pink, orange_red, red, sea_green, spring_green, yellow_green
*/
async changeColor(color: ChatUserColor): Promise<void> {
await this.api.chat.setColorForUser(await this._getBotUserId(), color);
}
/**
* Runs a commercial break on the given channel.
*
* @param channelName The name of the channel to run the commercial break on.
* @param length The duration of the commercial break.
*/
async runCommercial(channelName: string, length: CommercialLength = 30): Promise<void> {
const channelId = await this._resolveUserId(channelName);
await this.runCommercialById(channelId, length);
}
/**
* Runs a commercial break on the given channel using its ID.
*
* @param channel The channel to run the commercial break on.
* @param length The duration of the commercial break.
*/
async runCommercialById(channel: UserIdResolvable, length: CommercialLength = 30): Promise<void> {
await this.api.channels.startChannelCommercial(channel, length);
}
/**
* Deletes a message from the given channel.
*
* @param channelName The name of the channel to delete the message from.
* @param message The message (as message ID or message object) to delete.
*/
async deleteMessage(channelName: string, message: string | PrivateMessage): Promise<void> {
const channelId = await this._resolveUserId(channelName);
await this.deleteMessageById(channelId, message);
}
/**
* Deletes a message from the given channel using the channel ID.
*
* @param channel The channel to delete the message from.
* @param message The message (as message ID or message object) to delete.
*/
async deleteMessageById(channel: UserIdResolvable, message: string | PrivateMessage): Promise<void> {
await this.api.moderation.deleteChatMessages(
channel,
await this._getPreferredUserIdForModAction(channel),
extractMessageId(message)
);
}
/**
* Enables emote-only mode in the given channel.
*
* @param channelName The name of the channel to enable emote-only mode in.
*/
async enableEmoteOnly(channelName: string): Promise<void> {
const channelId = await this._resolveUserId(channelName);
await this.enableEmoteOnlyById(channelId);
}
/**
* Enables emote-only mode in the given channel using its ID.
*
* @param channel The channel to enable emote-only mode in.
*/
async enableEmoteOnlyById(channel: UserIdResolvable): Promise<void> {
await this._updateChannelSettings(channel, {
emoteOnlyModeEnabled: true
});
}
/**
* Disables emote-only mode in the given channel.
*
* @param channelName The name of the channel to disable emote-only mode in.
*/
async disableEmoteOnly(channelName: string): Promise<void> {
const channelId = await this._resolveUserId(channelName);
await this.disableEmoteOnlyById(channelId);
}
/**
* Disables emote-only mode in the given channel using its ID.
*
* @param channel The channel to disable emote-only mode in.
*/
async disableEmoteOnlyById(channel: UserIdResolvable): Promise<void> {
await this._updateChannelSettings(channel, {
emoteOnlyModeEnabled: false
});
}
/**
* Enables followers-only mode in the given channel.
*
* @param channelName The name of the channel to enable followers-only mode in.
* @param minFollowTime The time (in minutes) a user needs to be following before being able to send messages.
*/
async enableFollowersOnly(channelName: string, minFollowTime: number = 0): Promise<void> {
const channelId = await this._resolveUserId(channelName);
await this.enableFollowersOnlyById(channelId, minFollowTime);
}
/**
* Enables followers-only mode in the given channel using its ID.
*
* @param channel The channel to enable followers-only mode in.
* @param minFollowTime The time (in minutes) a user needs to be following before being able to send messages.
*/
async enableFollowersOnlyById(channel: UserIdResolvable, minFollowTime: number = 0): Promise<void> {
await this._updateChannelSettings(channel, {
followerOnlyModeEnabled: true,
followerOnlyModeDelay: minFollowTime
});
}
/**
* Disables followers-only mode in the given channel.
*
* @param channelName The name of the channel to disable followers-only mode in.
*/
async disableFollowersOnly(channelName: string): Promise<void> {
const channelId = await this._resolveUserId(channelName);
await this.disableFollowersOnlyById(channelId);
}
/**
* Disables followers-only mode in the given channel using its ID.
*
* @param channel The channel to disable followers-only mode in.
*/
async disableFollowersOnlyById(channel: UserIdResolvable): Promise<void> {
await this._updateChannelSettings(channel, {
followerOnlyModeEnabled: false
});
}
/**
* Gives a user moderator rights in the given channel.
*
* @param channelName The name of the channel to give the user moderator rights in.
* @param userName The name of the user to give moderator rights to.
*/
async mod(channelName: string, userName: string): Promise<void> {
const channelId = await this._resolveUserId(channelName);
const userId = await this._resolveUserId(userName);
await this.modByIds(channelId, userId);
}
/**
* Gives a user moderator rights in the given channel using the channel and user IDs.
*
* @param channel The channel to give the user moderator rights in.
* @param user The user to give moderator rights to.
*/
async modByIds(channel: UserIdResolvable, user: UserIdResolvable): Promise<void> {
await this.api.moderation.addModerator(channel, user);
}
/**
* Takes moderator rights from a user in the given channel.
*
* @param channelName The name of the channel to remove the user's moderator rights in.
* @param userName The name of the user to take moderator rights from.
*/
async unmod(channelName: string, userName: string): Promise<void> {
const channelId = await this._resolveUserId(channelName);
const userId = await this._resolveUserId(userName);
await this.unmodByIds(channelId, userId);
}
/**
* Takes moderator rights from a user in the given channel using the channel and user IDs.
*
* @param channel The channel to remove the user's moderator rights in.
* @param user The user to take moderator rights from.
*/
async unmodByIds(channel: UserIdResolvable, user: UserIdResolvable): Promise<void> {
await this.api.moderation.removeModerator(channel, user);
}
/**
* Enables unique chat mode in the given channel.
*
* @param channelName The name of the channel to enable unique chat mode in.
*/
async enableUniqueChat(channelName: string): Promise<void> {
const channelId = await this._resolveUserId(channelName);
await this.enableUniqueChatById(channelId);
}
/**
* Enables unique chat mode in the given channel using its ID.
*
* @param channel The channel to enable unique chat mode in.
*/
async enableUniqueChatById(channel: UserIdResolvable): Promise<void> {
await this._updateChannelSettings(channel, {
uniqueChatModeEnabled: true
});
}
/**
* Disables unique chat mode in the given channel.
*
* @param channelName The name of the channel to disable unique chat mode in.
*/
async disableUniqueChat(channelName: string): Promise<void> {
const channelId = await this._resolveUserId(channelName);
await this.disableUniqueChatById(channelId);
}
/**
* Disables unique chat mode in the given channel using its ID.
*
* @param channel The channel to disable unique chat mode in.
*/
async disableUniqueChatById(channel: UserIdResolvable): Promise<void> {
await this._updateChannelSettings(channel, {
uniqueChatModeEnabled: false
});
}
/**
* Enables slow mode in the given channel.
*
* @param channelName The name of the channel to enable slow mode in.
* @param delayBetweenMessages The time (in seconds) a user needs to wait between messages.
*/
async enableSlowMode(channelName: string, delayBetweenMessages: number = 30): Promise<void> {
const channelId = await this._resolveUserId(channelName);
await this.enableSlowModeById(channelId, delayBetweenMessages);
}
/**
* Enables slow mode in the given channel using its ID.
*
* @param channel The channel to enable slow mode in.
* @param delayBetweenMessages The time (in seconds) a user needs to wait between messages.
*/
async enableSlowModeById(channel: UserIdResolvable, delayBetweenMessages: number = 30): Promise<void> {
await this._updateChannelSettings(channel, {
slowModeEnabled: true,
slowModeDelay: delayBetweenMessages
});
}
/**
* Disables slow mode in the given channel.
*
* @param channelName The name of the channel to disable slow mode in.
*/
async disableSlowMode(channelName: string): Promise<void> {
const channelId = await this._resolveUserId(channelName);
await this.disableSlowModeById(channelId);
}
/**
* Disables slow mode in the given channel using its ID.
*
* @param channel The channel to disable slow mode in.
*/
async disableSlowModeById(channel: UserIdResolvable): Promise<void> {
await this._updateChannelSettings(channel, {
slowModeEnabled: false
});
}
/**
* Enables subscribers-only mode in the given channel.
*
* @param channelName The name of the channel to enable subscribers-only mode in.
*/
async enableSubsOnly(channelName: string): Promise<void> {
const channelId = await this._resolveUserId(channelName);
await this.enableSubsOnlyById(channelId);
}
/**
* Enables subscribers-only mode in the given channel using its ID.
*
* @param channel The channel to enable subscribers-only mode in.
*/
async enableSubsOnlyById(channel: UserIdResolvable): Promise<void> {
await this._updateChannelSettings(channel, {
subscriberOnlyModeEnabled: true
});
}
/**
* Disables subscribers-only mode in the given channel.
*
* @param channelName The name of the channel to disable subscribers-only mode in.
*/
async disableSubsOnly(channelName: string): Promise<void> {
const channelId = await this._resolveUserId(channelName);
await this.disableSubsOnlyById(channelId);
}
/**
* Disables subscribers-only mode in the given channel using its ID.
*
* @param channel The channel to disable subscribers-only mode in.
*/
async disableSubsOnlyById(channel: UserIdResolvable): Promise<void> {
await this._updateChannelSettings(channel, {
subscriberOnlyModeEnabled: false
});
}
/**
* Times out a user in the given channel and removes all their messages.
*
* @param channelName The name of the channel to time out the user in.
* @param userName The name of the user to time out.
* @param duration The time (in seconds) until the user can send messages again. Defaults to 1 minute.
* @param reason The reason for the timeout.
*/
async timeout(channelName: string, userName: string, duration: number = 60, reason: string = ''): Promise<void> {
if (!Number.isInteger(duration) || duration < 1 || duration > 1209600) {
throw new Error(`Invalid timeout duration: ${duration}. It must be an integer between 1 and 1209600.`);
}
const channelId = await this._resolveUserId(channelName);
const userId = await this._resolveUserId(userName);
await this.timeoutByIds(channelId, userId, duration, reason);
}
/**
* Times out a user in the given channel and removes all their messages using the channel and user IDs.
*
* @param channel The channel to time out the user in.
* @param user The user to time out.
* @param duration The time (in seconds) until the user can send messages again. Defaults to 1 minute.
* @param reason The reason for the timeout.
*/
async timeoutByIds(
channel: UserIdResolvable,
user: UserIdResolvable,
duration: number = 60,
reason: string = ''
): Promise<void> {
if (!Number.isInteger(duration) || duration < 1 || duration > 1209600) {
throw new Error(`Invalid timeout duration: ${duration}. It must be an integer between 1 and 1209600.`);
}
await this.api.moderation.banUser(channel, await this._getPreferredUserIdForModAction(channel), {