Example #1
0
function add_to_queue(strID, message, err) {
    if (isYoutube(strID)) {
        guilds[message.guild.id].queue.push(getYouTubeID(strID));
    } else {
        guilds[message.guild.id].queue.push(strID);
    }
}
Example #2
0
function getID(str, cb) {
    try {
        if (isYoutube(str)) {
            cb(getYouTubeID(str));
        } else {
            search_video(str, function (id) {
                cb(id);
            });
        }
    } catch (err) {
       message.channel.send(":sos: URL cant be used, Try using the share URL instead of the browser URL")
        return;
    }
}
Example #3
0
 render() {
   if (!this.props.url)
     return (<div/>);
   const id = getYouTubeID(this.props.url);
   return (
     <div className="youtube-aligner">
       <iframe
         allowFullScreen
         className="youtube"
         frameBorder="0"
         src={`https://www.youtube.com/embed/${id}?autoplay=1`}
       />
     </div>
   );
 }
Example #4
0
exports.add = function(req, res){
	if(req.body.url===undefined){
		//todo Validate req.body.url as a URL
		res.send("No URL received.");
	}
  var videoid = ytid(req.body.url);
	youtube.video(videoid, function (err,data) {
		var song = new Song({
			playlist: req.params.playlist,
			url: videoid,
			title: data.title
		});
		song.save();
		res.send(song.toJSON());
	});
};
Example #5
0
const createPlayer = (props, cb) => {
  const sdk = loadApi();

  const params = assign({}, props.opts, {
    videoId: getYouTubeId(props.url)
  });


  return sdk((err) => {
    // need to handle err better.
    if (err) {
      console.error(err);
    }

    return cb(new window.YT.Player(props.id, params));
  });
};
Example #6
0
  function route( req, res ) {
    global.navigator = { userAgent: req.headers[ 'user-agent' ] };

    var selected = req.params.pattern;

    res.locals.json = dataJSon;
    res.locals.about = about;
    res.locals.videoId = getYouTubeID( data[ selected ] && data[ selected ].url );
    res.locals.domain = req.protocol + '://' + req.get( 'host' );
    res.locals.url = redirect + (( selected ) ? '/' + selected : '' );
    res.locals.dev = ( settings.env === 'dev' );
    res.locals.DOM = ReactDOMServer.renderToString( App( {
      data: data,
      about: about,
      onCopyReady: function() {},
      selected: selected,
      format: req.params.format
    } ));

    res.render( 'index' );
  }
Example #7
0
            process: function(blk) {
                var videoId = getYouTubeID(blk.body) || blk.body;
                var url = "http://youtube.com/watch?v="+videoId;
                var videoThumb = 'http://img.youtube.com/vi/'+videoId+'/0.jpg' /* 0.jpg is default full resolution image. 1–3.jpg is thumbnails */
                var caption = blk.kwargs['caption'];

                var html;
                if (this.generator == "website") {
                    html = '<div style="position: relative;padding-bottom: 56.25%;padding-top: 25px;height: 0;">'
                      +'<iframe frameborder="0" allowfullscreen style="border: none;position: absolute;top: 0;left: 0;width: 100%;height: 100%;" src="//www.youtube.com/embed/'+videoId+'?rel=0&amp;showinfo=0"></iframe>'
                      +'</div>';
                } else {
                    html = '<img src="'+videoThumb+'" alt="YouTube video thumbnail" /><p><a href="'+url+'">Video link</p></a>';
                }

                if (caption) {
                  html = '<figure>'+html+'<figcaption>'+caption+'</figcaption></figure>';
                }

                return html;
            }
