Пример #1
0
exports.request = function (msg, suffix, bot) {
  var connect = bot.VoiceConnections
    .filter(function (connection) {
      return connection.voiceConnection.guild.id === msg.guild.id
    })
  if (connect.length < 1) {
    msg.channel.sendMessage("I'm not connected to any voice channel in this server, try initializing me with the command `voice` first!")
    return
  }
  var link = require('url').parse(suffix)
  var query = require('querystring').parse(link.query)
  msg.channel.sendTyping()
  if (suffix.includes('list=') !== suffix.includes('playlist?')) { // Checks to see whether the link the user posted includes url identifiers for playlists, but doesn't include the main playlist only identifier "playlist". The ? at the end is just to further make sure that the bot makes sure that it's only direct playlist IDs that are let through. Yes, this works with shortened youtu.be links too.
    msg.channel.sendMessage('Do you want the video or the playlist? Emend your link to only include the link to the video or the playlist.\n(Pay attention to the URL, you posted two youtube IDs, one for the video, and one for the playlist)\n\nExample: www.youtube.com/watch?v=__**u9dg-g7t2l4**__&list=__**PLhd1HyMTk3f5yqcPXjlo8qroWJiMMFBSk**__') // Tell the user what to look for in hopes that the user won't make the same mistake again.
  } else if (query.list && query.list.length > 8 && link.host.indexOf('youtu') > -1) {
    msg.channel.sendMessage('Playlist fetching might take a while...')
    var api = require('youtube-api')
    api.authenticate({
      type: 'key',
      key: Config.api_keys.google
    })
    api.playlistItems.list({
      part: 'snippet',
      pageToken: [],
      maxResults: 50,
      playlistId: query.list
    }, function (err, data) {
      if (err) {
        msg.channel.sendMessage('Something went wrong while requesting information about this playlist.').then((m) => {
          setTimeout(() => {
            m.delete().catch((e) => Logger.error(e))
          }, 3000)
        })
        Logger.error('Playlist failiure, ' + err)
        return
      } else if (data) {
        temp = data.items
        safeLoop(msg, suffix, bot)
      }
    })
  } else {
    fetch(suffix, msg).then((r) => {
      msg.channel.sendMessage(`Added **${r.title}** to the playlist.`).then((m) => {
        setTimeout(() => {
          m.delete().catch((e) => Logger.error(e))
        }, 3000)
      })
      if (r.autoplay === true) {
        next(msg, suffix, bot)
      }
    }).catch((e) => {
      Logger.error(e)
      msg.channel.sendMessage("I couldn't add that to the playlist.").then((m) => {
        setTimeout(() => {
          m.delete().catch((e) => Logger.error(e))
        }, 3000)
      })
    })
  }
}
Пример #2
0
      Request(options, function(err, response, body) {
        if (err) {
          return res.end(err);
        }

        try {
          body = JSON.parse(body);
        } catch (e) {
          return res.end(e.message + " :: " + body);
        }
        if (body.error) {
          return res.end(err || body.error);
        }

        // success
        if (body.access_token) {
          ACCESS_TOKEN = body.access_token;
          Youtube.authenticate({
            type: "oauth",
            token: ACCESS_TOKEN
          });

          res.writeHead(302, {
            "Location": "/"
          });
          res.end();
        }

        return res.end("Something wrong: \n" + JSON.stringify(body, null, 4));
      });
Пример #3
0
   setup: function (apiKEY) {
     this._APIKEY = apiKEY;
     youtubeAPI.authenticate({
         type: 'key',
         key: apiKEY
     });
 },
Пример #4
0
/**
 * Gets a particular video metadata given its youtube ID
 * @param  {Object}   request  The request from the user
 * @param  {Function} callback Callback function to send back
 * @return {Function} callback ^
 */
