How to use ytdl-core - 10 common examples

To help you get started, we’ve selected a few ytdl-core examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github funo-bot / Funo / src / util / musicHandler.js View on Github external
async addSong(song_url, textchannel, cb) {
    try {
      this.emit("addSong", {
        data: await YTDL.getInfo(song_url),
        cb: cb,
        channel: textchannel.id
      })
    } catch (err) {
      cb(err)
    }
    // console.log(await YTDL.getInfo(song_url))
  }
github fent / node-ytdl / bin / ytdl.js View on Github external
opts.outputHelp((help) => {
    return chalk.red('\n  url argument is required\n') + help;
  });
  process.exit(1);
}

const path         = require('path');
const fs           = require('fs');
const ytdl         = require('ytdl-core');
const homedir      = require('homedir');
const util         = require('../lib/util');

const label = chalk.bold.gray;


ytdl.cache.info.timeout = 0;
if (opts.cache !== false) {
  // Keep cache in file.
  const cachefile = path.resolve(homedir(), '.ytdl-cache.json');
  let cache = {};
  fs.readFile(cachefile, (err, contents) => {
    if (err) return;
    try {
      cache = JSON.parse(contents);
    } catch (err) {
      console.error(`Badly formatted cachefile (${cachefile}): ${err.message}`);
    }
  });

  ytdl.cache.sig.get = key => cache[key];
  ytdl.cache.sig.set = (key, value) => {
    cache[key] = value;
github efoxbr / megacubo / assets / js / playback.js View on Github external
self.run = () => {
        console.log('run() called');
        if(typeof(ytdl)=='undefined'){
            ytdl = require('ytdl-core')
        }
        var id = ytdl.getURLVideoID(self.entry.url);
        console.log('run() id', id, self.entry.url);
        ytdl.getInfo(id, (err, info) => {
            if (err){
                console.log('YTDL error');
                self.error = 'connect';
                self.trigger('error')
                throw err;
            } else {
                console.log('YT Info', info);
                if(info.title) {
                    self.rename(info.title, info.thumbnail_url)
                }
                var live = [];
                for(var i=0;i
github petercunha / Wizardli / server / lib / downloader.js View on Github external
function (err, info) {

					// Emit info about download
					self.emit("started", {
						info: info
					});

					if (parseInt(info.length_seconds) > MAX_LENGTH) {
						callback(`Video is too long, max seconds is ${MAX_LENGTH}`, resultObj);
					} else {
						// Stream setup
						var stream = ytdl.downloadFromInfo(info, {
							quality: self.youtubeVideoQuality,
							requestOptions: self.requestOptions
						});

						stream.on("response", function (httpResponse) {
							// Setup of progress module
							var str = progress({
								length: parseInt(
									httpResponse.headers["content-length"]
								),
								time: self.progressTimeout
							});

							// Add progress event listener
							str.on("progress", function (progress) {
								if (progress.percentage === 100) {
github LenoxBot / LenoxBot / src / commands / Music / play.js View on Github external
async run(message, [query]) {
		const music_settings = message.guildSettings.get('music');
		moment.locale(message.guildSettings.get('momentLanguage'));

		if (!this._getVoiceChannel(message)) return message.channel.sendLocale('MUSIC_NOTINVOICECHANNEL');
		/* Planned Removal */
		/*for (let i = 0; i < message.client.provider.getGuild(message.guild.id, 'musicchannelblacklist').length; i++) {
			if (voiceChannel.id === message.client.provider.getGuild(message.guild.id, 'musicchannelblacklist')[i]) return message.reply(lang.play_blacklistchannel);
		}*/
		/* Planned Removal */

		if ((ytdl.validateURL(query) || ytdl.validateID(query)) && !query.includes(' ')) { // youtube video
			/**
			 * @property { videoId, url, title, description, owner, channelId, thumbnailUrl, embedURL, datePublished, genre, paid, unlisted, isFamilyFriendly, duration, views, regionsAllowed, dislikeCount, likeCount, channelThumbnailUrl, commentCount }
			*/
			this._pushToQueue(message, await this._getYoutubeVideoInfo(ytdl.getVideoID(query)));
		} else if ((regexes.youtube_playlist.test(query) || (query.length >= 20 && query.length <= 34)) && !query.includes(' ') && decodeURIComponent(query).includes('/playlist?list=')) { // youtube playlist
			await message.send({ embed: { description: message.language.get('LOADING_MESSAGE'), color: 7506394 } });
			const videos = (await this._getYoutubePlaylistVideos(query)).map((info) => this._pushToQueue(message, info, { is_playlist: true }));
			await message.send({ embed: { description: message.language.get('MUSIC_ADDEDNUMITEMSTOQUEUE', videos.length), color: 7506394 } });
		} else if (!query.includes(' ') && regexes.domain_name.test(query) && !ytdl.validateURL(query)) { // radio stream
			const track = new StreamTrack(message, query);
			await track._autoFill();
			this._pushToQueue(message, track, { is_stream: true })
			//this._pushToQueue(message, { url: query, duration: Infinity }, { is_stream: true });
		} else { // play from stream [only supports youtube and radio streams currently]
				
			if (query.toLowerCase().startsWith('yt:')) {
github LenoxBot / LenoxBot / src / commands / Music / play.js View on Github external
}).then((connection) => {
			// Play the video.
			try {
				if (!current_audio) return message.channel.sendLocale('MUSIC_UNABLETOPLAYAUDIO');
				
				const dispatcher =/*!music_settings.stream_mode ?*/ connection.play(ytdl.validateURL(current_audio.url) ? ytdl(current_audio.url, { filter: 'audioonly' }) : current_audio.url, { volume: music_settings.volume / 100 });

				connection.once('failed', (reason) => {
					console.error(`Connection failed: ${reason.toString()}`);
					if (message && message.channel) message.channel.send(reason.toString());
					try {
						if (connection) connection.disconnect();
					} catch (err) {
						console.error(err.stack ? err.stack : err.toString());
					};
				});
				
				connection.once('error', (err) => {
					console.error(`Connection error: ${err.stack ? err.stack : err.toString()}`);
					if (message && message.channel) message.channel.sendLocale('MUSIC_CONNECTIONERROR', [err.toString()]);
					if (queue.length) {
						if (music_settings.loop && !current_audio.repeat) {
github LenoxBot / LenoxBot / src / commands / Music / play.js View on Github external
/* Planned Removal */
		/*for (let i = 0; i < message.client.provider.getGuild(message.guild.id, 'musicchannelblacklist').length; i++) {
			if (voiceChannel.id === message.client.provider.getGuild(message.guild.id, 'musicchannelblacklist')[i]) return message.reply(lang.play_blacklistchannel);
		}*/
		/* Planned Removal */

		if ((ytdl.validateURL(query) || ytdl.validateID(query)) && !query.includes(' ')) { // youtube video
			/**
			 * @property { videoId, url, title, description, owner, channelId, thumbnailUrl, embedURL, datePublished, genre, paid, unlisted, isFamilyFriendly, duration, views, regionsAllowed, dislikeCount, likeCount, channelThumbnailUrl, commentCount }
			*/
			this._pushToQueue(message, await this._getYoutubeVideoInfo(ytdl.getVideoID(query)));
		} else if ((regexes.youtube_playlist.test(query) || (query.length >= 20 && query.length <= 34)) && !query.includes(' ') && decodeURIComponent(query).includes('/playlist?list=')) { // youtube playlist
			await message.send({ embed: { description: message.language.get('LOADING_MESSAGE'), color: 7506394 } });
			const videos = (await this._getYoutubePlaylistVideos(query)).map((info) => this._pushToQueue(message, info, { is_playlist: true }));
			await message.send({ embed: { description: message.language.get('MUSIC_ADDEDNUMITEMSTOQUEUE', videos.length), color: 7506394 } });
		} else if (!query.includes(' ') && regexes.domain_name.test(query) && !ytdl.validateURL(query)) { // radio stream
			const track = new StreamTrack(message, query);
			await track._autoFill();
			this._pushToQueue(message, track, { is_stream: true })
			//this._pushToQueue(message, { url: query, duration: Infinity }, { is_stream: true });
		} else { // play from stream [only supports youtube and radio streams currently]
				
			if (query.toLowerCase().startsWith('yt:')) {
				await this._searchForYoutubeVideo(message, query.replace(/^yt\:/i, '')); // if query starts with `yt:` search for youtube video
			} else {
				await this._searchForYoutubeVideo(message, query); // if none match default to youtube
			}
			// search for builtin radio name or youtube video
			//otherwise it's a search query for youtube
		}

		if (music_settings.queue.length === 1 || !this._getVoiceConnection(message)) await this._executeQueue(message, music_settings.queue);
github LenoxBot / LenoxBot / src / commands / Music / play.js View on Github external
async run(message, [query]) {
		const music_settings = message.guildSettings.get('music');
		moment.locale(message.guildSettings.get('momentLanguage'));

		if (!this._getVoiceChannel(message)) return message.channel.sendLocale('MUSIC_NOTINVOICECHANNEL');
		/* Planned Removal */
		/*for (let i = 0; i < message.client.provider.getGuild(message.guild.id, 'musicchannelblacklist').length; i++) {
			if (voiceChannel.id === message.client.provider.getGuild(message.guild.id, 'musicchannelblacklist')[i]) return message.reply(lang.play_blacklistchannel);
		}*/
		/* Planned Removal */

		if ((ytdl.validateURL(query) || ytdl.validateID(query)) && !query.includes(' ')) { // youtube video
			/**
			 * @property { videoId, url, title, description, owner, channelId, thumbnailUrl, embedURL, datePublished, genre, paid, unlisted, isFamilyFriendly, duration, views, regionsAllowed, dislikeCount, likeCount, channelThumbnailUrl, commentCount }
			*/
			this._pushToQueue(message, await this._getYoutubeVideoInfo(ytdl.getVideoID(query)));
		} else if ((regexes.youtube_playlist.test(query) || (query.length >= 20 && query.length <= 34)) && !query.includes(' ') && decodeURIComponent(query).includes('/playlist?list=')) { // youtube playlist
			await message.send({ embed: { description: message.language.get('LOADING_MESSAGE'), color: 7506394 } });
			const videos = (await this._getYoutubePlaylistVideos(query)).map((info) => this._pushToQueue(message, info, { is_playlist: true }));
			await message.send({ embed: { description: message.language.get('MUSIC_ADDEDNUMITEMSTOQUEUE', videos.length), color: 7506394 } });
		} else if (!query.includes(' ') && regexes.domain_name.test(query) && !ytdl.validateURL(query)) { // radio stream
			const track = new StreamTrack(message, query);
			await track._autoFill();
			this._pushToQueue(message, track, { is_stream: true })
			//this._pushToQueue(message, { url: query, duration: Infinity }, { is_stream: true });
		} else { // play from stream [only supports youtube and radio streams currently]
				
			if (query.toLowerCase().startsWith('yt:')) {
				await this._searchForYoutubeVideo(message, query.replace(/^yt\:/i, '')); // if query starts with `yt:` search for youtube video
			} else {
				await this._searchForYoutubeVideo(message, query); // if none match default to youtube
			}
github pedromsilvapt / unicast / src / Extensions / MediaProviders / Youtube / SubtitlesDownloader.ts View on Github external
match ( video : string, subtitles : YoutubeSubtitleResult[] ) : YoutubeSubtitleResult {
        const id = ytdl.getVideoID( video );

        let result = this.findLanguage( this.languages, subtitles );

        if ( result ) {
            // console.log( result );
            return {
                language: result.lang_code,
                url: `${ this.downloadEndpoint }?lang=${ result.lang_code }&v=${ id }&fmt=${ this.format }`,
                format: this.format
            }
        }

        let englishLanguage = this.findLanguage( [ 'en', 'en-US', 'en-UK' ], subtitles );

        let original = ( englishLanguage || subtitles[ 0 ] ).lang_code;
github efoxbr / megacubo / assets / js / playback.js View on Github external
self.run = () => {
        console.log('run() called');
        if(typeof(ytdl)=='undefined'){
            ytdl = require('ytdl-core')
        }
        var id = ytdl.getURLVideoID(self.entry.url);
        console.log('run() id', id, self.entry.url);
        ytdl.getInfo(id, (err, info) => {
            if (err){
                console.log('YTDL error');
                self.error = 'connect';
                self.trigger('error')
                throw err;
            } else {
                console.log('YT Info', info);
                if(info.title) {
                    self.rename(info.title, info.thumbnail_url)
                }
                var live = [];
                for(var i=0;i