-
-
Notifications
You must be signed in to change notification settings - Fork 94
/
DisTube.ts
897 lines (869 loc) · 28.3 KB
/
DisTube.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
import ytsr from "@distube/ytsr";
import { TypedEmitter } from "tiny-typed-emitter";
import {
DirectLinkPlugin,
DisTubeError,
DisTubeHandler,
DisTubeVoiceManager,
Events,
Options,
Playlist,
QueueManager,
SearchResultPlaylist,
SearchResultType,
SearchResultVideo,
Song,
checkIntents,
defaultFilters,
isClientInstance,
isMemberInstance,
isMessageInstance,
isObject,
isSupportedVoiceChannel,
isTextChannelInstance,
isURL,
} from ".";
import type { Client, GuildTextBasedChannel, Message, VoiceBasedChannel } from "discord.js";
import type {
Awaitable,
CustomPlaylistOptions,
CustomPlugin,
DisTubeOptions,
ExtractorPlugin,
Filters,
GuildIdResolvable,
PlayOptions,
Queue,
SearchResult,
TypedDisTubeEvents,
} from ".";
// Cannot be `import` as it's not under TS root dir
// eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports
export const { version }: { version: string } = require("../package.json");
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
export interface DisTube extends TypedEmitter<TypedDisTubeEvents> {
/**
* @event
* Emitted after DisTube add a new playlist to the playing {@link Queue}.
*
* @example
* ```ts
* distube.on("addList", (queue, playlist) => queue.textChannel.send(
* `Added \`${playlist.name}\` playlist (${playlist.songs.length} songs) to the queue!`
* ));
* ```
*
* @param queue - The guild queue
* @param playlist - Playlist info
*/
[Events.ADD_LIST]: (queue: Queue, playlist: Playlist) => Awaitable;
/**
* @event
* Emitted after DisTube add a new song to the playing {@link Queue}.
*
* @example
* ```ts
* distube.on("addSong", (queue, song) => queue.textChannel.send(
* `Added ${song.name} - \`${song.formattedDuration}\` to the queue by ${song.user}.`
* ));
* ```
*
* @param queue - The guild queue
* @param song - Added song
*/
[Events.ADD_SONG]: (queue: Queue, song: Song) => Awaitable;
/**
* @event
* Emitted when a {@link Queue} is deleted with any reasons.
*
* @param queue - The guild queue
*/
[Events.DELETE_QUEUE]: (queue: Queue) => Awaitable;
/**
* @event
* Emitted when the bot is disconnected to a voice channel.
*
* @param queue - The guild queue
*/
[Events.DISCONNECT]: (queue: Queue) => Awaitable;
/**
* @event
* Emitted when there is no user in the voice channel, {@link DisTubeOptions}.leaveOnEmpty
* is `true` and there is a playing queue.
*
* If there is no playing queue (stopped and {@link DisTubeOptions}.leaveOnStop is
* `false`), it will leave the channel without emitting this event.
*
* @example
* ```ts
* distube.on("empty", queue => queue.textChannel.send("Channel is empty. Leaving the channel"))
* ```
*
* @param queue - The guild queue
*/
[Events.EMPTY]: (queue: Queue) => Awaitable;
/**
* @event
* Emitted when DisTube encounters an error while playing songs.
*
* @example
* ```ts
* distube.on('error', (channel, e) => {
* if (channel) channel.send(`An error encountered: ${e}`)
* else console.error(e)
* })
* ```
*
* @param channel - Text channel where the error is encountered.
* @param error - The error encountered
*/
[Events.ERROR]: (channel: GuildTextBasedChannel | undefined, error: Error) => Awaitable;
/**
* @event
* Emitted for FFmpeg debugging information.
*
* @param debug - The debug information
*/
[Events.FFMPEG_DEBUG]: (debug: string) => Awaitable;
/**
* @event
* Emitted when there is no more song in the queue and {@link Queue#autoplay} is
* `false`. DisTube will leave voice channel if {@link
* DisTubeOptions}.leaveOnFinish is `true`.
*
* @example
* ```ts
* distube.on("finish", queue => queue.textChannel.send("No more song in queue"));
* ```
*
* @param queue - The guild queue
*/
[Events.FINISH]: (queue: Queue) => Awaitable;
/**
* @event
* Emitted when DisTube finished a song.
*
* @example
* ```ts
* distube.on("finishSong", (queue, song) => queue.textChannel.send(`${song.name} has finished!`));
* ```
*
* @param queue - The guild queue
* @param song - Finished song
*/
[Events.FINISH_SONG]: (queue: Queue, song: Song) => Awaitable;
/**
* @event
* Emitted when DisTube initialize a queue to change queue default properties.
*
* @example
* ```ts
* distube.on("initQueue", queue => {
* queue.autoplay = false;
* queue.volume = 100;
* });
* ```ts
*
* @param queue - The guild queue
*/
[Events.INIT_QUEUE]: (queue: Queue) => Awaitable;
/**
* @event
* Emitted when {@link Queue#autoplay} is `true`, {@link Queue#songs} is empty, and
* DisTube cannot find related songs to play.
*
* @example
* ```ts
* distube.on("noRelated", queue => queue.textChannel.send("Can't find related video to play."));
* ```ts
*
* @param queue - The guild queue
*/
[Events.NO_RELATED]: (queue: Queue) => Awaitable;
/**
* @event
* Emitted when DisTube play a song.
*
* If {@link DisTubeOptions}.emitNewSongOnly is `true`, this event is not emitted
* when looping a song or next song is the previous one.
*
* @example
* ```ts
* distube.on("playSong", (queue, song) => queue.textChannel.send(
* `Playing \`${song.name}\` - \`${song.formattedDuration}\`\nRequested by: ${song.user}`
* ));
* ```ts
*
* @param queue - The guild queue
* @param song - Playing song
*/
[Events.PLAY_SONG]: (queue: Queue, song: Song) => Awaitable;
/**
* @event
* Emitted when {@link DisTubeOptions | DisTubeOptions.searchSongs} bigger than 0,
* and the search canceled due to {@link DisTubeOptions |
* DisTubeOptions.searchTimeout}.
*
* @example
* ```ts
* // DisTubeOptions.searchSongs > 0
* distube.on("searchCancel", (message) => message.channel.send(`Searching canceled`));
* ```ts
*
* @param message - The user message called play method
* @param query - The search query
*/
[Events.SEARCH_CANCEL]: (message: Message, query: string) => Awaitable;
/**
* @event
* Emitted when {@link DisTubeOptions | DisTubeOptions.searchSongs} bigger than 0,
* and after the user chose a search result to play.
*
* @param message - The user message called play method
* @param answer - The answered message of user
* @param query - The search query
*/
[Events.SEARCH_DONE]: (message: Message, answer: string, query: string) => Awaitable;
/**
* @event
* Emitted when {@link DisTubeOptions | DisTubeOptions.searchSongs} bigger than 0,
* and the search canceled due to user's next message is not a number or out of
* results range.
*
* @example
* ```ts
* // DisTubeOptions.searchSongs > 0
* distube.on("searchInvalidAnswer", (message) => message.channel.send(`You answered an invalid number!`));
* ```ts
*
* @param message - The user message called play method
* @param answer - The answered message of user
* @param query - The search query
*/
[Events.SEARCH_INVALID_ANSWER]: (message: Message, answer: string, query: string) => Awaitable;
/**
* @event
* Emitted when DisTube cannot find any results for the query.
*
* @example
* ```ts
* distube.on("searchNoResult", (message, query) => message.channel.send(`No result found for ${query}!`));
* ```ts
*
* @param message - The user message called play method
* @param query - The search query
*/
[Events.SEARCH_NO_RESULT]: (message: Message, query: string) => Awaitable;
/**
* @event
* Emitted when {@link DisTubeOptions | DisTubeOptions.searchSongs} bigger than 0,
* and song param of {@link DisTube#play} is invalid url. DisTube will wait for
* user's next message to choose a song manually. <info>{@link
* https://support.google.com/youtube/answer/7354993 | Safe search} is enabled if
* {@link DisTubeOptions}.nsfw is disabled and the message's channel is not a nsfw
* channel.</info>
*
* @example
* ```ts
* // DisTubeOptions.searchSongs > 0
* distube.on("searchResult", (message, results) => {
* message.channel.send(`**Choose an option from below**\n${
* results.map((song, i) => `**${i + 1}**. ${song.name} - \`${song.formattedDuration}\``).join("\n")
* }\n*Enter anything else or wait 60 seconds to cancel*`);
* });
* ```ts
*
* @param message - The user message called play method
* @param results - Searched results
* @param query - The search query
*/
[Events.SEARCH_RESULT]: (message: Message, results: SearchResult[], query: string) => Awaitable;
}
/**
* DisTube class
*/
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
export class DisTube extends TypedEmitter<TypedDisTubeEvents> {
readonly handler: DisTubeHandler;
readonly options: Options;
readonly client: Client;
readonly queues: QueueManager;
readonly voices: DisTubeVoiceManager;
readonly extractorPlugins: ExtractorPlugin[];
readonly customPlugins: CustomPlugin[];
readonly filters: Filters;
/**
* @deprecated Use `youtubeCookie: Cookie[]` instead. Guide: {@link
* https://github.com/skick1234/DisTube/wiki/YouTube-Cookies | YouTube Cookies}
*/
constructor(
client: Client,
opts: DisTubeOptions & {
youtubeCookie: string;
},
);
/**
* Create a new DisTube class.
*
* @example
* ```ts
* const Discord = require('discord.js'),
* DisTube = require('distube'),
* client = new Discord.Client();
* // Create a new DisTube
* const distube = new DisTube.default(client, { searchSongs: 10 });
* // client.DisTube = distube // make it access easily
* client.login("Your Discord Bot Token")
* ```ts
*
* @throws {@link DisTubeError}
*
* @param client - Discord.JS client
* @param opts - Custom DisTube options
*/
constructor(client: Client, opts?: DisTubeOptions);
constructor(client: Client, opts: DisTubeOptions = {}) {
super();
this.setMaxListeners(1);
if (!isClientInstance(client)) throw new DisTubeError("INVALID_TYPE", "Discord.Client", client, "client");
/**
* Discord.JS client
*/
this.client = client;
checkIntents(client.options);
/**
* DisTube options
*/
this.options = new Options(opts);
/**
* Voice connections manager
*/
this.voices = new DisTubeVoiceManager(this);
/**
* DisTube's Handler
*/
this.handler = new DisTubeHandler(this);
/**
* Queues manager
*/
this.queues = new QueueManager(this);
/**
* DisTube filters
*/
this.filters = { ...defaultFilters, ...this.options.customFilters };
// Default plugin
if (this.options.directLink) this.options.plugins.push(new DirectLinkPlugin());
this.options.plugins.forEach(p => p.init(this));
/**
* Extractor Plugins
*/
this.extractorPlugins = this.options.plugins.filter((p): p is ExtractorPlugin => p.type === "extractor");
/**
* Custom Plugins
*/
this.customPlugins = this.options.plugins.filter((p): p is CustomPlugin => p.type === "custom");
}
static get version() {
return version;
}
/**
* DisTube version
*/
get version() {
return version;
}
/**
* Play / add a song or playlist from url. Search and play a song if it is not a
* valid url.
*
* @example
* ```ts
* client.on('message', (message) => {
* if (!message.content.startsWith(config.prefix)) return;
* const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
* const command = args.shift();
* if (command == "play")
* distube.play(message.member.voice.channel, args.join(" "), {
* member: message.member,
* textChannel: message.channel,
* message
* });
* });
* ```ts
*
* @throws {@link DisTubeError}
*
* @param voiceChannel - The channel will be joined if the bot isn't in any channels, the bot will be
* moved to this channel if {@link DisTubeOptions}.joinNewVoiceChannel is `true`
* @param song - URL | Search string | {@link Song} | {@link SearchResult} | {@link Playlist}
* @param options - Optional options
*/
async play(
voiceChannel: VoiceBasedChannel,
song: string | Song | SearchResult | Playlist,
options: PlayOptions = {},
): Promise<void> {
if (!isSupportedVoiceChannel(voiceChannel)) {
throw new DisTubeError("INVALID_TYPE", "BaseGuildVoiceChannel", voiceChannel, "voiceChannel");
}
if (!isObject(options)) throw new DisTubeError("INVALID_TYPE", "object", options, "options");
const { textChannel, member, skip, message, metadata } = {
member: voiceChannel.guild.members.me ?? undefined,
textChannel: options?.message?.channel,
skip: false,
...options,
};
const position = Number(options.position) || (skip ? 1 : 0);
if (message && !isMessageInstance(message)) {
throw new DisTubeError("INVALID_TYPE", ["Discord.Message", "a falsy value"], message, "options.message");
}
if (textChannel && !isTextChannelInstance(textChannel)) {
throw new DisTubeError("INVALID_TYPE", "Discord.GuildTextBasedChannel", textChannel, "options.textChannel");
}
if (member && !isMemberInstance(member)) {
throw new DisTubeError("INVALID_TYPE", "Discord.GuildMember", member, "options.member");
}
const queue = this.getQueue(voiceChannel);
const queuing = queue && !queue._taskQueue.hasResolveTask;
if (queuing) await queue?._taskQueue.queuing(true);
try {
if (typeof song === "string") {
for (const plugin of this.customPlugins) {
if (await plugin.validate(song)) {
await plugin.play(voiceChannel, song, options);
return;
}
}
}
if (typeof song === "string" && !isURL(song)) {
if (!message) {
song = (await this.search(song, { limit: 1 }))[0];
} else {
const result = await this.handler.searchSong(message, song);
if (!result) return;
song = result;
}
}
song = await this.handler.resolve(song, { member, metadata });
if (song instanceof Playlist) {
await this.handler.playPlaylist(voiceChannel, song, { textChannel, skip, position });
} else {
await this.handler.playSong(voiceChannel, song, { textChannel, skip, position });
}
} catch (e: any) {
if (!(e instanceof DisTubeError)) {
try {
e.name = "PlayError";
e.message = `${typeof song === "string" ? song : song.url}\n${e.message}`;
} catch {
// Throw original error
}
}
throw e;
} finally {
if (queuing) queue?._taskQueue.resolve();
}
}
/**
* Create a custom playlist
*
* @example
* ```ts
* const songs = ["https://www.youtube.com/watch?v=xxx", "https://www.youtube.com/watch?v=yyy"];
* const playlist = await distube.createCustomPlaylist(songs, {
* member: message.member,
* properties: { name: "My playlist name", source: "custom" },
* parallel: true
* });
* distube.play(voiceChannel, playlist, { ... });
* ```ts
*
* @param songs - Array of url, Song or SearchResult
* @param options - Optional options
*/
async createCustomPlaylist(
songs: (string | Song | SearchResult)[],
options: CustomPlaylistOptions = {},
): Promise<Playlist> {
const { member, properties, parallel, metadata } = { parallel: true, ...options };
if (!Array.isArray(songs)) throw new DisTubeError("INVALID_TYPE", "Array", songs, "songs");
if (!songs.length) throw new DisTubeError("EMPTY_ARRAY", "songs");
const filteredSongs = songs.filter(
song => song instanceof Song || isURL(song) || (typeof song !== "string" && song.type === SearchResultType.VIDEO),
);
if (!filteredSongs.length) throw new DisTubeError("NO_VALID_SONG");
if (member && !isMemberInstance(member)) {
throw new DisTubeError("INVALID_TYPE", "Discord.Member", member, "options.member");
}
let resolvedSongs: Song[];
if (parallel) {
const promises = filteredSongs.map((song: string | Song | SearchResult) =>
this.handler.resolve(song, { member, metadata }).catch(() => undefined),
);
resolvedSongs = (await Promise.all(promises)).filter((s): s is Song => s instanceof Song);
} else {
resolvedSongs = [];
for (const song of filteredSongs) {
const resolved = await this.handler.resolve(song, { member, metadata }).catch(() => undefined);
if (resolved instanceof Song) resolvedSongs.push(resolved);
}
}
return new Playlist(resolvedSongs, { member, properties, metadata });
}
search(
string: string,
options?: { type?: SearchResultType.VIDEO; limit?: number; safeSearch?: boolean; retried?: boolean },
): Promise<Array<SearchResultVideo>>;
search(
string: string,
options: { type: SearchResultType.PLAYLIST; limit?: number; safeSearch?: boolean; retried?: boolean },
): Promise<Array<SearchResultPlaylist>>;
search(
string: string,
options?: { type?: SearchResultType; limit?: number; safeSearch?: boolean; retried?: boolean },
): Promise<Array<SearchResult>>;
/**
* Search for a song. You can customize how user answers instead of send a number.
* Then use {@link DisTube#play} to play it.
*
* @param string - The string search for
* @param options - Search options
* @param options.limit - Limit the results
* @param options.type - Type of results (`video` or `playlist`).
* @param options.safeSearch - Whether or not use safe search (YouTube restricted mode)
*
* @returns Array of results
*/
async search(
string: string,
options: {
type?: SearchResultType;
limit?: number;
safeSearch?: boolean;
retried?: boolean;
} = {},
): Promise<Array<SearchResult>> {
const opts = { type: SearchResultType.VIDEO, limit: 10, safeSearch: false, ...options };
if (typeof opts.type !== "string" || !["video", "playlist"].includes(opts.type)) {
throw new DisTubeError("INVALID_TYPE", ["video", "playlist"], opts.type, "options.type");
}
if (typeof opts.limit !== "number") throw new DisTubeError("INVALID_TYPE", "number", opts.limit, "options.limit");
if (opts.limit < 1) throw new DisTubeError("NUMBER_COMPARE", "option.limit", "bigger or equal to", 1);
if (typeof opts.safeSearch !== "boolean") {
throw new DisTubeError("INVALID_TYPE", "boolean", opts.safeSearch, "options.safeSearch");
}
try {
const search = await ytsr(string, { ...opts, requestOptions: { headers: { cookie: this.handler.ytCookie } } });
const results = search.items.map(i => {
if (i.type === "video") return new SearchResultVideo(i);
return new SearchResultPlaylist(i as any);
});
if (results.length === 0) throw new DisTubeError("NO_RESULT");
return results;
} catch (e) {
if (options.retried) throw e;
options.retried = true;
return this.search(string, options);
}
}
/**
* Get the guild queue
*
* @example
* ```ts
* client.on('message', (message) => {
* if (!message.content.startsWith(config.prefix)) return;
* const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
* const command = args.shift();
* if (command == "queue") {
* const queue = distube.getQueue(message);
* message.channel.send('Current queue:\n' + queue.songs.map((song, id) =>
* `**${id+1}**. [${song.name}](${song.url}) - \`${song.formattedDuration}\``
* ).join("\n"));
* }
* });
* ```ts
*
* @param guild - The type can be resolved to give a {@link Queue}
*/
getQueue(guild: GuildIdResolvable): Queue | undefined {
return this.queues.get(guild);
}
#getQueue(guild: GuildIdResolvable): Queue {
const queue = this.getQueue(guild);
if (!queue) throw new DisTubeError("NO_QUEUE");
return queue;
}
/**
* Pause the guild stream
*
* @param guild - The type can be resolved to give a {@link Queue}
*
* @returns The guild queue
*/
pause(guild: GuildIdResolvable): Queue {
return this.#getQueue(guild).pause();
}
/**
* Resume the guild stream
*
* @param guild - The type can be resolved to give a {@link Queue}
*
* @returns The guild queue
*/
resume(guild: GuildIdResolvable): Queue {
return this.#getQueue(guild).resume();
}
/**
* Stop the guild stream
*
* @example
* ```ts
* client.on('message', (message) => {
* if (!message.content.startsWith(config.prefix)) return;
* const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
* const command = args.shift();
* if (command == "stop") {
* distube.stop(message);
* message.channel.send("Stopped the queue!");
* }
* });
* ```ts
*
* @param guild - The type can be resolved to give a {@link Queue}
*/
stop(guild: GuildIdResolvable): Promise<void> {
return this.#getQueue(guild).stop();
}
/**
* Set the guild stream's volume
*
* @example
* ```ts
* client.on('message', (message) => {
* if (!message.content.startsWith(config.prefix)) return;
* const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
* const command = args.shift();
* if (command == "volume")
* distube.setVolume(message, Number(args[0]));
* });
* ```ts
*
* @param guild - The type can be resolved to give a {@link Queue}
* @param percent - The percentage of volume you want to set
*
* @returns The guild queue
*/
setVolume(guild: GuildIdResolvable, percent: number): Queue {
return this.#getQueue(guild).setVolume(percent);
}
/**
* Skip the playing song if there is a next song in the queue. <info>If {@link
* Queue#autoplay} is `true` and there is no up next song, DisTube will add and
* play a related song.</info>
*
* @example
* ```ts
* client.on('message', (message) => {
* if (!message.content.startsWith(config.prefix)) return;
* const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
* const command = args.shift();
* if (command == "skip")
* distube.skip(message);
* });
* ```ts
*
* @param guild - The type can be resolved to give a {@link Queue}
*
* @returns The new Song will be played
*/
skip(guild: GuildIdResolvable): Promise<Song> {
return this.#getQueue(guild).skip();
}
/**
* Play the previous song
*
* @example
* ```ts
* client.on('message', (message) => {
* if (!message.content.startsWith(config.prefix)) return;
* const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
* const command = args.shift();
* if (command == "previous")
* distube.previous(message);
* });
* ```ts
*
* @param guild - The type can be resolved to give a {@link Queue}
*
* @returns The new Song will be played
*/
previous(guild: GuildIdResolvable): Promise<Song> {
return this.#getQueue(guild).previous();
}
/**
* Shuffle the guild queue songs
*
* @example
* ```ts
* client.on('message', (message) => {
* if (!message.content.startsWith(config.prefix)) return;
* const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
* const command = args.shift();
* if (command == "shuffle")
* distube.shuffle(message);
* });
* ```ts
*
* @param guild - The type can be resolved to give a {@link Queue}
*
* @returns The guild queue
*/
shuffle(guild: GuildIdResolvable): Promise<Queue> {
return this.#getQueue(guild).shuffle();
}
/**
* Jump to the song number in the queue. The next one is 1, 2,... The previous one
* is -1, -2,...
*
* @example
* ```ts
* client.on('message', (message) => {
* if (!message.content.startsWith(config.prefix)) return;
* const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
* const command = args.shift();
* if (command == "jump")
* distube.jump(message, parseInt(args[0]))
* .catch(err => message.channel.send("Invalid song number."));
* });
* ```ts
*
* @param guild - The type can be resolved to give a {@link Queue}
* @param num - The song number to play
*
* @returns The new Song will be played
*/
jump(guild: GuildIdResolvable, num: number): Promise<Song> {
return this.#getQueue(guild).jump(num);
}
/**
* Set the repeat mode of the guild queue.
* Toggle mode `(Disabled -> Song -> Queue -> Disabled ->...)` if `mode` is `undefined`
*
* @example
* ```ts
* client.on('message', (message) => {
* if (!message.content.startsWith(config.prefix)) return;
* const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
* const command = args.shift();
* if (command == "repeat") {
* let mode = distube.setRepeatMode(message, parseInt(args[0]));
* mode = mode ? mode == 2 ? "Repeat queue" : "Repeat song" : "Off";
* message.channel.send("Set repeat mode to `" + mode + "`");
* }
* });
* ```ts
* @example
* ```ts
* const { RepeatMode } = require("distube");
* let mode;
* switch(distube.setRepeatMode(message, parseInt(args[0]))) {
* case RepeatMode.DISABLED:
* mode = "Off";
* break;
* case RepeatMode.SONG:
* mode = "Repeat a song";
* break;
* case RepeatMode.QUEUE:
* mode = "Repeat all queue";
* break;
* }
* message.channel.send("Set repeat mode to `" + mode + "`");
* ```ts
*
* @param guild - The type can be resolved to give a {@link Queue}
* @param mode - The repeat modes (toggle if `undefined`)
*
* @returns The new repeat mode
*/
setRepeatMode(guild: GuildIdResolvable, mode?: number): number {
return this.#getQueue(guild).setRepeatMode(mode);
}
/**
* Toggle autoplay mode
*
* @example
* ```ts
* client.on('message', (message) => {
* if (!message.content.startsWith(config.prefix)) return;
* const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
* const command = args.shift();
* if (command == "autoplay") {
* const mode = distube.toggleAutoplay(message);
* message.channel.send("Set autoplay mode to `" + (mode ? "On" : "Off") + "`");
* }
* });
* ```ts
*
* @param guild - The type can be resolved to give a {@link Queue}
*
* @returns Autoplay mode state
*/
toggleAutoplay(guild: GuildIdResolvable): boolean {
const queue = this.#getQueue(guild);
queue.autoplay = !queue.autoplay;
return queue.autoplay;
}
/**
* Add related song to the queue
*
* @param guild - The type can be resolved to give a {@link Queue}
*
* @returns The guild queue
*/
addRelatedSong(guild: GuildIdResolvable): Promise<Song> {
return this.#getQueue(guild).addRelatedSong();
}
/**
* Set the playing time to another position
*
* @example
* ```ts
* client.on('message', message => {
* if (!message.content.startsWith(config.prefix)) return;
* const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
* const command = args.shift();
* if (command = 'seek')
* distube.seek(message, Number(args[0]));
* });
* ```ts
*
* @param guild - The type can be resolved to give a {@link Queue}
* @param time - Time in seconds
*
* @returns Seeked queue
*/
seek(guild: GuildIdResolvable, time: number): Queue {
return this.#getQueue(guild).seek(time);
}
/**
* Emit error event
*
* @param error - error
* @param channel - Text channel where the error is encountered.
*/
emitError(error: Error, channel?: GuildTextBasedChannel): void {
if (this.listeners(Events.ERROR).length) {
this.emit(Events.ERROR, channel, error);
} else {
/* eslint-disable no-console */
console.error(error);
console.warn("Unhandled 'error' event.");
console.warn(
"See: https://distube.js.org/classes/DisTube.html#error and https://nodejs.org/api/events.html#events_error_events",
);
/* eslint-enable no-console */
}
}
}
export default DisTube;