function getVideo(request, callback) {
    if(!request.query.id) {
        return callback('Missing ID');
    }
    Youtube.authenticate({
        type: "oauth",
        token: config.oauth
    });
    Youtube.videos.list({part: 'snippet,statistics,contentDetails', id: request.query.id}, function (error, result) {
        return callback(null, result);
    });
}
Пример #5
0
app.post('/upload_video', ensureAuthenticated, function(req, res){
    var oauth = youtube.authenticate({
    type: "oauth",
    client_id: CREDENTIALS.web.client_id,
    client_secret: CREDENTIALS.web.client_secret,
    redirect_url: CREDENTIALS.web.redirect_uris[0]
    });
    oauth.setCredentials({'access_token': req.user.accesstoken});
    console.log(req.body)
    console.log(req.file.originalname)

    youtube.videos.insert({
        resource: {
            // Video title and description
            snippet: {
                title: req.body["title"],
                description: req.body["desc"]
                },
            // I don't want to spam my subscribers
            status: {
                privacyStatus: "public"
            }
            },
            // This is for the callback function
        part: "snippet,status",

            // Create the readable stream to upload the video
        media: {
            body: req.file.buffer
        }
    }, function (err, data) {
        if(err) {
            console.log('upload error');
            console.log(err);
            res.send('upload_error, please make sure you have a youtube channel. error detail: ' + err);
        } else {
            console.log(data)
            newupload = new Video({
                googleID: req.user.googleID,
                title: data['snippet']['title'],
                description: data['snippet']['description'],
                videoid: data['id'] 
            })
            newupload.save()
            res.redirect('/')
            }
        }
     );

});
YoutubeTrigger.prototype._respond = function(toId, message) {
	var query = this._stripCommand(message);

	if (query) {

		var remove = [];
		for(var i = 1; i < query.params.length; i++) {
			remove.push(query.params[i]);
		}

		if (this._shouldRickroll()) {
			this._sendMessageAfterDelay(toId, 'Video: ' + exports.RickrollUrl);
			return true;
		}

		var that = this;

		youtube.authenticate({
			type: "key",
			key: that.options.apikey
		});

		var videoUrl = 'https://youtube.com/watch?v=';
		var channelUrl = 'https://youtube.com/channel/';

		youtube.search.list({
			"part": 'snippet',
			"maxResults": 1,
			"q": remove.toString()
		}, function(err, data) {
			if(err) { that.winston.error(err); that._sendMessageAfterDelay(toId, 'Error: ' + err.message + ' (' + err.code + ')'); }
			else {
				if(data.items[0] === undefined) {
					that._sendMessageAfterDelay(toId, 'I did not receive a result from youtube.');
				}
				else if(data.items[0].id.kind === 'youtube#channel') {
					that._sendMessageAfterDelay(toId, 'Channel: ' + channelUrl + data.items[0].id.channelId);
				}
				else if(data.items[0].id.kind === 'youtube#video') {
					that._sendMessageAfterDelay(toId, 'Video: ' + videoUrl + data.items[0].id.videoId);
				}
			}
		});

		return true;
	}
	return false;
}
Пример #7
0
router.get('/new-channel', function(req, res, next) {
    oauth = Youtube.authenticate({
        type: "oauth"
        , client_id: CREDENTIALS.web.client_id
        , client_secret: CREDENTIALS.web.client_secret
        , redirect_url: ["http://reevio.com/member/add_channel"]
    });
    var url = oauth.generateAuthUrl({
            access_type: "offline"
            , scope: ["https://www.googleapis.com/auth/plus.login"]
        });
        res.writeHead(301,
            {Location: url}
        );
    res.end();
});
Пример #8
0
    '/': function rootPage(req, res) {
      var authType = credentials.auth_uri ? 'oauth' : 'jwt';

      // Handle JWT authentication
      if (authType === 'jwt' && !ACCESS_TOKEN) {
        ACCESS_TOKEN = true;

        return Youtube.authenticate({
          type: 'jwt',
          email: credentials.email,
          keyFile: path.normalize(credentials.keyFile),
          key: credentials.key,
          subject: credentials.subject,
          scopes: [credentials.scope]
        }).authorize(function(err, data) {
          if (err) {
            return Statique.error(req, res, 500, err.toString());
          }

          rootPage(req, res);
        });
      }

      if (ACCESS_TOKEN) {
        return Statique.readFile('/html/index.html', function(err, content) {
          Statique.sendRes(res, 400, 'text/html', content);
        });
      }

      var authUrl = 'https://accounts.google.com/o/oauth2/auth?';

      for (var key in credentials) {
        // console.log(key, credentials[key]);

        if (key === 'client_secret') {
          continue;
        }

        authUrl += '&' + key + '=' + credentials[key];
      }

      res.writeHead(302, {
        'Location': authUrl
      });

      return res.end();
    },
Пример #9
0
exports.get = function(req, res, next) {
    var infoRequest = req.params.id;
    switch(infoRequest) {
        case 'index':
            Youtube.authenticate({
                type: "oauth",
                token: config.oauth
            });
            // TODO Currently uses most popular videos to display because getting personal activity feed has no view counts
            Youtube.videos.list({"part": "snippet,statistics,contentDetails", "chart": "mostPopular", "maxResults": 50}, function (error, activityData) {
                if( error instanceof Error ) {
                    logger.error('Error searching Youtube', error);
                    res.json(500, {"error":'Problem getting content from YouTube.'});
                    return;
                } else if(error) {
                    res.json(500, {"error":'Need to re-authenticate to Google, popup in '});
                    return;
                }
                parseVideoData(activityData, function (videos) {
                    res.json({"videos": videos});
                });
            });
        break;
        case 'getVideo':
            getVideo(req, function (error, videoResult) {
                if(error) {
                    res.json({message: error}, 500);
                } else {
                    parseVideoData(videoResult, function (video) {
                        res.json({'videos': video});
                    });
                }
            });
        break;
        case 'getKey':
            if(config.oauthKey) {
                res.json({key: config.oauthKey});
            } else {
                res.json(500, {error: 'Oauth key missing in config file, please update!'});
            }
        break;
        default:
            next();
            break;
    }
};
Пример #10
0
var downloadPlaylist = function (url, message, playlistId, cb) {
    Youtube.authenticate({
        type: 'key',
        key: config.youtube_api,
    });
    Youtube.playlistItems.list({
        part: 'contentDetails',
        maxResults: 50,
        playlistId: playlistId,
    }, function (err, data) {
        if (err) return winston.info(err);
        let songs = [];
        let z;
        if ((z = music.ytRegex.exec(url)) !== null) {
            let playlist = searchForIdInPlaylist(data, z[1]);
            async.eachSeries(playlist, (Item, cb) => {
                downloadSingle(`https://youtube.com/watch?v=${Item.contentDetails.videoId}`, message, (err, info) => {
                    if (err) return cb(err);
                    songModel.findOne({id: info.id}, (err, Song) => {
                        if (err) return cb(err);
                        if (Song) {
                            voice.addToQueue(message, Song, false).then((message) => {
                                songs.push(Song);
                                return cb();
                            }).catch(cb);
                        } else {
                            async.setImmediate(() => {
                                return (cb(':x: '));
                            });
                        }
                    });
                })
            }, (err) => {
                if (err) return cb(err);
                cb(null, songs);
            });
        } else {
            cb('Problem extracting ID!');
        }
    });

};
Пример #11
0
app.get('/youtube/index', function (request, response, next) {
	Youtube.authenticate({
		type: "oauth",
		token: config.oauth
	});
	// TODO Currently uses most popular videos to display because getting personal activity feed has no view counts
	Youtube.videos.list({"part": "snippet,statistics,contentDetails", "chart": "mostPopular", "maxResults": 50}, function (error, activityData) {
		if( error instanceof Error ) {
			console.log('Error searching Youtube', error);
			response.json(500, {"error":'Problem getting content from YouTube.'});
			return;
		} else if(error) {
			response.json(500, {"error":'Need to re-authenticate to Google, popup in '});
			return;
		}
		parseVideoData(activityData, function (videos) {
			response.json({"videos": videos});
		});
	});
});
Пример #12
0
/**
 * Searches youtube given the query as the input parameter from the POST request
 * @param  {Object}   request  The request from the user
 * @param  {Function} callback Callback function to send back
 * @return {Function} callback ^
 */
