Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

yt-api

Package Overview
Dependencies
Maintainers
1
Versions
27
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

yt-api

`npm i yt-api`

  • 0.0.4
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

Welcome to the yt-api a light weight and easy to use api.

Installing is as simple as using

npm i yt-api

Setup

To use the api you need a api key from google and you can get that here
Once you have created the api key you need to enable the Youtube Data API v3 by clicking on the libraries tab and clicking on the Youtube Data API v3 then click on enable and your done!

Using the api

const yt-api = require("yt-api");
const API = new yt-api("PASTE_API_KEY_HERE");

Getting video info

API.getVideoInfo("YOUTUBE_VIDEO_ID" /*Needs to be a valid video id or it will throw a error!*/, info => {
    console.log("This video's title is "+info.title+" with a id of "+info.videoID+".");
});

//Results for the getVideoInfo
videoID: //the video's id,
url: //the url to the video,
title: //The video title
channel: {
    id: //The channel id
    user: //The user,
    url: //The video's channel url
},
livestream: //Is it a livestream?,
category: //The category its in,
thumbnail: //The videos thumbnail,
description: //The video's description,
publishDate: //The date it was published at,
duration: {
    days: //The durration in days
    hours: //The durration in hours,
    minutes: //The durration in minutes,
    seconds: //The durration in seconds
},
statistics: {
    views: //The total views the video has,
    likes: //The total likes the video has,
    dislikes: //The total dislikes the video has,
    comments: //The total commends the video has,
    favorites: //The people who favorited the video
}

Searching youtube

API.searchYouTube("Alan walker faded" /*If there are 0 results it will log to the console that it found no results*/, info => {
    console.log(`The video's title is ${info.title} and its id is ${info.videoID}`);
});

/*Results that you can use for the callback function.
NOTE: You can use the getVideoInfo function to get more info about this search*/

videoID: //The video's unique id,
url: //the video's url,
title: //the Video's title,
channel: {
    id: //The channel id,
    user: //The user,
    url: //The video's channel url
},
thumbnail: //The videos thumbnail,

Getting more than 1 video result aka the searchVideos function

API.searchVideos("Marshmello alone", 5 /*The amount of videos you want to be searched or the limit*/, videos => {
    //Mapping the videos
    let sidenum=0;
    console.log(videos.map(v=>`the video's title is ${v.title} and the id is ${v.videoID}`).join("\n"));
    //Getting a specific video
    let video = videos[/*number in between 0 and the ammount you specified in this case its 5*/];
    console.log(`This videos title is ${video.title} and the id is ${video.videoID}`);
});

//Returns
videoID: //The video's unique id,
url: //the video's url,
title: //the Video's title,
channel: {
    id: //The channel id,
    user: //The user,
    url: //The video's channel url
},
thumbnail: //The videos thumbnail,

Discord music bot example.

Ever wanted to make a music bot with a song selection well now you can using this code and this is the full code no cuts no unpasted code its all the same code minus the np and queue command wich i hope you can figure out your self's.
const { Client } = require("discord.js");
const bot = new Client();
const ytdl = require("ytdl-core");

//The api to get song info and user input.
let YouTube = require("./index.js");
let yt = new YouTube("API_KEY_HERE");
//The queue's
let guilds = {};
bot.login("BOT_TOKEN_HERE");
bot.on("ready", () => console.log("REEADY!"));

bot.on("message", msg => {
    let prefix = ';';
    let args = msg.content.slice(prefix.length).trim().split(" ");
    let cmd = args.shift().toLowerCase();

    let guild = guilds[msg.guild.id];

    if(cmd === "play") {
        if(!guild) guild = guilds[msg.guild.id] = {
            queue: [],
            isPlaying: false
        };
        if(!msg.member.voiceChannel) return msg.channel.send("You must be in a voice channel first!");
        let song = args.join(" ");
        if(!song) return msg.channel.send("You need to provide a searchterm!");
        if(guild.isPlaying) {
            yt.searchVideos(song, 5, async videos => {
                try {
                    let num=0;
                    let m = await msg.channel.send(`
**Song selection:**

${videos.map(v=>`**${++num}:** ${v.title}`).join("\n")}

Please provide a value between 1 and 5.
                    `);
                    let collector = await msg.channel.awaitMessages(m=>m.content > 0 && m.content < 6 && m.author.id === msg.author.id && m.channel.id === msg.channel.id, {
                        maxMatches: 1,
                        time: 10000,
                        errors: ['time']
                    });
                    let selection = parseInt(collector.first().content);
                    let vid = videos[selection - 1];
                    m.delete(5000);
                    yt.getVideoInfo(vid.videoID, i => {
                        guild.queue.push({
                            title: i.title,
                            id: i.videoID,
                            url: i.url,
                            duration: {
                                days: i.duration.days,
                                hours: i.duration.hours,
                                minutes: i.duration.minutes,
                                seconds: i.duration.seconds
                            }
                        });
                        return msg.channel.send(`Added **${i.title}** to the queue!`);
                    });
                } catch (error) {
                    return msg.channel.send("No value was entered. Canceling video selection!");
                }
            });
        } else {
            guild.isPlaying = true;
            yt.searchVideos(song, 5, async videos => {
                try {
                    let num=0;
                    let m = await msg.channel.send(`
**Song selection:**

${videos.map(v=>`**${++num}:** ${v.title}`).join("\n")}

Please provide a value between 1 and 5.
                    `);
                    let collector = await msg.channel.awaitMessages(m=>m.content > 0 && m.content < 6 && m.author.id === msg.author.id && m.channel.id === msg.channel.id, {
                        maxMatches: 1,
                        time: 10000,
                        errors: ['time']
                    });
                    let selection = parseInt(collector.first().content);
                    let vid = videos[selection - 1];
                    m.delete(5000);
                    yt.getVideoInfo(vid.videoID, i => {
                        guild.queue.push({
                            title: i.title,
                            id: i.videoID,
                            url: i.url,
                            duration: {
                                days: i.duration.days,
                                hours: i.duration.hours,
                                minutes: i.duration.minutes,
                                seconds: i.duration.seconds
                            }
                        });
                        return playSong(i.url, guild, msg);
                    });
                } catch (error) {
                    return msg.channel.send("No value was entered. Canceling video selection!");
                }
            });
        }
    }
});

function playSong(url, guild, msg) {
    let vc = msg.member.voiceChannel;
    vc.join().then(con => {
        let dispatcher = con.playStream(ytdl(url, { filter: "audioonly" }));
        dispatcher.on("end", () => {
            guild.queue.shift();
            if(guild.queue.length === 0) {
                vc.leave();
                delete guilds[msg.guild.id];
            } else {
                playSong(guild.queue[0].url, guild, msg);
            }
        });
    });
    msg.channel.send(`Now playing: **${guild.queue[0].title}** (${guild.queue[0].duration.hours}${guild.queue[0].duration.minutes}${guild.queue[0].duration.seconds})`);
}

FAQs

Package last updated on 20 Jan 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc