asjon/scripts/doge.coffee

68 lines
1.9 KiB
CoffeeScript
Raw Normal View History

2015-09-29 23:59:35 +02:00
# Description:
# Doge meme generator
2017-02-26 17:15:45 +01:00
# Requires hubot-matrix adapter to access history
2015-09-29 23:59:35 +02:00
#
# 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) ->
2017-02-26 17:15:45 +01:00
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
2015-10-01 06:10:11 +02:00
2017-02-26 17:15:45 +01:00
# concat list of lists
2015-10-01 06:10:11 +02:00
concat = (list) -> list.reduce (x, y) -> x.concat y
2017-02-26 17:15:45 +01:00
# remove duplicates in a list
nub = (list) -> Array.from new Set list
# URL escape strings
2015-10-01 06:10:11 +02:00
escape = (str) ->
str.replace(/\d|\?|#/g, '') # not supported
.replace( /\ /g, '%20') # spaces
2017-02-26 17:15:45 +01:00
# format doge API URL
2015-10-01 06:10:11 +02:00
doge_url = (text) ->
"http://dogr.io/#{escape text}.png?split=false"
2017-02-26 17:15:45 +01:00
# dogeify text
doge = (res, words) ->
2015-10-01 06:10:11 +02:00
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)
2017-02-26 17:15:45 +01:00
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?
2015-09-29 23:59:35 +02:00
2017-02-26 17:15:45 +01:00
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
2015-09-29 23:59:35 +02:00
2017-02-26 17:15:45 +01:00
sample = [0..15].map ->
if Math.random() <= 0.2 then 'wow'
else doge res, words
res.send doge_url sample.join '/'