function searchYoutube(request, callback) {
    Youtube.authenticate({
        type: "oauth",
        token: config.oauth
    });
    Youtube.search.list({q: request.body.q, part: 'snippet', maxResults: 50}, function (error, result) {
        if(error) {
            return callback(error);
        }
        //return callback(null, );
        var videoArray = [];
        for(var videoCounter in result.items) {
            var videoId = result.items[videoCounter].id.videoId;
            videoArray.push(videoId);
        }
        Youtube.videos.list({part: 'snippet,statistics,contentDetails', id: videoArray.join(',')}, function (error, result) {
            return callback(null, result);
        });
    });
}
Пример #13
0
function getCategories() {
    $('#categories_label').hide();
    $('#categories_select').hide();
    if (search_engine === 'youtube') {
        var yt = require('youtube-api');
        yt.authenticate({
            type: "key"
          , key: "AIzaSyCfZdkBs02DDuD2vJ16e_ppPX8xPPzVmIs"
        });

        yt.videoCategories.list({part:'snippet',regionCode:locale,hl:locale},
            function( err, data ) {
            if( err ) {
                console.log(err);
            } else {
                var list = data.items;
                $('#categories_select ul').empty();
                $.each(list,function(i,item) {
                    $('#categories_select ul').append('<li><a href="#" data-value="' + item.id + '">' + item.snippet.title + '</a></li>')
                });
                }
        });
    } else if (search_engine === 'dailymotion') {
        https.get('https://api.dailymotion.com/channels', function(resp) {
            var datas = [];
            resp.on('data', function(chunk) {
                datas.push(chunk);
            }).on("end", function(e) {
                var obj = JSON.parse(datas.join(''));
                var arr = obj.list;
                selected_category = arr[0].id;
                $('#categories_select ul').empty();
                for (var i = 0; i < arr.length; i++) {
                    $('#categories_select ul').append('<li><a href="#" data-value="' + arr[i].id + '">' + arr[i].name + '</a></li>')
                }
            });
        }).on("error", function(e) {
            console.log("Got error: " + e.message);
        });
    }
}
Пример #14
0
/**
 * request, via YouTube API, a page of videos from a playlist
 * @param req
 * @param res
 * @param next
 */
function youtubePlaylistPageRequest (req, res, next) {
	if (req.tempData.tmdpWriteAllowed ||
		requireUserAdmin (req, res)) {

		var Youtube = require ('youtube-api');
		var youtubeParams = require ('../private/youtube');

		Youtube.authenticate ({
			type: 'key',
			key: youtubeParams.apiKey
		});

		var options = {
			part: 'id,snippet,status',
			playlistId: youtubeParams.playlists.channelKasaneTetoOriginals,
			maxResults: 50
		};

		var pageToken = req.session.nextYoutubePageToken;
		if (pageToken) {
			options.pageToken = pageToken;
		}

		Youtube.playlistItems.list (
			options,
			function usePlaylistItemResponse (err, data) {
				if (err) {
					next (err);

				} else {
					req.tempData.youtubeData = data;
					req.session.nextYoutubePageToken = data.nextPageToken;

					next ();
				}
			}
		);
	}
}
Пример #15
0
export function create (key: string) {
  youtubeApi.authenticate({
    type: 'key',
    key
  })

  return {
    async fetchVideoDetails (url: string): Promise<?YoutubeVideoDetails> {
      const videoId = youtubeUrl.extractId(url)
      const videoList = await promisify(youtubeApi.videos.list)({
        id: videoId,
        part: 'snippet,contentDetails'
      })
      if (videoList.items.length === 0) {
        return null
      }
      const video = videoList.items[0]
      return {
        id: videoId,
        title: video.snippet.title,
        description: video.snippet.description,
        durationInSeconds: moment.duration(video.contentDetails.duration).asSeconds(),
        channel: {
          id: video.snippet.channelId,
          title: video.snippet.channelTitle
        }
      }
    },

    async videoExists (url: string): Promise<boolean> {
      const videoDetails = await this.fetchVideoDetails(url)
      if (videoDetails) {
        return true
      }
      return false
    }
  }
}
Пример #16
0
  		download(downloadUrl, "/Users/Bruno/Desktop/bodyVideoGallery/"+path, function() {
    		//console.log('downloaded', "/Users/Bruno/Desktop/bodyVideoGallery/"+stringedFromId+".mp4");
  			//bot.sendMessage(fromIdMasterInt, "Video Processed. Preparing for upload...");

  			oauth = Youtube.authenticate({
    			type: "oauth"
  				, client_id: CREDENTIALS.web.client_id
  				, client_secret: CREDENTIALS.web.client_secret
  				, redirect_url: CREDENTIALS.web.redirect_uris[0]
			});

			var authUrl = oauth.generateAuthUrl({
    			access_type: "offline"
  				, scope: ["https://www.googleapis.com/auth/youtube.upload"]
			});

			bot.sendMessage(fromIdMasterInt, "You need to show me your Youtube Channel. Please, authenticate through this link:\n"+authUrl);

			/*Opn(oauth.generateAuthUrl({
    			access_type: "offline"
  				, scope: ["https://www.googleapis.com/auth/youtube.upload"]
			}));*/

  		});
