asjon/scripts/doge.coffee
2015-10-01 16:09:25 +02:00

67 lines
1.9 KiB
CoffeeScript

# Description:
# Doge meme generator
# Requires hubot-tg adapter to access message history
#
# Configuration:
# Uses hubot-tg enviroment variables
#
# Commands
# hubot doge [n] - crea un meme doge con messaggi recenti della chat
#
# Author:
# Michele Guerini Rocco (rnhmjoj)
#
net = require 'net'
module.exports = (robot) ->
match_all = (regex, str) ->
matches = []
str.replace regex, ->
arr = [].slice.call arguments, 0
extras = arr.splice -2
arr.index = extras[0]
arr.input = extras[1]
matches.push arr
matches
concat = (list) -> list.reduce (x, y) -> x.concat y
escape = (str) ->
str.replace(/\d|\?|#/g, '') # not supported
.replace( /\ /g, '%20') # spaces
doge_url = (text) ->
"http://dogr.io/#{escape text}.png?split=false"
shiba = (res, words) ->
prefix = [ 'much', 'such', 'many', 'very']
word = words.filter (x) ->
/^[a-zA-ZàèéìòùÀÈÉÌÒÙ\-_!&@#?]{4,}$/.test x
(res.random prefix) + ' ' + (res.random words)
run_command = (command, callback) ->
client = net.connect robot.adapter.port, robot.adapter.host, ->
client.write command+'\n'
client.setEncoding 'utf8'
client.on 'data', (reply) ->
if callback?
callback (reply.split '\n')[1..-3]
client.end()
get_history = (chat, size, callback) ->
regex = /\[(.+)\] (.+) [>«»]+ ((?:(?!\n(\[|\d))[\s\S])+)/g
parse_line = (x) ->
date: x[1]
peer: x[2].replace chat + ' ', ''
text: x[3].trim().replace '\n', ' '
run_command "history #{chat} #{size}", (lines) ->
callback ((match_all regex, lines.join '\n').map parse_line)
robot.respond /doge(?: (\d+))?/, (res) ->
n = res.match[1] || 20
get_history res.message.room, n, (history) ->
words = concat (message.text.split ' ' for message in history)
sample = (res.random ['wow', shiba res, words] for _ in [0..8])
res.send (doge_url sample.join '/')