Example #8
0
  bot.addListener("message", function(from, to, text, message) {
    try {
    text = text.trim();
    var arr = text.split(" ", 2);
    var command = arr[0].toLowerCase();
    var rest = text.substr(text.indexOf(' ') + 1);

    if (tsundere_list[to] == true) {
      tsundere = true;
    } else {
      tsundere = false;
    }

    // Regex for detecting certain text patterns
    var thanksRegex = /thanks\W(\w*)$/i;
    var blessyouRegex = /bless you\W(\w*)$/i;
    var twitterurl = /\b(https|http):\/\/(www.)?twitter.com\/[\w]+\/status\/[0-9]+\b/;
    var vndburl = /\b(http|https):\/\/(www.)?vndb.org\/v[0-9]+\b/;
    var youtubeurl = /\b(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)(\w*)(&(amp;)?[\w\?=]*)?\-?\w*\b/;
    var lewd = /\b(one|1) sec\b/i;
    var inuit = /\binuit\b/i;
    var chan = /\b[\w]+\b/i;
    var pls = /\b(ddb|dumbdumbbot) pls\b/i;

    var nohash = chan.exec(to);
    var chanName = nohash[0];

    var dolphy = (from == "Dolphy" || from == "NotDolphy");

    // Use the person's ID and the date to calculate a value
    var len = from.length;
    var first = from.charCodeAt(0);
    var last = from.charCodeAt(len-1);
    var d = new Date();
    var date = d.getDate();
    var day = d.getDay();
    var year = d.getFullYear();
    var month = d.getMonth();
    var val = (len + first + last) * (date + first + year) * (day + last + month) * (month + date);

    if (command == "!hi" || command == "!sup") {
      if (from == "DDK") {
        bot.say(to, colorize("H-Hi " + from));
      } else {
        if (tsundere) {
          bot.say(to, colorize("I-It's not like I wanted to see you or anything "
          + from));
        } else {
          bot.say(to, colorize("HI " + from.toUpperCase()));
        }
      }
    }
    if (command == "!addfeed" && (dolphy || from == "Kasuteru" || from == "fuyutsukikaru")) {
      var feedRef = firebaseRef.child("feeds/" + chanName);
      var urlstring = rest.replace(/\./ig, ',');
      var urlstring2 = urlstring.replace(/\//ig, '__');
      console.log(urlstring2);
      feedRef.child(urlstring2).set({
        url: rest,
      }, function(error) {
        if (error) {
          bot.say(to, colorize("Could not add feed."));
          console.log(error);
        } else {
          bot.say(to, colorize("Feed added!"));
          feeds.repeat(bot, rest, chanName);
        }
      });
    }
    if (command == "!removefeed" && (dolphy || from == "Kasuteru" || from == "fuyutsukikaru")) {
      var feedRef = firebaseRef.child("feeds/" + chanName);
      var urlstring = rest.replace(/\./ig, ',');
      var urlstring2 = urlstring.replace(/\//ig, '__');
      feedRef.child(urlstring2).remove(function(error) {
        if (error) {
          bot.say(to, colorize("Could not remove feed."));
          console.log(error);
        } else {
          bot.say(to, colorize("Feed removed"));
        }
      });
    }
    if (command == "!listfeed") {
      var feedRef = firebaseRef.child("feeds/" + chanName);
      feedRef.once('value', function(dataSnapshot) {
        dataSnapshot.forEach(function(urlSnapshot) {
          bot.say(to, colorize(urlSnapshot.child("url").val()));
        });
      });
    }
    // Commands for detecting urls
    if (command != "!hide" && twitterurl.test(text)) {
      // Matches a Twitter url with a tweet
      var twitterid = /status\/[0-9]+\b/;
      var statusid = twitterid.exec(text);
      var id = /[0-9]+\b/.exec(statusid[0]);
      twitter.search(id[0], bot, to);
    }
    if (youtubeurl.test(text) && command != "!hide") {
      // Matches a YouTube url
      var urls = youtubeurl.exec(text);
      var youtube = new YouTube();
      youtube.setKey('AIzaSyB3zgUs5u4hXdf6UgUZRalu70WdwaSWgJ4');
      var id = youtubeid(urls[0]);
      youtube.getById(id, function(error, result) {
        if (!error) {
          bot.say(to, colorize(result.items[0].snippet.title));
        } else {
          bot.say(to, colorize("Could not get title."));
        }
      });
    }
    if (command != "!hide" && vndburl.test(text)) {
      // Detects a vndb url
      var urls = vndburl.exec(text);
      scrape.scraper(urls[0], bot, to);
    }
    // Features requested by dolphy
    if (lewd.test(text) && to != "#chromatiqa") {
      bot.say(to, colorize("one sex*"));
    }
    if (inuit.test(text)) {
      bot.say(to, colorize("INUIT TOO"));
    }
    if (pls.test(text)) {
      bot.say(to, colorize("申し訳ありません" + from + "さま"));
      bot.action(to, "feels hella bad.");
    }
    // Thanks and Bless You detected with regex
    if (thanksRegex.exec(text)) {
      matchWord = thanksRegex.exec(text)[1].toLowerCase();
      truncatedRegex = /[aeiou].*/;
      truncatedMatch = truncatedRegex.exec(matchWord);
      if (truncatedMatch !== null) {
        thanked = "Th" + truncatedMatch
        bot.say(to, colorize(thanked));
      } else {
        bot.say(to, colorize("Pshuu"));
      }
    }
    if (blessyouRegex.exec(text)) {
      matchWord = blessyouRegex.exec(text)[1].toLowerCase();
      truncatedRegex = /[aeiou].*/;
      truncatedMatch = truncatedRegex.exec(matchWord);
      if (truncatedMatch !== null) {
        thanked = "Bl" + truncatedMatch
        bot.say(to, colorize(thanked));
      } else {
        bot.say(to, colorize("Pshuu"));
      }
    }
    // Looks of approval and disapproval
    if (command == "!loa") {
      if(text.indexOf(' ') > 0) {
        bot.say(to, colorize(rest + ": ʘ‿ʘ"));
      }
      else {
        bot.say(to, colorize("ʘ‿ʘ"));
      }
    }
    if (command == "!lod") {
      if(text.indexOf(' ') > 0) {
        bot.say(to, colorize(rest + ": ಠ_ಠ"));
      }
      else {
        bot.say(to, colorize("ಠ_ಠ"));
      }
    }
    if (command == "!rawr") {
      if (tsundere) {
        bot.say(to, colorize("Haaaaa? Are you stupid or something?"));
      } else {
        bot.say(to, colorize("Gao gao! I'm verrrryyyy scary. Fear me! Gao!"));
      }
    }
    // Enables or disables the tsundere mode
    if (command == "!tsundere") {
      if (rest == "on") {
        tsundere_list[to] = true;
        bot.say(to, colorize("DumbDumbBot is now a tsundere!"));
      }
      else if (rest == "off") {
        tsundere_list[to] = false;
        bot.say(to, colorize("DumbDumbBot got over its tsundere phase."));
      }
    }
    if (command == "!goaway") {
      if (tsundere) {
        bot.say(to, colorize("I-It's not like I want you to go or anything " + rest));
      } else {
        bot.say(to, colorize("Rawr, go away " + rest + ", I hate you!!!"));
      }
    }
    if (command == "!bye") {
      if (!tsundere) {
        bot.say(to, colorize("BYE " + from.toUpperCase()));
      } else {
        bot.say(to, colorize("G-Goodbye...baka."));
      }
    }
    // A countdown timer that goes up to 15 seconds
    if (command == "!countdown") {
      var number = rest;
      if (typeof number === 'undefined' || (isNaN(number) && number != "next tourney")) {
        bot.say(to, colorize("You need to enter a number, baka!"));
      } else if (number <= 15) {
        if (tsundere) {
          bot.say(to, colorize("W-Why do I have to do that for you? F-Fine, starting!"));
        } else {
          bot.say(to, colorize("Starting!"));
        }
        (function counter() {
          if (number > 0) {
            bot.say(to, colorize(number));
            number--;
            setTimeout(counter, 1000);
          }
          else {
            bot.say(to, colorize("GO!"));
          }
        })();
      } else if (rest == "next tourney") {
        bot.say(to, colorize("Never."));
      } else {
        bot.say(to, colorize("I'm too dumb to count from that high."));
      }
    }
    // Yakuman of the day Shindan
    if (command == "!yakuman") {
      var hash = val % 13;
      var yakuman = [
        "Kokushi Musou",
        "Daisangen",
        "Shousuushii",
        "Daisuushi",
        "Chuurenpoutou",
        "Suu Ankou",
        "Ryuuiisou",
        "Suu Kantsu",
        "Tsuuiisou",
        "Chinroutou",
        "Tenhou",
        "Chiihou",
        "Renhou"
      ];
      if (from == "Restinya" || from == "LoliSenpai") {
        bot.say(to, colorize("Today you should try going for pinfu so you can finally learn what it is."));
      } else
        bot.say(to, colorize("Today you should try going for " + yakuman[hash]));
    }
    // Tweet to the appropriate account
    if (command == "!tweet") {
      twitter.tweet(rest, bot, to);
    }
    if (command == "!petite") {
      if (from == "DDK") {
        bot.say(to, colorize("I'm  DEFINITELY not a lolicon, I just like petite girls! *wink wink*"));
      }
      else if (from == "Piroko" || from == "kafushino") {
        bot.say(to, colorize("This is the FBI. Please take a seat."));
      }
      else if (from == "LoliSenpai" || from == "Restinya") {
        bot.say(to, colorize("I'm a lolicon! XD"));
      } else {
        if (tsundere)
          bot.say(to, colorize("I-It's not like I like lolis or anything, stupid, I just like them petite!"));
        else
          bot.say(to, colorize("I'm not a lolicon, I just like petite girls!"));
      }
    }
    if (command == "!lolicon") {
      bot.say(to, colorize("No just lol-"));
    }
    // A reminder function taht reminds you after a certain number of minutes
    if (command == "!remind") {
      var time = arr[1];
      var len = time.length;
      if (time == parseInt(time)) {
        var reminder = text.substr(text.indexOf(' ') + len + 2);
        bot.say(to, colorize("Reminder set for " + from));
        setTimeout(function() { bot.say(to, colorize(from + ": " + reminder)); }, 60000 * time);
      } else {
        bot.say(to, colorize("Need to set a valid number of minutes!"));
      }
    }
    // Saki shindan
    if (command == "!saki") {
      var characters = sakis.characters;
      var hash = val % characters.length;
      var saki = characters[hash];
      if (from == "Dolphy" || from == "CureRMN" || from == "NotDolphy") {
        hash = val % 2;
        if (hash == 0)
          saki = characters[2];
        else if (hash == 1)
          saki = characters[105];
      }
      else if (from == "fuyutsukikaru") {
        hash = val % 2;
        if (hash == 0)
          saki = characters[96];
        else if (hash == 1)
          saki = characters[3];
      }
      if (saki == "Maho Yumeno" || saki == "Kaori Senoo") {
        bot.say(to, colorize("Your spirit Saki today is the worst Saki, " + saki));
      } else {
        bot.say(to, colorize("Your spirit Saki today is " + saki));
      }
      var chars = saki.split(" ", 2);
      if (!chars[1]) {
        bot.say(to, colorize("http://saki.wikia.com/wiki/" + chars[0]));
      } else {
        bot.say(to, colorize("http://saki.wikia.com/wiki/" + chars[0] + "_" + chars[1]));
      }
    }
    // Aikatsu shindan
    if (command == "!aikatsu") {
      var fashion = aikatsu.fashion;
      //var fashion = pripara.pripara;
      var hash = val % fashion.length;
      var brand = fashion[hash];
      bot.say(to, colorize("Today your Aikatsu brand is " + brand));
      var words = brand.split(" ", 2);
      bot.say(to, colorize("http://aikatsu.wikia.com/wiki/" + words[0] + "_" + words[1]));
    }
    // A roulette that chooses between different input options
    if (command == "!roulette") {
      var choices = rest.split(/[ ]+/);
      var options = choices.length;
      var random = Math.floor((Math.random() * options));
      if (tsundere) {
        bot.say(to, colorize("Something like " + choices[random] + " is good enough for trash like you."));
      } else {
        bot.say(to, colorize("I choose " + choices[random]));
      }
    }
    if (command == "!senpai") {
      var random = Math.floor((Math.random() * 10));
      if (random == 0) {
        if (tsundere)
          bot.say(to, colorize("B-Baka! S-Senpai noticed you..."));
        else
          bot.say(to, colorize("Senpai noticed you!"));
      }
      else {
        if (tsundere)
          bot.say(to, colorize("H-Hmph! S-So what if senpai didn't notice you?"));
        else
          bot.say(to, colorize("Senpai will never notice you..."));
      }
    }
    // A variety of reaction faces
    if (command == "!:O") {
      var surprise = faces.surprise;
      var rows = surprise.length;
      var n;
      for (n = 0; n < rows; n++) {
        bot.say(to, colorize(surprise[n]));
      }
    }
    if (command == "!:(") {
      var sad = faces.sad;
      var rows = sad.length;
      var n;
      for (n = 0; n < rows; n++) {
        bot.say(to, colorize(sad[n]));
      }
    }
    if (command == "!XD") {
      var XD = faces.XD;
      var rows = XD.length;
      var n;
      for (n = 0; n < rows; n++) {
        bot.say(to, colorize(XD[n]));
      }
    }
    if (command == "!>_<") {
      var cutie = faces.cutie;
      var rows = cutie.length;
      var n;
      for (n = 0; n < rows; n++) {
        bot.say(to, colorize(cutie[n]));
      }
    }
    if (command == "!:)") {
      if (from == "DDK")
        bot.say(to, colorize(";)"));
      else {
        if (tsundere) {
          bot.say(to, colorize("I-It's not like I'm saving that smile for somebody or anything!!!"));
        } else {
          bot.say(to, colorize("I want to protect that smile for the one I truly love."));
        }
      }
    }
    if (command == "!:9") {
      var nine = faces.nine;
      var rows = nine.length;
      var n;
      for (n = 0; n < rows; n++) {
        bot.say(to, colorize(nine[n]));
      }
    }
    if (command == "!mibucchi" | command == "!meball") {
      var mibucchi = faces.mibucchi;
      var rows = mibucchi.length;
      var n;
      for (n = 0; n < rows; n++) {
        bot.say(to, colorize(mibucchi[n]));
      }
    }
    if (command == "!opn") {
      bot.say(to, colorize("Opn, you're a three year old, stop trying to act like a grown-up you big babby."));
    }
    if (command == "!help") {
      bot.say(to, colorize("Enter !hi or !sup to have DumbDumbBot greet you!"));
      bot.say(to, colorize("Enter !bye to have DumbDumbBot see you off!"));
      bot.say(to, colorize("Enter !goaway <name of person> to have DumbDumbBot be rude to a person."));
      bot.say(to, colorize("Enter !countdown <number> to have DumbDumbBot start a countdown! Limited to numbers under 15."));
      bot.say(to, colorize("Enter !remind <minutes> <message> to have DumbDumbBot remind you of things."));
      bot.say(to, colorize("Enter !tweet <message to send> to post a tweet."));
      bot.say(to, colorize("Use the !hide command to prevent DumbDumbBot from posting the titles of YouTube videos and VNs."));
      bot.say(to, colorize("Enter !yakuman to have DumbDumbBot tell you what yakuman you should go for today."));
      bot.say(to, colorize("Enter !saki to get your spiritual Saki of the day."));
      bot.say(to, colorize("Enter !roulette <choices separated by spaces> to have DumbDumbBot randomly pick something for you."));
      bot.say(to, colorize("Enter !senpai to ask DumbDumbBot if senpai has noticed you."));
      bot.say(to, colorize("Enter !:O, !:(, !XD, !>_< to have DumbDumbBot express its emotions."));
    }
  } catch(e) {
    console.log(e);
  }
  });
var fs = require('fs');
var youtubedl = require('youtube-dl');
var shelljs = require('shelljs');
var getYoutubeId = require('get-youtube-id');

var videoURL = process.argv.slice(2)[0];
var videoID = videoURL.length == 11 ? videoURL : getYoutubeId(videoURL);
var output = './files/'+ videoID +'.mp4';
var audio = output.replace('.mp4', '.mp3');
var url = 'https://www.youtube.com/watch?v=' + videoID;

if(!videoID){
  console.log('videoID cannot be extracted');
  console.log('videoID: ', videoID);
  console.log('videoURL: ', videoURL);
  process.exit(0);
}

var downloaded = 0;
if (fs.existsSync(output)) {
  downloaded = fs.statSync(output).size;
}

var video = youtubedl(url,

  // Optional arguments passed to youtube-dl.
  // it seems that arguments are not passed...
  ['-v', '--prefer-ffmpeg', '--ffmpeg-location', '/usr/bin/ffmpeg', '--extract-audio', '--audio-format', 'mp3'],

  // start will be sent as a range header
  { start: downloaded, cwd: __dirname });
Example #10
0
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';

			request(wiki, function (error, response, body) {
				if (!error && response.statusCode === 200) {
					var wikiSummary = JSON.parse(body);
					var pageId = wikiSummary.query.pageids[0];      // get pageID

					// if pageId is -1 then the article does not exist
					if (pageId === '-1') {

						// Try again with changing first letter of every word to upper case
						titleSecondTry = titleSecondTry.replace(/[^\s]+/g, function (word) {
							return word.replace(/^./, function (first) {
								return first.toUpperCase();
							});
						});

						titleSecondTry = querystring.stringify({ titles: titleSecondTry });

						wiki = 'https://en.wikipedia.org/w/api.php?continue=&action=query&' + titleSecondTry + '&indexpageids=&prop=extracts&exintro=&explaintext=&format=json';
						request(wiki, function (err, res, bod) {
							if (!err && res.statusCode === 200) {
								wikiSummary = JSON.parse(bod);
								pageId = wikiSummary.query.pageids[0];
								if (pageId === '-1') {
									bot.say(to, 'Article does not exist or could not be found. Sorry :C');
								} else {
									wikiSummary = wikiSummary.query.pages[pageId].extract;
									wikiSummary = wikiSummary.slice(0, 280);
									var checkRedirect = wikiSummary.slice(0, 70);
									if (checkRedirect === 'This is a redirect from a title with another method of capitalisation.') {
										bot.say(to, 'Article is redirecting, please use the following link: https://en.wikipedia.org/wiki/' + titleSecondTry.slice(7));
									} else {
										wikiSummary = wikiSummary.concat('... Read more: ' + 'https://en.wikipedia.org/wiki/' + titleSecondTry.slice(7));
										bot.say(to, wikiSummary);
									}
								}
							}
						});
					} else {
						wikiSummary = wikiSummary.query.pages[pageId].extract;
						wikiSummary = wikiSummary.slice(0, 280);
						var checkRedirect = wikiSummary.slice(0, 70);
						if (checkRedirect === 'This is a redirect from a title with another method of capitalisation.') {
							bot.say(to, 'Article is redirecting, please use the following link: https://en.wikipedia.org/wiki/' + title.slice(7));
						} else {
							wikiSummary = wikiSummary.concat('... Read more: ' + 'https://en.wikipedia.org/wiki/' + title.slice(7));
							bot.say(to, wikiSummary);
						}
					}
				}
			});
		}
	} else if (args[0] === '!google' || args[0] === '!g') {
		if (!args[1]) {
			bot.say(to, 'Missing arguments. Usage example: !g Terry Pratchett');
		} else {
			args.shift();
			args = args.join(' ');
			google(args, function (err, res) {
				if (err) {
					console.error(err);
				}
				bot.say(to, res.links[0].title + ' | ' + res.links[0].description + ' | ' + res.links[0].href);
			});
		}
	} else if (args[0] === '!weather' || args[0] === '!w') {
		if (!args[1]) {
			bot.say(to, 'Missing arguments. Usage example: !weather Moscow; !weather zip 10000,hr');
		} else {
			var currentWeather = 'http://api.openweathermap.org/data/2.5/weather?';
			var metric = '&units=metric';
			var apiKey = '&APPID=' + config.OWapiKey;
			var userInput;
			args.shift();

			// check if user wants to search by ZIP code or by city name
			if (args[0] === 'zip') {
				userInput = 'zip=' + args[1];
			} else {
				args = args.join('');
				userInput = 'q=' + args;
			}
			userInput += metric + apiKey;
			var openweatherLink = currentWeather + userInput;

			request(openweatherLink, function (error, response, body) {
				if (!error && response.statusCode === 200) {
					var openweatherJson = JSON.parse(body);
					if (openweatherJson.cod === '404') {
						console.error('error while trying to get weather, "cod" code: ', openweatherJson.cod);
						bot.say(to, 'Sorry, no weather info for that one.');
					} else if (openweatherJson.cod === 200) {
						// sunrise & sunset are currently not in use, uncomment if you want to use:
						// var sunrise = new Date(openweatherJson.sys.sunrise * 1000);
						// var sunset = new Date(openweatherJson.sys.sunset * 1000);

						var openweatherSummary = 'The current temperature in ' + openweatherJson.name +
												', ' + openweatherJson.sys.country + ' is: ' + openweatherJson.main.temp.toFixed(1) +
												' C, ' + openweatherJson.weather[0].description + '. Pressure: ' + openweatherJson.main.pressure +
												' hpa. Wind speed: ' + openweatherJson.wind.speed + ' m/s (' + (openweatherJson.wind.speed * 3.6).toFixed(2) + ' km/h).';

						bot.say(to, openweatherSummary);
					} else {
						console.error('error while trying to get weather for: ', openweatherLink);
						bot.say(to, 'Sorry, no weather info for that one.');
					}
				}
			});
		}
	} else if (args[0] === '!tv' || args[0] === '!next' || args[0] === '!last') {
		if (!args[1]) {
			bot.say(to, 'Missing arguments. Usage example: !tv Suits; !next Top Gear; !last The Simpsons');
		} else {
			var argInput = args[0];
			args.shift();
			args = args.join(' ');
			var TVMazeAPI = 'http://api.tvmaze.com/singlesearch/shows?q=' + args + '&embed[]=previousepisode&embed[]=nextepisode';

			request(TVMazeAPI, function(error, response, body) {
				var showSummary;
				if (!error && response.statusCode === 200) {
					body = JSON.parse(body);
					var showName = body.name,
						showUrl = body.url,
						showGenre = 'Genre: ' + body.genres.join(', '),
						showStatus = 'Status: ' + body.status,
						showStartDate = 'Premiered: ' + body.premiered,
						showLastEpInfo,
						showNextEpInfo,
						showLastEpAired, showLastEpAgo, showLastSeasonNum, showLastEpNum, showLastEp, showLastEpName,
						showNextEp, showNextEpName, showNextEpAir;

					if (body._embedded.previousepisode) {
						showLastEpAired = body._embedded.previousepisode.airstamp;
						showLastEpAgo = 'Last episode aired: ' + moment(showLastEpAired).countdown().toString() + ' ago';
						showLastSeasonNum = body._embedded.previousepisode.season;
						showLastEpNum = body._embedded.previousepisode.number;
						showLastEp = 'Number: S' + zeroPad(showLastSeasonNum) + 'E' + zeroPad(showLastEpNum);
						showLastEpName = 'Title: ' + body._embedded.previousepisode.name;
						showLastEpInfo = showLastEpAgo + ' | ' + showLastEp + ' | ' + showLastEpName;
					} else {
						showLastEpInfo = 'No info about last episode';
					}

					if (body._embedded.nextepisode) {
						showNextEp = 'Number: S' + zeroPad(body._embedded.nextepisode.season) + 'E' + zeroPad(body._embedded.nextepisode.number);
						showNextEpName = 'Title: ' + body._embedded.nextepisode.name;
						showNextEpAir = body._embedded.nextepisode.airstamp;
						showNextEpInfo = 'Next episode is in ' + moment(showNextEpAir).countdown().toString() + ' | ' + showNextEp + ' | ' + showNextEpName;
					} else {
						if (body.status === 'Ended') {
							showNextEpInfo = 'Show has ended';
						} else {
							showNextEpInfo = 'No info about next episode';
						}
					}

					if (argInput === '!tv') {
						showSummary = 'TVMaze info: ' + showName + ' | ' + showGenre + ' | ' + showStatus +
									' | ' + showStartDate + ' | ' + showLastEpInfo + ' | ' + showUrl;
					} else if (argInput === '!next') {
						showSummary = 'TVMaze info: ' + showName + ' | ' + showNextEpInfo + ' | ' + showUrl;
					} else if (argInput === '!last') {
						showSummary = 'TVMaze info: ' + showName + ' | ' + showLastEpInfo + ' | ' + showUrl;
					}
					bot.say(to, showSummary);

				} else {
					bot.say(to, 'TVMaze: Couldn\'t parse data');
				}

			});
		}
	} else if (args[0] === '!isup') {
		if (!args[1]) {
			bot.say(to, 'Missing arguments. Usage example: !isup imdb.com , !isup www.imdb.com ');
		} else {
			args.shift();
			// if there's 'http(s)://' remove it
			var urlToCheck = args[0].replace(/(http:|https:)\/\//g, '');

			// some sites like google.com don't get checked properly without 'www.'
			// so it checks if users has included 'www.' in link, if not add 'www.'
			if (!urlToCheck.match(/(www\.)/g)) {
				urlToCheck = 'www.' + urlToCheck;
			}
			// before request, check if URL is OK, for example: www.example.123 would not allow request
			if (urlToCheck.match(/(www\.)\w+(\.)[a-zA-Z]/g)) {
				request('https://downforeveryoneorjustme.com/' + urlToCheck, function (error, response, body) {
					if (!error && response.statusCode === 200) {
						if (body.match(/It\'s just you/g)) {
							bot.say(to, 'Site is up!');
						} else if (body.match(/Huh\?/g)) {
							bot.say(to, 'Sorry pal, that URL does not seem to be correct..');
						} else {
							bot.say(to, 'Site is down!');
						}
					}
				});
			} else {
				bot.say(to, 'Sorry pal, that URL does not seem to be correct..');
			}
		}
	} else if (text.match(/(http|https):\/\/(i\.imgur|imgur)\.(com\/gallery\/|com\/r\/(\S+)\/|com\/)(\S+)/g)) {
		var imgurR = /(?:http|https):\/\/(?:i\.imgur|imgur)\.(?:com\/gallery\/|com\/r\/(?:\S+)\/|com\/)(\S+)/g;

		var imageID = imgurR.exec(text)[1];
		imageID = /[^.]*/.exec(imageID)[0];

		var requestURL = 'https://imgur.com/gallery/' + imageID;
		request(requestURL, function (error, response, body) {
			if (!error && response.statusCode === 200) {
				var $ = cheerio.load(body);
				var imageTitle = $('title').text().trim();
				if (imageTitle !== 'Imgur') {
					bot.say(to, c.bold('Imgur: ') + imageTitle.replace(' - Imgur', ''));
				}
			}
		});
	} else if (text.match(/(https?(:\/\/))?(www.)?youtu(be|.be)?(.com)?\/(watch\?v=)?(\S+)/gi)) {
		var ytID = getYouTubeID(text);

		youtube.videos.list({
			part: 'snippet, contentDetails, statistics',
			id: ytID
		}, function (error, data) {
			if (!error && data.items[0]) {
				var nsfw, contentRating = data.items[0].contentDetails.contentRating;
				if (contentRating) {
					if (contentRating.ytRating === 'ytAgeRestricted') {
						nsfw = c.bold.red.bgwhite('NSFW') + ' | ';
					} else {
						nsfw = '';
					}
				} else {
					nsfw = '';
				}
				/*
				var ytSummaryOutput = nsfw + 'Youtube title: ' + c.bold(data.items[0].snippet.title) +
					' | Duration: ' + moment.duration(data.items[0].contentDetails.duration).format('hh:mm:ss', { trim: false }) +
					' | Like: ' + c.green(numeral(data.items[0].statistics.likeCount).format('0,0')) +
					' / Dislike: ' + c.red(numeral(data.items[0].statistics.dislikeCount).format('0,0')) +
					' | Views: ' + numeral(data.items[0].statistics.viewCount).format('0,0');
				*/

				var ytSummaryOutput = nsfw + c.bold('Youtube | ') + c.underline(data.items[0].snippet.title) +
					' by ' + c.bold(data.items[0].snippet.channelTitle) +
					c.bold(' | ') + moment.duration(data.items[0].contentDetails.duration).format('hh:mm:ss', { trim: false });

				bot.say(to, ytSummaryOutput);
			} else {
				bot.say(to, 'Something went wrong while trying to get information about that Youtube video, call CSI to zoom-enhance & investigate.');
			}
		});
	} else if (text.match(/https?:\/\/twitter.com\/\w*(\/status\/\d*)?/gi)) {
		var twitterURL = text.match(/https?:\/\/twitter.com\/\w*(\/status\/\d*)?/gi);
		request(twitterURL[0], function (error, response, body) {
			if (!error && response.statusCode === 200) {
				var $ = cheerio.load(body);
				var twitterTitle = $('title').text().trim();
				twitterTitle = twitterTitle.split(':');
				var twitterTitleText = twitterTitle[1].split('http')[0].substring(2);
				bot.say(to, 'Twitter' + c.bold(' | ' + twitterTitle[0].split(' on Twitter')[0] + ' | ') + twitterTitleText);
			}
		});
	} else if (text.match(/https?:\/\/github.com\/\S*/gi)) {
		var githubURL = text.match(/https?:\/\/github.com\/\S*/gi);
		request(githubURL[0], function (error, response, body) {
			if (!error && response.statusCode === 200) {
				var $ = cheerio.load(body);
				var githubDescription = $('.repository-description').text().trim();
				var githubUserFullName = $('.vcard-fullname').text().trim();
				var githubUserNick = $('.vcard-username ').text().trim();
				var githubOrganisationName = $('.org-name').text().trim();

				if (githubDescription !== '') {
					bot.say(to, c.bold('GitHub: ') + githubDescription);
				} else if (githubUserFullName !== '' && githubUserNick !== '') {
					bot.say(to, c.bold('GitHub user: '******' (' + githubUserNick + ')');
				} else if (githubUserFullName === '' && githubUserNick !== '') {
					bot.say(to, c.bold('GitHub user: '******'') {
					bot.say(to, c.bold('GitHub organisation: ') + githubOrganisationName);
				}
			}
		});
	} else if (text.match(/http?s:\/\/(www.)?soundcloud.com\/([^\/]*)\/(\S*)/gi)) {
		var soundCloudLink = text.match(/http?s:\/\/(www.)?soundcloud.com\/([^\/]*)\/(.*)/gi);
		request({
				uri: soundCloudLink[0],
				method: 'GET',
				headers: {
					'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0'
				}
			}, function (error, response, body) {
				if (!error && response.statusCode === 200) {
					var soundCloudSongID = body.match(/soundcloud:\/\/sounds:\d*/i);
					soundCloudSongID = soundCloudSongID[0].match(/\d{6,}/g);

					if (soundCloudSongID[0]) {
						soundCloudLink = 'https://api.soundcloud.com/tracks/' + soundCloudSongID[0] + '.json?client_id=' + config.soundCloudClientID;
						request({
								uri: soundCloudLink,
								method: 'GET',
								headers: {
									'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0'
								}
							}, function (error, response, data) {
								if (!error && response.statusCode === 200) {
									data = JSON.parse(data);

									var soundCloudSummary = 'SoundCloud:' + c.bold(data.title) +
										' | Duration: ' + moment.duration(data.duration).format('hh:mm:ss', { trim: false }) +
										' | Likes: ' + c.green(numeral(data.favoritings_count).format('0,0')) +
										' | Played: ' + c.white(numeral(data.playback_count).format('0,0')) + ' times';
									bot.say(to, soundCloudSummary);
								}
							});
					}
				}
			});
	} else if (args[0] === '!csgo') {
		var API = 'http://api.steampowered.com';
		var appid = '?key=' + config.steam;
		var chanoutput;
		if (!args[1]) {
			bot.say(to, 'You have to supply an user name in order to see some stats.');
		} else {
			request({
				uri: API + '/ISteamUser/ResolveVanityURL/v0001/' + appid + '&vanityurl=' + args[1],
				json: true
			}, function(error, response, body) {
				var uSteamID;
				if (body.response.success === 1) {
					uSteamID = body.response.steamid;
				} else {
					if (args[1].match(/\d{17}/)) {
						uSteamID = args[1];
					}
				}

				request({
					uri: API + '/ISteamUserStats/GetUserStatsForGame/v0002/' + appid + '&appid=730&steamid=' + uSteamID,
					json: true
				}, function(error, response, body) {
					if (!error && response.statusCode === 200) {
						if (_.isEmpty(body) !== true) {
							var getStats = {};
							body.playerstats.stats.forEach(function (el) {
								getStats[el.name] = el.value;
							});
							var kills = getStats['total_kills'];
							var deaths = getStats['total_deaths'];
							var KDR = nanToZero((kills / deaths).toFixed(2));
							var playTime = moment.duration(getStats['total_time_played'], 'seconds').format('h [hrs] m [min]');
							var hits = getStats['total_shots_hit'];
							var shots = getStats['total_shots_fired'];
							var accuracy = nanToZero(((hits / shots) * 100).toFixed(2));
							var headShots = getStats['total_kills_headshot'];
							var headShotsPerc = nanToZero(((headShots / kills) * 100).toFixed(2));
							var MVP = getStats['total_mvps'];
							var battles = getStats['total_rounds_played'];
							var wins = getStats['total_wins'];
							var winRate = nanToZero(((wins / battles) * 100).toFixed(2));

							request({
								uri: API + '/ISteamUser/GetPlayerSummaries/v0002/' + appid + '&appid=730&steamids=' + uSteamID,
								json: true
							}, function(error, response, body) {
								var userName = body.response.players[0].personaname;
								chanoutput = '[' + c.bold(userName) + '] Played: ' + playTime + ' | Battles: ' +
									battles + ' [won: ' + wins + ' (' + winRate + '%) | Accuracy: ' + accuracy +
									'% | K/D: ' + KDR + ' [kills: ' + kills + ' - HeadShots: ' + headShots +
									' (' + headShotsPerc + '%)] | MVP: ' + MVP;
								bot.say(to, chanoutput);
							});
						} else {
							chanoutput = 'Maybe ' + c.bold(args[1]) + ' hasn\'t played CS:GO yet, or this profile is not public.';
						}
					} else {
						chanoutput = 'Something went wrong on the API server. Status code: ' + response.statusCode;
					}
					bot.say(to, chanoutput);
				});
				bot.say(to, chanoutput);
			});
		}
	} else if (args[0] === '!help') {
		bot.say(nick, 'Commands available:\n!wp - Wikipedia summary\n!weather or !w - current weather\n' +
						'!tv, !next, !last - for TV show info\n!isup - check if a website is up\n' +
						'!csgo - CSGO Profile statistic\n!help\n' +
						'\nBot grabs titles for the following links posted in the channel:\n' +
						'imgur, youtube, twitter, github, soundcloud');
	} else if (args[0] === '!remind') {
		if (!args[1] || !args[2]) {
			bot.say(to, 'Missing TIME and TEXT. For example: !remind 14:30 Check pizza in oven');
		} else {
			var timeToRemind = args[1];
			var currentdate = new Date();
			var currMinutes = currentdate.getMinutes();
			if (currMinutes < 10) {
				currMinutes = '0' + currMinutes;
			}
			var currentTime = currentdate.getHours() + ':' + currMinutes;
			if (timeToRemind < currentTime) {
				bot.say(to, 'Current time: ' + currentTime +
						' is earlier then your set time, reminder is set for tomorrow.');
			}
			args.splice(0, 2);
			ontime({
				cycle: timeToRemind + ':00'
			}, function (ot) {
				bot.say(to, 'Hey ' + nick + ' , don\'t forget: ' + args.join(' '));
				ot.done();
				ot.cancel();
				return;
			});
			bot.say(to, 'Reminder set for ' + nick + '. At ' + timeToRemind + ' with: ' + args.join(' '));
		}
	}

});
Example #11
0
let generateNotificationImage = (push) => {
    logger.debug('generateNotificationImage')

    // Account Image
    let iconAccount
    const accountId = push.receiver_iden

    for (let account of window.pb.api.accounts.all) {
        if (account['iden'].startsWith(accountId)) {
            iconAccount = account.image_url
        }
    }

    // Grant Image
    let iconGrant
    const grantId = push.client_iden

    for (let grant of window.pb.api.grants.all) {
        if (grant['client']['iden'] === grantId) {
            iconGrant = grant['client']['image_url']
        }
    }

    // Device Image
    let iconDevice
    const deviceId = push.source_device_iden

    for (let device of window.pb.api.devices.all) {
        if (device.iden === deviceId) {
            iconDevice = `${pushbulletIconEndpoint}${device.icon}.png`
        }
    }

    // SMS Image
    let iconSms

    if (push.type === 'sms_changed') {
        iconSms = `${pushbulletIconEndpoint}phone.png`
    }

    // Chat Image
    let iconChat

    if (!!push.sender_email) {
        const target = window.pb.targets.by_email(push.sender_email)
        iconChat = target.image_url
    }

    // Mirroring Image
    let iconMirroring

    if (push.type === 'mirror') {
        iconMirroring = `data:image/jpeg;base64,${push.icon}`
    }

    // Link Image
    let iconLink

    if (push.type === 'link') {
        // Is YouTube URL?
        const youtubeId = getYoutubeId(push.url)
        if (youtubeId) {
            // Fetch YouTube Thumbnail
            iconLink = `${youtubeThumbnailEndpoint}${youtubeId}/hqdefault.jpg`
        } else {
            // Fetch Favicon
            iconLink = `${faviconEndpoint}${push.url}`
        }
    }

    // Image Fallbacks Sequence
    const iconUrl = iconLink || iconMirroring || iconChat || iconGrant || iconDevice || iconSms || iconAccount

    return iconUrl
}