summaryrefslogtreecommitdiff
path: root/modules/3-youtube.rkt
blob: 0ddd1a1a33c9ff3b3f18cef97336c3d1139ce52d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#lang racket/base
(require irc/bot irc/clean
         racket/string racket/format racket/function
         net/url net/uri-codec json)
(provide (all-defined-out))

(define (youtube-query url)
  (call/input-url
    (string->url (format "https://noembed.com/embed?url=~a"
                         (uri-encode (url->string url))))
    get-pure-port read-json))

(define (string->maybe-url s)
  (with-handlers ([url-exception? (const #f)])
    (string->url s)))

; catch youtube.com and youtu.be
(define (extract-youtube-url s)
  (define (is-yt-url u)
    (and u
         (url-host u)
         (string-contains? (url-host u) "youtu")))

  (let* ([urls (map (compose1 string->maybe-url clean-control) (string-split s))])
    (findf is-yt-url urls)))

(on (and (command-is 'PRIVMSG)
         (context-is "#code"))
    (let ([url (extract-youtube-url (suffix))])
      (when url
        (let* ([response (youtube-query url)]
               [title (hash-ref response 'title)])
          (reply (~v title))))))

;(format "\"~a\"" title))))))