asjon/scripts/doge.coffee
2017-02-26 17:28:29 +01:00

68 lines
1.9 KiB
CoffeeScript

# Description:
# Doge meme generator
# Requires hubot-matrix adapter to access 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)
#
module.exports = (robot) ->
matrix = robot.adapter.client
return unless robot.adapterName is 'matrix' and matrix?
# get the messages history for a chat room
get_history = (room, size, callback) ->
room = matrix.getRoom room.id
matrix.scrollback room, size, (err, res) ->
return callback err, null if err?
return unless res.chunk?
callback null, res.chunk.map (event) ->
type: event.content.msgtype
sender: robot.brain.userForId event.sender
content: event.content.body
# concat list of lists
concat = (list) -> list.reduce (x, y) -> x.concat y
# remove duplicates in a list
nub = (list) -> Array.from new Set list
# URL escape strings
escape = (str) ->
str.replace(/\d|\?|#/g, '') # not supported
.replace( /\ /g, '%20') # spaces
# format doge API URL
doge_url = (text) ->
"http://dogr.io/#{escape text}.png?split=false"
# dogeify text
doge = (res, words) ->
prefix = [ 'much', 'such', 'many', 'very']
word = words.filter (x) ->
/^[a-zA-ZàèéìòùÀÈÉÌÒÙ\-_!&@#?]{4,}$/.test x
(res.random prefix) + ' ' + (res.random words)
robot.respond /doge(?: (\d+))?/, (res) ->
n = res.match[1] || 10
get_history res.message.room, n, (err, history) ->
return res.send "c'è stato un errore: #{err}" if err?
words = ((nub concat (history.filter (msg) ->
msg.type is 'm.text').map (msg) ->
msg.content.split /\W/).sort (a, b) ->
b.length - a.length).slice 0, 50
sample = [0..15].map ->
if Math.random() <= 0.2 then 'wow'
else doge res, words
res.send doge_url sample.join '/'