UNPKG

2.83 kBtext/coffeescriptView Raw
1# Description:
2# Hubot plugin for searching for Simpsons screencaps on Frinkiac
3#
4# Dependencies:
5# axios
6#
7# Configuration:
8# None
9#
10# Commands:
11# hubot simpsons search <query> | <caption override> - displays a screenshot from the simpsons related to your search;
12#
13# Notes:
14# None
15#
16# Author:
17# None
18
19axios = require('axios')
20
21getRequestConfig = (endpoint, params) ->
22 searchUrl = 'https://frinkiac.com/api/search'
23 captionUrl = 'https://frinkiac.com/api/caption'
24 url = if endpoint is 'search' then searchUrl else captionUrl
25 return {
26 method: 'get'
27 url: url
28 params: params
29 }
30
31encode = (str) ->
32 encodeURIComponent(str).replace /[!'()*]/g, (c) ->
33 '%' + c.charCodeAt(0).toString(16)
34
35getImageUrl = (episode, timestamp, caption) ->
36 "https://frinkiac.com/meme/#{episode}/#{timestamp}.jpg?lines=#{encode(caption)}"
37
38getLongestWordLength = (words) ->
39 longestWordLength = 0
40 words.forEach (word) ->
41 longestWordLength = word.length if word.length > longestWordLength
42 longestWordLength
43
44getNumberOfWordsBeforeBreaking = (words) ->
45 longestWordLength = getLongestWordLength(words)
46 if longestWordLength <= 5
47 wordsBeforeBreaking = 5
48 else if 5 < longestWordLength <= 8
49 wordsBeforeBreaking = 4
50 else
51 wordsBeforeBreaking = 3
52 wordsBeforeBreaking
53
54addLineBreaks = (str) ->
55 newString = ''
56 words = str.split(' ')
57 wordsBeforeBreaking = getNumberOfWordsBeforeBreaking(words)
58 words.forEach (word, i) ->
59 i++
60 delimiter = if i % wordsBeforeBreaking then ' ' else '\n'
61 newString += word + delimiter
62 newString
63
64trimWhitespace = (string) ->
65 string.replace /^\s*|\s*$/g, ''
66
67formatCaption = (caption) ->
68 addLineBreaks(trimWhitespace(caption))
69
70combineCaptions = (captions) ->
71 if captions.length <= 4
72 newCaption = ''
73 captions.forEach (caption, i) ->
74 newCaption += formatCaption(caption.Content)
75 unless i == (captions.length - 1)
76 newCaption += '\n'
77 newCaption
78 else
79 captions[0].Content
80
81module.exports = (robot) ->
82 robot.respond /(simpsons search|frinkiac) (.*)/i, (msg) ->
83 query = msg.match[2].split('|')
84 customCaption = query[1]
85
86 axios(getRequestConfig('search', {q: query[0]}))
87 .then (response) ->
88 if (response.data.length)
89 episode = response.data[0].Episode
90 timestamp = response.data[0].Timestamp
91
92 if customCaption
93 msg.send getImageUrl(episode, timestamp, formatCaption(customCaption))
94
95 else
96 axios(getRequestConfig('caption', {e: episode, t: timestamp}))
97 .then (response) ->
98 msg.send getImageUrl(episode, timestamp, combineCaptions(response.data.Subtitles))
99
100 else
101 console.log("D'oh! I couldn't find anything for `#{query[0]}`.");
102
103 .catch (error) ->
104 console.error(error);