🏡 index : ~doyle/dave.git

author Jordan Doyle <jordan@doyle.wf> 2017-07-29 19:59:03.0 +00:00:00
committer Jordan Doyle <jordan@doyle.wf> 2017-07-29 19:59:03.0 +00:00:00
commit
3d2d26afe271ecca80f09aa7efd9417b9abe187a [patch]
tree
1c54751e38817c75b205eeb0096d4693656a2359
parent
b74540d16fe50db6b87c75f1e3cef04a3a384a31
download
3d2d26afe271ecca80f09aa7efd9417b9abe187a.tar.gz

Add module for grabbing YouTube info



Diff

 config.json.example             |  1 +-
 dave/modules/urbandictionary.py |  2 +-
 dave/modules/youtube.py         | 54 ++++++++++++++++++++++++++++++++++++++++++-
 requirements.txt                |  3 +-
 4 files changed, 58 insertions(+), 2 deletions(-)

diff --git a/config.json.example b/config.json.example
index a1afdb3..70664c4 100644
--- a/config.json.example
+++ b/config.json.example
@@ -7,6 +7,7 @@
  "api_keys": {
    "google_maps": "",
    "forecast.io": "",
    "youtube": ""
    "timezonedb": "",
    "mashape": "",
    "wolfram": ""
diff --git a/dave/modules/urbandictionary.py b/dave/modules/urbandictionary.py
index 9666aa1..e1e71b5 100644
--- a/dave/modules/urbandictionary.py
+++ b/dave/modules/urbandictionary.py
@@ -43,7 +43,7 @@ def urbandictionary(bot, args, sender, source):
        if len(definition) > 200:
            definition = definition[:197] + "..."

        definition = assembleFormattedText(A.normal[A.bold[str(res["word"])], ": {} [by {} +{}/-{}] [more at {}]".format(
        definition = assembleFormattedText(A.normal[A.bold[str(res["word"])], ": {} [by {}, 👍 {} 👎 {}] [more at {}]".format(
            definition,
            res["author"],
            res["thumbs_up"],
diff --git a/dave/modules/youtube.py b/dave/modules/youtube.py
new file mode 100644
index 0000000..17ebdf3
--- /dev/null
+++ b/dave/modules/youtube.py
@@ -0,0 +1,54 @@
import pickle

import dave.module
import dave.config
from twisted.words.protocols.irc import assembleFormattedText, attributes as A
from requests import get
from humanize import naturaltime, intcomma
from datetime import datetime, timezone
import isodate

BASE_URL = "https://www.googleapis.com/youtube/v3/videos?part=contentDetails,snippet," \
           "statistics&key={}".format(dave.config.config["api_keys"]["youtube"])

@dave.module.match(r'http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?‌​[\w\?‌​=]*)?')
@dave.module.dont_always_run_if_run()
def youtubevideo(bot, args, sender, source):
    """Ran whenever a YouTube video is sent"""
    if not dave.config.redis.exists("youtube:{}".format(args[0])):
        req = get("{}&id={}".format(BASE_URL, args[0]),
                  headers={'user-agent': 'irc bot (https://github.com/w4)'})

        if req.status_code != 200:
            bot.msg(source, "Bad response from YouTube API: {}".format(req.status_code))
            return

        req = req.json()

        if not req["pageInfo"]["totalResults"]:
            bot.msg(source, "That video doesn't exist.")
            return

        dave.config.redis.setex("youtube:{}".format(args[0]), 400,
                                pickle.dumps(req))
    else:
        req = pickle.loads(dave.config.redis.get("youtube:{}".format(args[0])))

    resp = req["items"][0]

    bot.msg(source, assembleFormattedText(
        A.normal[
            A.bold[resp["snippet"]["title"]],
            " ({}) by {} uploaded {}. {} views, 👍 {} 👎 {}.".format(
                str(isodate.parse_duration(resp["contentDetails"]["duration"])),
                resp["snippet"]["channelTitle"],
                naturaltime(
                    datetime.now(timezone.utc)
                        - isodate.parse_datetime(resp["snippet"]["publishedAt"])
                ),
                intcomma(resp["statistics"]["viewCount"]),
                intcomma(resp["statistics"]["likeCount"]),
                intcomma(resp["statistics"]["dislikeCount"])
            )
        ]
    ))
\ No newline at end of file
diff --git a/requirements.txt b/requirements.txt
index 45637eb..24e8a49 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -14,4 +14,5 @@ lxml==3.8.0
pysocks==1.6.7
wolframalpha==3.0
babel==2.4.0
humanize==0.5.1
\ No newline at end of file
humanize==0.5.1
isodate==0.5.4
\ No newline at end of file