discord-player-play-dl/src/Player.ts

76 lines
2.5 KiB
TypeScript
Raw Normal View History

2021-06-11 23:19:52 +05:00
import { Client, Collection, Guild, Snowflake, User } from "discord.js";
2021-06-11 15:32:22 +05:00
import { TypedEmitter as EventEmitter } from "tiny-typed-emitter";
import { Queue } from "./Structures/Queue";
2021-06-11 16:50:43 +05:00
import { VoiceUtils } from "./VoiceInterface/VoiceUtils";
2021-06-11 23:19:52 +05:00
import { PlayerEvents, PlayerOptions, QueryType } from "./types/types";
import Track from "./Structures/Track";
import { QueryResolver } from "./utils/QueryResolver";
import YouTube from "youtube-sr";
2021-06-11 15:32:22 +05:00
2021-06-11 23:19:52 +05:00
class DiscordPlayer extends EventEmitter<PlayerEvents> {
2021-06-11 15:32:22 +05:00
public readonly client: Client;
public readonly queues = new Collection<Snowflake, Queue>();
2021-06-11 16:50:43 +05:00
public readonly voiceUtils = new VoiceUtils();
2021-06-11 15:32:22 +05:00
constructor(client: Client) {
super();
this.client = client;
}
createQueue(guild: Guild, queueInitOptions?: PlayerOptions) {
if (this.queues.has(guild.id)) return this.queues.get(guild.id);
const queue = new Queue(this, guild, queueInitOptions);
this.queues.set(guild.id, queue);
return queue;
}
getQueue(guild: Snowflake) {
return this.queues.get(guild);
}
2021-06-11 19:57:49 +05:00
2021-06-11 23:19:52 +05:00
/**
* Search tracks
* @param {string|Track} query The search query
* @param {User} requestedBy The person who requested track search
* @returns {Promise<Track[]>}
*/
async search(query: string | Track, requestedBy: User) {
if (query instanceof Track) return [query];
// @todo: add extractors
const qt = QueryResolver.resolve(query);
switch (qt) {
2021-06-11 23:39:21 +05:00
case QueryType.YOUTUBE_SEARCH: {
const videos = await YouTube.search(query, {
2021-06-11 23:19:52 +05:00
type: "video"
});
2021-06-11 23:39:21 +05:00
return videos.map((m) => {
(m as any).source = "youtube";
return new Track(this, {
2021-06-11 23:19:52 +05:00
title: m.title,
description: m.description,
author: m.channel?.name,
url: m.url,
requestedBy: requestedBy,
thumbnail: m.thumbnail?.displayThumbnailURL("maxresdefault"),
views: m.views,
fromPlaylist: false,
duration: m.durationFormatted,
raw: m
})
2021-06-11 23:39:21 +05:00
});
2021-06-11 23:19:52 +05:00
}
2021-06-11 23:39:21 +05:00
default:
return [];
2021-06-11 23:19:52 +05:00
}
}
2021-06-11 19:57:49 +05:00
*[Symbol.iterator]() {
yield* Array.from(this.queues.values());
}
2021-06-11 15:32:22 +05:00
}
export { DiscordPlayer as Player };