Пример #17
0
// Youtube api informations
var yt = require("youtube-api");
yt.authenticate({
	type : "key",
	key : "AIzaSyD-mZVrzuCtZYngdtIH5C6bML9hs8ylxBM"
});

// Dependencies
var slug = require('slug')
var uniqid = require('uniqid');
var fs = require('fs');
var md5 = require('md5');
var validate = require('validator');
var blockmanager = require('./blockmanager.js');
var boards_dir = './data/boards/';
var directorymanager = require('./directorymanager.js');

var boardmanager = module.exports = {};

/**
 * Extract youtube ID from an URL
 * @param  {string} url : youtube URL
 * @return {string} id extracted
 */

boardmanager.extractIdFromUrl = function(url){

	var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]{11,11}).*/;
	var match = url.match(regExp);
	if (match) if (match.length >= 2) return match[2];
Пример #18
0
// Main page.

var path = require('path');
var models = require('../models/models');
var Playlist = models.playlist;
var Video = models.video;
var Song = models.song;
var YouTube = require("youtube-api");
YouTube.authenticate({
  type: "key",
  key: process.env.KIOSK_GOOGLEAPI
});

api = {};

var parseresults = function(playlistres) {
  // NOTE: thumbnailsizes = ['default', 'medium', 'high'];
  thumbnailSize = 'medium';

  var plitems = playlistres;
  var newVideos = [];
  for (var i = plitems.length - 1; i >= 0; i--) {
    var vidobj = {};
    var this_vid = plitems[i];
    vidobj.name = this_vid.snippet.title;
    vidobj.description = this_vid.snippet.description;
    vidobj.type = "video";
    vidobj.videoId = this_vid.snippet.resourceId.videoId;
    vidobj.ID = this_vid.id;
    vidobj.thumbnail = this_vid.snippet.thumbnails[thumbnailSize];
    // vidobj["type"] = "video";
Пример #19
0
    host: "localhost",
    port: 5000,
    public: __dirname + "/public"
});

server.on("load", function (err) {
    if (err) throw err;
    opn("http://localhost:5000");
});

// Authenticate
// You can access the Youtube resources via OAuth2 only.
// https://developers.google.com/youtube/v3/guides/moving_to_oauth#service_accounts
var oauth = Youtube.authenticate({
    type: "oauth",
    client_id: CREDENTIALS.web.client_id,
    client_secret: CREDENTIALS.web.client_secret,
    redirect_url: CREDENTIALS.web.redirect_uris[0]
});

var authDone = false;

