asjon/scripts/doge.coffee

67 lines
1.9 KiB
CoffeeScript
Raw Normal View History

2015-09-29 23:59:35 +02:00
# 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) ->
2015-10-01 06:10:11 +02:00
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']
2015-10-01 16:08:43 +02:00
word = words.filter (x) ->
/^[a-zA-ZàèéìòùÀÈÉÌÒÙ\-_!&@#?]{4,}$/.test x
2015-10-01 06:10:11 +02:00
(res.random prefix) + ' ' + (res.random words)
2015-09-29 23:59:35 +02:00
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) ->
2015-10-01 06:10:11 +02:00
regex = /\[(.+)\] (.+) [>«»]+ ((?:(?!\n(\[|\d))[\s\S])+)/g
2015-09-29 23:59:35 +02:00
parse_line = (x) ->
date: x[1]
peer: x[2].replace chat + ' ', ''
2015-10-01 06:10:11 +02:00
text: x[3].trim().replace '\n', ' '
2015-09-29 23:59:35 +02:00
run_command "history #{chat} #{size}", (lines) ->
2015-10-01 06:10:11 +02:00
callback ((match_all regex, lines.join '\n').map parse_line)
2015-09-29 23:59:35 +02:00
robot.respond /doge(?: (\d+))?/, (res) ->
2015-10-01 16:08:43 +02:00
n = res.match[1] || 20
2015-09-29 23:59:35 +02:00
get_history res.message.room, n, (history) ->
2015-10-01 06:10:11 +02:00
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 '/')