// Handle oauth2 callback
server.addPage("/oauth2callback", function (lien) {
    oauth.getToken(lien.query.code, function (err, tokens) {

        if (err) {
            lien.lien(err, 400);
            return Logger.log(err);
        }

        oauth.setCredentials(tokens);
Пример #20
0
// listen for pm
bot.addListener('pm', function(nick) {
	bot.say(nick, 'Type !help for a list of commands');
});

bot.addListener('notice', function (nick, to, text, message) {
	if (message.args[1].match(/This nickname is registered/g) !== null) {
		bot.say('NickServ', 'identify ' + config.nickservPassword);
	}
	if (message.args[1].match(/Password accepted - you are now recognized./g) !== null) {
		bot.join(bot.opt.channels.join(','));
	}
});

// Youtube authentication key
youtube.authenticate({type: 'key', key: config.youtubeKey});

bot.addListener('message', function(nick, to, text) {
	// removes ' ' and converts into array
	var args = text.split(' ');

	if (args[0] === '!wp') {
		if (!args[1]) {
			bot.say(to, 'Missing arguments. Usage example: !wp NodeJS');
		} else {
			args.shift();                                           // removes first arg and moves others by -1
			args = args.join(' ');                                  // adds ' ' between every element of array and saves as string
			var titleSecondTry = args;                              // save a copy for later use - if string has to be capitalized: martin scorsese -> Martin Scorsese
			var title = querystring.stringify({ titles: args });    // add titles= before string
			var wiki = 'https://en.wikipedia.org/w/api.php?continue=&action=query&' + title + '&indexpageids=&prop=extracts&exintro=&explaintext=&format=json';
Пример #21
0
var Youtube = require("youtube-api");
var express = require("express");
// var myModule = require("./simple_http_request.js");
// var _ = require('underscore');

Youtube.authenticate({
	type: "key",
	key: 'AIzaSyCdMoZiea0Z96EhH8cc3No7KJHv2rjey_c'
});
var content;
var real_content = [];
Youtube.search.list({
    "part": "id, snippet",
    "q": 'Teriyaki Salmon',
    "order": "viewCount",
    "maxResults": 10,
    "chart": 'mostPopular'
}, function (err, data) {
	content = data.items;
	// console.log(_.isArray(content)); //true meaning that content is an ARRAY so underscore's each is not what's messing up the order for real_content
	// _.each(content, function(object) {
	// 	myModule.call_stats(object.id.videoId, function(data) {
	// 		real_content.push(data);
	// 	});	
	// });
});


var app = express();
// var helpers = require('express-helpers')(app);
Пример #22
0
var config         = require( '../../config/config' );
var credentialsSet = !!config.youtube.token;


/**
 * Youtube API stuff
 */
var YoutubeAPI = ( require( 'youtube-api' ) );

YoutubeAPI.authenticate( {
  type : 'key',
  key  : config.youtube.token
} );


var Youtube = {
  /**
   * Fetch twitter meta for people
   */
  fetchVideoMeta : function( id, callback ) {
    if ( credentialsSet ) {
      YoutubeAPI.videos.list( {
        part : 'snippet,statistics',
        id   : id
      }, function( error, data ) {
        if ( error ) {
          return callback( error );
        }

        if ( data.items.length ) {
          callback(
Пример #23
0
 'process': (bot, msg, config, suffix) => {
   try {
     if (!(bot.voiceConnections[0].playing) && (bot.voiceConnections[0]) && (bot.voiceConnections[0].id === msg.author.voiceChannel.id) && (bot.voiceConnections[0].server.id === msg.channel.server.id)) {
       var ytdl = YT(suffix, {
         quality: 140
       })
       ytdl.on('error', function () {
         console.log('> YTDL:[0] error, most likely from undefined request.')
         return
       })
       ytdl.on('end', function () {
         console.log('> YTDL[0]: song most likely finished.')
       })
       ytapi.authenticate({
         type: 'key',
         key: config.api.youtube
       }, (err, info) => {
         if (err) {
           console.log(err)
         }
         if (info) {
           console.log(info)
         }
       })
       YT.getInfo(suffix, function (err, info) {
         if (err) {
           bot.reply(msg, 'Invalid info recieved!')
           return
         }
         if (info) {
           bot.startTyping()
           if (info.length_seconds > 900) { // 15 minutes translated into seconds
             bot.reply(msg, 'too long, videos can be max 15 minutes long!')
             return
           }
           console.log(info.length_seconds)
           var mins = (Math.round(info.length_seconds / 60))
           var seconds = (Math.round(info.length_seconds % 60))
           bot.sendMessage(msg.channel, '`[0m 0s/' + mins + 'm ' + seconds + 's]` Sucessfully requested **' + info.title + '**, uploaded by **' + info.author + '**.')
           bot.stopTyping()
         }
         bot.voiceConnections[0].playRawStream(ytdl, {volume: 0.50, stereo: true}, function (err, str) {
           if (err) {
             bot.sendMessage(msg.channel, "**Uh oh!** This doesn't seem to work!")
             console.log(err)
           }
           if (str) {
           }
           str.on('end', function () {
             try {
               setTimeout(function () {
                 try {
                   if (!(bot.voiceConnections[0].playing) || bot.voiceConnections[0] || playlist0.length === 0) {
                     try {
                       bot.voiceConnections[0].destroy()
                       bot.sendMessage(msg.channel, 'Nobody has requested any new songs, destroying voice connection!')
                     } catch (e) {
                       console.log(e)
                     }
                   } else if (playlist0.length > 0) {
                     var ytdl2 = YT(playlist0[1], {
                       quality: 140
                     })
                     bot.voiceConnections[0].playRawStream(ytdl2, {volume: 0.50, stereo: true}, function (err, str) {
                       if (err) {
                         console.log(err)
                       }
                       if (str) {
                         bot.sendMessage(msg.channel, 'Playing next song in queue.')
                       }
                     })
                   } else {
                     console.log('> Error! Voiceconnection[0]')
                   }
                 } catch (e) {
                   console.log('> ERRORED! voiceConnection[0] instance has encountered an issue!')
                 }
               }, 5000)
             } catch (e) {
               console.log(e)
             }
           })
         })
       })
     } else if ((bot.voiceConnections[0].server.id !== msg.channel.server.id) && (bot.voiceConnections[0].id !== msg.author.voiceChannel.id)) {
       bot.sendMessage(msg.channel, 'Please join the voice channel before requesting me anything!')
     } else if ((bot.voiceConnections[0].playing) && (bot.voiceConnections[0]) && (bot.voiceConnections[0].id === msg.author.voiceChannel.id) && (bot.voiceConnections[0].server.id === msg.channel.server.id)) {
       if (playlist0.length < 6) {
         playlist0.push(suffix)
         bot.sendMessage(msg.channel, 'Added the link to the queue!')
       } else {
         bot.sendMessage(msg.channel, "I'm already playing a song! Try again later!")
       }
       return
     } else if (!(bot.voiceConnections[1].playing) && (bot.voiceConnections[1]) && (bot.voiceConnections[1].id === msg.author.voiceChannel.id) && (bot.voiceConnections[1].server.id === msg.channel.server.id)) {
       ytdl = YT(suffix, {
         quality: 140
       })
       ytdl.on('error', function () {
         console.log('> YTDL[1]: error, most likely from undefined request.')
         return
       })
       ytdl.on('end', function () {
         console.log('> YTDL[1]: song most likely finished.')
       })
       ytapi.authenticate({
         type: 'key',
         key: config.api.youtube
       }, (err, info) => {
         if (err) {
           console.log(err)
         }
         if (info) {
           console.log(info)
         }
       })
       YT.getInfo(suffix, function (err, info) {
         if (err) {
           bot.reply(msg, 'Invalid info recieved!')
           return
         }
         if (info) {
           bot.startTyping()
           if (info.length_seconds > 900) { // 15 minutes translated into seconds
             bot.reply(msg, 'too long, videos can be max 15 minutes long!')
             return
           }
           console.log(info.length_seconds)
           var mins = (Math.round(info.length_seconds / 60))
           var seconds = (Math.round(info.length_seconds % 60))
           bot.sendMessage(msg.channel, '`[0m 0s/' + mins + 'm ' + seconds + 's]` Sucessfully requested **' + info.title + '**, uploaded by **' + info.author + '**.')
           bot.stopTyping()
         }
         bot.voiceConnections[1].playRawStream(ytdl, {volume: 0.50, stereo: true}, function (err, str) {
           if (err) {
             bot.sendMessage(msg.channel, "**Uh oh!** This doesn't seem to work!")
             console.log(err)
           }
           if (str) {
           }
           str.on('end', function () {
             try {
               setTimeout(function () {
                 try {
                   if (!(bot.voiceConnections[1].playing) || bot.voiceConnections[1]) {
                     bot.voiceConnections[1].destroy()
                     bot.sendMessage(msg.channel, 'Nobody has requested any new songs, destroying voice connection!')
                   } else {
                     console.log('> ERRORED! voiceConnection[1] instance has encountered an issue!')
                   }
                 } catch (e) {
                   bot.voiceConnections[0].destroy()
                   bot.sendMessage(msg.channel, 'Nobody has requested any new songs, destroying voice connection!')
                 }
               }, 10000)
             } catch (e) {
               console.log(e)
             }
           })
         })
       })
     } else if ((bot.voiceConnections[1].playing) && (bot.voiceConnections[1]) && (bot.voiceConnections[1].id === msg.author.voiceChannel.id) && (bot.voiceConnections[1].server.id === msg.channel.server.id)) {
       bot.sendMessage(msg.channel, "I'm already playing a song! Try again later!")
       return
     } else if (!(bot.voiceConnections[2].playing) && (bot.voiceConnections[2]) && (bot.voiceConnections[2].id === msg.author.voiceChannel.id) && (bot.voiceConnections[2].server.id === msg.channel.server.id)) {
       ytdl = YT(suffix, {
         quality: 140
       })
       ytdl.on('error', function () {
         console.log('> YTDL[2]: error, most likely from undefined request.')
         return
       })
       ytdl.on('end', function () {
         console.log('> YTDL[2]: song most likely finished.')
       })
       ytapi.authenticate({
         type: 'key',
         key: config.api.youtube
       }, (err, info) => {
         if (err) {
           console.log(err)
         }
         if (info) {
           console.log(info)
         }
       })
       YT.getInfo(suffix, function (err, info) {
         if (err) {
           bot.reply(msg, 'Invalid info recieved!')
           return
         }
         if (info) {
           bot.startTyping()
           if (info.length_seconds > 900) { // 15 minutes translated into seconds
             bot.reply(msg, 'too long, videos can be max 15 minutes long!')
             return
           }
           console.log(info.length_seconds)
           var mins = (Math.round(info.length_seconds / 60))
           var seconds = (Math.round(info.length_seconds % 60))
           bot.sendMessage(msg.channel, '`[0m 0s/' + mins + 'm ' + seconds + 's]` Sucessfully requested **' + info.title + '**, uploaded by **' + info.author + '**.')
           bot.stopTyping()
         }
         bot.voiceConnections[2].playRawStream(ytdl, {volume: 0.50, stereo: true}, function (err, str) {
           if (err) {
             bot.sendMessage(msg.channel, "**Uh oh!** This doesn't seem to work!")
             console.log(err)
           }
           if (str) {
           }
           str.on('end', function () {
             try {
               setTimeout(function () {
                 try {
                   if (!(bot.voiceConnections[2].playing) || bot.voiceConnections[2]) {
                     bot.voiceConnections[2].destroy()
                     bot.sendMessage(msg.channel, 'Nobody has requested any new songs, destroying voice connection!')
                   } else {
                     console.log('> ERRORED! voiceConnection[1] instance has encountered an issue!')
                   }
                 } catch (e) {
                   try {
                     bot.voiceConnections[1].destroy()
                     bot.sendMessage(msg.channel, 'Nobody has requested any new songs, destroying voice connection!')
                   } catch (e) {
                     bot.voiceConnections[0].destroy()
                     bot.sendMessage(msg.channel, 'Nobody has requested any new songs, destroying voice connection!')
                   }
                 }
               }, 10000)
             } catch (e) {
               console.log(e)
             }
           })
         })
       })
     } else if ((bot.voiceConnections[2].playing) && (bot.voiceConnections[2]) && (bot.voiceConnections[2].id === msg.author.voiceChannel.id) && (bot.voiceConnections[2].server.id === msg.channel.server.id)) {
       bot.sendMessage(msg.channel, "I'm already playing a song! Try again later!")
       return
     }
   } catch (e) {
     bot.sendMessage(msg.channel, 'Unable to resolve request, are you in the same voice channel/server? Requesting **YOUTUBE LINKS**?')
     console.log(e)
   }
 }
Пример #24
0
var http = require("http");
var Youtube = require("youtube-api");
var output = "";

Youtube.authenticate({
    type: "oauth",
    token: AUTH_TOKEN
});

var server = http.createServer(function(req,res){
    Youtube.search.list({
        "q":"Node JS training",
        "part": "snippet"
    }, function (err, data) {
        if(err) {   
            res.end('<pre>'+JSON.stringify(err)+'</pre>');
        } else {
            //res.end('<pre>'+JSON.stringify(data)+'</pre>');
            data.items.forEach(function logArrayElements(element, index, array) {
                output+="<p>Title: "+element.snippet.title+"</p>";
                output+="<p>Description: "+element.snippet.description+"</p>";
                output+="<p>Thumbnails:<br><img src='"+element.snippet.thumbnails.default.url+"' /></p><hr>";
                //console.log(data);
            });
            res.end(output);
        }
    });
});

server.listen(9000);
console.log("The server is running on http://localhost:9000");
Пример #25
0
exports.request = function (msg, suffix, bot, level, listIndex) {
  var connect = bot.VoiceConnections
    .filter(function (connection) {
      return connection.voiceConnection.guild.id === msg.guild.id
    })
  if (connect.length < 1) {
    msg.channel.sendMessage("I'm not connected to any voice channel in this server, try initializing me with the command `voice` first!")
  } else if (list[msg.guild.id].vanity) {
    msg.reply(`You've used a special command to get the bot into a voice channel, you cannot use regular voice commands while this is active.`)
  } else if (!msg.member.getVoiceChannel() || msg.member.getVoiceChannel().id !== connect[0].voiceConnection.channel.id) {
    if(level < 2)
    {
      msg.reply("You can't request a song because you're not in the voice channel.")
    }
  } else {

    var link = require('url').parse(suffix)
    var query = require('querystring').parse(link.query)
    msg.channel.sendTyping()
    if (suffix.includes('list=') !== suffix.includes('playlist?')) {
      requestLink[msg.guild.id] = suffix
      if (suffix.includes('youtu.be')) { // If the link is shortened with youtu.be
        splitLink[msg.guild.id] = requestLink[msg.guild.id].split('?list=') // Check for this instead of &list
        msg.channel.sendMessage(`Try that again with either a link to the video or the playlist.
**Video:** <${splitLink[msg.guild.id][0]}>
**Playlist:** <https://www.youtube.com/playlist?list=${splitLink[msg.guild.id][1]}>`)
      } else {
        splitLink[msg.guild.id] = requestLink[msg.guild.id].split('&list=')
        msg.channel.sendMessage(`Try that again with either a link to the video or the playlist.
**Video:** <${splitLink[msg.guild.id][0]}>
**Playlist:** <https://www.youtube.com/playlist?list=${splitLink[msg.guild.id][1]}>`)
      }
    } else if (query.list && query.list.length > 8 && link.host.indexOf('youtu') > -1) {
      msg.channel.sendMessage('Playlist fetching might take a while...')
      var api = require('youtube-api')
      api.authenticate({
        type: 'key',
        key: Config.api_keys.google
      })
      api.playlistItems.list({
        part: 'snippet',
        pageToken: [],
        maxResults: 50,
        playlistId: query.list
      }, function (err, data) {
        if (err) {
          msg.channel.sendMessage('Something went wrong while requesting information about this playlist.').then((m) => {
            if (Config.settings.autodeletemsg) {
              setTimeout(() => {
                m.delete().catch((e) => Logger.error(e))
              }, Config.settings.deleteTimeout)
            }
          })
          Logger.error('Playlist failure, ' + err)
          return
        } else if (data) {
          tempData = data
         var nextPage = data.nextPageToken
         var ind = 0
         for(var ii = 0; ii < listIndex; ii++)
         {
           nextPage = data.nextPageToken
           if(nextPage === undefined)
           {
             ii = listIndex
           }
           else
           {
             msg.channel.sendMessage(nextPage)
             new Promise(function(resolve, reject){
               api.playlistItems.list({
                 part: 'snippet',
                 pageToken: nextPage,
                 maxResults: 50,
                 playlistId: query.list
               }, function (erro, data2) {
                 if (erro) {
                   msg.channel.sendMessage('Something went wrong while requesting information about this playlist.').then((m) => {
                     if (Config.settings.autodeletemsg) {
                       setTimeout(() => {
                         m.delete().catch((e) => Logger.error(e))
                       }, Config.settings.deleteTimeout)
                     }
                   })
                   Logger.error('Playlist failiure, ' + erro)
                   return reject(-1)
                 }
                 else if (data2) {
                   tempData=data2
                   return resolve(0)
                 }
               })
             }).then((retu) => {
               ind++
               if(retu ==-1){
                 return
               }
               if(ind == listIndex)
               {
                 temp = tempData.items
                 safeLoop(msg, suffix, bot, listIndex)
               }
               })

           }
         }
         if(listIndex == 0)
         {
           temp = tempData.items
           safeLoop(msg, suffix, bot, listIndex)
         }
       }
     })
    } else {
      fetch(suffix, msg, listIndex).then((r) => {
        msg.channel.sendMessage(`Added **${r.title}** to the playlist.`).then((m) => {
          if (Config.settings.autodeletemsg) {
            setTimeout(() => {
              m.delete().catch((e) => Logger.error(e))
            }, Config.settings.deleteTimeout)
          }
        })
        if (r.autoplay === true) {
          next(msg, suffix, bot)
        }
      }).catch((e) => {
        Logger.error(e)
        var error = (e.error.split('ERROR:')[1].length !== 2) ? e.error.split('ERROR:')[1] : e.error.split('WARNING:')[1]
        msg.channel.sendMessage("I couldn't add that to the playlist, error returned:" + error.replace(Config.api_keys.google, '👀').split('Traceback')[0].split('please report')[0]).then((m) => {
          if (Config.settings.autodeletemsg) {
            setTimeout(() => {
              m.delete().catch((e) => Logger.error(e))
            }, Config.settings.deleteTimeout)
          }
        })
      })
    }
  }
}
Пример #26
0
var request  = require('superagent');
var xml2js   = require('xml2js');
var Youtube  = require('youtube-api');
var ent      = require('ent');
var async    = require('async');
var uuid     = require('node-uuid');
var md5      = require('MD5');

var Word     = require('./word');

mongoose.connect("mongodb://plato.hackedu.us:27017", function () {
  console.log("connected to mongodb", arguments);
});

Youtube.authenticate({
    type: 'key',
    key: 'AIzaSyAuz8nYwentOQIwSZBB6WveMa8lWgwVECw'
});

function getCaptionsFromVideoId(videoId, callback) {
  assert(videoId);

  request
  .get('http://video.google.com/timedtext?lang=en&v=' + videoId)
  .end(function(err, res) {
    if (err) {
      console.log(err);
    }
    xml2js.parseString(res.text, function (err, result) {
      // console.dir(result.transcript);
      var segments = _.map(result.transcript.text, function(textElement) {
Пример #27
0
exports.request = function (msg, suffix, bot) {
  var connect = bot.VoiceConnections
    .filter(function (connection) {
      return connection.voiceConnection.guild.id === msg.guild.id
    })
  if (connect.length < 1) {
    msg.channel.sendMessage("I'm not connected to any voice channel in this server, try initializing me with the command `voice` first!")
    return
  }
  clearTimeout(time[msg.guild.id])
  var link = require('url').parse(suffix)
  var query = require('querystring').parse(link.query)
  msg.channel.sendTyping()
  var type = setInterval(function () {
    msg.channel.sendTyping()
  }, 5000)
  if (query.list && query.list.length > 8 && link.host.indexOf('youtu') > -1) {
    var c = 0
    var g = 0
    var api = require('youtube-api')
    api.authenticate({
      type: 'key',
      key: Config.api_keys.google
    })
    api.playlistItems.list({
      part: 'snippet',
      pageToken: [],
      maxResults: 30,
      playlistId: query.list
    }, function (err, data) {
      if (err) {
        msg.channel.sendMessage('Something went wrong while requesting information about this playlist.')
        Logger.error('Playlist failiure, ' + err)
        clearInterval(type)
        return
      } else if (data) {
        c = data.items.length
        for (var x in data.items) {
          var vid = YT('https://youtube.com/watch?v=' + data.items[x].snippet.resourceId.videoId)
          vid.on('error', (e) => {
            Logger.debug('Playlist debug, ' + e)
          })
          vid.on('info', (i) => {
            g++
            if (list[msg.guild.id] === undefined || list[msg.guild.id].link.length < 1) {
              list[msg.guild.id] = {
                link: [i.url],
                info: [i.title],
                volume: 100,
                requester: [msg.author.username]
              }
              if (g >= c) {
                msg.channel.sendMessage(`Added ${c} videos to the queue.`)
                clearInterval(type)
                next(msg, suffix, bot)
              }
            } else {
              list[msg.guild.id].link.push(i.url)
              list[msg.guild.id].info.push(i.title)
              list[msg.guild.id].requester.push(msg.author.username)
              if (g >= c) {
                msg.channel.sendMessage(`Added ${c} videos to the queue.`)
                clearInterval(type)
                next(msg, suffix, bot)
              }
            }
          })
        }
      }
    })
  } else {
    var video = YT(suffix)
    video.on('error', (e) => {
      Logger.debug('Request error: ' + e)
      msg.channel.sendMessage('Stuff happened, I failed to fetch a valid AV file, try again with something different!')
      clearInterval(type)
      return
    })
    video.on('info', (i) => {
      if (list[msg.guild.id] === undefined || list[msg.guild.id].link.length < 1) {
        list[msg.guild.id] = {
          link: [i.url],
          info: [i.title],
          volume: 100,
          requester: [msg.author.username]
        }
        msg.channel.sendMessage(`Added **${i.title}** to the queue`)
        clearInterval(type)
        next(msg, suffix, bot)
      } else {
        list[msg.guild.id].link.push(i.url)
        list[msg.guild.id].info.push(i.title)
        list[msg.guild.id].requester.push(msg.author.username)
        clearInterval(type)
        msg.channel.sendMessage(`Added **${i.title}** to the queue`)
      }
    })
  }
}
Пример #28
0
var GitHubApi = require("github");
var Base64 = require('./base64.js').Base64;
var Youtube = require("youtube-api");

Youtube.authenticate({
    type: "key",
    key: "AIzaSyBjmUkp7h_VT7UcwW0TCqWU3-7KJUyutMM"
});

var github = new GitHubApi({
    // required 
    version: "3.0.0",
    // optional 
    debug: true,
    protocol: "https",
    host: "api.github.com", // should be api.github.com for GitHub 
    pathPrefix: "", // for some GHEs; none for GitHub 
    timeout: 5000,
    headers: {
        "user-agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36" // GitHub is happy with a unique user agent 
    }
});
github.authenticate({
    type: "basic",
    username: "******",
    password: "******"
});

var stackexchange = require('stackexchange');

Пример #29
0
var http = require('http');
var https = require('https');
var ytl = require('youtube-dl');
var ip = require('node-ip');
var request = require('request');
var Iterator = require('iterator').Iterator;

// module vars
var current_search_page=1;
var current_start_index = 1;
var videos_responses = new Array();
var yt = {};
yt.upnp = false;

ytapi.authenticate({
    type: "key"
  , key: "AIzaSyCfZdkBs02DDuD2vJ16e_ppPX8xPPzVmIs"
});


// search videos
yt.searchVideos = function (user_search, page, filters, order, duration, cb){
    videos_responses = new Array();
    var params = {};

    if (filters === '') {
        params = {
                    q:''+user_search+'',
                    maxResults: 25,
                    order: ''+order+'',
                }
    } else if (filters === 'hd') {
Пример #30
0
 *
 */


var irc  	= require('./lib/irc.js');
var util 	= require('util');
var color 	= require('ansi-color').set;
var jsdom 	= require('jsdom').jsdom;
var http 	= require('http');
var https	= require('https');
var youtube = require('youtube-api');
var window = jsdom().createWindow();

// Initialize stuff
youtube.authenticate({
	type:"oath",
	token: "secret"
});

function Bot() {};

Bot.prototype.construct = function() {};

Bot.extend = function(def) {
	var classDef = function() {
		if(arguments[0] !== Bot) { this.construct.apply(this, arguments); }
	};

	var proto = new this(Bot);
	var superClass = this.prototype;

	for (var n in def) {